diff --git a/CHANGELOG.md b/CHANGELOG.md
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,130 @@
-# Changelog for jsonnet
+# Changelog for haskell-jsonnet
 
 ## Unreleased changes
+
+## [0.5.0.0] - 2026-12-01
+
+Five years after the initial version, I sat down to fix object inheritance and
+accidentally rewrote the evaluator. On the bright side, it closes the gap in
+features/compliance with other implementations while getting decent performance,
+making this the very first non-toy release of `haskell-jsonnet`.
+
+### First-class `self` and `super`
+
+`self` and `super` used to masquerade as lexical variables, which they aren't.
+Jsonnet uses mixin-based object composition (open-recursive records where
+accessing a field ties the knot), and trying to wire that up via `MonadFix`
+(`mdo`) was convoluted. Previously, object composition beyond two layers was
+outright broken. Because objects were plain `HashMap`s, every `+` eagerly merged
+them—wasteful in a lazy language—and tied the knot too early, erasing their
+tree-like structure. We now use a two-level object design: an immutable
+recursive mixin tree (`Empty`, `Singleton`, `Base`, and `Mixin`, keeping `+`
+`O(1)` and avoiding `HashMap`s for empty or single-field objects), while each
+composed object pairs that tree with its own per-object cache indexed by layer.
+
+```jsonnet
+local base = { a: self.c };
+local mid  = { a: super.a + 1 };
+local o1   = base + mid + { a: super.a + 100, c: 5 };  // a = 106
+local o2   = base + mid + { c: 10 };                   // a = 11
+```
+
+Three constraints drive this structure:
+
+* **Per-object caching:** `base` and `mid` are shared between `o1` and `o2`, but
+  late-bound `self.c` resolves differently in each. Evaluated fields can only be
+  memoized once `self` is fixed to a specific final object&mdash;never on the
+  mixin layers themselves.
+* **Layer-indexed lookup:** Inside `o1`, field `a` has a different value at
+  every layer (`5`, `6`, `106`). Indexing the per-object cache by layer
+  memoizes each layer's view independently, avoiding repeated re-evaluation of
+  lower layers on `super` accesses.
+* **Defining-layer `super`:** Evaluating `o2.a` falls through to `mid`'s
+  definition. Inside `mid`, `self` remains `o2`, while `super` must step
+  strictly below `mid` (to `base`) rather than below the top layer.
+
+Side note: unlike `this` in languages like JavaScript, Jsonnet's `self` is not
+resolved at call sites: once late-bound to a composed object, it is captured in
+the environment of any closures produced by its fields (so detaching a method
+keeps its original `self`).
+
+### Performance and allocations
+
+Late cost-centre profiling (tracking time and allocations by call stack after
+optimizations), RTS GC stats, and GHC Core dumps (`-ddump-simpl`), alongside
+benchmarks—with Gemini/Claude helping read the output and suggest fixes—showed
+where time and memory were actually going. That led to a few main changes:
+
+* **Replacing `locally-nameless` with 2D de Bruijn indices:** The biggest win.
+  `locally-nameless` was a poor fit for a dynamically typed, environment-based
+  evaluator since closures and thunks already prevent variable capture. On top
+  of that, I was not even using correctly the library.
+
+* **Reimplementing allocation-heavy paths:** Profiles and Core dumps show
+  unnecessary allocations, and here is where help from Gemini came in handy.
+  Other improvements include selective source spans (source locations are only
+  attached to expressions that can actually fail), fast paths and
+  short-circuiting for certain primitive operations, e.g. for `+` on empty
+  arrays and objects, avoid allocating thunks when we can tell up front
+  something is in WHNF, but here one must be careful to preserve lazy errors:
+  when `self` is in scope you can skip the thunk; when it isn't, it still falls
+  back to allocating a thunk so that if inside an unevaluated branch doesn't
+  fire eagerly.
+
+* **Tightening strictness:** Enabling `StrictData` and making `Env`/`EvalState`
+  updates strict keeps closures and cached object fields from retaining caller
+  environments.
+
+
+### Modules and cycle detection
+
+Modules (imports) previously worked by naively pasting the imported AST inline,
+Imports are now properly evaluated and cached, with full support including
+cyclic imports. Additionally, thunks are now guarded with cycle detection,
+previously the interpreter would just loop indefinitely.
+
+### Miscellanea
+
+A non-exhaustive list of other changes:
+
+- Added several new errors: `UnboundSelf`, `UnboundSuper`, `NoSuperClass`,
+  `UnresolvedImport`, `InfiniteRecursion`, `ParamAlreadyBound`, and
+  `TooFewArgs`. Of note is how `super` behaves depending on context:
+
+  ```console
+  λ  cabal run hs-jsonnet -- -e 'super.x'
+  Runtime error: can't use super outside of an object.
+    :1:7-8
+
+  λ  cabal run hs-jsonnet -- -e '({ x: super.x }).x'
+  Runtime error: attempt to use super when there is no super class.
+    :1:13-15
+
+  λ  cabal run hs-jsonnet -- -e '({ x: "x" in super }).x'
+  false
+  ```
+
+- Fixed a bug where underlying errors escaped backtrace propagation:
+
+  ```console
+  λ  cabal run hs-jsonnet -- -e "local json(a) = std.parseJson('{\"%s\": \"bar' % a); json('foo')"
+  Runtime error: AesonException "Unexpected end-of-input while parsing string literal"
+    :1:17-30 function <json>
+    :1:51-55
+  ```
+
+- Fixed parser precedence for implicit object composition (`e { ... }`) so it
+  chains left-to-right with function calls and field lookups, allowing
+  expressions like `std.extVar('var2') { x+: 2 }.x` to parse.
+
+- Fixed value ordering failing on arrays: comparisons were previously
+  restricted to numbers instead of comparing arrays lexicographically.
+
+- Cleaned up module boundaries and internal ergonomics (after plenty of
+  bikeshedding): `Value` was decoupled from `Core` by _refunctionalizing_
+  `VThunk` (once the old object `+` implementation was gone, it no longer had
+  to pattern-match on `VThunk core env` just to inject `self` and `super` into
+  `env` after the fact). `HasValue` was also split into `Inj` and `Proj` to
+  separate converting to and from Jsonnet values, and optics were added—lenses
+  for reading and updating evaluation state, and prisms for inspecting and
+  constructing `Value` variants.
diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -11,13 +11,14 @@
 
 Here is the implementation status of the main language features:
 
-- [X] array and object comprehension (but see https://github.com/moleike/haskell-jsonnet/issues/46)
+- [X] array and object comprehension
 - [X] array slices
 - [X] Python-style string formatting
 - [X] text blocks
 - [X] verbatim strings
+- [X] computed field names
 - [X] object-level locals
-- [ ] object-level asserts (https://github.com/moleike/haskell-jsonnet/issues/39)
+- [X] object-level asserts (by Berk Özkütük)
 - [X] keyword parameters
 - [X] default arguments
 - [ ] top-level arguments (https://github.com/moleike/haskell-jsonnet/issues/24)
@@ -27,7 +28,7 @@
 - [X] outermost object reference `$`
 - [X] mixin inheritence and open recursion (operator `+` with `self` and `super`)
 - [X] field composition (operator `+:`)
-- [ ] multiple file output (https://github.com/moleike/haskell-jsonnet/issues/32)
+- [X] multiple file output (by Berk Özkütük)
 - [X] verbatim imports (by Berk Özkütük)
 
 ## Build
@@ -50,10 +51,11 @@
 
 ```console
 % hs-jsonnet --help
-Usage: hs-jsonnet [-v|--version] [-e|--exec] [<filename>] 
-                  [-o|--output-file <filename>] [-S|--string] 
-                  [-V|--ext-str VAR=VALUE] [--ext-str-file FILE] 
-                  [--ext-code VAR=EXPR] [--ext-code-file FILE]
+Usage: hs-jsonnet [-v|--version] [-e|--exec] [<filename>]
+                  [(-o|--output-file <filename>) | (-m|--multi <dir>)]
+                  [--compact] [-S|--string] [-V|--ext-str VAR=VALUE]
+                  [--ext-str-file FILE] [--ext-code VAR=EXPR]
+                  [--ext-code-file FILE]
 
 Available options:
   -v,--version             Print version of the program
@@ -62,6 +64,9 @@
   <filename>               Jsonnet source file or stdin
   -o,--output-file <filename>
                            Write to the output file rather than stdout
+  -m,--multi <dir>         Write multiple files to the directory, list files on
+                           stdout
+  --compact                Produce a compact JSON output
   -S,--string              Expect a string, manifest as plain text
   -V,--ext-str VAR=VALUE   External string variable
   --ext-str-file FILE      External string variable as file
diff --git a/app/Main.hs b/app/Main.hs
--- a/app/Main.hs
+++ b/app/Main.hs
@@ -2,182 +2,223 @@
 
 module Main where
 
-import qualified Data.Aeson as JSON
+import Control.Monad (when)
+import Data.Aeson qualified as JSON
+import Data.Aeson.Key qualified as JSON.Key
+import Data.Aeson.KeyMap qualified as JSON.KeyMap
 import Data.Bifunctor (first, second)
 import Data.ByteString.Builder (toLazyByteString)
-import qualified Data.ByteString.Lazy as L
-import Data.ByteString.Lazy.Char8 as LC (putStrLn)
+import Data.ByteString.Lazy qualified as L
+import Data.ByteString.Lazy.Char8 qualified as LC
+import Data.Functor (void)
 import Data.Maybe
 import Data.Text (Text)
-import qualified Data.Text as T
+import Data.Text qualified as T
 import Data.Text.Encoding (encodeUtf8Builder)
-import qualified Data.Text.IO as TIO
+import Data.Text.IO qualified as TIO
 import Data.Version (showVersion)
 import Data.Void (Void)
 import Language.Jsonnet
 import Language.Jsonnet.Error
-import Language.Jsonnet.Pretty (ppJson, prettyError)
+import Language.Jsonnet.Pretty (ppJsonIndent, prettyError)
 import Options.Applicative hiding (str)
 import Paths_jsonnet (version)
+import System.Directory qualified as Dir
 import System.Environment (lookupEnv)
 import System.Exit (die)
-import qualified Text.Megaparsec as MP
-import qualified Text.Megaparsec.Char as MPC
+import System.FilePath ((</>))
+import Text.Megaparsec qualified as MP
+import Text.Megaparsec.Char qualified as MPC
 
 main :: IO ()
 main = do
-  runProgram =<< execParser options
-  return ()
+    runProgram =<< execParser options
+    return ()
 
-runProgram ::
-  -- |
-  Options ->
-  IO ()
-runProgram opts@Options {..} = do
-  src <- readSource input
-  conf <- mkConfig opts
-  outp <- interpret conf src
-  either printError (printResult output outputMode format) outp
+runProgram :: Options -> IO ()
+runProgram opts@Options{..} = do
+    src <- readSource input
+    conf <- mkConfig opts
+    outp <- interpret conf src
+    either printError (printResult output outputMode format) outp
 
-encodeToLazyByteString :: Text -> L.ByteString
-encodeToLazyByteString = toLazyByteString . encodeUtf8Builder
+writeFileMulti :: FilePath -> L.ByteString -> IO ()
+writeFileMulti outFile content = do
+    -- We shouldn't touch the file if it exists and has the same content
+    fileExists <- Dir.doesFileExist outFile
+    if fileExists
+        then do
+            existingContent <- L.readFile outFile
+            when (existingContent /= content) $
+                L.writeFile outFile content
+        else L.writeFile outFile content
+    putStrLn outFile
 
 printResult :: Output -> OutputMode -> Format -> JSON.Value -> IO ()
-printResult outp outputMode Json val =
-  writeOutput (encode val) outp
+printResult outp outputMode format val =
+    case format of
+        Json -> case outp of
+            FileOutput path -> L.writeFile path (encode val)
+            FileOutputMulti outDir -> case val of
+                JSON.Object obj -> do
+                    Dir.createDirectoryIfMissing True outDir
+                    void $ flip JSON.KeyMap.traverseWithKey obj $ \fileName output ->
+                        writeFileMulti (outDir </> JSON.Key.toString fileName) (encode output)
+                _ -> die "Runtime error: result must be a JSON object in multi mode"
+            Stdout -> LC.putStrLn (encode val)
+        Plaintext -> case val of
+            JSON.String s -> case outp of
+                FileOutput path -> L.writeFile path (encodeToLazyByteString s)
+                FileOutputMulti _ -> die "Runtime error: multi mode can only be used with JSON output"
+                Stdout -> LC.putStrLn (encodeToLazyByteString s)
+            _ -> die "Runtime error: result must be a string for plaintext output"
   where
+    encode :: JSON.Value -> L.ByteString
     encode = case outputMode of
-      Pretty -> encodeToLazyByteString . T.pack . show . ppJson 4
-      Compact -> JSON.encode
-printResult outp _ Plaintext (JSON.String s) =
-  writeOutput (encodeToLazyByteString s) outp
-printResult _ _ Plaintext _ =
-  print "Runtime error: expected string result"
+        Pretty -> encodeToLazyByteString . T.pack . show . ppJsonIndent 4
+        Compact -> JSON.encode
 
-writeOutput :: L.ByteString -> Output -> IO ()
-writeOutput bs = \case
-  FileOutput path -> L.writeFile path bs
-  Stdout -> LC.putStrLn bs
+    encodeToLazyByteString :: Text -> L.ByteString
+    encodeToLazyByteString = toLazyByteString . encodeUtf8Builder
 
 printError :: Error -> IO ()
 printError = print . prettyError
 
 readSource :: Input -> IO Text
 readSource = \case
-  Stdin -> TIO.getContents
-  FileInput path -> TIO.readFile path
-  ExecInput str -> pure (T.pack str)
+    Stdin -> TIO.getContents
+    FileInput path -> TIO.readFile path
+    ExecInput str -> pure (T.pack str)
 
 mkExtVar :: (Text, Either ExtVarType ExtVar) -> IO (Text, ExtVar)
 mkExtVar = \case
-  (s, Right extVar) -> pure (s, extVar)
-  (envVar, Left extVarType) ->
-    lookupEnv (T.unpack envVar) >>= \case
-      Just extVar -> pure $ (envVar, ExtVar extVarType (Inline (T.pack extVar)))
-      Nothing -> die "No env variable"
+    (s, Right extVar) -> pure (s, extVar)
+    (envVar, Left extVarType) ->
+        lookupEnv (T.unpack envVar) >>= \case
+            Just extVar -> pure $ (envVar, ExtVar extVarType (Inline (T.pack extVar)))
+            Nothing -> die "No env variable"
 
 mkConfig :: Options -> IO Config
-mkConfig Options {..} = do
-  let fname = case input of
-        Stdin -> ""
-        FileInput path -> path
-        ExecInput _ -> ""
-  extVars' <- constructExtVars =<< traverse mkExtVar extVars
-  pure Config {fname = fname, extVars = extVars'}
+mkConfig Options{..} = do
+    let fname = case input of
+            Stdin -> ""
+            FileInput path -> path
+            ExecInput _ -> ""
+    extVars' <- constructExtVars =<< traverse mkExtVar extVars
+    pure defaultConfig{fname = fname, extVars = extVars', jpaths = reverse jpaths}
 
 fileOutput :: Parser Output
 fileOutput =
-  fromMaybe Stdout
-    <$> ( optional $
-            FileOutput
-              <$> strOption
+    fromMaybe Stdout <$> optional fileOpts
+  where
+    fileOpts :: Parser Output
+    fileOpts =
+        FileOutput
+            <$> strOption
                 ( long "output-file"
                     <> short 'o'
                     <> metavar "<filename>"
                     <> help "Write to the output file rather than stdout"
                 )
-        )
+                <|> FileOutputMulti
+            <$> strOption
+                ( long "multi"
+                    <> short 'm'
+                    <> metavar "<dir>"
+                    <> help "Write multiple files to the directory, list files on stdout"
+                )
 
 fileInput :: Parser (Maybe String)
 fileInput =
-  optional $
-    strArgument
-      ( metavar "<filename>"
-          <> help "Jsonnet source file or stdin"
-      )
+    optional $
+        strArgument
+            ( metavar "<filename>"
+                <> help "Jsonnet source file or stdin"
+            )
 
 parseOpts :: Parser Options
 parseOpts = do
-  input <- mkInput <$> exec <*> fileInput
-  output <- fileOutput
-  outputMode <-
-    flag
-      Pretty
-      Compact
-      ( long "compact"
-          <> help "Produce a compact JSON output"
-      )
-  format <-
-    flag
-      Json
-      Plaintext
-      ( long "string"
-          <> short 'S'
-          <> help "Expect a string, manifest as plain text"
-      )
-  extStrs <- parseExtStr
-  extStrFiles <- parseExtStrFile
-  extCodes <- parseExtCode
-  extCodeFiles <- parseExtCodeFile
-  pure Options {extVars = extStrs <> extStrFiles <> extCodes <> extCodeFiles, ..}
+    input <- mkInput <$> exec <*> fileInput
+    output <- fileOutput
+    outputMode <-
+        flag
+            Pretty
+            Compact
+            ( long "compact"
+                <> help "Produce a compact JSON output"
+            )
+    format <-
+        flag
+            Json
+            Plaintext
+            ( long "string"
+                <> short 'S'
+                <> help "Expect a string, manifest as plain text"
+            )
+    extStrs <- parseExtStr
+    extStrFiles <- parseExtStrFile
+    extCodes <- parseExtCode
+    extCodeFiles <- parseExtCodeFile
+    jpaths <- parseModSearchPath
+    pure Options{extVars = extStrs <> extStrFiles <> extCodes <> extCodeFiles, ..}
 
 parseExtStr :: Parser [(Text, Either ExtVarType ExtVar)]
 parseExtStr =
-  many $
-    option
-      (second (interpretAs ExtStr) <$> extVarParser)
-      ( long "ext-str"
-          <> short 'V'
-          <> metavar "VAR=VALUE"
-          <> help "External string variable"
-      )
+    many $
+        option
+            (second (interpretAs ExtStr) <$> extVarParser)
+            ( long "ext-str"
+                <> short 'V'
+                <> metavar "VAR=VALUE"
+                <> help "External string variable"
+            )
 
 parseExtStrFile :: Parser [(Text, Either ExtVarType ExtVar)]
 parseExtStrFile =
-  many $
-    option
-      (second (Right . ExtVar ExtStr) <$> extVarFileParser)
-      ( long "ext-str-file"
-          <> help "External string variable as file"
-          <> metavar "FILE"
-          <> action "file"
-      )
+    many $
+        option
+            (second (Right . ExtVar ExtStr) <$> extVarFileParser)
+            ( long "ext-str-file"
+                <> help "External string variable as file"
+                <> metavar "FILE"
+                <> action "file"
+            )
 
 parseExtCode :: Parser [(Text, Either ExtVarType ExtVar)]
 parseExtCode =
-  many $
-    option
-      (second (interpretAs ExtCode) <$> extVarParser)
-      ( long "ext-code"
-          <> metavar "VAR=EXPR"
-          <> help "External code variable"
-      )
+    many $
+        option
+            (second (interpretAs ExtCode) <$> extVarParser)
+            ( long "ext-code"
+                <> metavar "VAR=EXPR"
+                <> help "External code variable"
+            )
 
 parseExtCodeFile :: Parser [(Text, Either ExtVarType ExtVar)]
 parseExtCodeFile =
-  many $
-    option
-      (second (Right . ExtVar ExtCode) <$> extVarFileParser)
-      ( long "ext-code-file"
-          <> help "External code variable as file"
-          <> metavar "FILE"
-          <> action "file"
-      )
+    many $
+        option
+            (second (Right . ExtVar ExtCode) <$> extVarFileParser)
+            ( long "ext-code-file"
+                <> help "External code variable as file"
+                <> metavar "FILE"
+                <> action "file"
+            )
+            
+parseModSearchPath :: Parser [FilePath]
+parseModSearchPath =
+    many $
+        strOption
+            ( long "jpath"
+                <> short 'J'
+                <> metavar "<dir>"
+                <> help "Specify an additional library search directory"
+            )
 
 interpretAs :: ExtVarType -> Maybe ExtVarContent -> Either ExtVarType ExtVar
 interpretAs t = \case
-  Nothing -> Left t
-  Just s -> Right $ ExtVar t s
+    Nothing -> Left t
+    Just s -> Right $ ExtVar t s
 
 extVarParser :: ReadM (Text, Maybe ExtVarContent)
 extVarParser = eitherReader f
@@ -197,69 +238,71 @@
 
 parsePair :: MP.Parsec Void String (Text, String)
 parsePair =
-  first T.pack
-    <$> liftA2
-      (,)
-      (MP.someTill MPC.asciiChar (MPC.char '='))
-      (MP.someTill MPC.asciiChar MP.eof)
+    first T.pack
+        <$> liftA2
+            (,)
+            (MP.someTill MPC.asciiChar (MPC.char '='))
+            (MP.someTill MPC.asciiChar MP.eof)
 
 mkInput :: Bool -> Maybe String -> Input
 mkInput exec' = \case
-  Nothing -> Stdin
-  Just e | exec' -> ExecInput e
-  Just p | otherwise -> FileInput p
+    Nothing -> Stdin
+    Just e | exec' -> ExecInput e
+    Just p | otherwise -> FileInput p
 
 exec :: Parser Bool
 exec =
-  switch
-    ( long "exec"
-        <> short 'e'
-        <> help "Treat filename as code"
-    )
+    switch
+        ( long "exec"
+            <> short 'e'
+            <> help "Treat filename as code"
+        )
 
 ver :: Parser (a -> a)
 ver =
-  infoOption
-    verStr
-    ( long "version"
-        <> short 'v'
-        <> help "Print version of the program"
-    )
+    infoOption
+        verStr
+        ( long "version"
+            <> short 'v'
+            <> help "Print version of the program"
+        )
   where
     verStr = "Jsonnet command line " <> showVersion version
 
 options :: ParserInfo Options
 options =
-  info
-    (ver <*> helper <*> parseOpts)
-    ( fullDesc
-        <> noIntersperse
-    )
+    info
+        (ver <*> helper <*> parseOpts)
+        ( fullDesc
+            <> noIntersperse
+        )
 
 data Options = Options
-  { output :: Output,
-    outputMode :: OutputMode,
-    format :: Format,
-    input :: Input,
-    -- | ExtVarType determines the interpretation of the environment variable
-    extVars :: [(Text, Either ExtVarType ExtVar)]
-  }
+    { output :: Output
+    , outputMode :: OutputMode
+    , format :: Format
+    , input :: Input
+    , extVars :: [(Text, Either ExtVarType ExtVar)]
+    -- ^ ExtVarType determines the interpretation of the environment variable
+    , jpaths :: [FilePath]
+    }
 
 data Input
-  = FileInput FilePath
-  | ExecInput String
-  | Stdin
-  deriving (Eq, Show)
+    = FileInput FilePath
+    | ExecInput String
+    | Stdin
+    deriving (Eq, Show)
 
 data Output
-  = FileOutput FilePath
-  | Stdout
-  deriving (Eq, Show)
+    = FileOutput FilePath
+    | FileOutputMulti FilePath
+    | Stdout
+    deriving (Eq, Show)
 
 data OutputMode
-  = Pretty
-  | Compact
-  deriving (Eq, Show)
+    = Pretty
+    | Compact
+    deriving (Eq, Show)
 
 data Format = Json | Plaintext
-  deriving (Eq, Show)
+    deriving (Eq, Show)
diff --git a/benchmarks/Bench.hs b/benchmarks/Bench.hs
--- a/benchmarks/Bench.hs
+++ b/benchmarks/Bench.hs
@@ -1,10 +1,12 @@
 {-# LANGUAGE QuasiQuotes #-}
 
-import qualified Data.ByteString.Lazy as LBS
-import Data.Text.Lazy
+import Data.ByteString.Lazy qualified as LBS
+import Data.Text.Lazy hiding (show)
 import Data.Text.Lazy.Encoding (encodeUtf8)
 import Language.Jsonnet
-import Language.Jsonnet.Pretty (ppJson, prettyError)
+import Language.Jsonnet.Core (resolve)
+import Language.Jsonnet.Desugar (desugar)
+import Language.Jsonnet.Pretty (ppJsonIndent, prettyError)
 import Language.Jsonnet.Syntax.Annotated (Expr)
 import Language.Jsonnet.TH.QQ
 import Prettyprinter (Doc)
@@ -13,37 +15,36 @@
 render :: (a -> Doc ann) -> a -> LBS.ByteString
 render printer = encodeUtf8 . pack . show . printer
 
-conf :: Config
-conf = Config "" mempty
-
 eval :: Expr -> IO LBS.ByteString
 eval expr = do
-  outp <- runJsonnetM conf (desugar expr >>= evaluate)
-  pure (either (render prettyError) (render (ppJson 4)) outp)
+    outp <- runJsonnetM defaultConfig (evaluate $ resolve $ desugar expr)
+    pure (either (render prettyError) (render (ppJsonIndent 4)) outp)
 
 main :: IO ()
 main =
-  defaultMain
-    [ bgroup
-        "simple"
-        [ bench "bench01" $ nfAppIO eval bench01,
-          bench "bench02" $ nfAppIO eval bench02,
-          bench "bench03" $ nfAppIO eval bench03
-        ],
-      bgroup
-        "caching"
-        [ bench "bench08" $ nfAppIO eval bench08
-        ],
-      bgroup
-        "stdlib"
-        [ bench "bench04" $ nfAppIO eval bench04,
-          bench "bench06" $ nfAppIO eval bench06
+    defaultMain
+        [ bgroup
+            "simple"
+            [ bench "bench01" $ nfAppIO eval bench01
+            , bench "bench02" $ nfAppIO eval bench02
+            , bench "bench03" $ nfAppIO eval bench03
+            ]
+        , bgroup
+            "caching"
+            [ bench "bench08" $ nfAppIO eval bench08
+            ]
+        , bgroup
+            "stdlib"
+            [ bench "bench04" $ nfAppIO eval bench04
+            , bench "bench06" $ nfAppIO eval bench06
+            , bench "bench07" $ nfAppIO eval bench07
+            , bench "bench09" $ nfAppIO eval bench09
+            ]
         ]
-    ]
 
 bench01 :: Expr
 bench01 =
-  [jsonnet|
+    [jsonnet|
     local sum(x) =
       if x == 0 then
       0
@@ -54,7 +55,7 @@
 
 bench02 :: Expr
 bench02 =
-  [jsonnet|
+    [jsonnet|
     local Fib = {
       n: 1,
       local outer = self,
@@ -68,7 +69,7 @@
 
 bench03 :: Expr
 bench03 =
-  [jsonnet|
+    [jsonnet|
     local fibonacci(n) =
       if n <= 1 then
         1
@@ -79,13 +80,13 @@
 
 bench04 :: Expr
 bench04 =
-  [jsonnet|
+    [jsonnet|
     std.foldl(function(e, res) e + res, std.makeArray(20000, function(i) 'aaaaa'), '')
   |]
 
 bench06 :: Expr
 bench06 =
-  [jsonnet|
+    [jsonnet|
     // A benchmark for builtin sort
 
     local reverse = std.reverse;
@@ -99,9 +100,20 @@
     && std.assertEqual(std.makeArray(2000, function(i) std.floor((i + 2) / 2)), sort(std.range(1, 1000) + reverse(std.range(1, 1000))))
   |]
 
+bench07 :: Expr
+bench07 =
+    [jsonnet|
+    local f2(f) = function(x) f(f(x));
+    local id(x) = x;
+
+    local slowId = std.makeArray(20, function(i) if i == 0 then id else f2(slowId[i - 1]));
+
+    slowId[15](42)
+  |]
+
 bench08 :: Expr
 bench08 =
-  [jsonnet|
+    [jsonnet|
     local fib(n) =
       local go(n) =
         if n <= 1 then
@@ -114,4 +126,17 @@
       go(n)['fib'+n];
 
     fib(25)
+  |]
+
+bench09 :: Expr
+bench09 =
+    [jsonnet|
+    // This string must be longer than max stack frames
+    local veryLongString = std.join('', std.repeat(['e'], 510));
+    
+    std.assertEqual(std.stripChars(veryLongString + 'ok' + veryLongString, 'e'), 'ok') &&
+    std.assertEqual(std.lstripChars(veryLongString + 'ok', 'e'), 'ok') &&
+    std.assertEqual(std.rstripChars('ok' + veryLongString, 'e'), 'ok') &&
+    
+    true
   |]
diff --git a/jsonnet.cabal b/jsonnet.cabal
--- a/jsonnet.cabal
+++ b/jsonnet.cabal
@@ -1,39 +1,42 @@
-cabal-version:  3.0
-name:           jsonnet
-version:        0.4.0.0
-synopsis:       Jsonnet implementaton in pure Haskell
-description:    Please see the README on GitHub at <https://github.com/moleike/jsonnet-haskell#readme>
-homepage:       https://github.com/moleike/haskell-jsonnet#readme
-bug-reports:    https://github.com/moleike/haskell-jsonnet/issues
-author:         Alexandre Moreno
-maintainer:     alexmorenocano@gmail.com
-copyright:      2020 Alexandre Moreno
-category:       Compiler
-license:        BSD-3-Clause
-x-license:      BSD-3-Clause OR Apache-2.0
-license-file:   LICENSE
-build-type:     Simple
+cabal-version:      3.0
+name:               jsonnet
+version:            0.5.0.0
+synopsis:           Jsonnet implementation in pure Haskell
+description:
+  Please see the README on GitHub at <https://github.com/moleike/haskell-jsonnet#readme>
+
+homepage:           https://github.com/moleike/haskell-jsonnet#readme
+bug-reports:        https://github.com/moleike/haskell-jsonnet/issues
+author:             Alexandre Moreno
+maintainer:         alexmorenocano@gmail.com
+copyright:          2020 Alexandre Moreno
+category:           Compiler
+license:            BSD-3-Clause
+x-license:          BSD-3-Clause OR Apache-2.0
+license-file:       LICENSE
+build-type:         Simple
 extra-doc-files:
-    README.md
-    CHANGELOG.md
+  CHANGELOG.md
+  README.md
+
 extra-source-files:
-    stdlib/std.jsonnet
-    test/golden/*.jsonnet
-    test/golden/*.golden
-    test/golden/**/*.libsonnet
+  stdlib/std.jsonnet
+  test/golden/**/*.libsonnet
+  test/golden/*.golden
+  test/golden/*.jsonnet
 
 source-repository head
-  type: git
+  type:     git
   location: https://github.com/moleike/haskell-jsonnet
 
 common common-extensions
-  default-language: GHC2021
+  default-language:   GHC2021
   default-extensions:
-      LambdaCase
-      DerivingStrategies
-      DeriveAnyClass
-      DerivingVia
-      RecordWildCards
+    DeriveAnyClass
+    DerivingStrategies
+    DerivingVia
+    LambdaCase
+    RecordWildCards
 
 common common-warnings
   ghc-options:
@@ -43,124 +46,134 @@
 
 library
   import:
-      common-extensions
+    common-extensions
     , common-warnings
+
   exposed-modules:
-      Language.Jsonnet
-    , Language.Jsonnet.Error
-    , Language.Jsonnet.Pretty
-    , Language.Jsonnet.Parser
-    , Language.Jsonnet.Parser.SrcSpan
-    , Language.Jsonnet.Syntax
-    , Language.Jsonnet.Syntax.Annotated
-    , Language.Jsonnet.Annotate
-    , Language.Jsonnet.Common
-    , Language.Jsonnet.Value
-    , Language.Jsonnet.Std.Lib
-    , Language.Jsonnet.Std.TH
-    , Language.Jsonnet.TH
-    , Language.Jsonnet.TH.QQ
-    , Language.Jsonnet.Eval
-    , Language.Jsonnet.Eval.Monad
-    , Language.Jsonnet.Core
-    , Language.Jsonnet.Check
-    , Language.Jsonnet.Desugar
-  autogen-modules:
-      Paths_jsonnet
-  other-modules:
-      Paths_jsonnet
+    Language.Jsonnet
+    Language.Jsonnet.Annotate
+    Language.Jsonnet.Check
+    Language.Jsonnet.Common
+    Language.Jsonnet.Compiler
+    Language.Jsonnet.Core
+    Language.Jsonnet.Desugar
+    Language.Jsonnet.Error
+    Language.Jsonnet.Eval
+    Language.Jsonnet.Eval.Monad
+    Language.Jsonnet.Eval.Types
+    Language.Jsonnet.Parser
+    Language.Jsonnet.Parser.SrcSpan
+    Language.Jsonnet.Pretty
+    Language.Jsonnet.Std
+    Language.Jsonnet.Std.Lib
+    Language.Jsonnet.Std.TH
+    Language.Jsonnet.Syntax
+    Language.Jsonnet.Syntax.Annotated
+    Language.Jsonnet.TH
+    Language.Jsonnet.TH.QQ
+    Language.Jsonnet.Value
+    Language.Jsonnet.Object
 
-  hs-source-dirs:
-      src
+  autogen-modules: Paths_jsonnet
+  other-modules:   Paths_jsonnet
+  hs-source-dirs:  src
   build-depends:
-      aeson                         >= 2.2 && < 2.3,
-      base                          >= 4.20 && < 4.22,
-      bytestring                    >= 0.11 && < 0.13,
-      containers                    >= 0.6.2 && < 0.8,
-      scientific                    >= 0.3.7 && < 0.4,
-      text                          >= 2.0 && < 2.2,
-      template-haskell              >= 2.16.0 && < 2.23,
-      data-fix                      >= 0.3.1 && < 0.4,
-      transformers-compat           >= 0.6.6 && < 0.8,
-      unordered-containers          >= 0.2.14 && < 0.3,
-      mtl                           >= 2.2.2 && < 2.4,
-      vector                        >= 0.12.3 && < 0.14,
-      prettyprinter                 >= 1.7.0 && < 1.8,
-      directory                     >= 1.3.6 && < 1.4,
-      filepath                      >= 1.4.2 && < 1.6,
-      exceptions                    >= 0.10.4 && < 0.11,
-      lens                          >= 5.0.1 && < 5.4,
-      megaparsec                    >= 9.5 && < 9.8,
-      parser-combinators            >= 1.2.1 && < 1.4,
-      unbound-generics              >= 0.4.3 && < 0.5,
-      th-utilities                  >= 0.2.4.2 && < 0.3,
-      binary                        >= 0.8.8 && < 0.9,
-      th-lift-instances             >= 0.1.18 && < 0.2
+    aeson >=2.2 && <2.3 || ^>=2.3.1,
+    base >=4.20 && <4.22 || ^>=4.22.0,
+    base16-bytestring >=1.0.2 && <1.1,
+    bifunctors >=5.6.1 && <5.7,
+    binary >=0.8.8 && <0.9,
+    bytestring >=0.11 && <0.13,
+    containers >=0.6.2 && <0.8 || ^>=0.8,
+    cryptohash-md5 >=0.11.101 && <0.12,
+    data-fix >=0.3.1 && <0.4,
+    directory >=1.3.6 && <1.4,
+    exceptions >=0.10.4 && <0.11,
+    filepath >=1.4.2 && <1.6,
+    ghc-compact >=0.1 && <0.2,
+    lens >=5.0.1 && <5.4,
+    megaparsec >=9.5 && <9.8 || ^>=9.8.1,
+    mtl >=2.2.2 && <2.4,
+    parser-combinators >=1.2.1 && <1.4,
+    prettyprinter >=1.7.2 && <1.8,
+    primitive >=0.9 && <0.10,
+    scientific >=0.3.7 && <0.4,
+    template-haskell >=2.16.0 && <2.23 || ^>=2.23.0 || ^>=2.24.0,
+    text >=2.1.2 && <2.2,
+    th-lift-instances >=0.1.18 && <0.2,
+    th-utilities >=0.2.4.2 && <0.3,
+    transformers-compat >=0.6.6 && <0.8 || ^>=0.8,
+    unordered-containers >=0.2.16 && <0.3,
+    vector >=0.12.3 && <0.14,
+    yaml >=0.11.11 && <0.12
 
 executable hs-jsonnet
   import:
-      common-extensions
+    common-extensions
     , common-warnings
-  main-is: Main.hs
-  autogen-modules:
-      Paths_jsonnet
-  other-modules:
-      Paths_jsonnet
-  hs-source-dirs:
-      app
-  ghc-options: -threaded -rtsopts -with-rtsopts=-N
+
+  main-is:         Main.hs
+  autogen-modules: Paths_jsonnet
+  other-modules:   Paths_jsonnet
+  hs-source-dirs:  app
+  ghc-options:     -threaded -rtsopts -with-rtsopts=-N
   build-depends:
-      jsonnet,
-      aeson,
-      base,
-      bytestring,
-      text,
-      megaparsec,
-      optparse-applicative >= 0.16.1 && < 0.19
+    aeson,
+    base,
+    bytestring,
+    directory,
+    filepath,
+    jsonnet,
+    megaparsec,
+    optparse-applicative >=0.16.1 && <0.19 || ^>=0.19.0,
+    text
 
 test-suite jsonnet-test
   import:
-      common-extensions
+    common-extensions
     , common-warnings
-  type: exitcode-stdio-1.0
-  main-is: Main.hs
-  autogen-modules:
-      Paths_jsonnet
+
+  type:            exitcode-stdio-1.0
+  main-is:         Main.hs
+  autogen-modules: Paths_jsonnet
   other-modules:
-      Paths_jsonnet
-    , Language.Jsonnet.Test.Roundtrip
-    , Language.Jsonnet.Test.Golden
-  hs-source-dirs:
-      test
-    , test/golden
-  ghc-options: -threaded -rtsopts -with-rtsopts=-N
+    Language.Jsonnet.Test.Golden
+    Language.Jsonnet.Test.Roundtrip
+    Language.Jsonnet.Test.JPath
+    Paths_jsonnet
+
+  hs-source-dirs:  test test/golden
+  ghc-options:     -threaded -rtsopts -with-rtsopts=-N
   build-depends:
-      base
-    , containers
-    , prettyprinter
-    , jsonnet
-    , text
-    , filepath
-    , data-fix
-    , bytestring
-    , tasty
-    , tasty-golden
-    , hedgehog
-    , tasty-hedgehog
+    base,
+    bytestring,
+    containers,
+    data-fix,
+    filepath,
+    hedgehog,
+    jsonnet,
+    prettyprinter,
+    tasty,
+    tasty-golden,
+    tasty-hedgehog,
+    tasty-hunit,
+    directory,
+    temporary,
+    text
 
 benchmark jsonnet-bench
   import:
-      common-extensions
+    common-extensions
     , common-warnings
-  main-is: Bench.hs
-  type: exitcode-stdio-1.0
-  hs-source-dirs:
-      benchmarks
+
+  main-is:        Bench.hs
+  type:           exitcode-stdio-1.0
+  hs-source-dirs: benchmarks
   build-depends:
-      base
-    , tasty-bench
-    , jsonnet
-    , bytestring
-    , text
-    , prettyprinter
-  ghc-options: "-with-rtsopts=-A32m --nonmoving-gc"
+    base,
+    bytestring,
+    jsonnet,
+    prettyprinter,
+    tasty-bench,
+    text
+  ghc-options: -O2 -rtsopts
diff --git a/src/Language/Jsonnet.hs b/src/Language/Jsonnet.hs
--- a/src/Language/Jsonnet.hs
+++ b/src/Language/Jsonnet.hs
@@ -1,154 +1,148 @@
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE TemplateHaskell #-}
 
--- |
--- Module                  : Language.Jsonnet
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
-module Language.Jsonnet
-  ( JsonnetM,
+{- |
+Module                  : Language.Jsonnet
+Copyright               : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability               : experimental
+Portability             : non-portable
+-}
+module Language.Jsonnet (
+    JsonnetM,
     interpret,
     Config (..),
+    defaultConfig,
     Value (..),
     runJsonnetM,
-    parse,
+    compile,
     evaluate,
-    desugar,
     ExtVar (..),
     ExtVarType (..),
     ExtVarContent (..),
     interpretExtVar,
     constructExtVars,
-  )
+)
 where
 
-import Control.Monad ((>=>), (<=<))
+import Control.Monad (filterM, (<=<), (>=>))
+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow, handle, throwM, try)
 import Control.Monad.Fix (MonadFix)
-import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
-import Control.Monad.Except
 import Control.Monad.Reader
-import qualified Data.Aeson as JSON
-import Data.Binary (decode)
-import qualified Data.Map.Lazy as M
-import Data.Map.Strict (singleton)
+import Data.Aeson qualified as JSON
+import Data.ByteString qualified as BS
+import Data.Map.Lazy qualified as M
 import Data.Text (Text)
-import qualified Data.Text.IO as T
-import qualified Language.Jsonnet.Check as Check
-import Language.Jsonnet.Common
+import Data.Text.IO qualified as T
+import Language.Jsonnet.Compiler
 import Language.Jsonnet.Core
-import qualified Language.Jsonnet.Desugar as Desugar
 import Language.Jsonnet.Error
 import Language.Jsonnet.Eval
 import Language.Jsonnet.Eval.Monad
-import qualified Language.Jsonnet.Parser as Parser
+    ( EvalM,
+      Importer(Importer),
+      ImportResult(ImportResult),
+      Env(Env),
+      runEvalM,
+      asEvalError )
 import Language.Jsonnet.Pretty (prettyError)
-import qualified Language.Jsonnet.Std.Lib as Lib
-import Language.Jsonnet.Std.TH (mkStdlib)
-import Language.Jsonnet.Syntax.Annotated
+import Language.Jsonnet.Std
 import Language.Jsonnet.Value
+import System.Directory (doesFileExist)
 import System.Exit (die)
+import System.FilePath (takeDirectory, (</>))
+import System.FilePath.Posix (isAbsolute)
+import System.IO.Error (tryIOError)
 
 newtype JsonnetM a = JsonnetM
-  { unJsonnetM :: ReaderT Config (ExceptT Error IO) a
-  }
-  deriving newtype
-    ( Functor,
-      Applicative,
-      Monad,
-      MonadIO,
-      MonadFix,
-      MonadReader Config,
-      MonadError Error,
-      MonadThrow,
-      MonadCatch,
-      MonadMask,
-      MonadFail
-    )
+    { unJsonnetM :: ReaderT Config IO a
+    }
+    deriving newtype
+        ( Functor
+        , Applicative
+        , Monad
+        , MonadIO
+        , MonadFix
+        , MonadReader Config
+        , MonadThrow
+        , MonadCatch
+        , MonadMask
+        , MonadFail
+        )
 
 data Config = Config
-  { fname :: FilePath,
-    extVars :: ExtVars
-  }
-
-runJsonnetM :: Config -> JsonnetM a -> IO (Either Error a)
-runJsonnetM conf = runExceptT . (`runReaderT` conf) . unJsonnetM
+    { fname :: FilePath
+    , extVars :: ExtVars
+    , userFuncs :: UserFuncs
+    , jpaths :: [FilePath]
+    }
 
-interpret :: Config -> Text -> IO (Either Error JSON.Value)
-interpret conf =
-  runJsonnetM conf
-    . (parse >=> check >=> desugar >=> evaluate)
+defaultConfig :: Config
+defaultConfig =
+    Config
+        { fname = mempty
+        , extVars = mempty
+        , userFuncs = mempty
+        , jpaths = mempty
+        }
+  
+mkImporter :: Config -> Importer
+mkImporter = Importer . resolveImportPath . jpaths
 
-parse :: Text -> JsonnetM Expr
-parse inp =
-  asks fname >>= JsonnetM . lift . go
-  where
-    go fp = do
-      ast <- Parser.parse fp inp
-      Parser.resolveImports fp ast
+runEval :: EvalM a -> JsonnetM a
+runEval prog = do
+    env <- Env mempty Nothing Nothing <$> mkStdlib
+    run <- asks (runEvalM <$> fname <*> mkImporter)
+    liftIO $ run env prog
 
-check :: Expr -> JsonnetM Expr
-check expr = do
-  _ <-
-    JsonnetM $
-      lift $
-        Check.check expr
-  pure expr
+runJsonnetM :: Config -> JsonnetM a -> IO (Either Error a)
+runJsonnetM conf = try . (`runReaderT` conf) . unJsonnetM
 
-desugar :: Expr -> JsonnetM Core
-desugar = pure . Desugar.desugar
+interpret :: Config -> Text -> IO (Either Error JSON.Value)
+interpret conf = runJsonnetM conf . (compile >=> evaluate)
 
 -- | evaluate a Core expression with the implicit stdlib
 evaluate :: Core -> JsonnetM JSON.Value
-evaluate expr = do
-  env <- singleton "std" <$> std
-  JsonnetM $ lift $ ExceptT $ runEvalM env (rnf expr)
+evaluate = runEval . manifest
 
--- | the jsonnet stdlib is written in both jsonnet and Haskell, here we merge
---   the native (a small subset) with the interpreted (the splice mkStdlib)
-std :: JsonnetM Value
-std = do
-  extVars <- asks extVars
-  let stdlib = whnf core >>= flip mergeObjects (Lib.std extVars)
-  JsonnetM $ lift $ ExceptT $ runEvalM M.empty stdlib
-  where
-    core = decode $(mkStdlib)
-    mergeObjects x y = whnfPrim (BinOp Add) [Pos x, Pos y]
+compile :: Text -> JsonnetM Core
+compile inp = asks fname >>= flip compileThrow inp
 
+mkStdlib :: JsonnetM Value
+mkStdlib = asks (mkStdEnv <$> extVars <*> userFuncs) >>= runReaderT stdlib
+
+manifest :: Core -> EvalM JSON.Value
+manifest = handle asEvalError . rnf >=> proj
+{-# NOINLINE manifest #-}
+
 data ExtVar = ExtVar
-  { extVarType :: !ExtVarType,
-    extVarContent :: !ExtVarContent
-  }
+    { extVarType :: !ExtVarType
+    , extVarContent :: !ExtVarContent
+    }
 
 data ExtVarContent
-  = Inline !Text
-  | File !FilePath
+    = Inline !Text
+    | File !FilePath
 
 data ExtVarType
-  = ExtStr
-  | ExtCode
+    = ExtStr
+    | ExtCode
 
 interpretExtVar :: ExtVar -> IO Value
 interpretExtVar = \case
-  ExtVar ExtStr s -> VStr <$> readExtVarContent s
-  ExtVar ExtCode s -> either dieError pure <=< interpretToValue <=< readExtVarContent $ s
+    ExtVar ExtStr s -> VStr <$> readExtVarContent s
+    ExtVar ExtCode s -> either dieError pure <=< interpretToValue <=< readExtVarContent $ s
   where
     readExtVarContent :: ExtVarContent -> IO Text
     readExtVarContent = \case
-      Inline s -> pure s
-      File p -> T.readFile p
+        Inline s -> pure s
+        File p -> T.readFile p
 
     interpretToValue :: Text -> IO (Either Error Value)
     interpretToValue =
-      runJsonnetM (Config "External variable" mempty)
-        . (parse >=> check >=> desugar >=> evaluateToValue)
-
-    evaluateToValue :: Core -> JsonnetM Value
-    evaluateToValue expr = do
-      env <- singleton "std" <$> std
-      JsonnetM $ lift $ ExceptT $ runEvalM env (whnf expr)
+        runJsonnetM defaultConfig{fname = "External variable"}
+            . (compile >=> runEval . rnf)
 
     dieError :: Error -> IO a
     dieError = die . show . prettyError
@@ -158,3 +152,17 @@
   where
     interpretExtVarPair :: (Text, ExtVar) -> IO (Text, Value)
     interpretExtVarPair (s, extVar) = (s,) <$> interpretExtVar extVar
+
+resolveImportPath :: [FilePath] -> FilePath -> String -> IO ImportResult
+resolveImportPath jpaths baseFile importPath = do
+    matches <- filterM doesFileExist candidates
+    case matches of
+        (firstMatch : _) -> do
+            inp <- tryIOError $ BS.readFile firstMatch
+            either (throwM . UnresolvedImport importPath) (pure . ImportResult firstMatch) inp
+        [] -> throwM $ UnresolvedImport importPath (userError "Could not resolve import path")
+  where
+    candidates =
+        if isAbsolute importPath
+            then [importPath]
+            else (takeDirectory baseFile </> importPath) : map (</> importPath) jpaths
diff --git a/src/Language/Jsonnet/Annotate.hs b/src/Language/Jsonnet/Annotate.hs
--- a/src/Language/Jsonnet/Annotate.hs
+++ b/src/Language/Jsonnet/Annotate.hs
@@ -21,24 +21,30 @@
 type Ann f a = Fix (AnnF f a)
 
 {-# COMPLETE AnnF #-}
+
 pattern AnnF :: f a -> ann -> AnnF f ann a
 pattern AnnF f a = Pair (Const a) f
 
-annMap :: Functor f => (a -> b) -> Ann f a -> Ann f b
+{-# COMPLETE Ann #-}
+  
+pattern Ann :: f (Ann f ann) -> ann -> Ann f ann
+pattern Ann e ann = Fix (AnnF e ann)
+
+annMap :: (Functor f) => (a -> b) -> Ann f a -> Ann f b
 annMap g = go
   where
     go (Fix (AnnF f a)) = Fix $ AnnF (fmap go f) (g a)
 
-forget :: Functor f => Ann f a -> Ann f ()
+forget :: (Functor f) => Ann f a -> Ann f ()
 forget = annMap (const ())
 
-forget' :: Functor f => Ann f a -> Fix f
+forget' :: (Functor f) => Ann f a -> Fix f
 forget' (Fix (AnnF f _)) = Fix $ fmap forget' f
 
 attrib :: Ann f a -> a
 attrib (Fix (AnnF _ a)) = a
 
-inherit :: Functor f => (Fix f -> a -> (b, a)) -> a -> Fix f -> Ann f b
+inherit :: (Functor f) => (Fix f -> a -> (b, a)) -> a -> Fix f -> Ann f b
 inherit h = go
   where
     go p s@(Fix t) =
@@ -46,8 +52,8 @@
             h s p
        in Fix (AnnF (fmap (go a) t) b)
 
-annZip :: Functor f => Fix (AnnF (AnnF f a) b) -> Ann f (a, b)
+annZip :: (Functor f) => Fix (AnnF (AnnF f a) b) -> Ann f (a, b)
 annZip (Fix (AnnF (AnnF t x) y)) = Fix (AnnF (fmap annZip t) (x, y))
 
---instance (Show a, Show1 f) => Show1 (Const a :*: f) where
+-- instance (Show a, Show1 f) => Show1 (Const a :*: f) where
 --  liftShowsPrec = liftShowsPrecDefault
diff --git a/src/Language/Jsonnet/Check.hs b/src/Language/Jsonnet/Check.hs
--- a/src/Language/Jsonnet/Check.hs
+++ b/src/Language/Jsonnet/Check.hs
@@ -1,45 +1,56 @@
--- |
--- Module                  : Language.Jsonnet.Check
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
+{- |
+Module                  : Language.Jsonnet.Check
+Copyright               : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability               : experimental
+Portability             : non-portable
+-}
 module Language.Jsonnet.Check where
 
-import Control.Monad.Except
-import Data.Fix
+import Control.Monad.Except (MonadError, throwError)
+import Data.Fix ( foldFixM )
 import Data.List qualified as List
-import qualified Data.List.NonEmpty as NE
+import Data.List.NonEmpty qualified as NE
 import Language.Jsonnet.Annotate
 import Language.Jsonnet.Common hiding (span)
 import Language.Jsonnet.Error
 import Language.Jsonnet.Parser.SrcSpan
 import Language.Jsonnet.Syntax
-
-type Check = ExceptT Error IO
+import Data.Foldable (for_)
 
-check :: Ann ExprF SrcSpan -> Check ()
+check :: (MonadError Error m) => Ann ExprF SrcSpan -> m ()
 check = foldFixM alg
   where
-    alg (AnnF f a) = withExceptT (`CheckError` (Just a)) $ case f of
-      ELocal bnds _ -> checkLocal (NE.toList $ fst <$> bnds)
-      EFun ps _ -> checkFun (fst <$> ps)
-      EApply _ (Args as _) -> checkApply as
-      _ -> pure ()
+    alg (AnnF f a) = for_ (checkNode f) $ \err ->
+        throwError $ CheckError err (Just a)
+
+    checkNode = \case
+        ELocal bnds _ -> checkLocal (NE.toList $ fst <$> bnds)
+        EFun ps _ -> checkFun (fst <$> ps)
+        EApply _ (Args as _) -> checkApply as
+        EObj{..} -> checkLocal (fst <$> locals)
+        _ -> Nothing
+
+    checkLocal :: [Ident] -> Maybe CheckError
     checkLocal names = case dups names of
-      ((x:_) : _) -> throwError $ DuplicateBinding x
-      _ -> pure ()
+        ((x : _) : _) -> Just $ DuplicateBinding x
+        _ -> Nothing
+
+    checkFun :: [Ident] -> Maybe CheckError
     checkFun names = case dups names of
-      ((x:_) : _) -> throwError $ DuplicateParam x
-      _ -> pure ()
+        ((x : _) : _) -> Just $ DuplicateParam x
+        _ -> Nothing
+
+    checkApply :: [Arg a] -> Maybe CheckError
     checkApply args = case f args of
-      [] -> pure ()
-      _ -> throwError $ PosAfterNamedParam
+        [] -> Nothing
+        _ -> Just PosAfterNamedParam
       where
         f _ = filter isPos ns
         isPos = \case
-          Pos _ -> True
-          _ -> False
+            Pos _ -> True
+            _ -> False
         (_, ns) = span isPos args
+
     dups = filter ((> 1) . length) . List.group . List.sort
diff --git a/src/Language/Jsonnet/Common.hs b/src/Language/Jsonnet/Common.hs
--- a/src/Language/Jsonnet/Common.hs
+++ b/src/Language/Jsonnet/Common.hs
@@ -1,238 +1,225 @@
 {-# LANGUAGE DefaultSignatures #-}
 {-# LANGUAGE TemplateHaskell #-}
 
--- |
--- Module                  : Language.Jsonnet.Common
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
+{- |
+Module                  : Language.Jsonnet.Common
+Copyright               : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability               : experimental
+Portability             : non-portable
+-}
 module Language.Jsonnet.Common where
 
 import Data.Binary (Binary)
 import Data.Data (Data)
 import Data.Functor.Classes
 import Data.Functor.Classes.Generic
-import Data.Scientific (Scientific)
 import Data.Text (Text)
-import qualified Data.Text as T (pack)
 import Data.Typeable (Typeable)
 import GHC.Generics (Generic, Generic1)
 import Language.Jsonnet.Parser.SrcSpan (SrcSpan)
-import Unbound.Generics.LocallyNameless (Alpha (..), Name, name2String)
-import Unbound.Generics.LocallyNameless.TH (makeClosedAlpha)
 
-n2s :: Name a -> Text
-n2s = T.pack . name2String
+type Name = Text
 
 data Literal
-  = Null
-  | Bool Bool
-  | String Text
-  | Number Scientific
-  deriving
-    ( Show,
-      Eq,
-      Ord,
-      Generic,
-      Typeable,
-      Data,
-      Binary
-    )
-
-makeClosedAlpha ''Literal
+    = Null
+    | Bool Bool
+    | String Text
+    | Number Double
+    deriving
+        ( Show
+        , Eq
+        , Ord
+        , Generic
+        , Typeable
+        , Data
+        , Binary
+        )
 
 data Prim
-  = UnyOp UnyOp
-  | BinOp BinOp
-  | Cond
-  deriving
-    ( Show,
-      Eq,
-      Generic,
-      Typeable,
-      Data,
-      Alpha,
-      Binary
-    )
+    = UnyOp UnyOp
+    | BinOp BinOp
+    | Cond
+    deriving
+        ( Show
+        , Eq
+        , Generic
+        , Typeable
+        , Data
+        , Binary
+        )
 
 data BinOp
-  = Add
-  | Sub
-  | Mul
-  | Div
-  | Mod
-  | Lt
-  | Le
-  | Gt
-  | Ge
-  | Eq
-  | Ne
-  | And
-  | Or
-  | Xor
-  | ShiftL
-  | ShiftR
-  | LAnd
-  | LOr
-  | In
-  | Lookup
-  deriving
-    ( Show,
-      Eq,
-      Enum,
-      Bounded,
-      Generic,
-      Typeable,
-      Data,
-      Alpha,
-      Binary
-    )
+    = Add
+    | Sub
+    | Mul
+    | Div
+    | Mod
+    | Lt
+    | Le
+    | Gt
+    | Ge
+    | Eq
+    | Ne
+    | And
+    | Or
+    | Xor
+    | ShiftL
+    | ShiftR
+    | LAnd
+    | LOr
+    | In
+    | Lookup
+    deriving
+        ( Show
+        , Eq
+        , Enum
+        , Bounded
+        , Generic
+        , Typeable
+        , Data
+        , Binary
+        )
 
 data UnyOp
-  = Compl
-  | LNot
-  | Plus
-  | Minus
-  | Err
-  deriving
-    ( Eq,
-      Show,
-      Read,
-      Enum,
-      Bounded,
-      Generic,
-      Typeable,
-      Data,
-      Alpha,
-      Binary
-    )
+    = Compl
+    | LNot
+    | Plus
+    | Minus
+    | Err
+    | Super
+    deriving
+        ( Eq
+        , Show
+        , Read
+        , Enum
+        , Bounded
+        , Generic
+        , Typeable
+        , Data
+        , Binary
+        )
 
 data Strictness = Strict | Lazy
-  deriving
-    ( Eq,
-      Show,
-      Read,
-      Generic,
-      Typeable,
-      Data,
-      Alpha,
-      Binary
-    )
+    deriving
+        ( Eq
+        , Show
+        , Read
+        , Generic
+        , Typeable
+        , Data
+        , Binary
+        )
 
 data Arg a = Pos a | Named String a
-  deriving
-    ( Eq,
-      Read,
-      Show,
-      Typeable,
-      Data,
-      Generic,
-      Generic1,
-      Functor,
-      Foldable,
-      Traversable,
-      Alpha,
-      Binary
-    )
-  deriving
-    (Eq1, Show1)
-    via FunctorClassesDefault Arg
+    deriving
+        ( Eq
+        , Read
+        , Show
+        , Typeable
+        , Data
+        , Generic
+        , Generic1
+        , Functor
+        , Foldable
+        , Traversable
+        , Binary
+        )
+    deriving
+        (Eq1, Show1)
+        via FunctorClassesDefault Arg
 
 data Args a = Args
-  { args :: [Arg a],
-    strictness :: Strictness
-  }
-  deriving
-    ( Eq,
-      Read,
-      Show,
-      Typeable,
-      Data,
-      Generic,
-      Generic1,
-      Functor,
-      Foldable,
-      Traversable,
-      Alpha,
-      Binary
-    )
-  deriving
-    (Eq1, Show1)
-    via FunctorClassesDefault Args
+    { args :: [Arg a]
+    , strictness :: Strictness
+    }
+    deriving
+        ( Eq
+        , Read
+        , Show
+        , Typeable
+        , Data
+        , Generic
+        , Generic1
+        , Functor
+        , Foldable
+        , Traversable
+        , Binary
+        )
+    deriving
+        (Eq1, Show1)
+        via FunctorClassesDefault Args
 
 data Assert a = Assert
-  { cond :: a,
-    msg :: Maybe a,
-    expr :: a
-  }
-  deriving
-    ( Eq,
-      Read,
-      Show,
-      Typeable,
-      Data,
-      Generic,
-      Generic1,
-      Functor,
-      Foldable,
-      Traversable,
-      Alpha
-    )
-  deriving
-    (Eq1, Show1)
-    via FunctorClassesDefault Assert
+    { cond :: a
+    , msg :: Maybe a
+    }
+    deriving
+        ( Eq
+        , Read
+        , Show
+        , Typeable
+        , Data
+        , Generic
+        , Generic1
+        , Functor
+        , Foldable
+        , Traversable
+        )
+    deriving
+        (Eq1, Show1)
+        via FunctorClassesDefault Assert
 
 data CompSpec a = CompSpec
-  { -- |
-    var :: String,
-    -- |
-    forspec :: a,
-    -- |
-    ifspec :: Maybe a
-  }
-  deriving
-    ( Eq,
-      Read,
-      Show,
-      Typeable,
-      Data,
-      Generic,
-      Generic1,
-      Functor,
-      Foldable,
-      Traversable,
-      Alpha
-    )
-  deriving
-    (Eq1, Show1)
-    via FunctorClassesDefault CompSpec
+    { var :: String
+    , forspec :: a
+    , ifspec :: [a]
+    }
+    deriving
+        ( Eq
+        , Read
+        , Show
+        , Typeable
+        , Data
+        , Generic
+        , Generic1
+        , Functor
+        , Foldable
+        , Traversable
+        )
+    deriving
+        (Eq1, Show1)
+        via FunctorClassesDefault CompSpec
 
 data StackFrame a = StackFrame
-  { name :: Name a,
-    span :: SrcSpan
-  }
-  deriving (Eq, Show)
+    { name :: Name
+    , span :: SrcSpan
+    }
+    deriving (Eq, Show)
 
 newtype Backtrace a = Backtrace [StackFrame a]
-  deriving (Eq, Show)
+    deriving (Eq, Show)
 
 data Visibility = Visible | Hidden | Forced
-  deriving
-    ( Eq,
-      Read,
-      Show,
-      Enum,
-      Bounded,
-      Generic,
-      Typeable,
-      Data,
-      Alpha,
-      Binary
-    )
+    deriving
+        ( Eq
+        , Read
+        , Show
+        , Enum
+        , Bounded
+        , Generic
+        , Typeable
+        , Data
+        , Binary
+        )
 
-class HasVisibility a where
-  visible :: a -> Bool
-  forced :: a -> Bool
-  hidden :: a -> Bool
+instance Semigroup Visibility where
+    a <> Visible = a
+    _ <> b       = b
+
+instance Monoid Visibility where
+    mempty = Visible
+
+data Import = Code | Str | Bin
+    deriving (Show, Eq, Ord, Generic, Typeable, Data, Binary)
diff --git a/src/Language/Jsonnet/Compiler.hs b/src/Language/Jsonnet/Compiler.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Jsonnet/Compiler.hs
@@ -0,0 +1,31 @@
+-- |
+-- Module                  : Language.Jsonnet.Compiler
+-- Copyright               : (c) 2020-2026 Alexandre Moreno
+-- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+-- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
+-- Stability               : experimental
+-- Portability             : non-portable
+module Language.Jsonnet.Compiler (
+    compileModule,
+    compileThrow
+) where
+
+import Control.Monad.Except (MonadError)
+import Data.Text (Text)
+
+import Language.Jsonnet.Check (check)
+import Language.Jsonnet.Core (Core, resolve)
+import Language.Jsonnet.Desugar ( desugar )
+import Language.Jsonnet.Error ( Error )
+import Language.Jsonnet.Parser (parse)
+import Control.Monad.Catch (MonadThrow, throwM)
+
+compileModule :: MonadError Error m => FilePath -> Text -> m Core
+compileModule path content = do
+    expr <- parse path content
+    check expr
+    let core = (resolve (desugar expr))
+    pure core
+
+compileThrow :: MonadThrow m => FilePath -> Text -> m Core
+compileThrow  fp = either throwM pure . compileModule fp
diff --git a/src/Language/Jsonnet/Core.hs b/src/Language/Jsonnet/Core.hs
--- a/src/Language/Jsonnet/Core.hs
+++ b/src/Language/Jsonnet/Core.hs
@@ -1,95 +1,186 @@
-{-# OPTIONS_GHC -Wno-orphans #-}
--- |
--- Module                  : Language.Jsonnet.Core
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
-module Language.Jsonnet.Core where
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE PatternSynonyms #-}
+{-# LANGUAGE StrictData #-}
+{-# LANGUAGE TemplateHaskell #-}
 
-import Data.Binary (Binary)
-import Data.String (IsString (..))
+{- |
+Module                  : Language.Jsonnet.Core
+Copyright               : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability               : experimental
+Portability             : non-portable
+-}
+module Language.Jsonnet.Core (
+    Desugared,
+    Core,
+    Var (..),
+    Param,
+    RegularField (..),
+    CField (..),
+    Comp (..),
+    pattern CLoc,
+    pattern CLit,
+    pattern CVar,
+    pattern CLam,
+    pattern CPrim,
+    pattern CApp,
+    pattern CLet,
+    pattern CObj,
+    pattern CArr,
+    pattern CComp,
+    pattern CImp,
+    mkField,
+    resolve,
+) where
+
+import Control.Applicative (asum)
+import Data.Bifunctor (Bifunctor (first, second))
+import Data.Bifunctor.TH (deriveBifunctor)
+import Data.Binary (Binary (..))
+import Data.Fix (Fix (Fix), foldFix)
+import Data.List (elemIndex)
+import Data.Maybe (fromMaybe)
 import Data.Typeable (Typeable)
 import GHC.Generics (Generic)
-import Language.Jsonnet.Common (Args, Literal, Prim, Visibility)
+import Language.Jsonnet.Common (Args (..), Import, Literal, Name, Prim, Visibility (..))
 import Language.Jsonnet.Parser.SrcSpan (SrcSpan)
-import Unbound.Generics.LocallyNameless
-  ( Alpha,
-    Bind,
-    Embed,
-    Name,
-    Rec,
-    string2Name,
-  )
 
-type Param a = (Name a, Embed a)
+type Param a = (Name, a)
 
-data CField = CField
-  { -- |
-    fieldKey :: Core,
-    -- |
-    fieldVal :: Core,
-    -- |
-    fieldVis :: Visibility
-  }
-  deriving
-    ( Show,
-      Generic,
-      Alpha,
-      Binary
-    )
+data Var
+    = Idx Int Int -- 2D de Bruijn
+    | Self
+    | Super
+    | Std
+    | Unbound Name
+    deriving stock (Show, Generic)
+    deriving anyclass (Binary)
 
-mkField :: Core -> Core -> Visibility -> CField
-mkField = CField
+data RegularField a = RegularField
+    { fieldKey :: a
+    , fieldVal :: a
+    , fieldVis :: Visibility
+    }
+    deriving stock
+        (Show, Generic, Functor, Foldable, Traversable)
+    deriving anyclass (Binary)
 
-instance Binary a => Binary (Name a)
+data CField a
+    = CRegularField (RegularField a)
+    | -- | The desugared assertion expression
+      CAssertField a
+    deriving stock
+        (Show, Generic, Functor, Foldable, Traversable)
+    deriving anyclass (Binary)
 
-instance Binary a => Binary (Rec a)
+mkField :: a -> a -> Visibility -> CField a
+mkField k v h = CRegularField (RegularField k v h)
 
-instance Binary a => Binary (Embed a)
+data Comp a
+    = ArrC Name (a, [a])
+    | ObjC Name (CField a, [a])
+    deriving stock
+        (Show, Typeable, Generic, Functor, Foldable, Traversable)
+    deriving anyclass (Binary)
 
-instance (Binary a, Binary b) => Binary (Bind a b)
+data CoreF v a
+    = CLocF SrcSpan a
+    | CLitF Literal
+    | CVarF Name v
+    | CLamF [Param a] a
+    | CPrimF Prim
+    | CAppF a (Args a)
+    | CLetF [(Name, a)] a
+    | CObjF [CField a]
+    | CArrF [a]
+    | CCompF (Comp a) a
+    | CImpF Import FilePath
+    deriving stock
+        (Show, Typeable, Generic, Functor, Foldable, Traversable)
+    deriving anyclass (Binary)
 
-data Comp
-  = ArrC (Bind (Name Core) (Core, Maybe Core))
-  | ObjC (Bind (Name Core) (CField, Maybe Core))
-  deriving
-    ( Show,
-      Typeable,
-      Generic,
-      Alpha,
-      Binary
-    )
+$(deriveBifunctor ''CoreF)
 
-type Lam = Bind (Rec [Param Core]) Core
+type Desugared = Fix (CoreF Name)
 
-type Let = Bind (Rec [(Name Core, Embed Core)]) Core
+type Core = Fix (CoreF Var)
 
-data Core where
-  CLoc :: SrcSpan -> Core -> Core
-  CLit :: Literal -> Core
-  CVar :: Name Core -> Core
-  CLam :: Lam -> Core
-  CPrim :: Prim -> Core
-  CApp :: Core -> Args Core -> Core
-  CLet :: Let -> Core
-  CObj :: [CField] -> Core
-  CArr :: [Core] -> Core
-  CComp :: Comp -> Core -> Core
-  deriving
-    ( Show,
-      Typeable,
-      Generic,
-      Alpha,
-      Binary
-    )
+instance Binary (Fix (CoreF Var)) where
+    put (Fix expr) = put expr
+    get = Fix <$> get
 
---data Params
+pattern CLoc :: SrcSpan -> Fix (CoreF v) -> Fix (CoreF v)
+pattern CLoc sp e = Fix (CLocF sp e)
+
+pattern CLit :: Literal -> Fix (CoreF v)
+pattern CLit l = Fix (CLitF l)
+
+pattern CVar :: Name -> v -> Fix (CoreF v)
+pattern CVar n v = Fix (CVarF n v)
+
+pattern CLam :: [Param (Fix (CoreF v))] -> Fix (CoreF v) -> Fix (CoreF v)
+pattern CLam ps e = Fix (CLamF ps e)
+
+pattern CPrim :: Prim -> Fix (CoreF v)
+pattern CPrim p = Fix (CPrimF p)
+
+pattern CApp :: Fix (CoreF v) -> Args (Fix (CoreF v)) -> Fix (CoreF v)
+pattern CApp a es = Fix (CAppF a es)
+
+pattern CLet :: [(Name, Fix (CoreF v))] -> Fix (CoreF v) -> Fix (CoreF v)
+pattern CLet bnds e = Fix (CLetF bnds e)
+
+pattern CObj :: [CField (Fix (CoreF v))] -> Fix (CoreF v)
+pattern CObj fs = Fix (CObjF fs)
+
+pattern CArr :: [Fix (CoreF v)] -> Fix (CoreF v)
+pattern CArr es = Fix (CArrF es)
+
+pattern CComp :: Comp (Fix (CoreF v)) -> Fix (CoreF v) -> Fix (CoreF v)
+pattern CComp comp e = Fix (CCompF comp e)
+
+pattern CImp :: Import -> FilePath -> Fix (CoreF v)
+pattern CImp i fp = Fix (CImpF i fp)
+
+-- data Params
 --  = EmptyPs
 --  | ConsPs (Rebind (Name Core, Embed (Maybe Core)) Params)
 --  deriving (Show, Typeable, Generic)
---instance Alpha Params
+-- instance Alpha Params
 
-instance IsString (Name Core) where
-  fromString = string2Name
+type Env = [[Name]]
+
+resolve :: Desugared -> Core
+resolve ast = foldFix alg ast []
+  where
+    alg :: CoreF Name (Env -> Core) -> (Env -> Core)
+    alg = \case
+        CVarF n v -> CVar n . (`resolveVar` v)
+        CLetF bnds e -> \env ->
+            let env' = map fst bnds : env
+             in CLet (second ($ env') <$> bnds) (e env')
+        CLamF ps e -> \env ->
+            let env' = map fst ps : env
+             in CLam (second ($ env') <$> ps) (e env')
+        CCompF comp xs -> \env ->
+            let n = case comp of
+                    ArrC name _ -> name
+                    ObjC name _ -> name
+                env' = [n] : env
+             in CComp (($ env') <$> comp) (xs env)
+        -- reminaing constructors do not bind variables
+        other -> \env -> Fix (first Unbound (fmap ($ env) other))
+
+resolveVar :: Env -> Name -> Var
+resolveVar env = \case
+    "self" -> Self
+    "super" -> Super
+    n ->
+        fromMaybe (unbound n) $
+            asum $
+                zipWith (\d row -> Idx d <$> elemIndex n row) [0 ..] env
+  where
+    unbound = \case
+        "std" -> Std -- std is the only allowed free variable
+        free -> Unbound free
diff --git a/src/Language/Jsonnet/Desugar.hs b/src/Language/Jsonnet/Desugar.hs
--- a/src/Language/Jsonnet/Desugar.hs
+++ b/src/Language/Jsonnet/Desugar.hs
@@ -1,22 +1,27 @@
+{-# LANGUAGE LambdaCase #-}
 {-# LANGUAGE OverloadedLists #-}
 {-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RecordWildCards #-}
+{-# LANGUAGE TypeApplications #-}
 
--- |
--- Module                  : Language.Jsonnet.Desugar
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
+{- |
+Module    : Language.Jsonnet.Desugar
+Copyright : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer: Alexandre Moreno <alexmorenocano@gmail.com>
+Stability : experimental
+Portability: non-portable
+-}
 module Language.Jsonnet.Desugar (desugar) where
 
-import qualified Data.Bifunctor
+import Control.Monad.State
+import Data.Bifunctor
 import Data.Fix as F
 import Data.List.NonEmpty (NonEmpty (..), toList)
-import qualified Data.List.NonEmpty as NE
+import Data.List.NonEmpty qualified as NE
 import Data.Maybe (fromMaybe)
 import Data.Text (Text)
-import qualified Data.Text as T (pack)
+import Data.Text qualified as T
 import Language.Jsonnet.Annotate
 import Language.Jsonnet.Common
 import Language.Jsonnet.Core
@@ -24,199 +29,233 @@
 import Language.Jsonnet.Parser.SrcSpan
 import Language.Jsonnet.Pretty (prettyEvalError)
 import Language.Jsonnet.Syntax
-import Unbound.Generics.LocallyNameless
 
+type DesugarM = State Int
+
+freshName :: DesugarM Text
+freshName = do
+    n <- get
+    put (n + 1)
+    pure $ "$" <> T.pack (show n)
+
+mkVar n = CVar n n
+
 class Desugarer a where
-  desugar :: a -> Core
+    desugarM :: a -> DesugarM Desugared
 
+desugar :: (Desugarer a) => a -> Desugared
+desugar a = evalState (desugarM a) 0
+
 instance Desugarer (Ann ExprF ()) where
-  desugar = foldFix go . zipWithOutermost
-    where
-      go (AnnF f (_, b)) = alg b f
+    desugarM = foldFixM go . zipWithOutermost
+      where
+        go (AnnF f (_, b)) = alg b f
 
 instance Desugarer (Ann ExprF SrcSpan) where
-  desugar = foldFix go . zipWithOutermost
-    where
-      go (AnnF f (a, b)) = CLoc a (alg b f)
+    desugarM = foldFixM go . zipWithOutermost
+      where
+        go (AnnF f (a, b))
+            | needsLoc f = CLoc a <$> alg b f
+            | otherwise = alg b f
 
+needsLoc :: ExprF a -> Bool
+needsLoc = \case
+    ENull      -> False
+    EBool _    -> False
+    EStr _     -> False
+    ENum _     -> False
+    EArr _     -> False
+    ELocal _ _ -> False
+    _          -> True
+
 -- | annotate nodes with a boolean denoting outermost objects
 zipWithOutermost :: Ann ExprF a -> Ann ExprF (a, Bool)
 zipWithOutermost = annZip . inherit go False
   where
-    go (Fix (AnnF EObj {} _)) False = (True, True)
-    go (Fix (AnnF EObj {} _)) True = (False, True)
+    go (Fix (AnnF EObj{} _)) False = (True, True)
+    go (Fix (AnnF EObj{} _)) True = (False, True)
+    go (Fix (AnnF EObjComp{} _)) False = (True, True)
+    go (Fix (AnnF EObjComp{} _)) True = (False, True)
     go _ x = (False, x)
 
-alg :: Bool -> ExprF Core -> Core
+alg :: Bool -> ExprF Desugared -> DesugarM Desugared
 alg outermost = \case
-  ENull -> CLit Null
-  EBool b -> CLit (Bool b)
-  EStr s -> CLit (String s)
-  ENum n -> CLit (Number n)
-  EIdent i -> CVar (s2n i)
-  EFun ps e -> desugarFun ps e
-  EApply e es -> CApp e es
-  ELocal bnds e -> desugarLet bnds e
-  EBinOp Mod e1 e2 ->
-    -- operator % is overloaded for both modulo and string formatting
-    stdFunc "mod" (Args [Pos e1, Pos e2] Lazy)
-  EBinOp op e1 e2 -> desugarBinOp op e1 e2
-  EUnyOp op e -> desugarUnyOp op e
-  EIfElse c t e -> desugarIfElse c t e
-  EIf c t -> desugarIfElse c t (CLit Null)
-  EArr e -> CArr e
-  EObj {..} -> desugarObj outermost locals fields
-  ELookup e1 i -> desugarLookup e1 (CLit (String (T.pack i)))
-  EIndex e1 e2 -> desugarLookup e1 e2
-  EErr e -> desugarErr e
-  EAssert e -> desugarAssert e
-  ESlice {..} -> desugarSlice expr start end step
-  EArrComp {expr, comp} -> desugarArrComp expr comp
-  EObjComp {field, comp, locals} -> desugarObjComp field comp locals
+    ENull -> pure $ CLit Null
+    EBool b -> pure $ CLit (Bool b)
+    EStr s -> pure $ CLit (String s)
+    ENum n -> pure $ CLit (Number n)
+    EIdent i -> pure $ mkVar (T.pack i)
+    EFun ps e -> pure $ desugarFun ps e
+    EApply e es -> pure $ CApp e es
+    ELocal bnds e -> pure $ desugarLet bnds e
+    EBinOp Mod e1 e2 ->
+        -- operator % is overloaded for both modulo and string formatting
+        pure $ stdFunc "mod" (Args [Pos e1, Pos e2] Strict)
+    EBinOp op e1 e2 -> pure $ desugarBinOp op e1 e2
+    EUnyOp op e -> pure $ desugarUnyOp op e
+    EIfElse c t e -> pure $ desugarIfElse c t e
+    EIf c t -> pure $ desugarIfElse c t (CLit Null)
+    EArr e -> pure $ CArr e
+    EObj{..} -> desugarObj outermost locals fields asserts
+    ELookup e1 i -> pure $ desugarLookup e1 (CLit (String (T.pack i)))
+    EIndex e1 e2 -> pure $ desugarLookup e1 e2
+    EErr e -> pure $ desugarErr e
+    EAssert a e -> pure $ desugarAssert a e
+    ESlice{..} -> pure $ desugarSlice expr start end step
+    EArrComp{expr, comp} -> pure $ desugarArrComp expr comp
+    EObjComp{field, comp, locals} -> desugarObjComp outermost field comp locals
+    EImport it fp -> pure $ CImp it fp
 
-desugarSlice :: Core -> Maybe Core -> Maybe Core -> Maybe Core -> Core
+desugarSlice :: Desugared -> Maybe Desugared -> Maybe Desugared -> Maybe Desugared -> Desugared
 desugarSlice expr start end step =
-  stdFunc
-    "slice"
-    ( Args
-        [ Pos expr,
-          Pos $ maybeNull start,
-          Pos $ maybeNull end,
-          Pos $ maybeNull step
-        ]
-        Lazy
-    )
+    stdFunc
+        "slice"
+        ( Args
+            [ Pos expr
+            , Pos $ maybeNull start
+            , Pos $ maybeNull end
+            , Pos $ maybeNull step
+            ]
+            Lazy
+        )
   where
     maybeNull = fromMaybe (CLit Null)
 
-desugarIfElse :: Core -> Core -> Core -> Core
+desugarIfElse :: Desugared -> Desugared -> Desugared -> Desugared
 desugarIfElse c t e = CApp (CPrim Cond) (Args [Pos c, Pos t, Pos e] Lazy)
 
-desugarLookup :: Core -> Core -> Core
-desugarLookup e1 e2 = CApp (CPrim (BinOp Lookup)) (Args [Pos e1, Pos e2] Lazy)
+desugarLookup :: Desugared -> Desugared -> Desugared
+desugarLookup e1 e2 = CApp (CPrim (BinOp Lookup)) (Args [Pos e1, Pos e2] Strict)
 
-desugarErr :: Core -> Core
+desugarErr :: Desugared -> Desugared
 desugarErr e = CApp (CPrim (UnyOp Err)) (Args [Pos e] Lazy)
 
-desugarBinOp :: BinOp -> Core -> Core -> Core
-desugarBinOp op e1 e2 = CApp (CPrim (BinOp op)) (Args [Pos e1, Pos e2] Lazy)
+desugarBinOp :: BinOp -> Desugared -> Desugared -> Desugared
+desugarBinOp op e1 e2 = CApp (CPrim (BinOp op)) (Args [Pos e1, Pos e2] Strict)
 
-desugarUnyOp :: UnyOp -> Core -> Core
-desugarUnyOp op e = CApp (CPrim (UnyOp op)) (Args [Pos e] Lazy)
+desugarUnyOp :: UnyOp -> Desugared -> Desugared
+desugarUnyOp op e = CApp (CPrim (UnyOp op)) (Args [Pos e] Strict)
 
-desugarObj :: Bool -> [(String, Core)] -> [EField Core] -> Core
-desugarObj outermost locals fields = obj
+desugarObj :: Bool -> [(String, Desugared)] -> [EField Desugared] -> [Assert Desugared] -> DesugarM Desugared
+desugarObj outermost locals fields asserts = do
+    (hoisted, fields') <- unzip <$> mapM hoistField fields
+    let cFields = map desugarField fields'
+        cAsserts = map (CAssertField . flip desugarAssert (CLit (Bool True))) asserts
+        obj = CObj (cFields <> cAsserts)
+    pure $ case concat hoisted of
+        [] -> obj
+        bs -> CLet bs obj
   where
-    obj = CObj (desugarField <$> fields')
-
     bnds =
-      if outermost
-        then ("$", CVar "self") : locals
-        else locals
+        if outermost
+            then ("$", mkVar "self") : locals
+            else locals
 
     f v@(CLit _) = v
     f v@(CLoc _ (CLit _)) = v
     f v = case bnds of
-      [] -> v
-      xs -> desugarLet (NE.fromList xs) v
+        [] -> v
+        xs -> desugarLet (NE.fromList xs) v
 
-    fields' =
-      (\(EField key val comp v o) -> EField key (f val) comp v o) <$> fields
+    hoistField (EField key val comp vis ovr)
+        | comp && ovr = do
+            kName <- freshName
+            let kVar = mkVar kName
+            pure ([(kName, key)], EField kVar (f val) False vis True)
+        | otherwise =
+            pure ([], EField key (f val) comp vis ovr)
 
-desugarAssert :: Assert Core -> Core
-desugarAssert (Assert c m e) =
-  desugarIfElse
-    c
-    e
-    ( desugarErr $
-        fromMaybe
-          (CLit $ String "Assertion failed")
-          m
-    )
+desugarAssert :: Assert Desugared -> Desugared -> Desugared
+desugarAssert (Assert c m) e =
+    desugarIfElse
+        c
+        e
+        ( desugarErr $
+            fromMaybe
+                (CLit $ String "Assertion failed")
+                m
+        )
 
-desugarArrComp :: Core -> NonEmpty (CompSpec Core) -> Core
+desugarArrComp :: Desugared -> NonEmpty (CompSpec Desugared) -> Desugared
 desugarArrComp expr = foldr f (CArr [expr])
   where
-    f CompSpec {..} e =
-      CComp (ArrC (bind (s2n var) (e, ifspec))) forspec
+    f CompSpec{..} e =
+        CComp (ArrC (T.pack var) (e, ifspec)) forspec
 
-desugarField :: EField Core -> CField
-desugarField EField {..} = mkField key value' visibility
+desugarField :: EField Desugared -> CField Desugared
+desugarField EField{..} = mkField key value' visibility
   where
     value' =
-      if override
-        then
-          desugarIfElse
-            (desugarBinOp In key super)
-            (desugarBinOp Add (desugarLookup super key) value)
-            value
-        else value
-    super = CVar $ s2n "super"
+        if override
+            then
+                desugarIfElse
+                    (desugarBinOp In key super)
+                    (desugarBinOp Add (desugarLookup super key) value)
+                    value
+            else value
+    super = mkVar "super"
 
-desugarObjComp :: EField Core -> NonEmpty (CompSpec Core) -> [(String, Core)] -> Core
-desugarObjComp EField {..} comp locals =
-  CComp (ObjC (bind (s2n "arr") (kv', Nothing))) arrComp
-  where
-    kv' =
-      desugarField
-        ( EField
-            { key = key',
-              value = value',
-              visibility,
-              override,
-              computed
-            }
-        )
-    bnds = NE.zip (fmap var comp) xs
-    key' = desugarLet bnds key
-    value' = case locals of
-      [] -> desugarLet bnds value
-      -- we need to nest the let bindings due to the impl.
-      xs' -> desugarLet bnds $ desugarLet (NE.fromList xs') value
-    xs = desugarLookup (CVar $ s2n "arr") . CLit . Number . fromIntegral @Integer <$> [0 ..]
-    arrComp = desugarArrComp arr comp
-    arr = CArr $ NE.toList $ CVar . s2n . var <$> comp
+-- | ONLY ObjComp requires state to generate a safe `$arr_N` name
+desugarObjComp :: Bool -> EField Desugared -> NonEmpty (CompSpec Desugared) -> [(String, Desugared)] -> DesugarM Desugared
+desugarObjComp outermost EField{..} comp locals = do
+    arrVar <- freshName
+    let locals' = if outermost then ("$", mkVar "self") : locals else locals
 
-stdFunc :: Text -> Args Core -> Core
+        kv' =
+            desugarField
+                ( EField
+                    { key = key'
+                    , value = value'
+                    , visibility
+                    , override
+                    , computed
+                    }
+                )
+        bnds = NE.zip (fmap var comp) xs
+        key' = desugarLet bnds key
+
+        value' = case locals' of
+            [] -> desugarLet bnds value
+            xs' -> desugarLet bnds $ desugarLet (NE.fromList xs') value
+
+        xs = desugarLookup (mkVar arrVar) . CLit . Number . fromIntegral @Integer <$> [0 ..]
+        arrComp = desugarArrComp arr comp
+        arr = CArr $ NE.toList $ mkVar . T.pack . var <$> comp
+
+    pure $ CComp (ObjC arrVar (kv', [])) arrComp
+
+stdFunc :: Text -> Args Desugared -> Desugared
 stdFunc f =
-  CApp
-    ( desugarLookup
-        (CVar "std")
-        (CLit $ String f)
-    )
+    CApp
+        ( desugarLookup
+            (mkVar "std")
+            (CLit $ String f)
+        )
 
-desugarFun :: [(String, Maybe Core)] -> Core -> Core
+desugarFun :: [(String, Maybe Desugared)] -> Desugared -> Desugared
 desugarFun ps e =
-  CLam $
-    bind
-      ( rec $
-          fmap
+    CLam
+        ( fmap
             ( \(n, a) ->
-                (s2n n, Embed (fromMaybe (errNotBound (T.pack n)) a))
+                (T.pack n, fromMaybe (errNotBound n) a)
             )
             ps
-      )
-      e
+        )
+        e
   where
     errNotBound n =
-      desugarErr $
-        CLit $
-          String
-            ( T.pack $
-                show $
-                  prettyEvalError $ ParamNotBound n
-            )
+        desugarErr $
+            CLit $
+                String
+                    ( T.show $
+                        prettyEvalError $
+                            ParamNotBound (T.pack n)
+                    )
 
-desugarLet :: NonEmpty (String, Core) -> Core -> Core
+desugarLet :: NonEmpty (String, Desugared) -> Desugared -> Desugared
 desugarLet bnds e =
-  CLet $
-    bind
-      ( rec $
-          toList
-            ( fmap
-                ( Data.Bifunctor.bimap s2n Embed
-                )
-                bnds
-            )
-      )
-      e
+    CLet
+        ( toList
+            (fmap (first T.pack) bnds)
+        )
+        e
diff --git a/src/Language/Jsonnet/Error.hs b/src/Language/Jsonnet/Error.hs
--- a/src/Language/Jsonnet/Error.hs
+++ b/src/Language/Jsonnet/Error.hs
@@ -8,7 +8,6 @@
 module Language.Jsonnet.Error where
 
 import Control.Exception
-import Data.Scientific (Scientific)
 import Data.Text (Text)
 import Data.Typeable (Typeable)
 import Data.Void (Void)
@@ -27,32 +26,38 @@
 
 data EvalError
   = TypeMismatch
+      -- | expected
       Text
-      -- ^ expected
+      -- | actual
       Text
-      -- ^ actual
   | InvalidKey Text
   | DuplicateKey Text
   | NoSuchKey Text
   | InvalidIndex Text
-  | IndexOutOfBounds Scientific
+  | IndexOutOfBounds Double
   | DivByZero
   | VarNotFound Text
+  | UnboundSelf
+  | UnboundSuper
+  | NoSuperClass
   | ExtVarNotFound Text
   | AssertionFailed Text
   | TooManyArgs Int
+  | TooFewArgs Int
   | ParamNotBound Text
+  | ParamAlreadyBound Text
   | BadParam Text
   | StdError Text
   | RuntimeError Text
   | ManifestError Text
+  | UnresolvedImport FilePath IOError
+  | InfiniteRecursion
   deriving (Eq, Show, Typeable)
 
 instance Exception EvalError
 
 data ParserError
   = ParseError (ParseErrorBundle Text Void)
-  | ImportError IOError (Maybe SrcSpan)
   deriving (Eq, Show)
 
 data CheckError
@@ -60,3 +65,6 @@
   | PosAfterNamedParam
   | DuplicateBinding String
   deriving (Eq, Show)
+
+
+instance Exception CheckError
diff --git a/src/Language/Jsonnet/Eval.hs b/src/Language/Jsonnet/Eval.hs
--- a/src/Language/Jsonnet/Eval.hs
+++ b/src/Language/Jsonnet/Eval.hs
@@ -1,584 +1,396 @@
+{-# LANGUAGE BangPatterns #-}
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE MultiWayIf #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE RecursiveDo #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeApplications #-}
 {-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE ViewPatterns #-}
+{-# OPTIONS_GHC -Wno-incomplete-patterns #-}
+{-# OPTIONS_GHC -Wno-missing-signatures #-}
+{-# OPTIONS_GHC -Wno-name-shadowing #-}
 {-# OPTIONS_GHC -Wno-orphans #-}
 
--- |
--- Module                  : Language.Jsonnet.Eval
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
-module Language.Jsonnet.Eval where
+{- |
+Module      : Language.Jsonnet.Eval
+Copyright   : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer  : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability   : experimental
+Portability : non-portable
+-}
+module Language.Jsonnet.Eval (
+    rnf,
+    whnf,
+) where
 
 import Control.Applicative
-import Control.Lens (locally, view)
-import Control.Monad ((>=>), join, forM, (<=<))
-import Control.Monad.IO.Class (liftIO)
-import qualified Data.Aeson as JSON
-import qualified Data.Aeson.KeyMap as KeyMap
-import Data.Aeson.Text (encodeToLazyText)
-import Data.Bifunctor (second)
-import qualified Data.Bits as Bits
+import Control.Lens (view, (&), (.~), (^.))
+import Control.Monad (foldM, forM, unless, when, (<$!>), (>=>))
+import Control.Monad.Reader
 import Data.Bits ((.&.), (.|.))
-import Data.ByteString (ByteString)
+import Data.Bits qualified as Bits
+import Data.ByteString qualified as BS
 import Data.Foldable
-import Data.HashMap.Lazy (HashMap)
-import qualified Data.HashMap.Lazy as H
+import Data.HashMap.Strict qualified as H
 import Data.IORef
 import Data.Int (Int64)
-import qualified Data.List as L (sort)
-import qualified Data.Map.Lazy as M
+import Data.Map qualified as M
 import Data.Maybe
-import Data.Scientific
+import Data.Primitive (indexSmallArray)
+import Data.Primitive.SmallArray (smallArrayFromList)
 import Data.Text (Text)
-import qualified Data.Text as T
-import Data.Text.Encoding (decodeUtf8, encodeUtf8)
-import Data.Text.Lazy (toStrict)
-import Data.Traversable (for)
-import Data.Vector (Vector, (!?))
-import qualified Data.Vector as V
-import Language.Jsonnet.Common
-import Language.Jsonnet.Core
+import Data.Text qualified as T
+import Data.Text.Encoding qualified as TE
+import Data.Vector ((!?))
+import Data.Vector qualified as V
+import Language.Jsonnet.Common hiding (Super)
+import Language.Jsonnet.Common qualified as Prim
+import Language.Jsonnet.Compiler
+import Language.Jsonnet.Core hiding (fieldVal, fieldVis, mkField)
 import Language.Jsonnet.Error
 import Language.Jsonnet.Eval.Monad
-import Language.Jsonnet.Pretty ()
-import Language.Jsonnet.Value
-import Unbound.Generics.LocallyNameless
+import Language.Jsonnet.Object (Field (..), Object)
+import Language.Jsonnet.Object qualified as Object
+import Language.Jsonnet.Std.Lib qualified as Lib
+import Language.Jsonnet.Value (Inj (..), Proj (..), Value (..))
+import Language.Jsonnet.Value qualified as Value
 import Prelude hiding (length)
-import qualified Prelude as P (length)
 
-rnf :: Core -> Eval JSON.Value
-rnf = whnf >=> manifest
-
-whnfV :: Value -> Eval Value
-whnfV (VIndir loc) = whnfIndir loc >>= whnfV
-whnfV (VThunk c e) = withEnv e (whnf c)
-whnfV v = pure v
+rnf :: Core -> EvalM Value
+rnf = whnf >=> Value.forceWHNF
 
-whnf :: Core -> Eval Value
-whnf (CVar n) = lookupVar n
-whnf (CLoc sp c) = locally currentPos (const $ Just sp) (whnf c)
+whnf :: Core -> EvalM Value
+whnf (CVar _ v) = lookupVar v
+whnf (CLoc sp c) = withCurrentPos sp (whnf c)
 whnf (CLit l) = pure (whnfLiteral l)
-whnf (CObj bnd) = whnfObj bnd
+whnf (CObj fields) = whnfObj fields
 whnf (CArr cs) = VArr . V.fromList <$> mapM mkValue cs
-whnf (CLet bnd) = whnfLetrec bnd
-whnf (CPrim p) = pure (VPrim p)
+whnf (CLet bnd body) = whnfLetrec bnd body
+whnf (CPrim p) = pure $ VFun 0 (whnfPrim p)
 whnf (CApp e es) = whnfApp e es
-whnf (CLam f) = VClos f <$> view ctx
+whnf (CLam ps e) = VFun (length ps) . whnfClos ps e <$> view env
 whnf (CComp comp e) = whnfComp comp e
+whnf (CImp it path) = whnfImport it path
 
-mkValue :: Core -> Eval Value
-mkValue c@(CLit _) = whnf c
-mkValue c@(CLam _) = whnf c
-mkValue c@(CPrim _) = whnf c
-mkValue c = mkThunk c >>= mkIndirV
+stripLoc :: Core -> Core
+stripLoc (CLoc _ c) = stripLoc c
+stripLoc c = c
 
-lookupVar :: Name Core -> Eval Value
-lookupVar n = do
-  rho <- view ctx
-  v <- liftMaybe (VarNotFound (n2s n)) (M.lookup n rho)
-  whnfV v
+mkValue :: Core -> EvalM Value
+mkValue c = case stripLoc c of
+    c'@(CLit _) -> whnf c'
+    c'@(CLam _ _) -> whnf c'
+    c'@(CPrim _) -> whnf c'
+    CVar _ v@(Idx _ _) -> lookupVar v
+    CVar _ Self -> asks (^. env . self) >>= maybe (mkThunk c) pure
+    _ -> mkThunk c
 
+mkThunk :: Core -> EvalM Value
+mkThunk c = do
+    rho <- view env
+    Value.mkIndirV (Value.mkThunk (withEnv rho (whnf c)))
+
+lookupVar :: Var -> EvalM Value
+lookupVar = \case
+    Self -> liftMaybe UnboundSelf =<< view (env . self)
+    Super -> do
+        e <- view env
+        liftMaybe UnboundSuper (e ^. self)
+            *> maybe Value.emptyObject Value.mkObj (e ^. super)
+    Std -> view (env . std)
+    Idx d off -> flip indexSmallArray off . (!! d) <$> view (env . vars)
+    Unbound v -> throwE (VarNotFound v)
+
 whnfLiteral :: Literal -> Value
 whnfLiteral = \case
-  Null -> VNull
-  Bool b -> VBool b
-  String s -> VStr s
-  Number n -> VNum n
+    Null -> VNull
+    Bool b -> VBool b
+    String s -> VStr s
+    Number n -> VNum n
 
-whnfArgs :: Args Core -> Eval [Arg Value]
+whnfArgs :: Args Core -> EvalM [Arg Value]
 whnfArgs = \case
-  as@(Args _ Strict) -> args <$> mapM whnf as
-  as@(Args _ Lazy) -> args <$> mapM mkValue as
+    as@(Args _ Strict) -> args <$> mapM whnf as
+    as@(Args _ Lazy) -> args <$> mapM mkValue as
 
-whnfApp :: Core -> Args Core -> Eval Value
+whnfApp :: Core -> Args Core -> EvalM Value
+whnfApp (CPrim Cond) (Args [Pos c, Pos t, Pos e] _) = do
+    b <- whnf c >>= proj
+    if b then whnf t else whnf e
+whnfApp (CPrim (BinOp LAnd)) (Args [Pos e1, Pos e2] _) = do
+    b <- whnf e1 >>= proj
+    if b then VBool <$> (whnf e2 >>= proj) else pure (VBool False)
+whnfApp (CPrim (BinOp LOr)) (Args [Pos e1, Pos e2] _) = do
+    b <- whnf e1 >>= proj
+    if b then pure (VBool True) else VBool <$> (whnf e2 >>= proj)
+whnfApp (CPrim (BinOp Add)) (Args [Pos e1, Pos e2] _)
+    | CObj fields <- stripLoc e2 = do
+        v1 <- whnf e1 >>= proj
+        case v1 of
+            VObj x _ -> do
+                y <- whnfFields fields
+                Value.mkObj (x <> y)
+            _ -> do
+                v2 <- whnfObj fields
+                whnfBinOp Add v1 v2
+  where
+    stripLoc (CLoc _ c) = stripLoc c
+    stripLoc c = c
+whnfApp (CPrim (BinOp op)) (Args [Pos e1, Pos e2] _) = do
+    v1 <- whnf e1 >>= proj
+    v2 <- whnf e2 >>= proj
+    whnfBinOp op v1 v2
+whnfApp (CPrim (UnyOp op)) (Args [Pos e1] _) =
+    whnf e1 >>= proj >>= whnfUnyOp op
 whnfApp e es = withStackFrame e $ do
-  vs <- whnfArgs es
-  whnf e >>= whnfV >>= \case
-    VClos f env -> whnfClos env f vs
-    VPrim op -> whnfPrim op vs
-    v@(VFun _) -> foldlM f v vs
-      where
-        f (VFun g) (Pos v') = g v'
-        f v' _ = throwTypeMismatch "function" v'
-    v -> throwTypeMismatch "function" v
+    vs <- whnfArgs es
+    whnf e >>= Value.forceWHNF >>= \case
+        VFun _ f -> f vs >>= Value.forceWHNF
+        v -> Value.throwTypeMismatch "function" v
 
-withStackFrame :: Core -> Eval a -> Eval a
-withStackFrame (CLoc sp (CVar n)) e =
-  pushStackFrame (n, Just sp) e
-withStackFrame (CLoc sp _) e =
-  pushStackFrame (s2n "anonymous", Just sp) e
-withStackFrame (CVar _) e = e
---pushStackFrame (n, Nothing) e
+withStackFrame :: Core -> EvalM a -> EvalM a
+withStackFrame (CLoc sp (CVar n _)) e =
+    pushStackFrame (n, Just sp) e
+withStackFrame (CLoc sp (CLam _ _)) e =
+    pushStackFrame ("anonymous", Just sp) e
 withStackFrame _ e = e
 
---pushStackFrame (s2n "anonymous", Nothing) e
-
-whnfClos :: Env -> Lam -> [Arg Value] -> Eval Value
-whnfClos rho f args = do
-  (bnds, e) <- unbind f
-  (rs, ps, ns) <- splitArgs args (second unembed <$> unrec bnds)
-  withEnv rho $
-    extendEnv (M.fromList ps) $
-      extendEnv (M.fromList ns) $
-        appDefaults rs e
+whnfClos :: [Param Core] -> Core -> Env -> [Arg Value] -> EvalM Value
+whnfClos params body rho args = withEnv rho $ mdo
+    let (posArgs, namedArgs) = foldr splitArg ([], []) args
+        splitArg (Pos v) (ps, ns) = (v : ps, ns)
+        splitArg (Named n v) (ps, ns) = (ps, (T.pack n, v) : ns)
 
--- all parameter names are bound in default values
-appDefaults :: [(Name Core, Core)] -> Core -> Eval Value
-appDefaults rs e = mdo
-  bnds <-
-    M.fromList
-      <$> mapM
-        ( \(n, e') -> do
-            th <- extendEnv bnds (mkValue e')
-            pure (n, th)
-        )
-        rs
-  extendEnv bnds (whnf e)
+    let namedMap = M.fromList namedArgs
 
--- returns a triple with unapplied binders, positional and named
-splitArgs :: [Arg c] -> [(Name a, b)] -> EvalM s ([(Name a, b)], [(Name a, c)], [(Name a, c)])
-splitArgs args bnds = do
-  named <- getNamed
-  pos <- getPos
-  unapp <- getUnapp named
-  pure (unapp, pos, named)
-  where
-    (bnds1, bnds2) = splitAt (length ps) bnds
-    (ps, ns) = split args
-    pNames = map fst bnds
+    when (length posArgs > length params) $
+        throwE $
+            TooManyArgs (length params)
 
-    getPos =
-      if length ps > length bnds
-        then throwE $ TooManyArgs (length bnds)
-        else pure $ zip (map fst bnds1) ps
+    unless (null namedArgs) $ do
+        let (posNames, remNames) = splitAt (length posArgs) (map fst params)
+        forM_ namedArgs $ \(k, _) ->
+            if k `elem` posNames
+                then throwE (ParamAlreadyBound k)
+                else when (k `notElem` remNames) (throwE $ BadParam k)
 
-    -- checks the provided named arguments exist
-    getNamed = traverse f ns
-      where
-        f (a, b) = case g a of
-          Nothing -> throwE $ BadParam (T.pack a)
-          Just n -> pure (n, b)
-        g a = find ((a ==) . name2String) pNames
+    let alignArgs [] [] = pure []
+        alignArgs (p : ps) ((_, _) : pms) = do
+            rest <- alignArgs ps pms
+            pure (p : rest)
+        alignArgs [] ((name, defExpr) : pms) = do
+            v <- case M.lookup name namedMap of
+                Just val -> pure val
+                Nothing -> extendVars rib (mkValue defExpr)
+            rest <- alignArgs [] pms
+            pure (v : rest)
 
-    getUnapp named =
-      pure $ filter ((`notElem` ns') . fst) bnds2
-      where
-        ns' = map fst named
+    vals <- alignArgs posArgs params
 
-    split [] = ([], [])
-    split (Pos p : xs) =
-      let (ys, zs) = split xs in (p : ys, zs)
-    split (Named n v : xs) =
-      let (ys, zs) = split xs in (ys, (n, v) : zs)
+    let rib = smallArrayFromList vals
+    extendVars rib (whnf body)
 
-whnfPrim :: Prim -> [Arg Value] -> Eval Value
-whnfPrim (UnyOp op) [Pos e] = whnfV e >>= whnfUnyOp op
+whnfPrim :: Prim -> [Arg Value] -> EvalM Value
+whnfPrim (UnyOp op) [Pos e] = proj e >>= whnfUnyOp op
 whnfPrim (BinOp LAnd) [Pos e1, Pos e2] = whnfLogical id e1 e2
 whnfPrim (BinOp LOr) [Pos e1, Pos e2] = whnfLogical not e1 e2
 whnfPrim (BinOp op) [Pos e1, Pos e2] =
-  liftA2 (,) (whnfV e1) (whnfV e2) >>= uncurry (whnfBinOp op)
+    liftA2 (,) (proj e1) (proj e2) >>= uncurry (whnfBinOp op)
 whnfPrim Cond [Pos c, Pos t, Pos e] = whnfCond c t e
 
-whnfBinOp :: BinOp -> Value -> Value -> Eval Value
-whnfBinOp Lookup e1 e2 = whnfLookup e1 e2
-whnfBinOp Add x@(VStr _) y = inj <$> append x y
-whnfBinOp Add x y@(VStr _) = inj <$> append x y
-whnfBinOp Add x@(VArr _) y@(VArr _) = liftF2 ((V.++) @Value) x y
-whnfBinOp Add (VObj x) (VObj y) = x `mergeWith` y
-whnfBinOp Add n1 n2 = liftF2 ((+) @Double) n1 n2
-whnfBinOp Sub n1 n2 = liftF2 ((-) @Double) n1 n2
-whnfBinOp Mul n1 n2 = liftF2 ((*) @Double) n1 n2
-whnfBinOp Div (VNum _) (VNum 0) = throwE DivByZero
-whnfBinOp Div n1 n2 = liftF2 ((/) @Double) n1 n2
-whnfBinOp Mod (VNum _) (VNum 0) = throwE DivByZero
-whnfBinOp Mod n1 n2 = liftF2 (mod @Int64) n1 n2
-whnfBinOp Eq e1 e2 = inj <$> equals e1 e2
-whnfBinOp Ne e1 e2 = inj . not <$> equals e1 e2
-whnfBinOp Lt e1 e2 = liftF2 ((<) @Double) e1 e2
-whnfBinOp Gt e1 e2 = liftF2 ((>) @Double) e1 e2
-whnfBinOp Le e1 e2 = liftF2 ((<=) @Double) e1 e2
-whnfBinOp Ge e1 e2 = liftF2 ((>=) @Double) e1 e2
-whnfBinOp And e1 e2 = liftF2 ((.&.) @Int64) e1 e2
-whnfBinOp Or e1 e2 = liftF2 ((.|.) @Int64) e1 e2
-whnfBinOp Xor e1 e2 = liftF2 (Bits.xor @Int64) e1 e2
-whnfBinOp ShiftL e1 e2 = liftF2 (Bits.shiftL @Int64) e1 e2
-whnfBinOp ShiftR e1 e2 = liftF2 (Bits.shiftR @Int64) e1 e2
-whnfBinOp In s o = liftF2 (\o' s' -> objectHasEx o' s' True) o s
+whnfBinOp :: BinOp -> Value -> Value -> EvalM Value
+whnfBinOp = \case
+    Lookup -> whnfLookup
+    Add -> whnfAdd
+    Sub -> Value.liftF2 @Double (-)
+    Mul -> Value.liftF2 @Double (*)
+    Div -> noZero $ Value.liftF2 @Double (/)
+    Mod -> noZero $ Value.liftF2 @Int64 mod
+    Eq -> by id Value.equals
+    Ne -> by not Value.equals
+    Lt -> by (== LT) Value.compare
+    Gt -> by (== GT) Value.compare
+    Le -> by (/= GT) Value.compare
+    Ge -> by (/= LT) Value.compare
+    And -> Value.liftF2 @Int64 (.&.)
+    Or -> Value.liftF2 @Int64 (.|.)
+    Xor -> Value.liftF2 @Int64 Bits.xor
+    ShiftL -> Value.liftF2 @Int64 Bits.shiftL
+    ShiftR -> Value.liftF2 @Int64 Bits.shiftR
+    LAnd -> Value.liftF2 (&&)
+    LOr -> Value.liftF2 (||)
+    In -> flip $ Value.liftF2 (\o s -> Lib.objectHasEx o s True)
+  where
+    noZero _ (VNum _) (VNum 0) = throwE DivByZero
+    noZero f v1 v2 = f v1 v2
 
-whnfLogical :: HasValue a => (a -> Bool) -> Value -> Value -> Eval Value
+    by p f v1 v2 = VBool . p <$> f v1 v2
+
+whnfAdd :: Value -> Value -> EvalM Value
+whnfAdd x@(VStr a) y@(VStr b) = mappendBy T.null (pure . VStr) x a y b
+whnfAdd x@(VStr _) y = append x y
+whnfAdd x y@(VStr _) = append x y
+whnfAdd x@(VArr a) y@(VArr b) = mappendBy V.null (pure . VArr) x a y b
+whnfAdd x@(VObj a _) y@(VObj b _) = mappendBy Object.null Value.mkObj x a y b
+whnfAdd (VArr _) y = Value.throwTypeMismatch "array" y
+whnfAdd (VObj _ _) y = Value.throwTypeMismatch "object" y
+whnfAdd x y = Value.liftF2 @Double (+) x y
+
+mappendBy ::
+    (Semigroup a) =>
+    (a -> Bool) ->
+    (a -> EvalM Value) ->
+    Value ->
+    a ->
+    Value ->
+    a ->
+    EvalM Value
+mappendBy isNull wrap vx x vy y
+    | isNull x = pure vy
+    | isNull y = pure vx
+    | otherwise = wrap $! (x <> y)
+{-# INLINE mappendBy #-}
+
+append :: Value -> Value -> EvalM Value
+append x y = VStr <$!> liftA2 (<>) (Value.toString x) (Value.toString y)
+{-# INLINE append #-}
+
+whnfLogical :: (Inj a, Proj a) => (a -> Bool) -> Value -> Value -> EvalM Value
 whnfLogical f e1 e2 = do
-  x <- whnfV e1 >>= proj'
-  if f x
-    then inj <$> (whnfV e2 >>= proj' @Bool)
-    else pure (inj x)
+    x <- proj e1
+    if f x
+        then inj <$> (proj @Bool) e2
+        else pure (inj x)
 
-append :: Value -> Value -> Eval Text
-append v1 v2 = T.append <$> toString v1 <*> toString v2
+whnfUnyOp :: UnyOp -> Value -> EvalM Value
+whnfUnyOp = \case
+    Compl -> Value.liftF @Int64 Bits.complement
+    LNot -> Value.liftF not
+    Minus -> Value.liftF @Double negate
+    Plus -> Value.liftF @Double id
+    Err -> Value.toString >=> throwE . RuntimeError
+    Prim.Super -> whnfSuper
 
-whnfUnyOp :: UnyOp -> Value -> Eval Value
-whnfUnyOp Compl x = inj <$> fmap (Bits.complement @Int64) (proj' x)
-whnfUnyOp LNot x = inj <$> fmap not (proj' x)
-whnfUnyOp Minus x = inj <$> fmap (negate @Double) (proj' x)
-whnfUnyOp Plus x = inj <$> fmap (id @Double) (proj' x)
-whnfUnyOp Err x = (toString >=> throwE . RuntimeError) x
+whnfSuper :: Value -> EvalM Value
+whnfSuper x = do
+    e <- view env
+    selfVal <- liftMaybe UnboundSuper (e ^. self)
+    sup <- liftMaybe NoSuperClass (e ^. super)
+    proj x >>= Value.superLookup selfVal sup
 
-toString :: Value -> Eval Text
-toString (VStr s) = pure s
-toString v = toStrict . encodeToLazyText <$> manifest v
+whnfImport :: Import -> FilePath -> EvalM Value
+whnfImport it fp = do
+    ImportResult{..} <- fetchImport fp
+    let key = ImpKey it foundAt
+    ref <- view loadedModules
+    mods <- liftIO $ readIORef ref
+    case M.lookup key mods of
+        Just val -> pure val
+        Nothing -> do
+            val <- case it of
+                Code -> do
+                    core <- compileThrow foundAt (TE.decodeUtf8 content)
+                    pure $ Value.mkThunk (withCurrentFile foundAt $ withBaseEnv $ whnf core)
+                Bin -> pure $ inj (BS.unpack content)
+                Str -> pure $ inj (TE.decodeUtf8 content)
+            ptr <- Value.mkIndirV val
+            liftIO $ writeIORef ref (M.insert key ptr mods)
+            return ptr
 
-whnfCond :: Value -> Value -> Value -> Eval Value
+whnfCond :: Value -> Value -> Value -> EvalM Value
 whnfCond c e1 e2 = do
-  c' <- proj' c
-  if c'
-    then whnfV e1
-    else whnfV e2
+    c' <- proj c
+    if c'
+        then proj e1
+        else proj e2
 
-whnfLookup :: Value -> Value -> Eval Value
-whnfLookup (VObj o) (VStr s) =
-  whnfV . fieldValWHNF =<< liftMaybe (NoSuchKey s) (H.lookup s o)
+whnfLookup :: Value -> Value -> EvalM Value
+whnfLookup v@(VObj _ _) (VStr s) = Value.objectLookup v s
 whnfLookup (VArr a) (VNum i)
-  | isInteger i =
-    whnfV =<< liftMaybe (IndexOutOfBounds i) ((a !?) =<< toBoundedInteger i)
+    | Just i' <- Value.doubleToIntegral i =
+        proj =<< liftMaybe (IndexOutOfBounds i) (a !? i')
+    | Value.isIntegral i = throwE (IndexOutOfBounds i)
 whnfLookup (VArr _) _ =
-  throwE (InvalidIndex "array index was not integer")
+    throwE (InvalidIndex "array index was not integer")
 whnfLookup (VStr s) (VNum i)
-  | isInteger i =
-    liftMaybe (IndexOutOfBounds i) (f =<< bounded)
-  where
-    f = pure . VStr . T.singleton . T.index s
-    bounded =
-      toBoundedInteger i >>= \i' ->
-        if T.length s - 1 < i' && i' < 0
-          then Nothing
-          else Just i'
+    | Just i' <- Value.doubleToIntegral i =
+        liftMaybe (IndexOutOfBounds i) $
+            if i' < 0 || i' >= T.length s
+                then Nothing
+                else Just (VStr (T.singleton (T.index s i')))
 whnfLookup (VStr _) _ =
-  throwE (InvalidIndex "string index was not integer")
-whnfLookup v _ = throwTypeMismatch "array/object/string" v
-
-whnfIndir :: Ref -> Eval Value
-whnfIndir ref = do
-  c <- liftIO $ readIORef ref
-  case c of
-    Cell v True ->
-      return v -- Already evaluated, just return it
-    Cell v False -> do
-      v' <- whnfV v -- Needs to be reduced
-      liftIO $ writeIORef ref (Cell v' True)
-      return v'
-
-whnfLetrec :: Let -> Eval Value
-whnfLetrec bnd = mdo
-  (r, e1) <- unbind bnd
-  bnds <-
-    M.fromList
-      <$> mapM
-        ( \(n, Embed e) -> do
-            v <- extendEnv bnds (mkValue e)
-            pure (n, v)
-        )
-        (unrec r)
-  extendEnv bnds (mkValue e1)
-
-whnfObj :: [CField] -> Eval Value
-whnfObj xs = mdo
-  obj <-
-    mkIndirV . VObj . H.fromList . catMaybes
-      =<< mapM
-        ( \field ->
-            let self = M.singleton (s2n "self") obj
-             in whnfField self field
-        )
-        xs
-  pure obj
-
-whnfField ::
-  -- | self object
-  Env ->
-  -- |
-  CField ->
-  -- |
-  Eval (Maybe (Text, VField))
-whnfField self (CField k v h) = do
-  let fieldVis = h
-  fieldKey <- whnf k -- keys are strictly evaluated
-  fieldValWHNF <- extendEnv self (mkValue v)
-  fieldVal <- extendEnv self (mkThunk v)
-  fmap (,VField {..}) <$> proj' fieldKey
+    throwE (InvalidIndex "string index was not integer")
+whnfLookup v _ = Value.throwTypeMismatch "array/object/string" v
 
-flattenArrays :: Vector (Vector Value) -> Vector Value
-flattenArrays = join
+whnfLetrec :: [(Name, Core)] -> Core -> EvalM Value
+whnfLetrec binds body = mdo
+    vars <- smallArrayFromList <$> mapM (\(_, e) -> extendVars vars (mkValue e)) binds
+    extendVars vars (whnf body)
 
-whnfComp ::
-  Comp ->
-  Core ->
-  Eval Value
-whnfComp (ArrC bnd) cs = do
-  xs <- comp
-  liftF flattenArrays $ VArr $ V.mapMaybe id xs
-  where
-    comp =
-      whnf cs >>= \case
-        VArr xs -> forM xs $ \x -> do
-          (n, (e, cond)) <- unbind bnd
-          extendEnv (M.fromList [(n, x)]) $ do
-            b <- f cond
-            if b
-              then Just <$> mkValue e
-              else pure Nothing
-        v -> throwTypeMismatch "" v
-      where
-        f Nothing = pure True
-        f (Just c) = proj' =<< whnf c
-whnfComp (ObjC bnd) cs = do
-  xs <- comp
-  pure $ VObj $ H.fromList $ catMaybes $ V.toList xs
-  where
-    comp =
-      whnf cs >>= \case
-        VArr xs -> forM xs $ \x -> do
-          (n, (CField k v h, cond)) <- unbind bnd
-          extendEnv (M.fromList [(n, x)]) $ do
-            b <- f cond
-            if b
-              then do
-                fieldKey <- whnf k
-                fieldValWHNF <- mkValue v
-                fieldVal <- mkThunk v
-                let fieldVis = h
-                fmap (,VField {..}) <$> proj' fieldKey
-              else pure Nothing
-        v -> throwTypeMismatch "array" v
-    f Nothing = pure True
-    f (Just c) = proj' =<< whnf c
+whnfFields :: [CField Core] -> EvalM Object
+whnfFields [] = pure mempty
+whnfFields [f] = maybe mempty (uncurry Object.mkSingletonObject) <$!> whnfField f
+whnfFields xs = Object.mkBaseObject . H.fromList . catMaybes <$> traverse whnfField xs
 
--- | Right-biased union of two objects, i.e. '{x : 1} + {x : 2} == {x : 2}'
---   with OO-like `self` and `super` support via value recursion (knot-tying)
-mergeWith :: Object -> Object -> Eval Value
-mergeWith xs ys = mdo
-  zs' <- mkIndirV $ VObj (H.unionWith f xs' ys')
-  xs' <- for xs (update self zs')
-  ys' <- do
-    xs'' <- mkIndirV (VObj xs')
-    ys'' <- for ys (update self zs')
-    for ys'' (update super xs'')
-  pure zs'
-  where
-    self = s2n "self"
-    super = s2n "super"
-    f a b
-      | hidden a && visible b = a
-      | otherwise = b
-    update name xs' f'@VField {..} = case fieldVal of
-      VThunk c env -> do
-        let env' = M.insert name xs' env
-        let fieldVal' = VThunk c env'
-        fieldValWHNF' <- mkIndirV fieldVal'
-        pure VField {fieldVal = fieldVal', fieldValWHNF = fieldValWHNF', ..}
-      _ -> pure f'
+whnfObj :: [CField Core] -> EvalM Value
+whnfObj = whnfFields >=> Value.mkObj
 
-visibleKeys :: Object -> HashMap Text Value
-visibleKeys = H.mapMaybe f
+whnfField :: CField Core -> EvalM (Maybe (Text, Field))
+whnfField = \case
+    CRegularField (RegularField k v vis) ->
+        evalKey k >>= traverse \key ->
+            (key,) . (\val -> Field val vis False) <$> mkFieldVal v
+    CAssertField assertion ->
+        Just . ("$$assert_runtime",) . (\val -> Field val Hidden True) <$> mkFieldVal assertion
   where
-    f v@VField {..}
-      | not (hidden v) = Just fieldValWHNF
-      | otherwise = Nothing
-
-liftMaybe :: EvalError -> Maybe a -> Eval a
-liftMaybe e =
-  \case
-    Nothing -> throwE e
-    Just a -> pure a
-
-manifest :: Value -> Eval JSON.Value
-manifest = \case
-  VNull -> pure JSON.Null
-  VBool b -> pure (JSON.Bool b)
-  VStr s -> pure (JSON.String s)
-  VNum n -> pure (JSON.Number n)
-  VObj vs -> JSON.Object . KeyMap.fromHashMapText <$> mapM manifest (visibleKeys vs)
-  VArr vs -> JSON.Array <$> mapM manifest vs
-  VClos {} -> throwE (ManifestError "function")
-  VFun _ -> throwE (ManifestError "function")
-  v@VThunk {} -> whnfV v >>= manifest
-  v@VIndir {} -> whnfV v >>= manifest
-  _ -> throwE (ManifestError "impossible")
-
-objectFieldsEx :: Object -> Bool -> [Text]
-objectFieldsEx o True = L.sort (H.keys o) -- all fields
-objectFieldsEx o False = L.sort $ H.keys $ H.filter (not . hidden) o -- only visible (incl. forced)
+    evalKey :: Core -> EvalM (Maybe Text)
+    evalKey c = case stripLoc c of
+        CLit (String key) -> pure (Just key)
+        _ -> whnf c >>= proj
 
-objectHasEx :: Object -> Text -> Bool -> Bool
-objectHasEx o f all' = f `elem` objectFieldsEx o all'
+    mkFieldVal :: Core -> EvalM Value
+    mkFieldVal expr = case stripLoc expr of
+        CLit lit -> pure (whnfLiteral lit)
+        CVar _ idx@(Idx _ _) -> lookupVar idx
+        _ -> do
+            baseEnv <- view env
+            let !lexEnv = baseEnv & self .~ Nothing & super .~ Nothing
+            pure $ Value.mkThunk $ withFieldEnv lexEnv (whnf expr)
 
-primitiveEquals :: Value -> Value -> Eval Bool
-primitiveEquals VNull VNull = pure True
-primitiveEquals (VBool a) (VBool b) = pure (a == b)
-primitiveEquals (VStr a) (VStr b) = pure (a == b)
-primitiveEquals (VNum a) (VNum b) = pure (a == b)
-primitiveEquals _ _ =
-  throwE
-    ( StdError "primitiveEquals operates on primitive types "
-    )
+whnfIfs :: [Core] -> EvalM Bool
+whnfIfs = foldM (\b c -> (b &&) <$> (whnf c >>= proj)) True
 
-equals :: Value -> Value -> Eval Bool
-equals e1 e2 = liftA2 (,) (whnfV e1) (whnfV e2) >>= uncurry go
+whnfComp :: Comp Core -> Core -> EvalM Value
+whnfComp (ArrC _ (e, conds)) cs =
+    whnf cs >>= Value.forceWHNF >>= \case
+        VArr xs -> do
+            chunks <- forM xs $ \x ->
+                pushVar x $ do
+                    b <- whnfIfs conds
+                    if b
+                        then
+                            whnf e >>= Value.forceWHNF >>= \case
+                                VArr ys -> pure ys
+                                v -> Value.throwTypeMismatch "array" v
+                        else pure V.empty
+            pure $ VArr (V.concat (V.toList chunks))
+        v -> Value.throwTypeMismatch "array" v
+whnfComp (ObjC _ (cField, conds)) cs =
+    whnf cs >>= Value.forceWHNF >>= \case
+        VArr arr -> do
+            fields <- V.foldM step H.empty arr
+            Value.mkObj (Object.mkBaseObject fields)
+        v -> Value.throwTypeMismatch "array" v
   where
-    go as@(VArr a) bs@(VArr b)
-      | P.length a == P.length b = do
-        as' <- proj' as
-        bs' <- proj' bs
-        allM (uncurry equals) (zip as' bs')
-      | P.length a /= P.length b = pure False
-    go (VObj a) (VObj b) = do
-      let fields = objectFieldsEx a False
-      if fields /= objectFieldsEx b False
-        then pure False
-        else allM objectFieldEquals fields
-      where
-        objectFieldEquals field =
-          let a' = fieldValWHNF (a H.! field)
-              b' = fieldValWHNF (b H.! field)
-           in equals a' b'
-    go a b = do
-      ta <- showTy a
-      tb <- showTy b
-      if ta == tb
-        then primitiveEquals a b
-        else pure False
-
-allM :: Monad m => (a -> m Bool) -> [a] -> m Bool
-allM p = foldrM (\a b -> (&& b) <$> p a) True
-
--- better names?
-liftF ::
-  (HasValue a, HasValue b) =>
-  (a -> b) ->
-  (Value -> Eval Value)
-liftF f v = inj . f <$> proj' v
-{-# INLINE liftF #-}
-
-liftF2 ::
-  (HasValue a, HasValue b, HasValue c) =>
-  (a -> b -> c) ->
-  Value ->
-  Value ->
-  Eval Value
-liftF2 f v1 v2 = inj <$> liftA2 f (proj' v1) (proj' v2)
-{-# INLINE liftF2 #-}
-
-proj' :: HasValue a => Value -> Eval a
-proj' = whnfV >=> proj
-{-# INLINE proj' #-}
-
-throwTypeMismatch :: Text -> Value -> Eval a
-throwTypeMismatch e = throwE . TypeMismatch e <=< showTy
-
-showTy :: Value -> Eval Text
-showTy = \case
-  VNull -> pure "null"
-  VNum _ -> pure "number"
-  VBool _ -> pure "boolean"
-  VStr _ -> pure "string"
-  VObj _ -> pure "object"
-  VArr _ -> pure "array"
-  VClos {} -> pure "function"
-  VFun _ -> pure "function"
-  VPrim _ -> pure "function"
-  VThunk {} -> pure "thunk"
-  VIndir {} -> pure "pointer"
-
---v@VThunk {} -> whnfV v >>= showTy
---v@VIndir {} -> whnfV v >>= showTy
-
-instance HasValue Bool where
-  proj (VBool n) = pure n
-  proj v = throwTypeMismatch "bool" v
-  inj = VBool
-  {-# INLINE inj #-}
-
-instance HasValue Text where
-  proj (VStr s) = pure s
-  proj v = throwTypeMismatch "string" v
-  inj = VStr
-  {-# INLINE inj #-}
-
-instance {-# OVERLAPPING #-} HasValue [Char] where
-  proj (VStr s) = pure $ T.unpack s
-  proj v = throwTypeMismatch "string" v
-  inj = VStr . T.pack
-  {-# INLINE inj #-}
-
-instance HasValue ByteString where
-  proj (VStr s) = pure (encodeUtf8 s)
-  proj v = throwTypeMismatch "string" v
-  inj = VStr . decodeUtf8
-  {-# INLINE inj #-}
-
-instance HasValue Scientific where
-  proj (VNum n) = pure n
-  proj v = throwTypeMismatch "number" v
-  inj = VNum
-  {-# INLINE inj #-}
-
-instance HasValue Double where
-  proj (VNum n) = pure (toRealFloat n)
-  proj v = throwTypeMismatch "number" v
-  inj = VNum . fromFloatDigits
-  {-# INLINE inj #-}
-
-instance {-# OVERLAPS #-} Integral a => HasValue a where
-  proj (VNum n) = pure (round n)
-  proj v = throwTypeMismatch "number" v
-  inj = VNum . fromIntegral
-  {-# INLINE inj #-}
-
-instance HasValue a => HasValue (Maybe a) where
-  proj VNull = pure Nothing
-  proj a = Just <$> proj' a
-  inj Nothing = VNull
-  inj (Just a) = inj a
-  {-# INLINE inj #-}
-
-instance {-# OVERLAPS #-} HasValue Object where
-  proj (VObj o) = pure o
-  proj v = throwTypeMismatch "object" v
-  inj = VObj
-  {-# INLINE inj #-}
-
-instance HasValue a => HasValue (Vector a) where
-  proj (VArr as) = mapM proj' as
-  proj v = throwTypeMismatch "array" v
-  inj as = VArr (inj <$> as)
-  {-# INLINE inj #-}
-
-instance {-# OVERLAPPABLE #-} HasValue a => HasValue [a] where
-  proj = fmap V.toList . proj'
-  inj = inj . V.fromList
-  {-# INLINE inj #-}
-
-instance {-# OVERLAPS #-} (HasValue a, HasValue b) => HasValue (a -> b) where
-  inj f = VFun $ fmap (inj . f) . proj'
-  {-# INLINE inj #-}
-  proj = throwTypeMismatch "impossible"
-
-instance {-# OVERLAPS #-} (HasValue a, HasValue b, HasValue c) => HasValue (a -> b -> c) where
-  inj f = inj $ \x -> inj (f x)
-  {-# INLINE inj #-}
-  proj = throwTypeMismatch "impossible"
-
-instance {-# OVERLAPS #-} (HasValue a, HasValue b) => HasValue (a -> Eval b) where
-  inj f = VFun $ proj' >=> fmap inj . f
-  {-# INLINE inj #-}
-  proj (VFun f) = pure $ \x -> f (inj x) >>= proj'
-  proj (VClos f e) = pure $ \x -> proj =<< whnfClos e f [Pos (inj x)]
-  proj v = throwTypeMismatch "function" v
-
-instance {-# OVERLAPS #-} (HasValue a, HasValue b, HasValue c) => HasValue (a -> b -> Eval c) where
-  inj f = inj $ \x -> inj (f x)
-  {-# INLINE inj #-}
-  proj (VFun f) = pure $ \x y -> f (inj x) >>= \(VFun g) -> g (inj y) >>= proj'
-  proj (VClos f env) = pure $ \x y -> proj' =<< whnfClos env f [Pos (inj x), Pos (inj y)]
-  proj v = throwTypeMismatch "function" v
+    step acc x = pushVar x $ do
+        b <- if null conds then pure True else whnfIfs conds
+        if b
+            then
+                whnfField cField >>= \case
+                    Nothing -> pure acc
+                    Just (k, f)
+                        | H.member k acc -> throwE (DuplicateKey k)
+                        | otherwise -> pure (H.insert k f acc)
+            else pure acc
diff --git a/src/Language/Jsonnet/Eval/Monad.hs b/src/Language/Jsonnet/Eval/Monad.hs
--- a/src/Language/Jsonnet/Eval/Monad.hs
+++ b/src/Language/Jsonnet/Eval/Monad.hs
@@ -1,109 +1,188 @@
-{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE OverloadedStrings #-}
 
--- |
--- Module                  : Language.Jsonnet.Eval.Monad
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
-module Language.Jsonnet.Eval.Monad where
+{- |
+Module                  : Language.Jsonnet.Eval.Monad
+Copyright               : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability               : experimental
+Portability             : non-portable
+-}
+module Language.Jsonnet.Eval.Monad (
+    -- * Monad
+    EvalM (..),
+    runEvalM,
 
-import Control.Lens (locally, makeLenses, view)
-import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
-import Control.Monad.Except
-import Control.Monad.Fix (MonadFix)
-import Control.Monad.IO.Class (MonadIO, liftIO)
-import Control.Monad.Reader (MonadReader, ReaderT (..))
-import Data.IORef
-import Data.Map.Lazy (Map)
-import qualified Data.Map.Lazy as M (union)
-import Language.Jsonnet.Common (Backtrace (..), StackFrame (..))
+    -- * Environment & state
+    Env (..),
+    vars,
+    self,
+    super,
+    std,
+    CallStack (..),
+    spans,
+    scopes,
+    EvalState (..),
+    env,
+    baseEnv,
+    callStack,
+    currentPos,
+    currentFile,
+    loadedModules,
+    importer,
+    emptyStack,
+
+    -- * Import plumbing
+    ImportResult (..),
+    Importer (..),
+    ImpKey (..),
+
+    -- * Error handling
+    throwE,
+    liftMaybe,
+    asEvalError,
+    (<?>),
+
+    -- * Environment manipulation
+    extendVars,
+    pushVar,
+    withBaseEnv,
+    withEnv,
+    withFieldEnv,
+    withObjectEnv,
+    withCurrentFile,
+
+    -- * Call-stack / position tracking
+    pushStackFrame,
+    withCurrentPos,
+    getBacktrace,
+    getLineNum,
+    getFileName,
+
+    -- * Import helper
+    fetchImport,
+) where
+
+import Control.Lens (Lens', view, (%~), (&), (.~), (^.))
+import Control.Monad.Catch (SomeException, fromException, throwM, try)
+import Control.Monad.Reader
+import Data.IORef (IORef, readIORef, writeIORef)
+import Data.Primitive (SmallArray, newSmallArray)
+import Data.Primitive.SmallArray (runSmallArray)
+import Data.Text qualified as T
+import Language.Jsonnet.Common (Backtrace (..), Name, StackFrame (..))
 import Language.Jsonnet.Core (Core)
-import Language.Jsonnet.Error (Error (EvalError), EvalError)
-import Language.Jsonnet.Parser.SrcSpan (SrcSpan)
-import Unbound.Generics.LocallyNameless
-import Unbound.Generics.LocallyNameless.Name
+import Language.Jsonnet.Error (Error (EvalError), EvalError (..))
+import Language.Jsonnet.Eval.Types
+import Language.Jsonnet.Parser.SrcSpan (SrcSpan, spanBegin)
+import Text.Megaparsec.Pos (sourceLine, unPos)
 
-type Ctx a = Map (Name Core) a
+throwE :: EvalError -> EvalM a
+throwE e = throwM . EvalError e =<< getBacktrace
+{-# INLINE throwE #-}
 
--- | Simulate a call-stack to report stack traces
-data CallStack = CallStack
-  { -- | source location of call-sites
-    _spans :: [Maybe SrcSpan],
-    -- | names of called functions
-    _scopes :: [Name Core]
-  }
+infixl 0 <?>
+(<?>) :: EvalM (Either e a) -> (e -> EvalError) -> EvalM a
+m <?> mkErr = m >>= either (throwE . mkErr) pure
+{-# INLINE (<?>) #-}
 
-makeLenses ''CallStack
+liftMaybe :: EvalError -> Maybe a -> EvalM a
+liftMaybe e = maybe (throwE e) pure
 
-emptyStack :: CallStack
-emptyStack = CallStack [] [s2n "top-level"]
+asEvalError :: SomeException -> EvalM a
+asEvalError ex = case fromException ex of
+    Just (e :: Error) -> throwM e
+    Nothing -> throwE (RuntimeError (T.pack (show ex)))
 
-data EvalState a = EvalState
-  { -- | binding local variables to their values
-    _ctx :: Ctx a,
-    -- | call-stack simulation
-    _callStack :: CallStack,
-    -- | source span of expression being evaluated
-    _currentPos :: Maybe SrcSpan,
-    -- | fresh names
-    _gen :: IORef Integer
-  }
+{- | Strictly update 'EvalState' so closures and object caches never retain
+unevaluated chains of caller environments. ('StrictData' cascades '!st''
+into '_env' automatically.)
+-}
+localState :: (EvalState -> EvalState) -> EvalM a -> EvalM a
+localState f act = do
+    !st' <- asks f
+    local (const st') act
+{-# INLINE localState #-}
 
-makeLenses ''EvalState
+localEnv :: (Env -> Env) -> EvalM a -> EvalM a
+localEnv f = localState (env %~ f)
+{-# INLINE localEnv #-}
 
-newtype EvalM a b = EvalM
-  { unEval :: ExceptT Error (ReaderT (EvalState a) IO) b
-  }
-  deriving newtype
-    ( Functor,
-      Applicative,
-      Monad,
-      MonadIO,
-      MonadReader (EvalState a),
-      MonadError Error,
-      MonadThrow,
-      MonadCatch,
-      MonadMask,
-      MonadFail,
-      MonadFix
-    )
+extendVars :: SmallArray Value -> EvalM a -> EvalM a
+extendVars arr = localEnv (vars %~ (arr :))
+{-# INLINE extendVars #-}
 
-instance Fresh (EvalM a) where
-  fresh (Fn s _) = EvalM $ do
-    ref <- view gen
-    n <- liftIO $ readIORef ref
-    liftIO $ modifyIORef' ref (+ 1)
-    return $ (Fn s n)
-  fresh nm@(Bn {}) = return nm
+pushVar :: Value -> EvalM a -> EvalM a
+pushVar v = extendVars (runSmallArray (newSmallArray 1 v))
+{-# INLINE pushVar #-}
 
-runEvalM :: Ctx a -> EvalM a b -> IO (Either Error b)
-runEvalM ctx' e = do
-  gen' <- newIORef 0
-  let st = EvalState ctx' emptyStack Nothing gen'
-  (`runReaderT` st) (runExceptT (unEval e))
+withBaseEnv :: EvalM a -> EvalM a
+withBaseEnv = localState (\st -> st & env .~ (st ^. baseEnv))
+{-# INLINE withBaseEnv #-}
 
-throwE :: EvalError -> EvalM a b
-throwE e = throwError . EvalError e =<< getBacktrace
+withEnv :: Env -> EvalM a -> EvalM a
+withEnv e = localEnv (const e)
+{-# INLINE withEnv #-}
 
-extendEnv :: Ctx a -> EvalM a b -> EvalM a b
-extendEnv = locally ctx . M.union
+withObjectEnv :: Value -> Maybe Object -> EvalM a -> EvalM a
+withObjectEnv selfVal sup =
+    localEnv $ (self .~ Just selfVal) . (super .~ sup)
+{-# INLINE withObjectEnv #-}
 
-withEnv :: Ctx a -> EvalM a b -> EvalM a b
-withEnv = locally ctx . const
+withFieldEnv :: Env -> EvalM a -> EvalM a
+withFieldEnv lexEnv =
+    localEnv $ \cur ->
+        lexEnv & self .~ (cur ^. self) & super .~ (cur ^. super)
+{-# INLINE withFieldEnv #-}
 
-pushStackFrame :: (Name Core, Maybe SrcSpan) -> EvalM a b -> EvalM a b
-pushStackFrame (name, span') =
-  locally (callStack . scopes) (name :)
-    . locally (callStack . spans) (span' :)
+withCurrentFile :: FilePath -> EvalM a -> EvalM a
+withCurrentFile fp = localState (currentFile .~ fp)
+{-# INLINE withCurrentFile #-}
 
-getBacktrace :: EvalM a (Backtrace Core)
+readRef :: Lens' EvalState (IORef a) -> EvalM a
+readRef l = view l >>= liftIO . readIORef
+{-# INLINE readRef #-}
+
+{- | Temporarily update a mutable ref for the duration of an action.
+Intentionally does not restore 'old' on exception so top-level 'asEvalError'
+preserves the crash site's source position and call stack.
+-}
+withRef :: Lens' EvalState (IORef a) -> (a -> a) -> EvalM b -> EvalM b
+withRef l f action = do
+    ref <- view l
+    old <- liftIO (readIORef ref)
+    liftIO $ writeIORef ref $! f old
+    res <- action
+    liftIO $ writeIORef ref old
+    pure res
+{-# INLINE withRef #-}
+
+pushStackFrame :: (Name, Maybe SrcSpan) -> EvalM a -> EvalM a
+pushStackFrame (name, sp) =
+    withRef callStack $ \(CallStack sps scs) ->
+        CallStack (sp : sps) (name : scs)
+
+withCurrentPos :: SrcSpan -> EvalM a -> EvalM a
+withCurrentPos sp = withRef currentPos (const (Just sp))
+
+getBacktrace :: EvalM (Backtrace Core)
 getBacktrace = do
-  sp <- (:) <$> view currentPos <*> view (callStack . spans)
-  sc <- view (callStack . scopes)
-  pure $
-    Backtrace $
-      case sequence sp of
-        Just sp' -> zipWith StackFrame sc sp'
-        Nothing -> []
+    mPos <- readRef currentPos
+    CallStack sps scs <- readRef callStack
+    pure $ Backtrace $ case sequence (mPos : sps) of
+        Just sps' -> zipWith StackFrame scs sps'
+        Nothing -> maybe [] (\pos -> [StackFrame "top-level" pos]) mPos
+
+getLineNum :: EvalM (Maybe Int)
+getLineNum = do
+    mPos <- readRef currentPos
+    pure (unPos . sourceLine . spanBegin <$> mPos)
+
+getFileName :: EvalM FilePath
+getFileName = view currentFile
+
+fetchImport :: String -> EvalM ImportResult
+fetchImport path = do
+    cf <- view currentFile
+    Importer resolve <- view importer
+    either throwE pure =<< liftIO (try (resolve cf path))
diff --git a/src/Language/Jsonnet/Eval/Types.hs b/src/Language/Jsonnet/Eval/Types.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Jsonnet/Eval/Types.hs
@@ -0,0 +1,205 @@
+{-# LANGUAGE ConstraintKinds #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE KindSignatures #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RoleAnnotations #-}
+{-# LANGUAGE StrictData #-}
+{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE UndecidableInstances #-}
+
+{- |
+Module      : Language.Jsonnet.Eval.Types
+Copyright   : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer  : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability   : experimental
+Portability : non-portable
+-}
+module Language.Jsonnet.Eval.Types where
+
+import Control.Lens (makeLenses, (&), (.~), (^.))
+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
+import Control.Monad.Fix (MonadFix)
+import Control.Monad.IO.Class (MonadIO, liftIO)
+import Control.Monad.Reader (MonadReader, ReaderT (..))
+import Data.ByteString (ByteString)
+import Data.HashMap.Strict (HashMap)
+import Data.HashMap.Strict qualified as H
+import Data.IORef (IORef, newIORef)
+import Data.Map (Map)
+import Data.Primitive.SmallArray (SmallArray)
+import Data.Text (Text)
+import Data.Vector (Vector)
+import GHC.Generics (Generic)
+import Language.Jsonnet.Common (Arg, Import, Name, Visibility (..))
+import Language.Jsonnet.Parser.SrcSpan (SrcSpan)
+
+data Env = Env
+    { _vars :: [SmallArray Value]
+    , _self :: Maybe Value
+    , _super :: Maybe Object
+    , _std :: Value
+    }
+
+-- | Simulated call-stack for error reporting.
+data CallStack = CallStack
+    { _spans :: [Maybe SrcSpan]
+    -- ^ source location of call-sites
+    , _scopes :: [Name]
+    -- ^ names of called functions
+    }
+
+data ImportResult = ImportResult
+    { foundAt :: FilePath
+    , content :: ByteString
+    }
+
+newtype Importer = Importer
+    {runImporter :: FilePath -> String -> IO ImportResult}
+
+data ImpKey = ImpKey !Import !FilePath
+    deriving (Eq, Ord)
+
+data EvalState = EvalState
+    { _env :: Env
+    -- ^ binding local variables to their values
+    , _baseEnv :: Env
+    -- ^ pristine context with only std
+    , _callStack :: IORef CallStack
+    -- ^ call-stack simulation
+    , _currentPos :: IORef (Maybe SrcSpan)
+    -- ^ source span of expression being evaluated
+    , _currentFile :: FilePath
+    -- ^ current file being evaluated
+    , _loadedModules :: IORef (Map ImpKey Value)
+    -- ^ memoisation of imports
+    , _importer :: Importer
+    -- ^ resolves import paths
+    }
+
+newtype EvalM a = EvalM
+    { unEval :: ReaderT EvalState IO a
+    }
+    deriving newtype
+        ( Functor
+        , Applicative
+        , Monad
+        , MonadIO
+        , MonadReader EvalState
+        , MonadThrow
+        , MonadCatch
+        , MonadMask
+        , MonadFail
+        , MonadFix
+        )
+
+-- | Per-object memoisation table: keyed by (inheritance-depth, field-name).
+newtype Cache = Cache (IORef (HashMap (Int, Text) (IORef Value)))
+
+data Value
+    = VNull
+    | VBool Bool
+    | VStr Text
+    | VNum Double
+    | VObj Object Cache
+    | VArr (Vector Value)
+    | VFun Int ([Arg Value] -> EvalM Value)
+    | VThunk (EvalM Value)
+    | VIndir (IORef Value)
+    | VBlackhole
+
+mkIndirV :: (MonadIO m) => Value -> m Value
+mkIndirV v@VThunk{} = VIndir <$> liftIO (newIORef v)
+mkIndirV v = pure v
+{-# INLINE mkIndirV #-}
+
+mkThunk :: EvalM Value -> Value
+mkThunk = VThunk
+{-# INLINE mkThunk #-}
+
+newCache :: (MonadIO m) => m Cache
+newCache = Cache <$> liftIO (newIORef H.empty)
+{-# INLINE newCache #-}
+
+mkObj :: (MonadIO m) => Object -> m Value
+mkObj o = VObj o <$> newCache
+{-# INLINE mkObj #-}
+
+emptyObject :: (MonadIO m, Monoid Object) => m Value
+emptyObject = mkObj mempty
+{-# INLINE emptyObject #-}
+
+data Object
+    = Empty
+    | Singleton Text Field
+    | Base (HashMap Text Field)
+    | Mixin Int Object Object
+
+data Field = Field
+    { _fieldVal :: Value
+    , _fieldVis :: Visibility
+    , _assertField :: Bool
+    }
+    deriving (Generic)
+
+makeLenses ''Field
+
+instance Semigroup Field where
+    l <> r = r & fieldVis .~ (l ^. fieldVis <> r ^. fieldVis)
+    {-# INLINE (<>) #-}
+
+-- | Number of prototype layers in an 'Object'.
+layers :: Object -> Int
+layers Empty = 0
+layers (Mixin n _ _) = n
+layers _ = 1
+{-# INLINE layers #-}
+
+null :: Object -> Bool
+null Empty = True
+null _ = False
+{-# INLINE null #-}
+
+instance Semigroup Object where
+    Empty <> r = r
+    l <> Empty = l
+    l <> r = Mixin (layers l + layers r) l r
+    {-# INLINE (<>) #-}
+
+instance Monoid Object where
+    mempty = Empty
+
+mkBaseObject :: HashMap Text Field -> Object
+mkBaseObject m = case H.size m of
+    0 -> Empty
+    1 | [(k, f)] <- H.toList m -> Singleton k f
+    _ -> Base m
+{-# INLINE mkBaseObject #-}
+
+mkSingletonObject :: Text -> Field -> Object
+mkSingletonObject = Singleton
+{-# INLINE mkSingletonObject #-}
+
+runEvalM :: FilePath -> Importer -> Env -> EvalM a -> IO a
+runEvalM fp importer' env' act = do
+    mods <- newIORef mempty
+    cs <- newIORef emptyStack
+    pos <- newIORef Nothing
+    let st =
+            EvalState
+                { _env = env'
+                , _baseEnv = env'
+                , _callStack = cs
+                , _currentPos = pos
+                , _currentFile = fp
+                , _loadedModules = mods
+                , _importer = importer'
+                }
+    runReaderT (unEval act) st
+
+emptyStack :: CallStack
+emptyStack = CallStack{_spans = [], _scopes = ["top-level"]}
+
+makeLenses ''Env
+makeLenses ''CallStack
+makeLenses ''EvalState
diff --git a/src/Language/Jsonnet/Object.hs b/src/Language/Jsonnet/Object.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Jsonnet/Object.hs
@@ -0,0 +1,91 @@
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE StrictData #-}
+{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE TupleSections #-}
+
+{- |
+Module      : Language.Jsonnet.Object
+Copyright   : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer  : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability   : experimental
+Portability : non-portable
+-}
+module Language.Jsonnet.Object (
+    -- * Re-exported from Eval.Types
+    Object (..),
+    Field (..),
+    fieldVal,
+    fieldVis,
+    layers,
+    null,
+    assertField,
+    mkBaseObject,
+    mkSingletonObject,
+
+    -- * Query functions
+    isVisible,
+    allKeys,
+    visibleKeys,
+    regularKeys,
+    assertionKeys,
+    lookupField,
+) where
+
+import Control.Lens (view)
+import Data.HashMap.Strict (HashMap)
+import Data.HashMap.Strict qualified as H
+import Data.List qualified as L
+import Data.Text (Text)
+import Language.Jsonnet.Common (Visibility (..))
+import Language.Jsonnet.Eval.Types (
+    Field (..),
+    Object (..),
+    assertField,
+    fieldVal,
+    fieldVis,
+    layers,
+    null,
+    mkBaseObject,
+    mkSingletonObject,
+ )
+import Prelude hiding (null)
+
+isVisible :: Field -> Bool
+isVisible f = view fieldVis f /= Hidden && not (view assertField f)
+
+filterKeys :: (Field -> Bool) -> Object -> [Text]
+filterKeys _ Empty = []
+filterKeys p (Singleton k f) = [k | p f]
+filterKeys p obj = L.sort [k | (k, f) <- H.toList (flattenFields obj), p f]
+
+allKeys, visibleKeys, regularKeys, assertionKeys :: Object -> [Text]
+allKeys = filterKeys (const True)
+visibleKeys = filterKeys isVisible
+regularKeys = filterKeys (not . view assertField)
+assertionKeys = filterKeys (view assertField)
+
+flattenFields :: Object -> HashMap Text Field
+flattenFields = \case
+    Empty -> H.empty
+    Singleton k f -> H.singleton k f
+    Base m -> m
+    Mixin _ l (Singleton k f) -> H.insertWith (flip (<>)) k f (flattenFields l)
+    Mixin _ l r -> H.unionWith (<>) (flattenFields l) (flattenFields r)
+
+{- | Look up a field, returning the field, its depth in the prototype chain,
+  and the super-object (if any) for @super@ references.
+-}
+lookupField :: Text -> Object -> Maybe (Field, Int, Maybe Object)
+lookupField k = go 0
+  where
+    go !_ Empty = Nothing
+    go !d (Singleton k' f)
+        | k == k' = Just (f, d, Nothing)
+        | otherwise = Nothing
+    go !d (Base m) = (,d,Nothing) <$> H.lookup k m
+    go !d (Mixin _ l r) =
+        case go (d + layers l) r of
+            Just (f, d', rSuper) ->
+                Just (f, d', Just (maybe l (l <>) rSuper))
+            Nothing -> go d l
diff --git a/src/Language/Jsonnet/Parser.hs b/src/Language/Jsonnet/Parser.hs
--- a/src/Language/Jsonnet/Parser.hs
+++ b/src/Language/Jsonnet/Parser.hs
@@ -1,37 +1,35 @@
 {-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ViewPatterns #-}
 
--- |
--- Module                  : Language.Jsonnet.Parser
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
---
--- Parser for Jsonnet source code.
-module Language.Jsonnet.Parser
-  ( parse,
-    resolveImports,
+{- |
+Module                  : Language.Jsonnet.Parser
+Copyright               : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability               : experimental
+Portability             : non-portable
+
+Parser for Jsonnet source code.
+-}
+module Language.Jsonnet.Parser (
+    parse,
     reservedKeywords,
-  )
+)
 where
 
 import Control.Applicative hiding (many, some)
 import Control.Arrow (left)
 import Control.Monad
 import Control.Monad.Combinators.Expr
-import qualified Control.Monad.Combinators.NonEmpty as NE
+import Control.Monad.Combinators.NonEmpty qualified as NE
 import Control.Monad.Except
-import Control.Monad.IO.Class (MonadIO, liftIO)
 import Data.Char
 import Data.Either
 import Data.Fix
 import Data.Functor
-import Data.Functor.Sum
 import Data.List.NonEmpty (NonEmpty)
 import Data.Text (Text)
-import qualified Data.Text as T
-import qualified Data.Text.IO as T
+import Data.Text qualified as T
 import Data.Void
 import Language.Jsonnet.Annotate
 import Language.Jsonnet.Common
@@ -39,76 +37,18 @@
 import Language.Jsonnet.Parser.SrcSpan
 import Language.Jsonnet.Syntax
 import Language.Jsonnet.Syntax.Annotated
-import System.Directory
-import System.FilePath.Posix (takeDirectory)
-import System.IO.Error (tryIOError)
 import Text.Megaparsec hiding (ParseError, parse)
 import Text.Megaparsec.Char
-import qualified Text.Megaparsec.Char.Lexer as L
-import Data.Word (Word8)
-import qualified Data.ByteString as BS
+import Text.Megaparsec.Char.Lexer qualified as L
+import Data.Scientific (toRealFloat)
 
 type Parser = Parsec Void Text
 
-parse ::
-  MonadError Error m =>
-  -- | File name (only for source location annotations)
-  FilePath ->
-  -- | Input for parser
-  Text ->
-  -- | AST with unresolved imports
-  m Expr'
+parse :: (MonadError Error m) => FilePath -> Text -> m Expr
 parse fp inp =
-  liftEither $
-    left (ParserError . ParseError) $
-      runParser (sc *> exprP <* eof) fp inp
-
-resolveImports :: forall m.
-  (MonadError Error m, MonadIO m) =>
-  -- | File path (modules are resolved relative to this path)
-  FilePath ->
-  -- | AST with unresolved imports
-  Expr' ->
-  -- | AST with imports resolved
-  m Expr
-resolveImports fp = foldFixM go
-  where
-    go (AnnF (InL e) a) = pure $ Fix $ AnnF e a
-    go (AnnF (InR (Const import')) a) =
-      case import' of
-        Import fp' -> do
-          resolveImports fp'
-            =<< parse fp'
-            =<< readImportFile fp' a
-        Importstr fp' -> do
-          content <- readImportFile fp' a
-          pure $ Fix $ AnnF (EStr content) a
-        Importbin fp' -> do
-          content <- readBinaryFile fp' a
-          pure $ mkBinaryLiteral content a
-
-    readImportFile :: FilePath -> SrcSpan -> m Text
-    readImportFile = readFileWith T.readFile
-
-    readBinaryFile :: FilePath -> SrcSpan -> m [Word8]
-    readBinaryFile = readFileWith (fmap BS.unpack . BS.readFile)
-
-    readFileWith :: (FilePath -> IO a) -> FilePath -> SrcSpan -> m a
-    readFileWith reader fp' a = do
-      inp <- (handleIO . reader) fp'
-      liftEither $ left (ParserError . flip ImportError (Just a)) inp
-      where
-        handleIO :: IO a -> m (Either IOError a)
-        handleIO =
-          liftIO
-          . tryIOError
-          . withCurrentDirectory (takeDirectory fp)
-
-    mkBinaryLiteral :: [Word8] -> SrcSpan -> Expr
-    mkBinaryLiteral ws a = Fix $ AnnF (EArr $ map wordExpr ws) a
-      where
-        wordExpr :: Word8 -> Expr
-        wordExpr w = Fix $ AnnF (ENum (fromIntegral w)) a
+    liftEither $
+        left (ParserError . ParseError) $
+            runParser (sc *> exprP <* eof) fp inp
 
 sc :: Parser ()
 sc = L.space space1 lineComment blockComment
@@ -139,24 +79,24 @@
 
 annotateLoc :: Parser (f a) -> Parser (AnnF f SrcSpan a)
 annotateLoc p = do
-  begin <- getSourcePos
-  res <- p
-  AnnF res . SrcSpan begin <$> getSourcePos
+    begin <- getSourcePos
+    res <- p
+    AnnF res . SrcSpan begin <$> getSourcePos
 
 identifier :: Parser String
 identifier = do
-  ident <- p
-  when (ident `elem` reservedKeywords) $
-    fail $
-      "Keyword " <> ident <> " cannot be an identifier."
-  pure ident
+    ident <- p
+    when (ident `elem` reservedKeywords) $
+        fail $
+            "Keyword " <> ident <> " cannot be an identifier."
+    pure ident
   where
     p =
-      lexeme
-        ( (:)
-            <$> (letterChar <|> char '_')
-            <*> many (alphaNumChar <|> char '_')
-        )
+        lexeme
+            ( (:)
+                <$> (letterChar <|> char '_')
+                <*> many (alphaNumChar <|> char '_')
+            )
 
 keywordP :: Text -> Parser Text
 keywordP keyword = lexeme (string keyword <* notFollowedBy alphaNumChar)
@@ -166,53 +106,54 @@
 stringLiteral = quoted (char '\"') <|> quoted (char '\'')
   where
     quoted c =
-      c
-        *> manyTill
-          ( try escapeUnicode <|> escapeAscii
-              <|> anySingle
-          )
-          c
+        c
+            *> manyTill
+                ( try escapeUnicode
+                    <|> escapeAscii
+                    <|> anySingle
+                )
+                c
 
 escapeAscii :: Parser Char
 escapeAscii = do
-  void (char '\\')
-  choice
-    [ char '\"' $> '\"',
-      char '\'' $> '\'', -- this one is jsonnet specific
-      char '\\' $> '\\',
-      char '/' $> '/',
-      char 'n' $> '\n',
-      char 'r' $> '\r',
-      char 'f' $> '\f',
-      char 't' $> '\t',
-      char 'b' $> '\b'
-    ]
+    void (char '\\')
+    choice
+        [ char '\"' $> '\"'
+        , char '\'' $> '\'' -- this one is jsonnet specific
+        , char '\\' $> '\\'
+        , char '/' $> '/'
+        , char 'n' $> '\n'
+        , char 'r' $> '\r'
+        , char 'f' $> '\f'
+        , char 't' $> '\t'
+        , char 'b' $> '\b'
+        ]
 
 escapeUnicode :: Parser Char
 escapeUnicode = do
-  _ <- string "\\u"
-  hex <- ("0x" ++) <$> count 4 hexDigitChar
-  pure (chr $ read hex)
+    _ <- string "\\u"
+    hex <- ("0x" ++) <$> count 4 hexDigitChar
+    pure (chr $ read hex)
 
 verbatimString :: Parser String
 verbatimString = char '@' *> (quoted (char '\'') <|> quoted (char '\"'))
   where
     quoted c =
-      c
-        *> manyTill
-          (c *> c <|> anySingle)
-          (try $ c <* notFollowedBy c)
+        c
+            *> manyTill
+                (c *> c <|> anySingle)
+                (try $ c <* notFollowedBy c)
 
 textBlock :: Parser String
 textBlock = do
-  _ <- symbol "|||" <* sc'
-  ref <- L.indentLevel
-  x <- line
-  xs <-
-    manyTill
-      (L.indentGuard (sc'' ref) EQ ref >> line)
-      (try $ sc' *> symbol "|||")
-  pure $ concat (x : xs)
+    _ <- symbol "|||" <* sc'
+    ref <- L.indentLevel
+    x <- line
+    xs <-
+        manyTill
+            (L.indentGuard (sc'' ref) EQ ref >> line)
+            (try $ sc' *> symbol "|||")
+    pure $ concat (x : xs)
   where
     line :: Parser String
     line = (++) <$> many (anySingleBut '\n') <*> some (char '\n')
@@ -221,287 +162,311 @@
     sc'' :: Pos -> Parser ()
     sc'' x = void $ count' 0 (unPos x - 1) (oneOf [' ', '\t'])
 
-identStringP :: Parser Expr'
+identStringP :: Parser Expr
 identStringP = Fix <$> annotateLoc (mkStrF <$> identifier)
 
-stringP :: Parser Expr'
+stringP :: Parser Expr
 stringP =
-  Fix
-    <$> annotateLoc
-      ( mkStrF
-          <$> ( verbatimString
-                  <|> stringLiteral
-                  <|> textBlock
-              )
-      )
-    <?> "string"
+    Fix
+        <$> annotateLoc
+            ( mkStrF
+                <$> ( verbatimString
+                        <|> stringLiteral
+                        <|> textBlock
+                    )
+            )
+        <?> "string"
 
-numberP :: Parser Expr'
+numberP :: Parser Expr
 numberP = Fix <$> annotateLoc number <?> "number"
   where
-    number = mkFloatF <$> lexeme L.scientific
+    number = mkFloatF . toRealFloat <$> lexeme L.scientific
 
-identP :: Parser Expr'
+identP :: Parser Expr
 identP =
-  Fix
-    <$> annotateLoc
-      (mkIdentF <$> (try (T.unpack <$> symbol "$") <|> identifier))
-    <?> "identifier"
+    Fix
+        <$> annotateLoc
+            (mkIdentF <$> (try (T.unpack <$> symbol "$") <|> identifier))
+        <?> "identifier"
 
-booleanP :: Parser Expr'
+booleanP :: Parser Expr
 booleanP = Fix <$> annotateLoc boolean <?> "bool"
   where
     boolean =
-      keywordP "true" $> mkBoolF True
-        <|> keywordP "false" $> mkBoolF False
+        keywordP "true" $> mkBoolF True
+            <|> keywordP "false" $> mkBoolF False
 
-nullP :: Parser Expr'
+nullP :: Parser Expr
 nullP = Fix <$> annotateLoc null'
   where
     null' = keywordP "null" $> mkNullF
 
-errorP :: Parser Expr'
+errorP :: Parser Expr
 errorP = Fix <$> annotateLoc error'
   where
     error' = keywordP "error" *> (mkErrorF <$> exprP)
 
-assertP :: Parser Expr'
+assertP :: Parser Expr
 assertP = Fix <$> annotateLoc assert
   where
     assert = do
-      cond <- keywordP "assert" *> exprP
-      msg <- optional (colon *> exprP)
-      _ <- symbol ";"
-      mkAssertF cond msg <$> exprP
+        assert' <- assertP'
+        _ <- symbol ";"
+        mkAssertF assert' <$> exprP
 
-ifElseP :: Parser Expr'
+assertP' :: Parser (Assert Expr)
+assertP' = do
+    cond <- keywordP "assert" *> exprP
+    msg <- optional (colon *> exprP)
+    pure $ Assert cond msg
+
+ifElseP :: Parser Expr
 ifElseP = Fix <$> annotateLoc ifElseExpr <?> "if"
   where
     ifElseExpr = do
-      cond <- keywordP "if" *> exprP
-      expr <- keywordP "then" *> exprP
-      option
-        (mkIfF cond expr)
-        (keywordP "else" *> (mkIfElseF cond expr <$> exprP))
+        cond <- keywordP "if" *> exprP
+        expr <- keywordP "then" *> exprP
+        option
+            (mkIfF cond expr)
+            (keywordP "else" *> (mkIfElseF cond expr <$> exprP))
 
-paramsP :: Parser [Param Expr']
+paramsP :: Parser [Param Expr]
 paramsP = parens (param `sepEndBy` comma)
   where
     param = (,) <$> identifier <*> optional (symbol "=" *> exprP)
 
 function ::
-  Parser [Param Expr'] ->
-  Parser Expr' ->
-  Parser Expr'
+    Parser [Param Expr] ->
+    Parser Expr ->
+    Parser Expr
 function ps expr =
-  Fix
-    <$> annotateLoc (mkFunF <$> ps <*> expr)
-    <?> "function"
+    Fix
+        <$> annotateLoc (mkFunF <$> ps <*> expr)
+        <?> "function"
 
-functionP :: Parser Expr'
+functionP :: Parser Expr
 functionP = keywordP "function" *> function paramsP exprP
 
-forspecP :: Parser (CompSpec Expr')
+forspecP :: Parser (CompSpec Expr)
 forspecP = do
-  _ <- keywordP "for"
-  var <- identifier
-  _ <- keywordP "in"
-  forspec <- exprP
-  ifspec <- optional (keywordP "if" *> exprP)
-  pure CompSpec {..}
+    _ <- keywordP "for"
+    var <- identifier
+    _ <- keywordP "in"
+    forspec <- exprP
+    ifspec <- many (keywordP "if" *> exprP)
+    pure CompSpec{..}
 
-binding :: Parser (String, Expr')
+binding :: Parser (String, Expr)
 binding = do
-  name <- identifier
-  _ <- symbol "="
-  expr <- exprP
-  pure (name, expr)
+    name <- identifier
+    _ <- symbol "="
+    expr <- exprP
+    pure (name, expr)
 
-localFunc :: Parser (String, Expr')
+localFunc :: Parser (String, Expr)
 localFunc = do
-  name <- identifier
-  ps <- paramsP
-  _ <- symbol "="
-  expr <- function (pure ps) exprP
-  pure (name, expr)
+    name <- identifier
+    ps <- paramsP
+    _ <- symbol "="
+    expr <- function (pure ps) exprP
+    pure (name, expr)
 
-localBndsP :: Parser (NonEmpty (String, Expr'))
+localBndsP :: Parser (NonEmpty (String, Expr))
 localBndsP = do
-  _ <- keywordP "local"
-  (try binding <|> localFunc) `NE.sepBy1` comma
+    _ <- keywordP "local"
+    (try binding <|> localFunc) `NE.sepBy1` comma
 
-localP :: Parser Expr'
+localP :: Parser Expr
 localP = Fix <$> annotateLoc localExpr <?> "local"
   where
     localExpr = do
-      bnds <- localBndsP
-      _ <- symbol ";"
-      mkLocalF bnds <$> exprP
+        bnds <- localBndsP
+        _ <- symbol ";"
+        mkLocalF bnds <$> exprP
 
-arrayP :: Parser Expr'
+arrayP :: Parser Expr
 arrayP = Fix <$> annotateLoc (brackets (try arrayComp <|> array)) <?> "array"
   where
     array = mkArrayF <$> (exprP `sepEndBy` comma)
     arrayComp = do
-      expr <- exprP <* optional comma
-      comps <- NE.some forspecP
-      return $ mkArrCompF expr comps
+        expr <- exprP <* optional comma
+        comps <- NE.some forspecP
+        return $ mkArrCompF expr comps
 
-objectP :: Parser Expr'
+objectP :: Parser Expr
 objectP = Fix <$> annotateLoc (braces (try objectComp <|> object)) <?> "object"
   where
     object = do
-      xs <- eitherP localP' fieldP `sepEndBy` comma
-      let (ls, fs) = (lefts xs, rights xs)
-      pure $ mkObjectF fs ls
+        (partitionEithers -> (partitionEithers -> (asserts, locals), fields)) <-
+            eitherP (eitherP (try assertP') localP') fieldP `sepEndBy` comma
+        pure $ mkObjectF fields locals asserts
     fieldP = try methodP <|> pairP
     pairP = do
-      (key, computed) <- keyP
-      (override, visibility) <-
-        (,)
-          <$> option False (symbol "+" $> True) <*> sepP
-      value <- exprP
-      pure $ EField {..}
+        (key, computed) <- keyP
+        (override, visibility) <-
+            (,)
+                <$> option False (symbol "+" $> True)
+                <*> sepP
+        value <- exprP
+        pure $ EField{..}
     keyP = ((,True) <$> brackets exprP) <|> ((,False) <$> (identStringP <|> stringP))
     methodP = do
-      let override = False
-          computed = False
-      key <- identStringP
-      ps <- paramsP
-      visibility <- sepP
-      value <- function (pure ps) exprP
-      pure $ EField {..}
+        let override = False
+        (key, computed) <- keyP
+        ps <- paramsP
+        visibility <- sepP
+        value <- function (pure ps) exprP
+        pure $ EField{..}
     sepP =
-      try (symbol ":::" $> Forced)
-        <|> try (symbol "::" $> Hidden)
-        <|> symbol ":" $> Visible
+        try (symbol ":::" $> Forced)
+            <|> try (symbol "::" $> Hidden)
+            <|> symbol ":" $> Visible
     localP' = do
-      _ <- keywordP "local"
-      try binding <|> localFunc
+        _ <- keywordP "local"
+        try binding <|> localFunc
     objectComp = do
-      locals1 <- localP' `sepEndBy` comma
-      expr <- pairP <* optional comma
-      locals2 <- localP' `sepEndBy` comma
-      comps <- NE.some forspecP
-      return $ mkObjCompF expr (locals1 <> locals2) comps
+        locals1 <- localP' `sepEndBy` comma
+        expr <- pairP <* optional comma
+        locals2 <- localP' `sepEndBy` comma
+        comps <- NE.some forspecP
+        return $ mkObjCompF expr (locals1 <> locals2) comps
 
-importP :: Parser Expr'
+importP :: Parser Expr
 importP = Fix <$> annotateLoc importDecl <?> "import"
   where
     importDecl = mkImportF <$> (keywordP "import" *> stringLiteral)
 
-importstrP :: Parser Expr'
+importstrP :: Parser Expr
 importstrP = Fix <$> annotateLoc importstrDecl <?> "importstr"
   where
     importstrDecl = mkImportstrF <$> (keywordP "importstr" *> stringLiteral)
 
-importbinP :: Parser Expr'
+importbinP :: Parser Expr
 importbinP = Fix <$> annotateLoc importbinDecl <?> "importbin"
   where
     importbinDecl = mkImportbinF <$> (keywordP "importbin" *> stringLiteral)
 
 binary ::
-  Text ->
-  (Expr' -> Expr' -> Expr') ->
-  Operator Parser Expr'
+    Text ->
+    (Expr -> Expr -> Expr) ->
+    Operator Parser Expr
 binary name f = InfixL (f <$ operator name)
   where
     operator sym = try $ symbol sym <* notFollowedBy opChar
     opChar = oneOf (":~+&|^=<>*/%" :: String) <?> "operator"
 
 prefix ::
-  Text ->
-  (Expr' -> Expr') ->
-  Operator Parser Expr'
+    Text ->
+    (Expr -> Expr) ->
+    Operator Parser Expr
 prefix name f = Prefix (f <$ symbol name)
 
--- | associativity and operator precedence
---  1. @e(...)@ @e[...]@ @e.f@ (application and indexing)
---  2. @+@ @-@ @!@ @~@ (the unary operators)
---  3. @*@ @/@ @%@ (these, and the remainder below, are binary operators)
---  4. @+@ @-@
---  5. @<<@ @>>@
---  6. @<@ @>@ @<=@ @>=@ @in@
---  7. @==@ @!=@
---  8. @&@
---  9. @^@
--- 10. @|@
--- 11. @&&@
--- 12. @||@
--- default is associate to the left
-opTable :: [[Operator Parser Expr']]
+{- | associativity and operator precedence
+ 1. @e(...)@ @e[...]@ @e.f@ (application and indexing)
+ 2. @+@ @-@ @!@ @~@ (the unary operators)
+ 3. @*@ @/@ @%@ (these, and the remainder below, are binary operators)
+ 4. @+@ @-@
+ 5. @<<@ @>>@
+ 6. @<@ @>@ @<=@ @>=@ @in@
+ 7. @==@ @!=@
+ 8. @&@
+ 9. @^@
+10. @|@
+11. @&&@
+12. @||@
+default is associate to the left
+-}
+opTable :: [[Operator Parser Expr]]
 opTable =
-  [ [Postfix postfixOperators],
-    [ prefix "+" (mkUnyOp Plus),
-      prefix "-" (mkUnyOp Minus),
-      prefix "!" (mkUnyOp LNot),
-      prefix "~" (mkUnyOp Compl)
-    ],
-    [ binary "*" (mkBinOp Mul),
-      binary "/" (mkBinOp Div),
-      binary "%" (mkBinOp Mod)
-    ],
-    [ binary "+" (mkBinOp Add),
-      binary "-" (mkBinOp Sub),
-      Postfix postfixObjectMerge
-    ],
-    [ binary ">>" (mkBinOp ShiftR),
-      binary "<<" (mkBinOp ShiftL)
-    ],
-    [ binary "in" (mkBinOp In),
-      binary ">" (mkBinOp Gt),
-      binary "<=" (mkBinOp Le),
-      binary ">=" (mkBinOp Ge),
-      binary "<" (mkBinOp Lt)
-    ],
-    [ binary "==" (mkBinOp Eq),
-      binary "!=" (mkBinOp Ne)
-    ],
-    [binary "&" (mkBinOp And)],
-    [binary "^" (mkBinOp Xor)],
-    [binary "|" (mkBinOp Or)],
-    [binary "&&" (mkBinOp LAnd)],
-    [binary "||" (mkBinOp LOr)]
-  ]
+    [ [Postfix postfixOperators]
+    ,
+        [ prefix "+" (mkUnyOp Plus)
+        , prefix "-" (mkUnyOp Minus)
+        , prefix "!" (mkUnyOp LNot)
+        , prefix "~" (mkUnyOp Compl)
+        ]
+    ,
+        [ binary "*" (mkBinOp Mul)
+        , binary "/" (mkBinOp Div)
+        , binary "%" (mkBinOp Mod)
+        ]
+    ,
+        [ binary "+" (mkBinOp Add)
+        , binary "-" (mkBinOp Sub)
+        ]
+    ,
+        [ binary ">>" (mkBinOp ShiftR)
+        , binary "<<" (mkBinOp ShiftL)
+        ]
+    ,
+        [ Postfix inSuperP
+        , binary "in" (mkBinOp In)
+        , binary ">" (mkBinOp Gt)
+        , binary "<=" (mkBinOp Le)
+        , binary ">=" (mkBinOp Ge)
+        , binary "<" (mkBinOp Lt)
+        ]
+    ,
+        [ binary "==" (mkBinOp Eq)
+        , binary "!=" (mkBinOp Ne)
+        ]
+    , [binary "&" (mkBinOp And)]
+    , [binary "^" (mkBinOp Xor)]
+    , [binary "|" (mkBinOp Or)]
+    , [binary "&&" (mkBinOp LAnd)]
+    , [binary "||" (mkBinOp LOr)]
+    ]
 
--- | shorthand syntax for object composition:
--- when the right-hand side is an object literal the '+'
--- operator can be elided.
-postfixObjectMerge :: Parser (Expr' -> Expr')
+{- | shorthand syntax for object composition:
+when the right-hand side is an object literal the '+'
+operator can be elided.
+-}
+postfixObjectMerge :: Parser (Expr -> Expr)
 postfixObjectMerge = flip (mkBinOp Add) <$> objectP
 
--- | application, indexing and lookup: e(...) e[...] e.f
--- all have the same precedence (the highest)
-postfixOperators :: Parser (Expr' -> Expr')
+inSuperP :: Parser (Expr -> Expr)
+inSuperP =
+    flip (mkBinOp In) . Fix
+        <$> try
+            ( keywordP "in"
+                *> annotateLoc (keywordP "super" $> mkIdentF "super")
+            )
+
+{- | application, indexing, lookup, and implicit object composition:
+e(...) e[...] e.f e{...}
+All have the exact same precedence (the highest) and chain left-to-right.
+-}
+postfixOperators :: Parser (Expr -> Expr)
 postfixOperators =
-  foldr1 (flip (.))
-    <$> some
-      ( applyP
-          <|> try sliceP
-          <|> indexP
-          <|> lookupP
-      )
+    foldr1 (flip (.))
+        <$> some
+            ( applyP
+                <|> try sliceP
+                <|> indexP
+                <|> lookupP
+                <|> postfixObjectMerge
+            )
 
-indexP :: Parser (Expr' -> Expr')
+indexP :: Parser (Expr -> Expr)
 indexP = flip mkIndex <$> brackets exprP
 
-lookupP :: Parser (Expr' -> Expr')
+lookupP :: Parser (Expr -> Expr)
 lookupP = flip mkLookup <$> (symbol "." *> annotatedIdent) <?> "."
   where
     annotatedIdent :: Parser (Ident, SrcSpan)
     annotatedIdent = do
-      begin <- getSourcePos
-      res <- identifier
-      end <- getSourcePos
-      let sourceSpan = SrcSpan begin end
-      pure (res, sourceSpan)
+        begin <- getSourcePos
+        res <- identifier
+        end <- getSourcePos
+        let sourceSpan = SrcSpan begin end
+        pure (res, sourceSpan)
 
 -- arguments are many postional followed by many named
 -- just like Python
-applyP :: Parser (Expr' -> Expr')
+applyP :: Parser (Expr -> Expr)
 applyP = flip mkApply <$> argsP
   where
-    argsP :: Parser (Args Expr')
+    argsP :: Parser (Args Expr)
     argsP = Args <$> parens (args `sepEndBy` comma) <*> tailstrict
       where
         args = try named <|> posal
@@ -509,54 +474,62 @@
         named = Named <$> identifier <*> (symbol "=" *> exprP)
         tailstrict = option Lazy (keywordP "tailstrict" $> Strict)
 
-sliceP :: Parser (Expr' -> Expr')
+sliceP :: Parser (Expr -> Expr)
 sliceP = brackets $ do
-  start <- optional exprP <* colon
-  end <- optional exprP
-  step <- optional (colon *> optional exprP)
-  pure $ mkSlice start end (join step)
+    start <- optional exprP <* colon
+    end <- optional exprP
+    step <- optional (colon *> optional exprP)
+    pure $ mkSlice start end (join step)
 
-primP :: Parser Expr'
+superP :: Parser Expr
+superP =
+    mkUnyOp Super
+        <$> (keywordP "super" *> (brackets exprP <|> (symbol "." *> identStringP)))
+        <?> "super"
+
+primP :: Parser Expr
 primP =
-  lexeme $
-    choice
-      [ try identP,
-        numberP,
-        stringP,
-        booleanP,
-        nullP,
-        ifElseP,
-        functionP,
-        objectP,
-        arrayP,
-        localP,
-        importstrP,
-        importbinP,
-        importP,
-        errorP,
-        assertP,
-        parens exprP
-      ]
+    lexeme $
+        choice
+            [ try superP
+            , try identP
+            , numberP
+            , stringP
+            , booleanP
+            , nullP
+            , ifElseP
+            , functionP
+            , objectP
+            , arrayP
+            , localP
+            , importstrP
+            , importbinP
+            , importP
+            , errorP
+            , assertP
+            , parens exprP
+            ]
 
-exprP :: Parser Expr'
+exprP :: Parser Expr
 exprP = makeExprParser primP opTable
 
 reservedKeywords :: [String]
 reservedKeywords =
-  [ "assert",
-    "else",
-    "error",
-    "false",
-    "for",
-    "function",
-    "if",
-    "import",
-    "importstr",
-    "importbin",
-    "in",
-    "local",
-    "null",
-    "tailstrict",
-    "then",
-    "true"
-  ]
+    [ "assert"
+    , "else"
+    , "error"
+    , "false"
+    , "for"
+    , "function"
+    , "if"
+    , "import"
+    , "importstr"
+    , "importbin"
+    , "in"
+    , "local"
+    , "null"
+    , "tailstrict"
+    , "then"
+    , "true"
+    , "super"
+    ]
diff --git a/src/Language/Jsonnet/Parser/SrcSpan.hs b/src/Language/Jsonnet/Parser/SrcSpan.hs
--- a/src/Language/Jsonnet/Parser/SrcSpan.hs
+++ b/src/Language/Jsonnet/Parser/SrcSpan.hs
@@ -16,8 +16,6 @@
 import Data.Function (on)
 import GHC.Generics (Generic)
 import Text.Megaparsec.Pos (Pos, SourcePos (..))
-import Unbound.Generics.LocallyNameless
-import Unbound.Generics.LocallyNameless.TH
 
 data SrcSpan = SrcSpan
   { spanBegin :: SourcePos,
@@ -33,17 +31,11 @@
       Data
     )
 
-$(makeClosedAlpha ''SrcSpan)
-
 instance Binary SourcePos
 
 instance Binary Pos
 
 instance Binary SrcSpan
-
-instance Subst b SourcePos => Subst b SrcSpan where
-  subst _ _ = id
-  substs _ = id
 
 instance Semigroup SrcSpan where
   s1 <> s2 = SrcSpan ((min `on` spanBegin) s1 s2) ((max `on` spanEnd) s1 s2)
diff --git a/src/Language/Jsonnet/Pretty.hs b/src/Language/Jsonnet/Pretty.hs
--- a/src/Language/Jsonnet/Pretty.hs
+++ b/src/Language/Jsonnet/Pretty.hs
@@ -1,217 +1,256 @@
--- |
--- Module                  : Language.Jsonnet.Pretty
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
+{-# LANGUAGE OverloadedStrings #-}
+{-# OPTIONS_GHC -Wno-incomplete-patterns #-}
+
+{- |
+Module                  : Language.Jsonnet.Pretty
+Copyright               : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability               : experimental
+Portability             : non-portable
+-}
 module Language.Jsonnet.Pretty where
 
-import Control.Applicative (Const (..))
-import qualified Data.Aeson as JSON
-import qualified Data.Aeson.Key as Key
-import qualified Data.Aeson.KeyMap as KeyMap
-import qualified Data.Aeson.Text as JSON (encodeToLazyText)
+import Data.Aeson qualified as JSON
+import Data.Aeson.Key qualified as Key
+import Data.Aeson.KeyMap qualified as KeyMap
+import Data.Aeson.Text qualified as JSON (encodeToLazyText)
 import Data.Bifunctor (bimap, first)
 import Data.Bool (bool)
 import Data.Fix
-import Data.Functor.Sum
-import Data.Maybe (fromMaybe)
 import Data.List (sortOn)
 import Data.List.NonEmpty (NonEmpty)
-import qualified Data.List.NonEmpty as NE
-import Data.Scientific (Scientific (..))
-import qualified Data.Text as T
-import qualified Data.Text.Lazy as LT
+import Data.List.NonEmpty qualified as NE
+import Data.Maybe (fromMaybe)
+import Data.Scientific (Scientific (..), base10Exponent, coefficient, fromFloatDigits, toRealFloat)
+import Data.Text (Text)
 import Data.Text.Lazy.Builder
 import Data.Text.Lazy.Builder.Scientific (scientificBuilder)
-import qualified Data.Vector as V
+import Data.Vector qualified as V
 import GHC.IO.Exception (IOException (..))
 import Language.Jsonnet.Annotate
 import Language.Jsonnet.Common
 import Language.Jsonnet.Error
 import Language.Jsonnet.Parser.SrcSpan
 import Language.Jsonnet.Syntax
-import qualified Language.Jsonnet.Syntax.Annotated as Ann
+import Language.Jsonnet.Syntax.Annotated qualified as Ann
 import Prettyprinter
 import Text.Megaparsec.Error (errorBundlePretty)
 import Text.Megaparsec.Pos
-import Unbound.Generics.LocallyNameless (Name, name2String)
 
 (<$$>) :: Doc ann -> Doc ann -> Doc ann
 (<$$>) = \x y -> vcat [x, y]
 
 -- reserved keywords
-pnull, ptrue, pfalse, pif, pthen, pelse, pimport, pimportstr, pimportbin,
-  perror, plocal, pfunction, passert, pfor, pin :: Doc ann
-pnull = pretty "null"
-ptrue = pretty "true"
-pfalse = pretty "false"
-pif = pretty "if"
-pthen = pretty "then"
-pelse = pretty "else"
-pimport = pretty "import"
-pimportstr = pretty "importstr"
-pimportbin = pretty "importbin"
-perror = pretty "error"
-plocal = pretty "local"
-pfunction = pretty "function"
-passert = pretty "assert"
-pfor = pretty "for"
-pin = pretty "in"
+pnull
+    , ptrue
+    , pfalse
+    , pif
+    , pthen
+    , pelse
+    , pimport
+    , pimportstr
+    , pimportbin
+    , perror
+    , plocal
+    , pfunction
+    , passert
+    , pfor
+    , pin ::
+        Doc ann
+pnull = "null"
+ptrue = "true"
+pfalse = "false"
+pif = "if"
+pthen = "then"
+pelse = "else"
+pimport = "import"
+pimportstr = "importstr"
+pimportbin = "importbin"
+perror = "error"
+plocal = "local"
+pfunction = "function"
+passert = "assert"
+pfor = "for"
+pin = "in"
 
-prettyName :: Name a -> Doc ann
-prettyName = pretty . name2String
+prettyName :: Name -> Doc ann
+prettyName = pretty
 
-ppNumber :: Scientific -> Doc ann
-ppNumber s
-  | e < 0 || e > 1024 =
-    pretty $
-      LT.unpack $
-        toLazyText $
-          scientificBuilder s
-  | otherwise = pretty (coefficient s * 10 ^ e)
+ppNumber :: Double -> Doc ann
+ppNumber d
+    | e < 0 || e > 1024 =
+        pretty $
+            toLazyText $
+                scientificBuilder s
+    | otherwise = pretty (coefficient s * 10 ^ e)
   where
+    s = fromFloatDigits d
     e = base10Exponent s
 
-ppJson :: Int -> JSON.Value -> Doc ann
-ppJson i = \case
-  JSON.Null -> pnull
-  JSON.Number n -> ppNumber n
-  JSON.Bool True -> ptrue
-  JSON.Bool False -> pfalse
-  JSON.String s -> ppString (Key.fromText s)
-  JSON.Array a -> ppArray a
-  JSON.Object o -> ppObject' o
+ppJsonIndent :: Int -> JSON.Value -> Doc ann
+ppJsonIndent indentLevel = ppJson False indentLevel
+
+ppJsonCompact :: JSON.Value -> Doc ann
+ppJsonCompact = ppJson True 0
+
+ppJson :: Bool -> Int -> JSON.Value -> Doc ann
+ppJson isCompact i = \case
+    JSON.Null -> pnull
+    JSON.Number n -> ppNumber (toRealFloat n)
+    JSON.Bool True -> ptrue
+    JSON.Bool False -> pfalse
+    JSON.String s -> ppString (Key.fromText s)
+    JSON.Array a -> ppArray a
+    JSON.Object o -> ppObject o
   where
-    encloseSep' l r s ds = case ds of
-      [] -> l <> r
-      _ -> l <$$> indent i (vcat $ punctuate s ds) <$$> r
-    ppObject' o = encloseSep' lbrace rbrace comma xs
+    encloseSep' l r ds = case ds of
+        [] -> if isCompact then l <> space <> r else l <> r
+        _ ->
+            if isCompact
+                then l <> hcat (punctuate (comma <> space) ds) <> r
+                else l <$$> indent i (vcat $ punctuate comma ds) <$$> r
+
+    ppObject o = encloseSep' lbrace rbrace xs
       where
-        prop (k, v) = ppString k <> colon <+> ppJson i v
+        prop (k, v) = ppString k <> colon <+> ppJson isCompact i v
         xs = map prop (sortOn fst $ KeyMap.toList o)
-    ppArray a = encloseSep' lbracket rbracket comma xs
+
+    ppArray a = encloseSep' lbracket rbracket xs
       where
-        xs = map (ppJson i) (V.toList a)
-    ppString = pretty . LT.unpack . JSON.encodeToLazyText
+        xs = map (ppJson isCompact i) (V.toList a)
 
+    ppString = pretty . JSON.encodeToLazyText
+
 prettySrcSpan :: SrcSpan -> Doc ann
-prettySrcSpan SrcSpan {spanBegin, spanEnd} =
-  pretty (sourceName spanBegin)
-    <> colon
-    <> lc spanBegin spanEnd
+prettySrcSpan SrcSpan{spanBegin, spanEnd} =
+    pretty (sourceName spanBegin)
+        <> colon
+        <> lc spanBegin spanEnd
   where
     lc (SourcePos _ lb cb) (SourcePos _ le ce)
-      | lb == le =
-        pretty (unPos lb) <> colon
-          <> pretty (unPos cb)
-          <> dash
-          <> pretty (unPos ce)
-      | otherwise =
-        pretty (unPos lb) <> colon <> pretty (unPos cb) <> dash
-          <> pretty (unPos le)
-          <> colon
-          <> pretty (unPos ce)
+        | lb == le =
+            pretty (unPos lb)
+                <> colon
+                <> pretty (unPos cb)
+                <> dash
+                <> pretty (unPos ce)
+        | otherwise =
+            pretty (unPos lb)
+                <> colon
+                <> pretty (unPos cb)
+                <> dash
+                <> pretty (unPos le)
+                <> colon
+                <> pretty (unPos ce)
     dash = pretty '-'
 
 prettyParserError :: ParserError -> Doc ann
 prettyParserError (ParseError e) = pretty (errorBundlePretty e)
-prettyParserError (ImportError (IOError _ _ _ desc _ f) sp) =
-  pretty "Parse error:"
-    <+> pretty f
-    <+> parens (pretty desc)
-    <$$> indent 4 (maybe mempty prettySrcSpan sp)
 
 prettyCheckError :: CheckError -> Doc ann
 prettyCheckError = \case
-  DuplicateParam e ->
-    pretty "duplicate parameter"
-      <+> squotes (pretty e)
-  DuplicateBinding e ->
-    pretty "duplicate local var"
-      <+> squotes (pretty e)
-  PosAfterNamedParam ->
-    pretty "positional after named argument"
+    DuplicateParam e ->
+        "duplicate parameter"
+            <+> squotes (pretty e)
+    DuplicateBinding e ->
+        "duplicate local var"
+            <+> squotes (pretty e)
+    PosAfterNamedParam ->
+        "positional after named argument"
 
 prettyEvalError :: EvalError -> Doc ann
 prettyEvalError = \case
-  TypeMismatch expected actual ->
-    pretty "type mismatch:"
-      <+> pretty "expected"
-      <+> pretty (T.unpack expected)
-      <+> pretty "but got"
-      <+> pretty (T.unpack actual)
-  InvalidKey k ->
-    pretty "invalid key:"
-      <+> pretty k
-  DuplicateKey k ->
-    pretty "duplicate key:"
-      <+> pretty k
-  InvalidIndex k ->
-    pretty "invalid index:"
-      <+> pretty k
-  NoSuchKey k ->
-    pretty "no such key:"
-      <+> pretty k
-  IndexOutOfBounds i ->
-    pretty "index out of bounds:"
-      <+> ppNumber i
-  DivByZero ->
-    pretty "divide by zero exception"
-  VarNotFound v ->
-    pretty "variable"
-      <+> squotes (pretty $ show v)
-      <+> pretty "is not defined"
-  ExtVarNotFound v ->
-    pretty "external variable"
-      <+> squotes (pretty v)
-      <+> pretty "is not defined"
-  AssertionFailed e ->
-    pretty "assertion failed:" <+> pretty e
-  StdError e -> pretty e
-  RuntimeError e -> pretty e
-  ParamNotBound s ->
-    pretty "parameter not bound:"
-      <+> pretty (show s)
-  BadParam s ->
-    pretty "function has no parameter"
-      <+> squotes (pretty s)
-  ManifestError e ->
-    pretty "manifest error:"
-      <+> pretty e
-  TooManyArgs n ->
-    pretty "too many args, function has"
-      <+> pretty n
-      <+> pretty "parameter(s)"
+    TypeMismatch expected actual ->
+        "type mismatch:"
+            <+> "expected"
+            <+> pretty expected
+            <+> "but got"
+            <+> pretty actual
+    InvalidKey k ->
+        "invalid key:"
+            <+> pretty k
+    DuplicateKey k ->
+        "duplicate key:"
+            <+> pretty k
+    InvalidIndex k ->
+        "invalid index:"
+            <+> pretty k
+    NoSuchKey k ->
+        "no such key:"
+            <+> pretty k
+    IndexOutOfBounds i ->
+        "index out of bounds:"
+            <+> ppNumber i
+    DivByZero ->
+        "divide by zero exception"
+    VarNotFound v ->
+        "variable"
+            <+> squotes (pretty v)
+            <+> "is not defined"
+    UnboundSelf ->
+        "can't use self outside of an object."
+    UnboundSuper ->
+        "can't use super outside of an object."
+    NoSuperClass ->
+        "attempt to use super when there is no super class."
+    ExtVarNotFound v ->
+        "external variable"
+            <+> squotes (pretty v)
+            <+> "is not defined"
+    AssertionFailed e ->
+        "assertion failed:" <+> pretty e
+    StdError e -> pretty e
+    RuntimeError e -> pretty e
+    ParamNotBound s ->
+        "parameter not bound:" <+> pretty s
+    ParamAlreadyBound s ->
+        "argument" <+> pretty s <+> "already provided"
+    BadParam s ->
+        "function has no parameter"
+            <+> squotes (pretty s)
+    ManifestError e ->
+        "manifest error:"
+            <+> pretty e
+    TooManyArgs n ->
+        "too many args, function has"
+            <+> pretty n
+            <+> "parameter(s)"
+    UnresolvedImport f (IOError _ _ _ desc _ _) ->
+        "import error:"
+            <+> pretty desc
+            <+> squotes (pretty f)
+    InfiniteRecursion ->
+        "infinite recursion detected"
 
 prettyStackFrame :: StackFrame a -> Doc ann
-prettyStackFrame StackFrame {name, span = span'} =
-  prettySrcSpan span' <+> f (name2String name)
+prettyStackFrame StackFrame{name, span = span'} =
+    prettySrcSpan span' <+> f name
   where
+    f :: Text -> Doc ann
     f "top-level" = mempty
-    f x = pretty "function" <+> angles (pretty x)
+    f x = "function" <+> angles (pretty x)
 
 prettyBacktrace :: Backtrace a -> Doc ann
 prettyBacktrace (Backtrace xs) = vcat $ prettyStackFrame <$> xs
 
 prettyError :: Error -> Doc ann
 prettyError = \case
-  EvalError e bt ->
-    pretty "Runtime error:"
-      <+> prettyEvalError e
-      <$$> indent 2 (prettyBacktrace bt)
-  ParserError e -> prettyParserError e
-  CheckError e sp ->
-    pretty "Static error:"
-      <+> prettyCheckError e
-      <$$> indent 2 (maybe mempty prettySrcSpan sp)
+    EvalError e bt ->
+        "Runtime error:"
+            <+> prettyEvalError e
+                <$$> indent 2 (prettyBacktrace bt)
+    ParserError e -> prettyParserError e
+    CheckError e sp ->
+        "Static error:"
+            <+> prettyCheckError e
+                <$$> indent 2 (maybe mempty prettySrcSpan sp)
 
 prettyVisibility :: Visibility -> Doc ann
 prettyVisibility = \case
-  Visible -> pretty ":"
-  Hidden -> pretty "::"
-  Forced -> pretty ":::"
+    Visible -> ":"
+    Hidden -> "::"
+    Forced -> ":::"
 
 commaSep :: [Doc ann] -> Doc ann
 commaSep = concatWith (surround comma)
@@ -226,67 +265,72 @@
 braceSep = encloseSep lbrace rbrace
 
 ppField :: EField (Doc ann) -> Doc ann
-ppField EField {..} =
-  surround (ppOverride <> prettyVisibility visibility) key' value
+ppField EField{..} =
+    surround (ppOverride <> prettyVisibility visibility) key' value
   where
-    ppOverride = pretty (bool "" "+" override)
+    ppOverride = bool mempty "+" override
     key' = bool key (brackets key) computed
 
-ppObject :: [(Ident, Doc ann)] -> [Doc ann] -> Doc ann
-ppObject l o =
-  encloseSep
-    lbrace
-    rbrace
-    comma
-    (mcons (ppLocal' l) o)
+ppObject :: forall ann. [(Ident, Doc ann)] -> [Assert (Doc ann)] -> [Doc ann] -> Doc ann
+ppObject l asserts o =
+    encloseSep
+        lbrace
+        rbrace
+        comma
+        (mcons (ppLocal' l) (asserts' <> o))
   where
+    mcons :: Maybe a -> [a] -> [a]
     mcons ma as = maybe as (: as) ma
+
+    asserts' :: [Doc ann]
+    asserts' = map prettyAssert asserts
+
     ppLocal' :: [(Ident, Doc ann)] -> Maybe (Doc ann)
     ppLocal' [] = Nothing
     ppLocal' xs =
-      Just $ commaSep ((plocal <+>) . uncurry (surround equals) <$> xs')
+        Just $ commaSep ((plocal <+>) . uncurry (surround equals) <$> xs')
       where
         xs' = first pretty <$> xs
 
 ppLocal :: [(Ident, Doc ann)] -> Doc ann -> Doc ann
 ppLocal xs e =
-  plocal
-    <+> commaSep (uncurry (surround equals) <$> xs')
-      <> semi
-    <+> e
+    plocal
+        <+> commaSep (uncurry (surround equals) <$> xs')
+        <> semi
+        <+> e
   where
     xs' = first pretty <$> xs
 
 prettyUnyOp :: UnyOp -> Doc ann
 prettyUnyOp = \case
-  Compl -> pretty "~"
-  LNot -> pretty "!"
-  Plus -> pretty "+"
-  Minus -> pretty "-"
-  Err -> pretty "<prim:err>"
+    Compl -> "~"
+    LNot -> "!"
+    Plus -> "+"
+    Minus -> "-"
+    Err -> "<prim:err>"
 
 prettyBinOp :: BinOp -> Doc ann
 prettyBinOp = \case
-  Add -> pretty "+"
-  Sub -> pretty "-"
-  Mul -> pretty "*"
-  Div -> pretty "/"
-  Mod -> pretty "%"
-  Lt -> pretty "<"
-  Le -> pretty "<="
-  Gt -> pretty ">"
-  Ge -> pretty ">="
-  Eq -> pretty "=="
-  Ne -> pretty "!="
-  And -> pretty "&"
-  Or -> pretty "|"
-  Xor -> pretty "^"
-  ShiftL -> pretty "<<"
-  ShiftR -> pretty ">>"
-  LAnd -> pretty "&&"
-  LOr -> pretty "||"
-  In -> pretty "in"
-  Lookup -> pretty "<prim:lookup>"
+    Add -> "+"
+    Sub -> "-"
+    Mul -> "*"
+    Div -> "/"
+    Mod -> "%"
+    Lt -> "<"
+    Le -> "<="
+    Gt -> ">"
+    Ge -> ">="
+    Eq -> "=="
+    Ne -> "!="
+    And -> "&"
+    Or -> "|"
+    Xor -> "^"
+    ShiftL -> "<<"
+    ShiftR -> ">>"
+    LAnd -> "&&"
+    LOr -> "||"
+    In -> "in"
+    Lookup -> "<prim:lookup>"
 
 ppFun :: [Param (Doc ann)] -> Doc ann -> Doc ann
 ppFun ps e = pfunction <> parens (commaSep ps') <+> e
@@ -297,19 +341,11 @@
 ppMaybeDoc :: Maybe (Doc ann) -> Doc ann
 ppMaybeDoc = fromMaybe mempty
 
-prettyExpr' :: Ann.Expr' -> Doc ann
-prettyExpr' = prettyFixExprF' . forget'
-
-prettyImport :: Import -> Doc ann
-prettyImport = \case
-  Import fp -> pimport <+> squotes (pretty fp)
-  Importstr fp -> pimportstr <+> squotes (pretty fp)
-  Importbin fp -> pimportbin <+> squotes (pretty fp)
-
-prettyFixExprF' :: Fix ExprF' -> Doc ann
-prettyFixExprF' = foldFix $ \case
-  InR (Const import') -> prettyImport import'
-  InL e -> ppExpr e
+prettyImport :: FilePath -> Import -> Doc ann
+prettyImport fp = \case
+    Code -> pimport <+> squotes (pretty fp)
+    Str -> pimportstr <+> squotes (pretty fp)
+    Bin -> pimportbin <+> squotes (pretty fp)
 
 prettyFixExprF :: Fix ExprF -> Doc ann
 prettyFixExprF = foldFix ppExpr
@@ -327,34 +363,38 @@
 ppCompSpec :: NonEmpty (CompSpec (Doc ann)) -> Doc ann
 ppCompSpec cs = hsep $ f <$> NE.toList cs
   where
-    f (CompSpec v f' c) =
-      pfor
-        <+> pretty v
-        <+> pin
-        <+> parens f'
-        <+> ppMaybeDoc ((pif <+>) <$> c)
+    f (CompSpec v f' ifspecs) =
+        pfor
+            <+> pretty v
+            <+> pin
+            <+> parens f'
+            <+> hsep (map (pif <+>) ifspecs)
 
+prettyAssert :: Assert (Doc ann) -> Doc ann
+prettyAssert (Assert c m) = passert <+> c <> ppMaybeDoc ((colon <>) <$> m)
+
 ppExpr :: ExprF (Doc ann) -> Doc ann
 ppExpr = \case
-  ENull -> pnull
-  EBool True -> ptrue
-  EBool False -> pfalse
-  EStr s -> squotes (pretty s)
-  ENum n -> ppNumber n
-  EFun ps e -> ppFun ps e
-  EApply a args -> parens a <> ppArgs args
-  EIdent i -> pretty i
-  EIf c t -> pif <+> c <+> pthen <+> parens t
-  EIfElse c t e -> pif <+> c <+> pthen <+> parens t <+> pelse <+> parens e
-  EArr a -> bracketSep comma a
-  EObj ls o -> ppObject ls (ppField <$> o)
-  ELocal xs e -> ppLocal (NE.toList xs) (parens e)
-  EErr a -> perror <+> parens a
-  EAssert (Assert c m e) -> passert <+> c <> ppMaybeDoc ((colon <>) <$> m) <> semi <+> e
-  EIndex a b -> parens a <> brackets b
-  ELookup a i -> enclose a (pretty i) dot
-  EUnyOp o a -> parens (prettyUnyOp o <> a)
-  EBinOp o a b -> parens (parens a <+> prettyBinOp o <+> parens b)
-  ESlice a b e s -> parens a <> bracketSep colon (ppMaybeDoc <$> [b, e, s])
-  EArrComp e cs -> lbracket <> e <+> ppCompSpec cs <> rbracket
-  EObjComp f ls cs -> ppObject ls [ppField f <+> ppCompSpec cs]
+    ENull -> pnull
+    EBool True -> ptrue
+    EBool False -> pfalse
+    EStr s -> squotes (pretty s)
+    ENum n -> ppNumber n
+    EFun ps e -> ppFun ps e
+    EApply a args -> parens a <> ppArgs args
+    EIdent i -> pretty i
+    EIf c t -> pif <+> c <+> pthen <+> parens t
+    EIfElse c t e -> pif <+> c <+> pthen <+> parens t <+> pelse <+> parens e
+    EArr a -> bracketSep comma a
+    EObj ls o asserts -> ppObject ls asserts (ppField <$> o)
+    ELocal xs e -> ppLocal (NE.toList xs) (parens e)
+    EErr a -> perror <+> parens a
+    EAssert assert e -> prettyAssert assert <> semi <+> e
+    EIndex a b -> parens a <> brackets b
+    ELookup a i -> enclose a (pretty i) dot
+    EUnyOp o a -> parens (prettyUnyOp o <> a)
+    EBinOp o a b -> parens (parens a <+> prettyBinOp o <+> parens b)
+    ESlice a b e s -> parens a <> bracketSep colon (ppMaybeDoc <$> [b, e, s])
+    EArrComp e cs -> lbracket <> e <+> ppCompSpec cs <> rbracket
+    EObjComp f ls cs -> ppObject ls [] [ppField f <+> ppCompSpec cs]
+    EImport it fp -> prettyImport fp it
diff --git a/src/Language/Jsonnet/Std.hs b/src/Language/Jsonnet/Std.hs
new file mode 100644
--- /dev/null
+++ b/src/Language/Jsonnet/Std.hs
@@ -0,0 +1,34 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE StrictData #-}
+{-# LANGUAGE TemplateHaskell #-}
+
+module Language.Jsonnet.Std (
+    module Language.Jsonnet.Std.Lib,
+    mkStdEnv,
+) where
+
+import Data.Binary (decode)
+import GHC.Compact (compact, getCompact)
+import Language.Jsonnet.Eval (whnf)
+import Language.Jsonnet.Eval.Types (Env (..), Importer (..), runEvalM)
+import Language.Jsonnet.Object (Object)
+import Language.Jsonnet.Std.Lib
+import Language.Jsonnet.Std.TH (mkStdlib)
+import Language.Jsonnet.Value (Value (VNull), proj)
+import System.IO.Unsafe (unsafePerformIO)
+
+{-# NOINLINE nonnative #-}
+nonnative :: Object
+nonnative =
+    unsafePerformIO $ do
+        compactCore <- compact core
+        runEvalM "<stdlib>" dummyImporter emptyEnv $
+            whnf (getCompact compactCore) >>= proj
+  where
+    emptyEnv = Env mempty Nothing Nothing VNull
+    core = decode $(mkStdlib)
+    dummyImporter = Importer $ \_ _ ->
+        fail "Fatal: std.jsonnet attempted to import a file!"
+
+mkStdEnv :: ExtVars -> UserFuncs -> StdEnv
+mkStdEnv = StdEnv nonnative
diff --git a/src/Language/Jsonnet/Std/Lib.hs b/src/Language/Jsonnet/Std/Lib.hs
--- a/src/Language/Jsonnet/Std/Lib.hs
+++ b/src/Language/Jsonnet/Std/Lib.hs
@@ -1,102 +1,148 @@
-{-# LANGUAGE NoImplicitPrelude #-}
 {-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE NoImplicitPrelude #-}
 
--- |
--- Module                  : Language.Jsonnet.Std.Lib
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
-module Language.Jsonnet.Std.Lib
-  ( std,
+module Language.Jsonnet.Std.Lib (
+    ExtVars (..),
+    UserFuncs (..),
+    StdEnv (..),
+    stdlib,
+    mkStdObject,
+    objectFieldsEx,
     objectHasEx,
-  )
-where
+) where
 
-import qualified Data.Aeson as JSON
-import qualified Data.ByteString as B
-import qualified Data.HashMap.Lazy as H
-import qualified Data.List as L (intercalate)
-import qualified Data.Map.Strict as M
+import Control.Lens ((<&>))
+import Control.Monad.IO.Class (MonadIO (liftIO))
+import Control.Monad.Reader (MonadReader, asks)
+import Crypto.Hash.MD5 qualified as MD5
+import Data.Aeson qualified as JSON
+import Data.ByteString qualified as B
+import Data.ByteString.Base16 qualified as B16
+import Data.Fixed (mod')
+import Data.Functor (($>))
+import Data.HashMap.Strict qualified as H
+import Data.List qualified as L
+import Data.Map qualified as Map
+import Data.Map.Strict (Map)
 import Data.Text (Text)
-import qualified Data.Text as T
-import qualified Data.Text.Encoding as T
-import Data.Vector (Vector)
-import qualified Data.Vector as V
-import Data.Word
-import Language.Jsonnet.Common
-import Language.Jsonnet.Error
-import Language.Jsonnet.Eval
+import Data.Text qualified as T
+import Data.Text.Encoding qualified as T
+import Data.Text.IO (hPutStrLn)
+import Data.Vector qualified as V
+import Data.Yaml qualified as Yaml
+import Language.Jsonnet.Common (Visibility (..))
+import Language.Jsonnet.Error (EvalError (ExtVarNotFound, StdError))
 import Language.Jsonnet.Eval.Monad
+import Language.Jsonnet.Object (Field (..), Object)
+import Language.Jsonnet.Object qualified as Object
 import Language.Jsonnet.Value
-import Unbound.Generics.LocallyNameless
+import System.IO (stderr)
 import Prelude hiding (length)
-import qualified Prelude as P (length)
+import Prelude qualified as P (length)
 
--- | Jsonnet standard library built-in methods
-std :: ExtVars -> Value
-std extVars = VObj $ H.fromList $ map f xs
+newtype ExtVars = ExtVars {unExtVars :: Map Text Value}
+    deriving newtype (Semigroup, Monoid)
+
+newtype UserFuncs = UserFuncs {unUserFuncs :: Map Text Value}
+    deriving newtype (Semigroup, Monoid)
+
+data StdEnv = StdEnv
+    { stdNonNative :: Object
+    , stdExtVars :: ExtVars
+    , stdUserFuncs :: UserFuncs
+    }
+
+stdlib :: (MonadIO m, MonadReader StdEnv m) => m Value
+stdlib = asks mkStdObject >>= mkObj
+
+mkStdObject :: StdEnv -> Object
+mkStdObject (StdEnv nonnative (ExtVars ev) (UserFuncs uf)) =
+    nonnative <> Object.mkBaseObject (H.fromList xs)
   where
-    f = \(k, v) -> (k, VField (VStr k) v v Hidden)
+    infixr 8 ~>
+    k ~> v = (k, Field (inj v) Hidden False)
     xs =
-      [ ("type", inj showTy),
-        ("primitiveEquals", inj primitiveEquals),
-        ("equals", inj equals),
-        ("length", inj length),
-        ("pow", inj ((^^) @Double @Int)),
-        ("exp", inj (exp @Double)),
-        ("log", inj (log @Double)),
-        ("exponent", inj (exponent @Double)),
-        ("mantissa", inj (significand @Double)),
-        ("floor", inj (floor @Double @Integer)),
-        ("ceil", inj (ceiling @Double @Integer)),
-        ("sqrt", inj (sqrt @Double)),
-        ("sin", inj (sin @Double)),
-        ("cos", inj (cos @Double)),
-        ("tan", inj (tan @Double)),
-        ("asin", inj (asin @Double)),
-        ("acos", inj (acos @Double)),
-        ("atan", inj (atan @Double)),
-        ("modulo", inj (mod @Integer)),
-        ("codepoint", inj (fromEnum . T.head)),
-        ("char", inj (T.singleton . toEnum)),
-        ("encodeUTF8", inj (B.unpack . T.encodeUtf8 :: Text -> [Word8])),
-        ("decodeUTF8", inj (T.decodeUtf8 . B.pack :: [Word8] -> Text)),
-        ("makeArray", inj (makeArray @Eval)),
-        ("filter", inj (V.filterM @Eval @Value)),
-        ("join", inj intercalate),
-        ("objectHasEx", inj objectHasEx),
-        ("objectFieldsEx", inj objectFieldsEx),
-        ("parseJson", inj (JSON.decodeStrict @Value)),
-        ("extVar", inj (lookupExtVar extVars))
-      ]
-
-lookupExtVar :: ExtVars -> Text -> Eval Value
-lookupExtVar (ExtVars extVars) s = liftMaybe (ExtVarNotFound s) (M.lookup s extVars)
+        [ "type" ~> showTy
+        , "primitiveEquals" ~> primitiveEquals
+        , "equals" ~> equals
+        , "length" ~> length
+        , "pow" ~> (**) @Double
+        , "exp" ~> exp @Double
+        , "log" ~> log @Double
+        , "exponent" ~> exponent @Double
+        , "mantissa" ~> significand @Double
+        , "floor" ~> floor @Double @Integer
+        , "ceil" ~> ceiling @Double @Integer
+        , "sqrt" ~> sqrt @Double
+        , "sin" ~> sin @Double
+        , "cos" ~> cos @Double
+        , "tan" ~> tan @Double
+        , "asin" ~> asin @Double
+        , "acos" ~> acos @Double
+        , "atan" ~> atan @Double
+        , "atan2" ~> atan2 @Double
+        , "hypot" ~> \a b -> (sqrt @Double) (a * a + b * b)
+        , "modulo" ~> mod' @Double
+        , "codepoint" ~> fromEnum . T.head
+        , "char" ~> T.singleton . toEnum
+        , "encodeUTF8" ~> B.unpack . T.encodeUtf8
+        , "decodeUTF8" ~> T.decodeUtf8 . B.pack
+        , "makeArray" ~> V.generateM @EvalM @Value
+        , "filter" ~> V.filterM @EvalM @Value
+        , "join" ~> intercalate
+        , "objectHasEx" ~> objectHasEx
+        , "objectFieldsEx" ~> objectFieldsEx
+        , "objectRemoveKey" ~> flip (H.delete @Text @Value)
+        , "parseJson" ~> JSON.throwDecodeStrict @JSON.Value @EvalM
+        , "parseYaml" ~> parseYaml
+        , "extVar" ~> (liftMaybe . ExtVarNotFound <*> (`Map.lookup` ev))
+        , "thisFile" ~> getFileName
+        , "trace" ~> trace
+        , "native" ~> (`Map.lookup` uf)
+        , "md5" ~> T.decodeUtf8 . B16.encode . MD5.hash . T.encodeUtf8
+        ]
 
-intercalate :: Value -> [Value] -> Eval Value
+intercalate :: Value -> [Value] -> EvalM Value
 intercalate sep arr = go sep (filter notNull arr)
   where
     notNull VNull = False
-    notNull _     = True
+    notNull _ = True
     go sep'@(VArr _) = app (L.intercalate @Value) sep'
     go sep'@(VStr _) = app T.intercalate sep'
-    go _             = const $ throwE ( StdError "join's separator must be a string or an array" )
+    go _ = const $ throwE (StdError "join's separator must be a string or an array")
     app f sep' arr' = inj <$> (f <$> proj sep' <*> traverse proj arr')
 
-length :: Value -> Eval Int
+length :: Value -> EvalM Int
 length = \case
-  VStr s -> pure $ T.length s
-  VArr a -> pure $ P.length a
-  VObj o -> pure $ P.length (H.keys o)
-  VClos f _ -> do
-    (ps, _) <- unbind f
-    pure $ P.length (unrec ps)
-  _ ->
-    throwE
-      ( StdError "length operates on strings, objects, functions and arrays, got "
-      )
+    VStr s -> pure $ T.length s
+    VArr a -> pure $ P.length a
+    VObj o _ -> pure $ P.length (objectFieldsEx o True)
+    VFun l _ -> pure $ l
+    _ ->
+        throwE
+            (StdError "length operates on strings, objects, functions and arrays, got ")
 
-makeArray :: Monad m => Int -> (Int -> m Value) -> m (Vector Value)
-makeArray n f = traverse f (V.fromList [0 .. n - 1])
+trace :: Text -> Value -> EvalM Value
+trace str =
+    ($>)
+        ( do
+            fn <- T.pack <$> getFileName
+            ln <- getLineNum
+            let loc = maybe fn (\l -> fn <> ":" <> T.pack (show l)) ln
+            liftIO $ hPutStrLn stderr ("TRACE: " <> loc <> " " <> str)
+        )
+
+parseYaml :: B.ByteString -> EvalM Value
+parseYaml bs =
+    Yaml.decodeAllThrow @EvalM @JSON.Value bs <&> \case
+        [] -> VNull
+        [doc] -> inj doc
+        docs -> inj docs
+
+objectFieldsEx :: Object -> Bool -> [Text]
+objectFieldsEx o = \case
+    True -> Object.regularKeys o
+    False -> Object.visibleKeys o
+
+objectHasEx :: Object -> Text -> Bool -> Bool
+objectHasEx o f all' = f `elem` objectFieldsEx o all'
diff --git a/src/Language/Jsonnet/Std/TH.hs b/src/Language/Jsonnet/Std/TH.hs
--- a/src/Language/Jsonnet/Std/TH.hs
+++ b/src/Language/Jsonnet/Std/TH.hs
@@ -7,7 +7,7 @@
 -- Portability             : non-portable
 module Language.Jsonnet.Std.TH where
 
-import qualified Data.Text.IO as TIO
+import Data.Text.IO qualified as TIO
 import Language.Haskell.TH
 import Language.Haskell.TH.Quote ()
 import Language.Haskell.TH.Syntax (addDependentFile)
diff --git a/src/Language/Jsonnet/Syntax.hs b/src/Language/Jsonnet/Syntax.hs
--- a/src/Language/Jsonnet/Syntax.hs
+++ b/src/Language/Jsonnet/Syntax.hs
@@ -1,4 +1,5 @@
 {-# OPTIONS_GHC -Wno-partial-fields #-}
+
 -- |
 -- Module                  : Language.Jsonnet.Syntax
 -- Copyright               : (c) 2020-2021 Alexandre Moreno
@@ -8,19 +9,15 @@
 -- Portability             : non-portable
 module Language.Jsonnet.Syntax where
 
-import Control.Applicative (Const (..))
 import Data.Data (Data)
 import Data.Functor.Classes
 import Data.Functor.Classes.Generic
-import Data.Functor.Sum
 import Data.List.NonEmpty
-import Data.Scientific (Scientific)
 import Data.Text (Text)
-import qualified Data.Text as T
+import Data.Text qualified as T
 import Data.Typeable (Typeable)
 import GHC.Generics
 import Language.Jsonnet.Common
-import Unbound.Generics.LocallyNameless
 
 type Ident = String
 
@@ -45,7 +42,6 @@
       Foldable,
       Traversable
     )
-  deriving anyclass (Alpha)
   deriving
     (Eq1, Show1)
     via FunctorClassesDefault EField
@@ -53,7 +49,7 @@
 data ExprF a
   = ENull
   | EBool Bool
-  | ENum Scientific
+  | ENum Double
   | EStr Text
   | EIdent Ident
   | EFun [Param a] a
@@ -65,45 +61,35 @@
         expr :: a
       }
   | EObj
-      { -- |
-        locals :: [(Ident, a)],
-        -- |
-        fields :: [EField a]
-        --asserts :: [Assert a]
+      { locals :: [(Ident, a)],
+        fields :: [EField a],
+        asserts :: [Assert a]
       }
   | EArr [a]
   | EErr a
   | ELookup a Ident
   | EIndex a a
-  | EAssert (Assert a)
+  | EAssert (Assert a) a
   | EIf a a
   | EIfElse a a a
   | ESlice
-      { -- |
-        expr :: a,
-        -- |
+      { expr :: a,
         start :: Maybe a,
-        -- |
         end :: Maybe a,
-        -- |
         step :: Maybe a
       }
   | EBinOp BinOp a a
   | EUnyOp UnyOp a
   | EArrComp
-      { -- |
-        expr :: a,
-        -- |
+      { expr :: a,
         comp :: NonEmpty (CompSpec a)
       }
   | EObjComp
-      { -- |
-        field :: EField a,
-        -- |
+      { field :: EField a,
         locals :: [(Ident, a)],
-        -- |
         comp :: NonEmpty (CompSpec a)
       }
+  | EImport Import FilePath
   deriving stock
     ( Eq,
       Show,
@@ -119,103 +105,87 @@
     (Eq1, Show1)
     via FunctorClassesDefault ExprF
 
-data Import
-  = Import FilePath
-  | Importstr FilePath
-  | Importbin FilePath
-  deriving stock (Show, Eq)
-
-type ExprF' = Sum ExprF (Const Import)
-
-mkImportF :: FilePath -> ExprF' a
-mkImportF = InR . Const . Import
+mkImportF :: FilePath -> ExprF a
+mkImportF = EImport Code
 
-mkImportstrF :: FilePath -> ExprF' a
-mkImportstrF = InR . Const . Importstr
+mkImportstrF :: FilePath -> ExprF a
+mkImportstrF = EImport Str
 
-mkImportbinF :: FilePath -> ExprF' a
-mkImportbinF = InR . Const . Importbin
+mkImportbinF :: FilePath -> ExprF a
+mkImportbinF = EImport Bin
 
-mkNullF :: ExprF' a
-mkNullF = InL ENull
+mkNullF :: ExprF a
+mkNullF = ENull
 
-mkIntF :: Integral b => b -> ExprF' a
-mkIntF = InL . ENum . fromIntegral
+mkIntF :: (Integral b) => b -> ExprF a
+mkIntF = ENum . fromIntegral
 
-mkFloatF :: Scientific -> ExprF' a
-mkFloatF = InL . ENum
+mkFloatF :: Double -> ExprF a
+mkFloatF = ENum
 
-mkTextF :: Text -> ExprF' a
-mkTextF = InL . EStr
+mkTextF :: Text -> ExprF a
+mkTextF = EStr
 
-mkStrF :: String -> ExprF' a
+mkStrF :: String -> ExprF a
 mkStrF s = mkTextF (T.pack s)
 
-mkBoolF :: Bool -> ExprF' a
-mkBoolF = InL . EBool
+mkBoolF :: Bool -> ExprF a
+mkBoolF = EBool
 
-mkIdentF :: Ident -> ExprF' a
-mkIdentF = InL . EIdent
+mkIdentF :: Ident -> ExprF a
+mkIdentF = EIdent
 
-mkFunF :: [Param a] -> a -> ExprF' a
-mkFunF a = InL . EFun a
+mkFunF :: [Param a] -> a -> ExprF a
+mkFunF a = EFun a
 
-mkApplyF :: a -> Args a -> ExprF' a
-mkApplyF a = InL . EApply a
+mkApplyF :: a -> Args a -> ExprF a
+mkApplyF a = EApply a
 
-mkIfF :: a -> a -> ExprF' a
-mkIfF c = InL . EIf c
+mkIfF :: a -> a -> ExprF a
+mkIfF c = EIf c
 
-mkIfElseF :: a -> a -> a -> ExprF' a
-mkIfElseF c a = InL . EIfElse c a
+mkIfElseF :: a -> a -> a -> ExprF a
+mkIfElseF c a = EIfElse c a
 
-mkLocalF :: NonEmpty (Ident, a) -> a -> ExprF' a
-mkLocalF n = InL . ELocal n
+mkLocalF :: NonEmpty (Ident, a) -> a -> ExprF a
+mkLocalF n = ELocal n
 
-mkLookupF :: a -> Ident -> ExprF' a
-mkLookupF e = InL . ELookup e
+mkLookupF :: a -> Ident -> ExprF a
+mkLookupF e = ELookup e
 
-mkIndexF :: a -> a -> ExprF' a
-mkIndexF e = InL . EIndex e
+mkIndexF :: a -> a -> ExprF a
+mkIndexF e = EIndex e
 
 mkSliceF ::
-  -- |
   a ->
-  -- |
   Maybe a ->
-  -- |
   Maybe a ->
-  -- |
   Maybe a ->
-  ExprF' a
-mkSliceF e f g = InL . ESlice e f g
+  ExprF a
+mkSliceF e f g = ESlice e f g
 
 mkObjectF ::
-  -- |
   [EField a] ->
-  -- |
   [(Ident, a)] ->
-  ExprF' a
-mkObjectF fs ls = InL $ EObj ls fs
+  [Assert a] ->
+  ExprF a
+mkObjectF fs ls = EObj ls fs
 
-mkArrayF :: [a] -> ExprF' a
-mkArrayF = InL . EArr
+mkArrayF :: [a] -> ExprF a
+mkArrayF = EArr
 
-mkErrorF :: a -> ExprF' a
-mkErrorF = InL . EErr
+mkErrorF :: a -> ExprF a
+mkErrorF = EErr
 
-mkAssertF :: a -> Maybe a -> a -> ExprF' a
-mkAssertF e m = InL . EAssert . Assert e m
+mkAssertF :: Assert a -> a -> ExprF a
+mkAssertF a = EAssert a
 
-mkArrCompF :: a -> NonEmpty (CompSpec a) -> ExprF' a
-mkArrCompF e = InL . EArrComp e
+mkArrCompF :: a -> NonEmpty (CompSpec a) -> ExprF a
+mkArrCompF e = EArrComp e
 
 mkObjCompF ::
-  -- |
   EField a ->
-  -- |
   [(Ident, a)] ->
-  -- |
   NonEmpty (CompSpec a) ->
-  ExprF' a
-mkObjCompF f ls = InL . EObjComp f ls
+  ExprF a
+mkObjCompF f ls = EObjComp f ls
diff --git a/src/Language/Jsonnet/Syntax/Annotated.hs b/src/Language/Jsonnet/Syntax/Annotated.hs
--- a/src/Language/Jsonnet/Syntax/Annotated.hs
+++ b/src/Language/Jsonnet/Syntax/Annotated.hs
@@ -1,3 +1,5 @@
+{-# LANGUAGE PatternSynonyms #-}
+{-# LANGUAGE ViewPatterns #-}
 -- |
 -- Module                  : Language.Jsonnet.Syntax.Annotated
 -- Copyright               : (c) 2020-2021 Alexandre Moreno
@@ -8,42 +10,38 @@
 module Language.Jsonnet.Syntax.Annotated where
 
 import Data.Fix
-import Data.Functor.Sum
 import Language.Jsonnet.Annotate
 import Language.Jsonnet.Common
 import Language.Jsonnet.Parser.SrcSpan
 import Language.Jsonnet.Syntax
+import Control.Arrow ((&&&))
 
--- | annotated syntax tree with resolved imports
 type Expr = Ann ExprF SrcSpan
 
--- | annotated syntax tree with unresolved imports
-type Expr' = Ann ExprF' SrcSpan
-
-mkApply :: Expr' -> Args Expr' -> Expr'
+mkApply :: Expr -> Args Expr -> Expr
 mkApply a@(Fix (AnnF _ ann)) args =
-  Fix $ AnnF (InL $ EApply a args) ann
-
---mkApply a@(Fix (AnnF _ ann)) b =
---  Fix $ AnnF (InL $ EApply a b) (fold1 (ann <| fmap attrib (fromList b)))
+  Ann (EApply a args) ann
 
-mkLookup :: Expr' -> (Ident, SrcSpan) -> Expr'
+mkLookup :: Expr -> (Ident, SrcSpan) -> Expr
 mkLookup a@(Fix (AnnF _ ann1)) (ident, ann2) =
-  Fix $ AnnF (InL $ ELookup a ident) (ann1 <> ann2)
+  Ann (ELookup a ident) (ann1 <> ann2)
 
-mkIndex :: Expr' -> Expr' -> Expr'
+mkIndex :: Expr -> Expr -> Expr
 mkIndex a@(Fix (AnnF _ ann1)) b@(Fix (AnnF _ ann2)) =
-  Fix $ AnnF (InL $ EIndex a b) (ann1 <> ann2)
+  Ann (EIndex a b) (ann1 <> ann2)
 
-mkSlice :: Maybe Expr' -> Maybe Expr' -> Maybe Expr' -> Expr' -> Expr'
+mkSlice :: Maybe Expr -> Maybe Expr -> Maybe Expr -> Expr -> Expr
 mkSlice i n s e@(Fix (AnnF _ ann1)) =
-  Fix $ AnnF (InL $ ESlice e i n s) ann1
+  Ann (ESlice e i n s) ann1
 
-mkBinOp :: BinOp -> Expr' -> Expr' -> Expr'
+mkBinOp :: BinOp -> Expr -> Expr -> Expr
 mkBinOp op a@(Fix (AnnF _ ann1)) b@(Fix (AnnF _ ann2)) =
-  Fix $ AnnF (InL $ EBinOp op a b) (ann1 <> ann2)
+  Ann (EBinOp op a b) (ann1 <> ann2)
 
 -- FIXME we are manually here updating the span
-mkUnyOp :: UnyOp -> Expr' -> Expr'
+mkUnyOp :: UnyOp -> Expr -> Expr
 mkUnyOp op a@(Fix (AnnF _ ann)) =
-  Fix $ AnnF (InL $ EUnyOp op a) ann
+  Ann (EUnyOp op a) ann
+
+para :: Functor f => (f (Fix f, a) -> a) -> Fix f -> a
+para f = f . fmap (id &&& para f) . unFix
diff --git a/src/Language/Jsonnet/TH.hs b/src/Language/Jsonnet/TH.hs
--- a/src/Language/Jsonnet/TH.hs
+++ b/src/Language/Jsonnet/TH.hs
@@ -9,26 +9,26 @@
 -- Portability             : non-portable
 module Language.Jsonnet.TH where
 
-import Control.Monad ((>=>))
 import Control.Monad.Except
 import Data.Binary (encode)
 import Data.Data
 import Data.Text (Text)
-import qualified Data.Text as T
+import Data.Text qualified as T
 import Instances.TH.Lift ()
 import Language.Haskell.TH
 import Language.Haskell.TH.Syntax
 import Language.Jsonnet.Annotate (forget)
 import Language.Jsonnet.Desugar
-import qualified Language.Jsonnet.Parser as Parser
+import Language.Jsonnet.Parser qualified as Parser
 import Language.Jsonnet.Pretty (prettyError)
 import Language.Jsonnet.Syntax.Annotated
+import Language.Jsonnet.Core (resolve)
 
 liftText :: Text -> Q Exp
 liftText txt = AppE (VarE 'T.pack) <$> lift (T.unpack txt)
 
 -- ouch: https://gitlab.haskell.org/ghc/ghc/-/issues/12596
-liftDataWithText :: Data a => a -> Q Exp
+liftDataWithText :: (Data a) => a -> Q Exp
 liftDataWithText = dataToExpQ (fmap liftText . cast)
 
 parse0 :: FilePath -> Text -> Q Expr
@@ -37,11 +37,7 @@
     Left err -> fail (show $ prettyError err)
     Right res -> pure res
   where
-    parse' =
-      runExceptT
-        . ( Parser.parse path
-              >=> Parser.resolveImports path
-          )
+    parse' = runExceptT . Parser.parse path
 
 parse :: FilePath -> Text -> Q Exp
 parse path str =
@@ -56,5 +52,6 @@
   parse0 path str
     >>= lift
       . encode
+      . resolve
       . desugar
       . forget
diff --git a/src/Language/Jsonnet/TH/QQ.hs b/src/Language/Jsonnet/TH/QQ.hs
--- a/src/Language/Jsonnet/TH/QQ.hs
+++ b/src/Language/Jsonnet/TH/QQ.hs
@@ -7,7 +7,7 @@
 -- Portability             : non-portable
 module Language.Jsonnet.TH.QQ where
 
-import qualified Data.Text as T
+import Data.Text qualified as T
 import Language.Haskell.TH.Quote (QuasiQuoter (..))
 import Language.Jsonnet.TH
 
diff --git a/src/Language/Jsonnet/Value.hs b/src/Language/Jsonnet/Value.hs
--- a/src/Language/Jsonnet/Value.hs
+++ b/src/Language/Jsonnet/Value.hs
@@ -1,109 +1,455 @@
--- |
--- Module                  : Language.Jsonnet.Value
--- Copyright               : (c) 2020-2021 Alexandre Moreno
--- SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
--- Maintainer              : Alexandre Moreno <alexmorenocano@gmail.com>
--- Stability               : experimental
--- Portability             : non-portable
-module Language.Jsonnet.Value where
+{-# LANGUAGE AllowAmbiguousTypes #-}
+{-# LANGUAGE ConstraintKinds #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE StrictData #-}
+{-# LANGUAGE TemplateHaskell #-}
+{-# LANGUAGE TypeApplications #-}
+{-# LANGUAGE UndecidableInstances #-}
 
-import Control.Lens (view)
-import Control.Monad.IO.Class (MonadIO, liftIO)
-import Data.HashMap.Lazy (HashMap)
-import Data.IORef
-import Data.Map.Strict (Map)
-import Data.Scientific
+{- |
+Module      : Language.Jsonnet.Value
+Copyright   : (c) 2020-2021 Alexandre Moreno
+SPDX-License-Identifier : BSD-3-Clause OR Apache-2.0
+Maintainer  : Alexandre Moreno <alexmorenocano@gmail.com>
+Stability   : experimental
+Portability : non-portable
+-}
+module Language.Jsonnet.Value (
+    -- * Re-exported from Eval.Types
+    Value (VNull, VBool, VStr, VNum, VObj, VArr, VFun),
+    Cache,
+
+    -- * Smart constructors & evaluation
+    mkObj,
+    emptyObject,
+    mkIndirV,
+    mkThunk,
+    mkFun,
+    forceWHNF,
+    force,
+    liftF,
+    liftF2,
+
+    -- * Operations
+    objectLookup,
+    superLookup,
+    equals,
+    primitiveEquals,
+    compare,
+    toString,
+    showTy,
+    doubleToIntegral,
+    isIntegral,
+    throwTypeMismatch,
+
+    -- * Typeclasses
+    Inj (..),
+    Proj (..),
+    HasValue,
+    Arity (..),
+) where
+
+import Control.Lens (Prism', makePrisms, matching, prism', review, (^.))
+import Control.Monad (forM, (>=>), (<$!>))
+import Control.Monad.IO.Class (MonadIO (..))
+import Data.Aeson qualified as JSON
+import Data.Aeson.KeyMap qualified as KeyMap
+import Data.ByteString (ByteString)
+import Data.HashMap.Strict (HashMap)
+import Data.HashMap.Strict qualified as H
+import Data.HashSet qualified as HS
+import Data.IORef (IORef, newIORef, readIORef, writeIORef)
+import Data.Scientific (Scientific, fromFloatDigits, toRealFloat)
 import Data.Text (Text)
+import Data.Text qualified as T
+import Data.Text.Encoding (decodeUtf8, encodeUtf8)
 import Data.Vector (Vector)
-import GHC.Generics
-import Language.Jsonnet.Common
-import Language.Jsonnet.Core hiding (mkField)
+import Data.Vector qualified as V
+import Language.Jsonnet.Common (Arg (..), Visibility (..))
+import Language.Jsonnet.Error (EvalError (..))
 import Language.Jsonnet.Eval.Monad
-import Language.Jsonnet.Pretty ()
-import Data.Aeson (FromJSON (..))
-import qualified Data.Aeson as JSON
-import qualified Data.Aeson.KeyMap as KeyMap
-import qualified Data.HashMap.Lazy as H
+import Language.Jsonnet.Eval.Types
+import Language.Jsonnet.Object qualified as Object
+import Language.Jsonnet.Pretty (ppJsonCompact)
+import Data.Int (Int64)
+import Prelude hiding (compare)
+import Prelude qualified as P
 
-type Eval = EvalM Value
+makePrisms ''Value
 
-type Env = Ctx Value
+expect :: Text -> Value -> EvalError
+expect expected actual = TypeMismatch expected (showTy actual)
+{-# INLINE expect #-}
 
-newtype ExtVars = ExtVars (Map Text Value)
-  deriving newtype (Semigroup, Monoid)
+throwTypeMismatch :: Text -> Value -> EvalM a
+throwTypeMismatch expected = throwE . expect expected
+{-# INLINE throwTypeMismatch #-}
 
-data Value
-  = VNull
-  | VBool !Bool
-  | VStr !Text
-  | VNum !Scientific
-  | VObj !Object -- !Object
-  | VArr !(Vector Value)
-  | VThunk !Core !Env
-  | VIndir !Ref
-  | VPrim !Prim
-  | VClos !Lam !Env
-  | VFun !Fun
+objectLookup :: Value -> Text -> EvalM Value
+objectLookup v key =
+    forceWHNF v >>= \case
+        selfVal@(VObj obj _) -> superLookup selfVal obj key
+        v' -> throwTypeMismatch "object" v'
+{-# INLINE objectLookup #-}
 
-instance FromJSON Value where
-  parseJSON = \case
-    JSON.Null -> pure VNull
-    JSON.Bool b -> pure $ VBool b
-    JSON.Number n -> pure $ VNum n
-    JSON.String s -> pure $ VStr s
-    JSON.Array a -> VArr <$> traverse parseJSON a
-    JSON.Object o -> VObj . f <$> traverse parseJSON (KeyMap.toHashMapText o)
-    where
-      f :: HashMap Text Value -> Object
-      f o =
-        H.fromList
-          [ mkField k v
-            | (k, v) <- H.toList o
-          ]
-      mkField k v = (k, VField (VStr k) v v Visible)
+superLookup :: Value -> Object -> Text -> EvalM Value
+superLookup selfVal@(VObj _ cache) obj key = do
+    (field, layer, nextSup) <- liftMaybe (NoSuchKey key) (Object.lookupField key obj)
+    case field ^. fieldVal of
+        VThunk compute ->
+            memoizeLookup cache layer key $
+                withObjectEnv selfVal nextSup compute
+        val -> forceWHNF val
+superLookup v _ _ = throwTypeMismatch "object" v
+{-# INLINE superLookup #-}
 
-data VField = VField
-  { -- |
-    fieldKey :: Value,
-    -- |
-    fieldValWHNF :: Value,
-    -- |
-    fieldVal :: Value,
-    -- |
-    fieldVis :: Visibility
-  }
-  deriving (Generic)
+isFinite :: Double -> Bool
+isFinite d = not (isNaN d || isInfinite d)
+{-# INLINE isFinite #-}
 
-type Fun = Value -> Eval Value
+exactIntegral :: (Integral a) => Double -> Maybe a
+exactIntegral d =
+    let !i = truncate d
+     in if fromIntegral i == d then Just i else Nothing
+{-# INLINE exactIntegral #-}
 
-type Object = HashMap Text VField
+doubleToIntegral :: forall a. (Integral a, Bounded a) => Double -> Maybe a
+doubleToIntegral d
+    | not (isFinite d) = Nothing
+    | d < fromIntegral (minBound @a) || d > fromIntegral (maxBound @a) = Nothing
+    | otherwise = exactIntegral d
+{-# INLINE doubleToIntegral #-}
 
-data Cell = Cell {cellVal :: Value, cellIsWHNF :: Bool}
-  deriving (Generic)
+isIntegral :: Double -> Bool
+isIntegral d =
+    not (isNaN d || isInfinite d)
+        && (abs d >= 4503599627370496 || fromIntegral (truncate d :: Int64) == d)
 
-type Ref = IORef Cell
+_Integer :: Prism' Value Integer
+_Integer = _VNum . prism' fromIntegral (\d -> if isFinite d then exactIntegral d else Nothing)
+{-# INLINE _Integer #-}
 
-instance HasVisibility VField where
-  visible VField {..} = fieldVis == Visible
-  forced VField {..} = fieldVis == Forced
-  hidden VField {..} = fieldVis == Hidden
+_Integral :: forall a. (Integral a, Bounded a) => Prism' Value a
+_Integral = _VNum . prism' fromIntegral doubleToIntegral
+{-# INLINE _Integral #-}
 
-class HasValue a where
-  inj :: a -> Value
-  proj :: Value -> Eval a
+_Scientific :: Prism' Value Scientific
+_Scientific = _VNum . prism' toRealFloat (\d -> if isFinite d then Just (fromFloatDigits d) else Nothing)
+{-# INLINE _Scientific #-}
 
-instance HasValue Value where
-  inj = id
-  proj = pure
+forceWHNF :: Value -> EvalM Value
+forceWHNF = \case
+    VIndir ref -> memoize ref
+    VThunk m -> m >>= forceWHNF
+    v -> pure v
 
-mkCell :: Value -> Cell
-mkCell v = Cell v False
+memoize :: IORef Value -> EvalM Value
+memoize ref =
+    liftIO (readIORef ref) >>= \case
+        VBlackhole -> throwE InfiniteRecursion
+        VThunk m -> do
+            liftIO (writeIORef ref VBlackhole)
+            val <- m >>= forceWHNF
+            liftIO (writeIORef ref val)
+            pure val
+        val -> pure val
 
-mkIndirV :: MonadIO m => Value -> m Value
-mkIndirV v = VIndir <$> allocate v
+memoizeLookup :: Cache -> Int -> Text -> EvalM Value -> EvalM Value
+memoizeLookup (Cache ref) !depth key compute = do
+    let !k = (depth, key)
+    m <- liftIO (readIORef ref)
+    cell <- case H.lookup k m of
+        Just c -> pure c
+        Nothing -> liftIO $ do
+            c <- newIORef (VThunk compute)
+            writeIORef ref $! H.insert k c m
+            pure c
+    memoize cell
 
-mkThunk :: Core -> Eval Value
-mkThunk c = VThunk c <$> view ctx
+mkFun :: Int -> (Value -> EvalM Value) -> Value
+mkFun !n g = VFun n go
+  where
+    go (Named k _ : _) = throwE (BadParam (T.pack k))
+    go args | length args < n = throwE (TooFewArgs n)
+    go [] = throwE (TooFewArgs n)
+    go [Pos x] = g x >>= forceWHNF
+    go (Pos x : rest) =
+        g x >>= forceWHNF >>= \case
+            VFun _ k -> k rest
+            v -> throwTypeMismatch "function" v
 
-allocate :: MonadIO m => Value -> m (IORef Cell)
-allocate = liftIO . newIORef . mkCell
+toString :: Value -> EvalM Text
+toString =
+    forceWHNF >=> \case
+        VStr s -> pure s
+        v -> T.show . ppJsonCompact <$> proj @JSON.Value v
+
+showTy :: Value -> Text
+showTy = \case
+    VNull -> "null"
+    VBool _ -> "boolean"
+    VNum _ -> "number"
+    VStr _ -> "string"
+    VArr _ -> "array"
+    VObj _ _ -> "object"
+    VFun _ _ -> "function"
+    VThunk _ -> "thunk"
+    VIndir _ -> "pointer"
+    VBlackhole -> "blackhole"
+
+primitiveEquals :: Value -> Value -> EvalM Bool
+primitiveEquals e1 e2 = do
+    v1 <- forceWHNF e1
+    v2 <- forceWHNF e2
+    case (v1, v2) of
+        (VNull, VNull) -> pure True
+        (VBool a, VBool b) -> pure (a == b)
+        (VStr a, VStr b) -> pure (a == b)
+        (VNum a, VNum b) -> pure (a == b)
+        _
+            | showTy v1 /= showTy v2 -> pure False
+            | otherwise -> throwE (StdError "primitiveEquals operates on primitive types ")
+
+equals :: Value -> Value -> EvalM Bool
+equals e1 e2 = do
+    v1 <- forceWHNF e1
+    v2 <- forceWHNF e2
+    go v1 v2
+  where
+    go (VArr a) (VArr b)
+        | V.length a == V.length b =
+            allM (\i -> equals (a V.! i) (b V.! i)) [0 .. V.length a - 1]
+        | otherwise = pure False
+    go (VObj a c1) (VObj b c2) = do
+        let keysA = Object.visibleKeys a
+            keysB = Object.visibleKeys b
+        if length keysA /= length keysB || HS.fromList keysA /= HS.fromList keysB
+            then pure False
+            else do
+                ok <- allM (uncurry checkAssertions) [(selfA, a), (selfB, b)]
+                if ok then allM compareField keysA else pure False
+      where
+        selfA = VObj a c1
+        selfB = VObj b c2
+        compareField k = do
+            va <- objectLookup selfA k
+            vb <- objectLookup selfB k
+            equals va vb
+    go a b = primitiveEquals a b
+
+    checkAssertions :: Value -> Object -> EvalM Bool
+    checkAssertions selfVal obj =
+        allM
+            ( \k ->
+                objectLookup selfVal k >>= \case
+                    VBool b -> pure b
+                    _ -> pure True
+            )
+            (Object.assertionKeys obj)
+
+compare :: Value -> Value -> EvalM Ordering
+compare (VNum a) (VNum b) = pure (P.compare a b)
+compare (VStr a) (VStr b) = pure (P.compare a b)
+compare (VArr a) (VArr b) = do
+    as <- mapM proj (V.toList a)
+    bs <- mapM proj (V.toList b)
+    go as bs
+  where
+    go [] [] = pure EQ
+    go [] _ = pure LT
+    go _ [] = pure GT
+    go (x : xs) (y : ys) = do
+        ord <- compare x y
+        case ord of
+            EQ -> go xs ys
+            _ -> pure ord
+compare v1 _ = throwTypeMismatch "number, string, or array" v1
+
+allM :: (Monad m, Foldable t) => (a -> m Bool) -> t a -> m Bool
+allM p = foldr (\x acc -> p x >>= \b -> if b then acc else pure False) (pure True)
+
+force :: Prism' Value a -> Value -> EvalM (Either Value a)
+force p = fmap (matching p) . forceWHNF
+{-# INLINE force #-}
+
+-- ---------------------------------------------------------------------------
+-- Inj / Proj type classes
+-- ---------------------------------------------------------------------------
+
+class Inj a where
+    inj :: a -> Value
+
+class Proj a where
+    proj :: Value -> EvalM a
+
+type HasValue a = (Inj a, Proj a)
+
+instance Inj Value where
+    inj = id
+    {-# INLINE inj #-}
+instance Proj Value where
+    proj = forceWHNF
+    {-# INLINE proj #-}
+
+instance Inj Bool where
+    inj = VBool
+    {-# INLINE inj #-}
+instance Proj Bool where
+    proj v = force _VBool v <?> expect "bool"
+    {-# INLINE proj #-}
+
+instance Inj Text where
+    inj = VStr
+    {-# INLINE inj #-}
+instance Proj Text where
+    proj v = force _VStr v <?> expect "string"
+    {-# INLINE proj #-}
+
+instance {-# OVERLAPPING #-} Inj [Char] where
+    inj = VStr . T.pack
+    {-# INLINE inj #-}
+instance {-# OVERLAPPING #-} Proj [Char] where
+    proj = fmap T.unpack . proj
+    {-# INLINE proj #-}
+
+instance Inj ByteString where
+    inj = VStr . decodeUtf8
+    {-# INLINE inj #-}
+instance Proj ByteString where
+    proj = fmap encodeUtf8 . proj
+    {-# INLINE proj #-}
+
+instance Inj Double where
+    inj = VNum
+    {-# INLINE inj #-}
+instance Proj Double where
+    proj v = force _VNum v <?> expect "number"
+    {-# INLINE proj #-}
+
+instance Inj Scientific where
+    inj = review _Scientific
+    {-# INLINE inj #-}
+instance Proj Scientific where
+    proj v = force _Scientific v <?> expect "number"
+    {-# INLINE proj #-}
+
+instance Inj Integer where
+    inj = review _Integer
+    {-# INLINE inj #-}
+instance Proj Integer where
+    proj v = force _Integer v <?> expect "integer"
+    {-# INLINE proj #-}
+
+instance {-# OVERLAPPABLE #-} (Integral a, Bounded a) => Inj a where
+    inj = review _Integral
+    {-# INLINE inj #-}
+instance {-# OVERLAPPABLE #-} (Integral a, Bounded a) => Proj a where
+    proj v = force _Integral v <?> expect "integer"
+    {-# INLINE proj #-}
+
+instance (Inj a) => Inj (Maybe a) where
+    inj = maybe VNull inj
+    {-# INLINE inj #-}
+instance (Proj a) => Proj (Maybe a) where
+    proj =
+        forceWHNF >=> \case
+            VNull -> pure Nothing
+            v -> Just <$> proj v
+
+instance Inj Object where
+    inj = VThunk . mkObj
+    {-# INLINE inj #-}
+instance Proj Object where
+    proj v = fst <$> (force _VObj v <?> expect "object")
+    {-# INLINE proj #-}
+
+instance (Inj a) => Inj (Vector a) where
+    inj = VArr . fmap inj
+    {-# INLINE inj #-}
+instance (Proj a) => Proj (Vector a) where
+    proj v = (force _VArr v <?> expect "array") >>= V.mapM proj
+    {-# INLINE proj #-}
+
+instance {-# OVERLAPPABLE #-} (Inj a) => Inj [a] where
+    inj = VArr . V.fromList . map inj
+    {-# INLINE inj #-}
+instance {-# OVERLAPPABLE #-} (Proj a) => Proj [a] where
+    proj v = (force _VArr v <?> expect "array") >>= traverse proj . V.toList
+    {-# INLINE proj #-}
+
+instance (Inj a) => Inj (HashMap Text a) where
+    inj = VThunk . mkObj . mkBaseObject . H.map (\v -> Field (inj v) Visible False)
+
+instance (Proj a) => Proj (HashMap Text a) where
+    proj =
+        forceWHNF >=> \case
+            v@(VObj obj _) -> do
+                pairs <- forM (Object.visibleKeys obj) $ \k -> do
+                    val <- proj =<< objectLookup v k
+                    pure (k, val)
+                pure (H.fromList pairs)
+            v -> throwTypeMismatch "object" v
+
+instance (Inj a) => Inj (EvalM a) where
+    inj = VThunk . fmap inj
+    {-# INLINE inj #-}
+
+class Arity a where
+    arityOf :: Int
+
+instance {-# OVERLAPPABLE #-} Arity a where
+    arityOf = 0
+    {-# INLINE arityOf #-}
+
+instance (Arity b) => Arity (a -> b) where
+    arityOf = 1 + arityOf @b
+    {-# INLINE arityOf #-}
+
+instance (Proj a, Inj r, Arity (a -> r)) => Inj (a -> r) where
+    inj f = mkFun (arityOf @(a -> r)) (fmap (inj . f) . proj)
+    {-# INLINE inj #-}
+
+instance (Inj a, Proj b) => Proj (a -> EvalM b) where
+    proj v = do
+        (_, f) <- force _VFun v <?> expect "function"
+        pure (\x -> f [Pos (inj x)] >>= proj)
+    {-# INLINE proj #-}
+
+instance (Inj a) => Inj (KeyMap.KeyMap a) where
+    inj = inj . KeyMap.toHashMapText
+    {-# INLINE inj #-}
+
+instance (Proj a) => Proj (KeyMap.KeyMap a) where
+    proj = fmap KeyMap.fromHashMapText . proj
+    {-# INLINE proj #-}
+
+instance Inj JSON.Value where
+    inj = \case
+        JSON.Null -> VNull
+        JSON.Bool b -> inj b
+        JSON.Number n -> inj n
+        JSON.String s -> inj s
+        JSON.Array a -> inj a
+        JSON.Object o -> inj o
+
+instance Proj JSON.Value where
+    proj =
+        forceWHNF >=> \case
+            VNull -> pure JSON.Null
+            VBool b -> pure (JSON.Bool b)
+            VStr s -> pure (JSON.String s)
+            v@(VNum _) -> JSON.Number <$> proj v
+            VArr a -> JSON.Array <$> V.mapM proj a
+            v@(VObj _ _) -> JSON.Object <$> proj v
+            VFun{} -> throwE (ManifestError "function")
+            _ -> throwE (ManifestError "impossible")
+
+liftF :: (Proj a, Inj b) => (a -> b) -> (Value -> EvalM Value)
+liftF f v = (inj $!) . f <$!> proj v
+{-# INLINE liftF #-}
+
+liftF2 :: (Proj a, Proj b, Inj c) => (a -> b -> c) -> Value -> Value -> EvalM Value
+liftF2 f v1 v2 = (inj $!) <$!> liftA2 f (proj v1) (proj v2)
+{-# INLINE liftF2 #-}
diff --git a/stdlib/std.jsonnet b/stdlib/std.jsonnet
--- a/stdlib/std.jsonnet
+++ b/stdlib/std.jsonnet
@@ -25,12 +25,15 @@
   local std = self,
   local id = function(x) x,
 
+  local go_only_function = error 'This function is only supported in go version of jsonnet. See https://github.com/google/go-jsonnet',
+
   isString(v):: std.type(v) == 'string',
   isNumber(v):: std.type(v) == 'number',
   isBoolean(v):: std.type(v) == 'boolean',
   isObject(v):: std.type(v) == 'object',
   isArray(v):: std.type(v) == 'array',
   isFunction(v):: std.type(v) == 'function',
+  isNull(v):: v == null,
 
   toString(a)::
     if std.type(a) == 'string' then a else '' + a,
@@ -125,7 +128,7 @@
     local aux(idx, ret, val) =
       if idx >= strLen then
         ret + [val]
-      else if str[idx : idx + cLen : 1] == c &&
+      else if str[idx:idx + cLen:1] == c &&
               (maxsplits == -1 || std.length(ret) < maxsplits) then
         aux(idx + cLen, ret + [val], '')
       else
@@ -140,7 +143,7 @@
     if maxsplits == -1 then
       std.splitLimit(str, c, -1)
     else
-      local revStr(str) = std.join('', std.reverse(str));
+      local revStr(str) = std.join('', std.reverse(std.stringChars(str)));
       std.map(function(e) revStr(e), std.reverse(std.splitLimit(revStr(str), revStr(c), maxsplits))),
 
   strReplace(str, from, to)::
@@ -204,20 +207,29 @@
     local invar =
       // loop invariant with defaults applied
       {
+        length: std.length(indexable),
         indexable: indexable,
         index:
-          if index == null then 0
-          else index,
+          if index == null
+          then 0
+          else
+            if index < 0
+            then std.max(0, self.length + index)
+            else index,
         end:
-          if end == null then std.length(indexable)
-          else end,
+          if end == null
+          then self.length
+          else
+            if end < 0
+            then self.length + end
+            else end,
         step:
-          if step == null then 1
+          if step == null
+          then 1
           else step,
-        length: std.length(indexable),
-        type: std.type(indexable),
+        type: std.type(indexable)
       };
-    assert invar.index >= 0 && invar.end >= 0 && invar.step >= 0 : 'got [%s:%s:%s] but negative index, end, and steps are not supported' % [invar.index, invar.end, invar.step];
+    assert invar.step >= 0 : 'got [%s:%s:%s] but negative steps are not supported' % [invar.index, invar.end, invar.step];
     assert step != 0 : 'got %s but step must be greater than 0' % step;
     assert std.isString(indexable) || std.isArray(indexable) : 'std.slice accepts a string or an array, but got: %s' % std.type(indexable);
     local build(slice, cur) =
@@ -250,6 +262,15 @@
     else
       error 'Operator % cannot be used on types ' + std.type(a) + ' and ' + std.type(b) + '.',
 
+  // this is the most precision that will fit in a f64
+  pi:: 3.14159265358979311600,
+
+  deg2rad(x):: x * std.pi / 180,
+  rad2deg(x):: x * 180 / std.pi,
+
+  log2(x):: std.log(x) / std.log(2),
+  log10(x):: std.log(x) / std.log(10),
+
   map(func, arr)::
     if !std.isFunction(func) then
       error ('std.map first param must be function, got ' + std.type(func))
@@ -278,9 +299,19 @@
     if !std.isFunction(func) then
       error ('std.flatMap first param must be function, got ' + std.type(func))
     else if std.isArray(arr) then
-      std.flattenArrays(std.makeArray(std.length(arr), function(i) func(arr[i])))
+      std.flattenArrays(std.makeArray(
+        std.length(arr), function(i)
+          local o = func(arr[i]);
+          if std.isArray(o) then o else
+            error ('std.flatMap on arrays, provided function must return an array, got ' + std.type(o))
+      ))
     else if std.isString(arr) then
-      std.join('', std.makeArray(std.length(arr), function(i) func(arr[i])))
+      std.join('', std.makeArray(
+        std.length(arr), function(i)
+          local o = func(arr[i]);
+          if std.isString(o) then o else
+            error ('std.flatMap on strings, provided function must return a string, got ' + std.type(o))
+      ))
     else error ('std.flatMap second param must be array / string, got ' + std.type(arr)),
 
   join(sep, arr)::
@@ -657,7 +688,7 @@
           error 'Format required number at '
                 + i + ', got ' + std.type(val)
         else
-          local exponent = std.floor(std.log(std.abs(val)) / std.log(10));
+          local exponent = if val != 0 then std.floor(std.log(std.abs(val)) / std.log(10)) else 0;
           if exponent < -4 || exponent >= fpprec then
             render_float_sci(val,
                              zp,
@@ -820,10 +851,14 @@
       std.map(map_func, std.filter(filter_func, arr)),
 
   assertEqual(a, b)::
+    // If the values are strings, escape them for printing.
+    // If not, they'll be JSON-stringified anyway by the later string concatenation.
+    local astr = if std.type(a) == 'string' then std.escapeStringJson(a) else a;
+    local bstr = if std.type(b) == 'string' then std.escapeStringJson(b) else b;
     if a == b then
       true
     else
-      error 'Assertion failed. ' + a + ' != ' + b,
+      error 'Assertion failed. ' + astr + ' != ' + bstr,
 
   abs(n)::
     if !std.isNumber(n) then
@@ -865,6 +900,12 @@
   flattenArrays(arrs)::
     std.foldl(function(a, b) a + b, arrs, []),
 
+  flattenDeepArray(value)::
+    if std.isArray(value) then
+      [y for x in value for y in std.flattenDeepArray(x)]
+    else
+      [value],
+
   manifestIni(ini)::
     local body_lines(body) =
       std.join([], [
@@ -891,7 +932,7 @@
     local
       escapeStringToml = std.escapeStringJson,
       escapeKeyToml(key) =
-        local bare_allowed = std.set(std.stringChars("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"));
+        local bare_allowed = std.set(std.stringChars('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'));
         if std.setUnion(std.set(std.stringChars(key)), bare_allowed) == bare_allowed then key else escapeStringToml(key),
       isTableArray(v) = std.isArray(v) && std.length(v) > 0 && std.all(std.map(std.isObject, v)),
       isSection(v) = std.isObject(v) || isTableArray(v),
@@ -917,19 +958,19 @@
             local separator = if inline then ' ' else '\n';
             local lines = ['[' + separator]
                           + std.join([',' + separator],
-                                    [
-                                      [new_indent + renderValue(v[i], indexedPath + [i], true, '')]
-                                      for i in range
-                                    ])
+                                     [
+                                       [new_indent + renderValue(v[i], indexedPath + [i], true, '')]
+                                       for i in range
+                                     ])
                           + [separator + (if inline then '' else cindent) + ']'];
             std.join('', lines)
         else if std.isObject(v) then
           local lines = ['{ ']
                         + std.join([', '],
-                                  [
-                                    [escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], true, '')]
-                                    for k in std.objectFields(v)
-                                  ])
+                                   [
+                                     [escapeKeyToml(k) + ' = ' + renderValue(v[k], indexedPath + [k], true, '')]
+                                     for k in std.objectFields(v)
+                                   ])
                         + [' }'];
           std.join('', lines),
       renderTableInternal(v, path, indexedPath, cindent) =
@@ -939,10 +980,11 @@
           if !isSection(v[k])
         ]);
         local sections = [std.join('\n', kvp)] + [
-          (if std.isObject(v[k]) then
-            renderTable(v[k], path + [k], indexedPath + [k], cindent)
-          else
-            renderTableArray(v[k], path + [k], indexedPath + [k], cindent)
+          (
+            if std.isObject(v[k]) then
+              renderTable(v[k], path + [k], indexedPath + [k], cindent)
+            else
+              renderTableArray(v[k], path + [k], indexedPath + [k], cindent)
           )
           for k in std.objectFields(v)
           if isSection(v[k])
@@ -956,8 +998,8 @@
         local range = std.range(0, std.length(v) - 1);
         local sections = [
           (cindent + '[[' + std.join('.', std.map(escapeKeyToml, path)) + ']]'
-          + (if v[i] == {} then '' else '\n')
-          + renderTableInternal(v[i], path, indexedPath + [i], cindent + indent))
+           + (if v[i] == {} then '' else '\n')
+           + renderTableInternal(v[i], path, indexedPath + [i], cindent + indent))
           for i in range
         ];
         std.join('\n\n', sections);
@@ -996,22 +1038,24 @@
 
   escapeStringBash(str_)::
     local str = std.toString(str_);
-    local trans(ch) =
-      if ch == "'" then
-        "'\"'\"'"
-      else
-        ch;
-    "'%s'" % std.join('', [trans(ch) for ch in std.stringChars(str)]),
+    "'%s'" % std.strReplace(str, "'", "'\"'\"'"),
 
   escapeStringDollars(str_)::
     local str = std.toString(str_);
-    local trans(ch) =
-      if ch == '$' then
-        '$$'
-      else
-        ch;
-    std.foldl(function(a, b) a + trans(b), std.stringChars(str), ''),
+    std.strReplace(str, '$', '$$'),
 
+  local xml_escapes = {
+    '<': '&lt;',
+    '>': '&gt;',
+    '&': '&amp;',
+    '"': '&quot;',
+    "'": '&apos;',
+  },
+
+  escapeStringXML(str_)::
+    local str = std.toString(str_);
+    std.join('', [std.get(xml_escapes, ch, ch) for ch in std.stringChars(str)]),
+
   manifestJson(value):: std.manifestJsonEx(value, '    '),
 
   manifestJsonMinified(value):: std.manifestJsonEx(value, '', '', ':'),
@@ -1064,11 +1108,24 @@
       // the risk of missing a permutation.
       local reserved = [
         // Boolean types taken from https://yaml.org/type/bool.html
-        'true', 'false', 'yes', 'no', 'on', 'off', 'y', 'n',
+        'true',
+        'false',
+        'yes',
+        'no',
+        'on',
+        'off',
+        'y',
+        'n',
         // Numerical words taken from https://yaml.org/type/float.html
-        '.nan', '-.inf', '+.inf', '.inf', 'null', 
+        '.nan',
+        '-.inf',
+        '+.inf',
+        '.inf',
+        'null',
         // Invalid keys that contain no invalid characters
-        '-', '---', '',
+        '-',
+        '---',
+        '',
       ];
       local bad = [word for word in reserved if word == std.asciiLower(key)];
       if std.length(bad) > 0 then
@@ -1108,7 +1165,7 @@
       local keySet = std.set(keyChars);
       local keySetLc = std.set(std.stringChars(keyLc));
       // Check for unsafe characters
-      if ! onlyChars(safeChars, keySet) then
+      if !onlyChars(safeChars, keySet) then
         false
       // Check for reserved words
       else if isReserved(key) then
@@ -1120,8 +1177,8 @@
            - has exactly 2 dashes
          are considered dates.
       */
-      else if onlyChars(dateChars, keySet) 
-          && std.length(std.findSubstr('-', key)) == 2 then
+      else if onlyChars(dateChars, keySet)
+              && std.length(std.findSubstr('-', key)) == 2 then
         false
       /* Check for integers.  Keys that meet all of the following:
            - all characters match [0-9_\-]
@@ -1129,7 +1186,7 @@
          are considered integers.
       */
       else if onlyChars(intChars, keySetLc)
-          && std.length(std.findSubstr('-', key)) < 2 then
+              && std.length(std.findSubstr('-', key)) < 2 then
         false
       /* Check for binary integers.  Keys that meet all of the following:
            - all characters match [0-9b_\-]
@@ -1138,8 +1195,8 @@
          are considered binary integers.
       */
       else if onlyChars(binChars, keySetLc)
-          && std.length(key) > 2
-          && typeMatch(key, '0b') then
+              && std.length(key) > 2
+              && typeMatch(key, '0b') then
         false
       /* Check for floats. Keys that meet all of the following:
            - all characters match [0-9e._\-]
@@ -1149,9 +1206,9 @@
          are considered floats.
       */
       else if onlyChars(floatChars, keySetLc)
-          && std.length(std.findSubstr('.', key)) == 1
-          && std.length(std.findSubstr('-', key)) < 3 
-          && std.length(std.findSubstr('e', keyLc)) < 2 then
+              && std.length(std.findSubstr('.', key)) == 1
+              && std.length(std.findSubstr('-', key)) < 3
+              && std.length(std.findSubstr('e', keyLc)) < 2 then
         false
       /* Check for hexadecimals.  Keys that meet all of the following:
            - all characters match [0-9a-fx_\-]
@@ -1160,10 +1217,10 @@
            - starts with (-)0x
          are considered hexadecimals.
       */
-      else if onlyChars(hexChars, keySetLc) 
-          && std.length(std.findSubstr('-', key)) < 2
-          && std.length(keyChars) > 2
-          && typeMatch(key, '0x') then
+      else if onlyChars(hexChars, keySetLc)
+              && std.length(std.findSubstr('-', key)) < 2
+              && std.length(keyChars) > 2
+              && typeMatch(key, '0x') then
         false
       // All checks pass. Key is safe for emission without quotes.
       else true;
@@ -1506,7 +1563,7 @@
     else
       patch,
 
-  get(o, f, default = null, inc_hidden = true)::
+  get(o, f, default=null, inc_hidden=true)::
     if std.objectHasEx(o, f, inc_hidden) then o[f] else default,
 
   objectFields(o)::
@@ -1527,6 +1584,12 @@
   objectValuesAll(o)::
     [o[k] for k in std.objectFieldsAll(o)],
 
+  objectKeysValues(o)::
+    [{ key: k, value: o[k] } for k in std.objectFields(o)],
+
+  objectKeysValuesAll(o)::
+    [{ key: k, value: o[k] } for k in std.objectFieldsAll(o)],
+
   equals(a, b)::
     local ta = std.type(a);
     local tb = std.type(b);
@@ -1614,7 +1677,7 @@
         true
       else
         local e = arr[idx];
-        assert std.isBoolean(e) : std.format('element "%s" of type %s is not a boolean', e, std.type(e));
+        assert std.isBoolean(e) : 'element "%s" of type %s is not a boolean' % [e, std.type(e)];
         if !e then
           false
         else
@@ -1629,7 +1692,7 @@
         false
       else
         local e = arr[idx];
-        assert std.isBoolean(e) : std.format('element "%s" of type %s is not a boolean', e, std.type(e));
+        assert std.isBoolean(e) : 'element "%s" of type %s is not a boolean' % [e, std.type(e)];
         if e then
           true
         else
@@ -1669,4 +1732,74 @@
   __array_less_or_equal(arr1, arr2):: std.__compare_array(arr1, arr2) <= 0,
   __array_greater_or_equal(arr1, arr2):: std.__compare_array(arr1, arr2) >= 0,
 
+  sum(arr):: std.foldl(function(a, b) a + b, arr, 0),
+
+  avg(arr)::
+    if std.length(arr) == 0 then
+      error 'Cannot calculate average of an empty array.'
+    else
+      std.sum(arr)/std.length(arr),
+
+  minArray(arr, keyF=id, onEmpty=error 'Expected at least one element in array. Got none')::
+    if std.length(arr) == 0 then
+      onEmpty
+    else
+      local minVal = arr[0];
+      local minFn(a, b) =
+        if std.__compare(keyF(a), keyF(b)) > 0 then
+          b
+        else
+          a;
+      std.foldl(minFn, arr, minVal),
+
+  maxArray(arr, keyF=id, onEmpty=error 'Expected at least one element in array. Got none')::
+    if std.length(arr) == 0 then
+      onEmpty
+    else
+      local maxVal = arr[0];
+      local maxFn(a, b) =
+        if std.__compare(keyF(a), keyF(b)) < 0 then
+          b
+        else
+          a;
+      std.foldl(maxFn, arr, maxVal),
+
+  xor(x, y):: x != y,
+
+  xnor(x, y):: x == y,
+
+  round(x):: std.floor(x + 0.5),
+
+  isEmpty(str):: std.length(str) == 0,
+
+  contains(arr, elem):: std.any([e == elem for e in arr]),
+
+  equalsIgnoreCase(str1, str2):: std.asciiLower(str1) == std.asciiLower(str2),
+
+  isEven(x):: std.round(x) % 2 == 0,
+  isOdd(x):: std.round(x) % 2 != 0,
+  isInteger(x):: std.round(x) == x,
+  isDecimal(x):: std.round(x) != x,
+  
+  removeAt(arr, at):: [
+    arr[i],
+    for i in std.range(0, std.length(arr) - 1)
+    if i != at
+  ],
+
+  remove(arr, elem):: 
+    local indexes = std.find(elem, arr);
+    if std.length(indexes) == 0
+    then
+      arr
+    else
+      std.removeAt(arr, indexes[0])
+  ,
+
+  sha1(str):: go_only_function,
+  sha256(str):: go_only_function,
+  sha512(str):: go_only_function,
+  sha3(str):: go_only_function,
+
+  trim(str):: std.stripChars(str, ' \t\n\f\r\u0085\u00A0'),
 }
diff --git a/test/Language/Jsonnet/Test/Golden.hs b/test/Language/Jsonnet/Test/Golden.hs
--- a/test/Language/Jsonnet/Test/Golden.hs
+++ b/test/Language/Jsonnet/Test/Golden.hs
@@ -1,19 +1,20 @@
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE TemplateHaskell #-}
 
--- |
 module Language.Jsonnet.Test.Golden where
 
-import qualified Data.ByteString.Lazy as LBS
-import qualified Data.Map.Strict as M
-import qualified Data.Text.IO as T (readFile)
-import Data.Text.Lazy
+import Data.ByteString.Lazy qualified as LBS
+import Data.Map.Strict qualified as M
+import Data.Text (Text)
+import Data.Text.IO qualified as T (readFile)
+import Data.Text.Lazy hiding (Text, show)
 import Data.Text.Lazy.Encoding (encodeUtf8)
 import Language.Jsonnet hiding (extVars)
-import Language.Jsonnet.Pretty (ppJson, prettyError)
-import Language.Jsonnet.Value
+import Language.Jsonnet.Pretty (ppJsonIndent, prettyError)
+import Language.Jsonnet.Std.Lib
+import Language.Jsonnet.Value (inj)
 import Prettyprinter (Doc)
-import System.FilePath (replaceExtension, takeBaseName)
+import System.FilePath (replaceExtension, takeDirectory, takeFileName)
 import System.IO.Unsafe (unsafePerformIO)
 import Test.Tasty (TestTree, testGroup)
 import Test.Tasty.Golden (findByExtension, goldenVsString)
@@ -21,31 +22,41 @@
 render :: (a -> Doc ann) -> a -> LBS.ByteString
 render printer = encodeUtf8 . pack . show . printer
 
-run :: Config -> IO LBS.ByteString
-run conf = do
-  prog <- T.readFile (fname conf)
-  outp <- interpret conf prog
-  pure (either (render prettyError) (render (ppJson 4)) outp)
 
+run :: FilePath -> Config -> IO LBS.ByteString
+run fp conf = do
+    prog <- T.readFile fp
+    outp <- interpret conf prog
+    pure (either (render prettyError) (render (ppJsonIndent 4)) outp)
+
 -- Adapted from the C++ test suite
 extVars :: ExtVars
 extVars =
-  ExtVars $
-    M.fromList
-      [ ("var1", VStr "test"),
-        ("var2", unsafePerformIO $ interpretExtVar (ExtVar ExtCode (Inline "{x:1,y:2}")))
-      ]
+    ExtVars $
+        M.fromList
+            [ ("var1", VStr "test")
+            , ("var2", unsafePerformIO $ interpretExtVar (ExtVar ExtCode (Inline "{x:1,y:2}")))
+            ]
 
+testUserFuncs :: UserFuncs
+testUserFuncs =
+    UserFuncs $
+        M.fromList
+            [ ("concat", inj ((<>) @Text))
+            , ("add", inj ((+) @Int))
+            ]
+
 goldenTests :: IO TestTree
 goldenTests = do
-  jsonnetFiles <- findByExtension [".jsonnet"] "./test/golden"
-  return $
-    testGroup
-      "Jsonnet golden tests"
-      [ goldenVsString
-          (takeBaseName jsonnetFile) -- test name
-          goldenFile -- golden file path
-          (run $ Config jsonnetFile extVars)
-        | jsonnetFile <- jsonnetFiles,
-          let goldenFile = replaceExtension jsonnetFile ".golden"
-      ]
+    jsonnetFiles <- findByExtension [".jsonnet"] "./test/golden"
+    return $
+        testGroup
+            "Jsonnet golden tests"
+            [ goldenVsString
+                fileName
+                goldenFile -- golden file path
+                (run jsonnetFile $ Config fileName extVars testUserFuncs [takeDirectory jsonnetFile])
+            | jsonnetFile <- jsonnetFiles
+            , let goldenFile = replaceExtension jsonnetFile ".golden"
+                  fileName = takeFileName jsonnetFile
+            ]
diff --git a/test/Language/Jsonnet/Test/JPath.hs b/test/Language/Jsonnet/Test/JPath.hs
new file mode 100644
--- /dev/null
+++ b/test/Language/Jsonnet/Test/JPath.hs
@@ -0,0 +1,59 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+module Language.Jsonnet.Test.JPath (jpathTests) where
+
+import Data.Text.IO qualified as T
+import Language.Jsonnet
+import Language.Jsonnet.Pretty
+import System.Directory (createDirectory)
+import System.FilePath ((</>))
+import System.IO.Temp (withSystemTempDirectory)
+import Test.Tasty
+import Test.Tasty.HUnit
+
+run :: Config -> IO String
+run conf = do
+    prog <- T.readFile (fname conf)
+    outp <- interpret conf prog
+    pure (either show (show . ppJsonIndent 4) outp)
+
+jpathTests :: TestTree
+jpathTests =
+    testGroup
+        "JPath Import Resolution"
+        [ testCase "Local directory beats JPath" $
+            withSystemTempDirectory "jsonnet" $ \tmp -> do
+                writeFile (tmp </> "main.jsonnet") "import 'target.jsonnet'"
+                writeFile (tmp </> "target.jsonnet") "\"local\""
+
+                createDirectory (tmp </> "lib")
+                writeFile (tmp </> "lib" </> "target.jsonnet") "\"jpath\""
+
+                let conf = defaultConfig{fname = tmp </> "main.jsonnet", jpaths = [tmp </> "lib"]}
+                result <- run conf
+                result @?= "\"local\""
+        , testCase "Falls back to JPath when not in local directory" $
+            withSystemTempDirectory "jsonnet" $ \tmp -> do
+                writeFile (tmp </> "main.jsonnet") "import 'target.jsonnet'"
+
+                createDirectory (tmp </> "lib")
+                writeFile (tmp </> "lib" </> "target.jsonnet") "\"jpath\""
+
+                let conf = defaultConfig{fname = tmp </> "main.jsonnet", jpaths = [tmp </> "lib"]}
+                result <- run conf
+                result @?= "\"jpath\""
+        , testCase "Right-most CLI arg (left-most in list) wins" $
+            withSystemTempDirectory "jsonnet" $ \tmp -> do
+                writeFile (tmp </> "main.jsonnet") "import 'target.jsonnet'"
+
+                createDirectory (tmp </> "lib1")
+                writeFile (tmp </> "lib1" </> "target.jsonnet") "\"lib1\""
+
+                createDirectory (tmp </> "lib2")
+                writeFile (tmp </> "lib2" </> "target.jsonnet") "\"lib2\""
+
+                -- lib2 is listed first, simulating the right-most CLI argument
+                let conf = defaultConfig{fname = tmp </> "main.jsonnet", jpaths = [tmp </> "lib2", tmp </> "lib1"]}
+                result <- run conf
+                result @?= "\"lib2\""
+        ]
diff --git a/test/Language/Jsonnet/Test/Roundtrip.hs b/test/Language/Jsonnet/Test/Roundtrip.hs
--- a/test/Language/Jsonnet/Test/Roundtrip.hs
+++ b/test/Language/Jsonnet/Test/Roundtrip.hs
@@ -1,18 +1,16 @@
 {-# LANGUAGE OverloadedStrings #-}
 
--- |
 module Language.Jsonnet.Test.Roundtrip where
 
 import Data.Fix
-import Data.Functor.Sum
 import Data.Text (Text)
 import Hedgehog
-import qualified Hedgehog.Gen as Gen
-import qualified Hedgehog.Range as Range
+import Hedgehog.Gen qualified as Gen
+import Hedgehog.Range qualified as Range
 import Language.Jsonnet.Annotate
 import Language.Jsonnet.Common
 import Language.Jsonnet.Error (Error)
-import qualified Language.Jsonnet.Parser as Parser
+import Language.Jsonnet.Parser qualified as Parser
 import Language.Jsonnet.Pretty
 import Language.Jsonnet.Syntax
 import Prettyprinter
@@ -26,30 +24,31 @@
     (`notElem` Parser.reservedKeywords)
     (Gen.string (Range.constant 2 4) Gen.alpha)
 
-genText :: Gen Text
+genText :: Gen Data.Text.Text
 genText = Gen.text (Range.constant 2 4) Gen.alpha
 
 genField :: Gen a -> Gen (EField a)
 genField a = EField <$> a <*> a <*> pure True <*> Gen.enumBounded <*> Gen.bool
 
-genObject :: Gen (Fix ExprF')
+genObject :: Gen (Fix ExprF)
 genObject =
   Fix
     <$> ( mkObjectF
             <$> Gen.list (Range.linear 0 10) (genField genExpr)
             <*> Gen.list (Range.linear 0 10) ((,) <$> genString <*> genExpr)
+            <*> Gen.list (Range.linear 0 10) genAssert'
         )
 
-genArray :: Gen (Fix ExprF')
+genArray :: Gen (Fix ExprF)
 genArray = Fix <$> (mkArrayF <$> Gen.list (Range.linear 0 10) genExpr)
 
-genIf :: Gen (Fix ExprF')
+genIf :: Gen (Fix ExprF)
 genIf = Gen.subterm2 genExpr genExpr (\a b -> Fix (mkIfF a b))
 
-genIfElse :: Gen (Fix ExprF')
+genIfElse :: Gen (Fix ExprF)
 genIfElse = Gen.subterm3 genExpr genExpr genExpr (\a b c -> Fix (mkIfElseF a b c))
 
-genSlice :: Gen (Fix ExprF')
+genSlice :: Gen (Fix ExprF)
 genSlice =
   Fix
     <$> ( mkSliceF
@@ -59,28 +58,25 @@
             <*> Gen.maybe genExpr
         )
 
-genError :: Gen (Fix ExprF')
+genError :: Gen (Fix ExprF)
 genError = Fix . mkErrorF <$> genExpr
 
-genImport :: Gen (Fix ExprF')
+genImport :: Gen (Fix ExprF)
 genImport = Fix . mkImportF <$> genString
 
-genIndex :: Gen (Fix ExprF')
+genIndex :: Gen (Fix ExprF)
 genIndex = Gen.subterm2 genExpr genExpr (\a b -> Fix (mkIndexF a b))
 
-genLookup :: Gen (Fix ExprF')
+genLookup :: Gen (Fix ExprF)
 genLookup = Fix <$> (mkLookupF <$> genIdent <*> genString)
 
-genAssert :: Gen (Fix ExprF')
-genAssert =
-  Fix
-    <$> ( mkAssertF
-            <$> genExpr
-            <*> Gen.maybe genExpr
-            <*> genExpr
-        )
+genAssert :: Gen (Fix ExprF)
+genAssert = Fix <$> (mkAssertF <$> genAssert' <*> genExpr)
 
-genLocal :: Gen (Fix ExprF')
+genAssert' :: Gen (Assert (Fix ExprF))
+genAssert' = Assert <$> genExpr <*> Gen.maybe genExpr
+
+genLocal :: Gen (Fix ExprF)
 genLocal =
   Fix
     <$> ( mkLocalF
@@ -88,10 +84,10 @@
             <*> genExpr
         )
 
-genLitStr :: Gen (Fix ExprF')
+genLitStr :: Gen (Fix ExprF)
 genLitStr = Fix <$> (mkTextF <$> genText)
 
-genLiteral :: Gen (Fix ExprF')
+genLiteral :: Gen (Fix ExprF)
 genLiteral =
   Gen.choice
     [ pure (Fix mkNullF),
@@ -106,12 +102,13 @@
 genArgs :: Gen a -> Gen (Args a)
 genArgs a =
   Args
-    <$> Gen.list (Range.linear 0 10) (genArg a) <*> pure Lazy
+    <$> Gen.list (Range.linear 0 10) (genArg a)
+    <*> pure Lazy
 
-genApply :: Gen (Fix ExprF')
+genApply :: Gen (Fix ExprF)
 genApply = Fix <$> (mkApplyF <$> genExpr <*> genArgs genExpr)
 
-genFunc :: Gen (Fix ExprF')
+genFunc :: Gen (Fix ExprF)
 genFunc =
   Fix
     <$> ( mkFunF
@@ -119,19 +116,19 @@
             <*> genExpr
         )
 
-genIdent :: Gen (Fix ExprF')
+genIdent :: Gen (Fix ExprF)
 genIdent = Fix . mkIdentF <$> genString
 
-genUnyOp :: Gen (Fix ExprF')
-genUnyOp = Fix <$> (InL <$> (EUnyOp <$> Gen.enum Compl Minus <*> genExpr))
+genUnyOp :: Gen (Fix ExprF)
+genUnyOp = Fix <$> (EUnyOp <$> Gen.enum Compl Minus <*> genExpr)
 
-genBinOp :: Gen (Fix ExprF')
-genBinOp = Fix <$> (InL <$> (EBinOp <$> Gen.enum Add In <*> genExpr <*> genExpr))
+genBinOp :: Gen (Fix ExprF)
+genBinOp = Fix <$> (EBinOp <$> Gen.enum Add In <*> genExpr <*> genExpr)
 
 genCompSpec :: Gen a -> Gen (CompSpec a)
-genCompSpec a = CompSpec <$> genString <*> a <*> Gen.maybe a
+genCompSpec a = CompSpec <$> genString <*> a <*> Gen.list (Range.linear 0 10) a
 
-genArrComp :: Gen (Fix ExprF')
+genArrComp :: Gen (Fix ExprF)
 genArrComp =
   Fix
     <$> ( mkArrCompF
@@ -139,7 +136,7 @@
             <*> Gen.nonEmpty (Range.linear 0 10) (genCompSpec genExpr)
         )
 
-genObjComp :: Gen (Fix ExprF')
+genObjComp :: Gen (Fix ExprF)
 genObjComp =
   Fix
     <$> ( mkObjCompF
@@ -148,7 +145,7 @@
             <*> Gen.nonEmpty (Range.linear 0 10) (genCompSpec genExpr)
         )
 
-genExpr :: Gen (Fix ExprF')
+genExpr :: Gen (Fix ExprF)
 genExpr =
   Gen.recursive
     Gen.choice
@@ -176,13 +173,13 @@
       genArrComp
     ]
 
-printExpr :: Fix ExprF' -> Text
+printExpr :: Fix ExprF -> Data.Text.Text
 printExpr =
   renderStrict
     . layoutPretty defaultLayoutOptions
-    . prettyFixExprF'
+    . prettyFixExprF
 
-parseExpr :: Text -> Either Error (Fix ExprF')
+parseExpr :: Data.Text.Text -> Either Error (Fix ExprF)
 parseExpr = fmap forget' . Parser.parse ""
 
 prop_roundtrip :: Property
diff --git a/test/Main.hs b/test/Main.hs
--- a/test/Main.hs
+++ b/test/Main.hs
@@ -1,8 +1,8 @@
--- |
 module Main where
 
 import Language.Jsonnet.Test.Golden
 import Language.Jsonnet.Test.Roundtrip
+import Language.Jsonnet.Test.JPath
 import Test.Tasty
 
 main :: IO ()
@@ -12,5 +12,6 @@
     testGroup
       "tests"
       [ testRoundtripGroup,
-        goldenTests'
+        goldenTests',
+        jpathTests
       ]
diff --git a/test/golden/assert.golden b/test/golden/assert.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/assert.golden
@@ -0,0 +1,1 @@
+true
diff --git a/test/golden/assert.jsonnet b/test/golden/assert.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/assert.jsonnet
@@ -0,0 +1,22 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+assert true;
+assert 10 > 5;
+
+std.assertEqual(assert 10 > 5; 32, 32) &&
+
+true
diff --git a/test/golden/chained-ifspec.golden b/test/golden/chained-ifspec.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/chained-ifspec.golden
@@ -0,0 +1,3 @@
+[
+    2
+]
diff --git a/test/golden/chained-ifspec.jsonnet b/test/golden/chained-ifspec.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/chained-ifspec.jsonnet
@@ -0,0 +1,1 @@
+[x for x in [1,2,3] if x > 1 if x < 3]
diff --git a/test/golden/error-examples.golden b/test/golden/error-examples.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error-examples.golden
@@ -0,0 +1,4 @@
+{
+    "f": 1,
+    "g": 2
+}
diff --git a/test/golden/error-examples.jsonnet b/test/golden/error-examples.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error-examples.jsonnet
@@ -0,0 +1,5 @@
+{
+    assert self.f < self.g : 'wat',
+    f: 1,
+    g: 2,
+}
diff --git a/test/golden/error.01.golden b/test/golden/error.01.golden
--- a/test/golden/error.01.golden
+++ b/test/golden/error.01.golden
@@ -1,5 +1,5 @@
 Runtime error: foo
-  ./test/golden/error.01.jsonnet:17:29-40 function <bananas>
-  ./test/golden/error.01.jsonnet:18:29-36 function <oranges>
-  ./test/golden/error.01.jsonnet:19:28-35 function <apples>
-  ./test/golden/error.01.jsonnet:20:1-7 
+  error.01.jsonnet:17:29-40 function <bananas>
+  error.01.jsonnet:18:29-36 function <oranges>
+  error.01.jsonnet:19:28-35 function <apples>
+  error.01.jsonnet:20:1-7 
diff --git a/test/golden/error.02.golden b/test/golden/error.02.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.02.golden
@@ -0,0 +1,2 @@
+Runtime error: Foo.
+  error.02.jsonnet:17:1-18:1 
diff --git a/test/golden/error.02.jsonnet b/test/golden/error.02.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.02.jsonnet
@@ -0,0 +1,17 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+error 'Foo.'
diff --git a/test/golden/error.03.golden b/test/golden/error.03.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.03.golden
@@ -0,0 +1,2 @@
+Runtime error: foo
+  error.03.jsonnet:17:21-33 
diff --git a/test/golden/error.03.jsonnet b/test/golden/error.03.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.03.jsonnet
@@ -0,0 +1,18 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+local ErrObj = { x: error 'foo' };
+ErrObj.x
diff --git a/test/golden/error.04.golden b/test/golden/error.04.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.04.golden
@@ -0,0 +1,2 @@
+Runtime error: foo
+  error.04.jsonnet:17:21-33 
diff --git a/test/golden/error.04.jsonnet b/test/golden/error.04.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.04.jsonnet
@@ -0,0 +1,18 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+local ErrObj = { x: error 'foo' };
+ErrObj
diff --git a/test/golden/error.05.golden b/test/golden/error.05.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.05.golden
@@ -0,0 +1,2 @@
+Runtime error: foo
+  error.05.jsonnet:17:21-33 
diff --git a/test/golden/error.05.jsonnet b/test/golden/error.05.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.05.jsonnet
@@ -0,0 +1,19 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+local ErrObj = { x: error 'foo' };
+local WrapperObj = { y: ErrObj };
+WrapperObj
diff --git a/test/golden/error.06.golden b/test/golden/error.06.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.06.golden
@@ -0,0 +1,3 @@
+Runtime error: divide by zero exception
+  error.06.jsonnet:17:13-18 function <f>
+  error.06.jsonnet:19:1-2 
diff --git a/test/golden/error.06.jsonnet b/test/golden/error.06.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.06.jsonnet
@@ -0,0 +1,19 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+local err = 1 / 0;
+local f = function() err;
+f() + 1
diff --git a/test/golden/error.07.golden b/test/golden/error.07.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.07.golden
@@ -0,0 +1,3 @@
+Runtime error: sarcasm
+  error.07.jsonnet:18:31-46 function <third>
+  error.07.jsonnet:18:15-20 
diff --git a/test/golden/error.07.jsonnet b/test/golden/error.07.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.07.jsonnet
@@ -0,0 +1,19 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+local third = function(arr) arr[3];
+local toxic = third([0, 1, 2, error 'sarcasm', 4, 5]);
+toxic + 1
diff --git a/test/golden/error.08.golden b/test/golden/error.08.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.08.golden
@@ -0,0 +1,2 @@
+Runtime error: {"a": 1, "b": 2, "c": 3}
+  error.08.jsonnet:18:1-19:1 
diff --git a/test/golden/error.08.jsonnet b/test/golden/error.08.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.08.jsonnet
@@ -0,0 +1,18 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+local x = { a: 1, b: 2, c: self.a + self.b };
+error x
diff --git a/test/golden/error.array_index_string.golden b/test/golden/error.array_index_string.golden
--- a/test/golden/error.array_index_string.golden
+++ b/test/golden/error.array_index_string.golden
@@ -1,2 +1,2 @@
 Runtime error: invalid index: array index was not integer
-  ./test/golden/error.array_index_string.jsonnet:14:1-15:1 
+  error.array_index_string.jsonnet:14:1-15:1 
diff --git a/test/golden/error.array_large_index.golden b/test/golden/error.array_large_index.golden
--- a/test/golden/error.array_large_index.golden
+++ b/test/golden/error.array_large_index.golden
@@ -1,2 +1,2 @@
 Runtime error: index out of bounds: 18446744073709552000
-  ./test/golden/error.array_large_index.jsonnet:14:1-18 
+  error.array_large_index.jsonnet:14:1-18 
diff --git a/test/golden/error.assert.fail1.golden b/test/golden/error.assert.fail1.golden
--- a/test/golden/error.assert.fail1.golden
+++ b/test/golden/error.assert.fail1.golden
@@ -1,2 +1,2 @@
 Runtime error: x should be equal to y
-  ./test/golden/error.assert.fail1.jsonnet:17:1-20:1 
+  error.assert.fail1.jsonnet:17:1-20:1 
diff --git a/test/golden/error.assert.fail2.golden b/test/golden/error.assert.fail2.golden
--- a/test/golden/error.assert.fail2.golden
+++ b/test/golden/error.assert.fail2.golden
@@ -1,3 +1,3 @@
 Runtime error: a must be bigger than b
-  ./test/golden/error.assert.fail2.jsonnet:2:3-3:8 function <subtract>
-  ./test/golden/error.assert.fail2.jsonnet:5:1-10 
+  error.assert.fail2.jsonnet:2:3-3:8 function <subtract>
+  error.assert.fail2.jsonnet:5:1-10 
diff --git a/test/golden/error.assert_equal_obj.golden b/test/golden/error.assert_equal_obj.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.assert_equal_obj.golden
@@ -0,0 +1,2 @@
+Runtime error: Assertion failed. {"a": 1} != {"b": 1}
+  error.assert_equal_obj.jsonnet:17:1-16 
diff --git a/test/golden/error.assert_equal_obj.jsonnet b/test/golden/error.assert_equal_obj.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.assert_equal_obj.jsonnet
@@ -0,0 +1,17 @@
+/*
+Copyright 2024 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+std.assertEqual({ a: 1 }, { b: 1 })
diff --git a/test/golden/error.computed_field_scope.golden b/test/golden/error.computed_field_scope.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.computed_field_scope.golden
@@ -0,0 +1,2 @@
+Runtime error: variable 'x' is not defined
+  error.computed_field_scope.jsonnet:17:21-22 
diff --git a/test/golden/error.computed_field_scope.jsonnet b/test/golden/error.computed_field_scope.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.computed_field_scope.jsonnet
@@ -0,0 +1,17 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+{ local x = 'bar', [x]: 1 }
diff --git a/test/golden/error.divide-zero.golden b/test/golden/error.divide-zero.golden
--- a/test/golden/error.divide-zero.golden
+++ b/test/golden/error.divide-zero.golden
@@ -1,2 +1,2 @@
 Runtime error: divide by zero exception
-  ./test/golden/error.divide-zero.jsonnet:14:1-15:1 
+  error.divide-zero.jsonnet:14:1-15:1 
diff --git a/test/golden/error.duplicate_local_var.golden b/test/golden/error.duplicate_local_var.golden
--- a/test/golden/error.duplicate_local_var.golden
+++ b/test/golden/error.duplicate_local_var.golden
@@ -1,2 +1,2 @@
 Static error: duplicate local var 'a'
-  ./test/golden/error.duplicate_local_var.jsonnet:1:1-3:1
+  error.duplicate_local_var.jsonnet:1:1-3:1
diff --git a/test/golden/error.field-not-exist.golden b/test/golden/error.field-not-exist.golden
--- a/test/golden/error.field-not-exist.golden
+++ b/test/golden/error.field-not-exist.golden
@@ -1,2 +1,2 @@
 Runtime error: no such key: y
-  ./test/golden/error.field-not-exist.jsonnet:14:1-15:1 
+  error.field-not-exist.jsonnet:14:1-15:1 
diff --git a/test/golden/error.function_arg_positional_after_named.golden b/test/golden/error.function_arg_positional_after_named.golden
--- a/test/golden/error.function_arg_positional_after_named.golden
+++ b/test/golden/error.function_arg_positional_after_named.golden
@@ -1,2 +1,2 @@
 Static error: positional after named argument
-  ./test/golden/error.function_arg_positional_after_named.jsonnet:16:1-4
+  error.function_arg_positional_after_named.jsonnet:16:1-4
diff --git a/test/golden/error.function_duplicate_param.golden b/test/golden/error.function_duplicate_param.golden
--- a/test/golden/error.function_duplicate_param.golden
+++ b/test/golden/error.function_duplicate_param.golden
@@ -1,2 +1,2 @@
-Parse error: foo.bar (No such file or directory)
-    ./test/golden/error.function_duplicate_param.jsonnet:14:13-29
+Static error: duplicate parameter 'x'
+  error.function_duplicate_param.jsonnet:16:9-17:1
diff --git a/test/golden/error.function_no_such_param.golden b/test/golden/error.function_no_such_param.golden
--- a/test/golden/error.function_no_such_param.golden
+++ b/test/golden/error.function_no_such_param.golden
@@ -1,3 +1,3 @@
 Runtime error: function has no parameter 'b'
-  ./test/golden/error.function_no_such_param.jsonnet:2:1-3 function <id>
-  ./test/golden/error.function_no_such_param.jsonnet:2:1-3 
+  error.function_no_such_param.jsonnet:2:1-3 function <id>
+  error.function_no_such_param.jsonnet:2:1-3 
diff --git a/test/golden/error.function_too_many_args.golden b/test/golden/error.function_too_many_args.golden
--- a/test/golden/error.function_too_many_args.golden
+++ b/test/golden/error.function_too_many_args.golden
@@ -1,3 +1,3 @@
 Runtime error: too many args, function has 2 parameter(s)
-  ./test/golden/error.function_too_many_args.jsonnet:16:1-4 function <foo>
-  ./test/golden/error.function_too_many_args.jsonnet:16:1-4 
+  error.function_too_many_args.jsonnet:16:1-4 function <foo>
+  error.function_too_many_args.jsonnet:16:1-4 
diff --git a/test/golden/error.index-out-of-bounds.golden b/test/golden/error.index-out-of-bounds.golden
--- a/test/golden/error.index-out-of-bounds.golden
+++ b/test/golden/error.index-out-of-bounds.golden
@@ -1,2 +1,2 @@
 Runtime error: index out of bounds: 100
-  ./test/golden/error.index-out-of-bounds.jsonnet:3:10-17 
+  error.index-out-of-bounds.jsonnet:3:10-17 
diff --git a/test/golden/error.invalid-key.golden b/test/golden/error.invalid-key.golden
--- a/test/golden/error.invalid-key.golden
+++ b/test/golden/error.invalid-key.golden
@@ -1,2 +1,2 @@
 Runtime error: type mismatch: expected string but got number
-  ./test/golden/error.invalid-key.jsonnet:1:1-6:1 
+  error.invalid-key.jsonnet:1:1-6:1 
diff --git a/test/golden/error.obj_assert.fail1.golden b/test/golden/error.obj_assert.fail1.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.obj_assert.fail1.golden
@@ -0,0 +1,2 @@
+Runtime error: Assertion failed
+  error.obj_assert.fail1.jsonnet:20:1-50 
diff --git a/test/golden/error.obj_assert.fail1.jsonnet b/test/golden/error.obj_assert.fail1.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.obj_assert.fail1.jsonnet
@@ -0,0 +1,22 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+local x = 'foo';
+local y = 'bar';
+
+{ assert true, assert x == y, x: 1 } == { x: 1 } &&
+
+true
diff --git a/test/golden/error.obj_assert.fail2.golden b/test/golden/error.obj_assert.fail2.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.obj_assert.fail2.golden
@@ -0,0 +1,2 @@
+Runtime error: foo was not equal to bar
+  error.obj_assert.fail2.jsonnet:20:1-86 
diff --git a/test/golden/error.obj_assert.fail2.jsonnet b/test/golden/error.obj_assert.fail2.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.obj_assert.fail2.jsonnet
@@ -0,0 +1,22 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+local x = 'foo';
+local y = 'bar';
+
+{ assert true, assert x == y : '%s was not equal to %s' % [x, y], x: 1 } == { x: 1 } &&
+
+true
diff --git a/test/golden/error.parse.object_local_clash.golden b/test/golden/error.parse.object_local_clash.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/error.parse.object_local_clash.golden
@@ -0,0 +1,2 @@
+Static error: duplicate local var 'x'
+  error.parse.object_local_clash.jsonnet:17:1-18:1
diff --git a/test/golden/error.parse.object_local_clash.jsonnet b/test/golden/error.parse.object_local_clash.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/error.parse.object_local_clash.jsonnet
@@ -0,0 +1,17 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+{ local x=10, local x=20 }
diff --git a/test/golden/error.sanity.golden b/test/golden/error.sanity.golden
--- a/test/golden/error.sanity.golden
+++ b/test/golden/error.sanity.golden
@@ -1,3 +1,2 @@
 Runtime error: Assertion failed. 1 != 2
-  ./test/golden/error.sanity.jsonnet:14:1-16 function <anonymous>
-  ./test/golden/error.sanity.jsonnet:14:1-16 
+  error.sanity.jsonnet:14:1-16 
diff --git a/test/golden/importstr-nonexistent.golden b/test/golden/importstr-nonexistent.golden
--- a/test/golden/importstr-nonexistent.golden
+++ b/test/golden/importstr-nonexistent.golden
@@ -1,2 +1,2 @@
-Parse error: this file does not exist (No such file or directory)
-    ./test/golden/importstr-nonexistent.jsonnet:1:1-37
+Runtime error: import error: Could not resolve import path 'this file does not exist'
+  importstr-nonexistent.jsonnet:1:1-37 
diff --git a/test/golden/invariant.golden b/test/golden/invariant.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/invariant.golden
@@ -0,0 +1,1 @@
+true
diff --git a/test/golden/invariant.jsonnet b/test/golden/invariant.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/invariant.jsonnet
@@ -0,0 +1,76 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+std.assertEqual({}, { assert true, assert true }) &&
+std.assertEqual({}, { assert true, assert 1 == 1 }) &&
+std.assertEqual({ assert true, assert 1 == 1 }, {}) &&
+std.assertEqual({ assert 1 == 1 }, {}) &&
+std.assertEqual({ assert true, f: 1 }.f, 1) &&
+std.assertEqual({ assert self.f == 1, f: 1 }.f, 1) &&
+std.assertEqual({ assert self.f == g, f: 1, local g = 1 }.f, 1) &&
+
+local x = { assert x.f == y.f, f: 1 },
+      y = { assert x.f == y.f, f: 1 };
+
+std.assertEqual(x.f, y.f) &&
+
+
+local Mixin1 = {
+  assert self.x > 0,
+  x: super.x,
+};
+
+std.assertEqual({ x: 1 } + Mixin1, { x: 1 }) &&
+
+local Mixin2 = {
+  assert self.x > super.x,
+  x+: self.increment,
+  increment:: 1,
+};
+
+std.assertEqual({ x: 1 } + Mixin2, { x: 2 }) &&
+
+//local Template = {
+//  assert self == output,
+//  local template = self,
+//  local output = {
+//    str: '%d %d' % [template.x, template.y],
+//  },
+//  x:: error 'Must set x',
+//  y:: error 'Must set y',
+//
+//  str: output.str,
+//};
+
+//std.assertEqual(Template { x: 1, y: 2 }, { str: '1 2' }) &&
+
+std.assertEqual(std.type({ assert false }), 'object') &&
+
+std.assertEqual(std.length({ assert false }), 0) &&
+
+std.assertEqual(std.objectHas({ assert false, f: 3 }, 'f'), true) &&
+std.assertEqual(std.objectHas({ assert false, f: 3, g:: 3 }, 'g'), false) &&
+std.assertEqual(std.objectHas({ assert false, f: 3, g:: 3 }, 'h'), false) &&
+
+std.assertEqual(std.objectFields({ assert false, f: 3, g:: 3 }), ['f']) &&
+
+std.assertEqual(std.objectHasAll({ assert false, f: 3 }, 'f'), true) &&
+std.assertEqual(std.objectHasAll({ assert false, f: 3, g:: 3 }, 'g'), true) &&
+std.assertEqual(std.objectHasAll({ assert false, f: 3, g:: 3 }, 'h'), false) &&
+
+std.assertEqual(std.objectFieldsAll({ assert false, f: 3, g:: 3 }), ['f', 'g']) &&
+
+true
diff --git a/test/golden/native.golden b/test/golden/native.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/native.golden
@@ -0,0 +1,10 @@
+{
+    "curried_test": [
+        11,
+        12,
+        13
+    ],
+    "missing_func_is_null": true,
+    "number_test": 42,
+    "string_test": "hello world"
+}
diff --git a/test/golden/native.jsonnet b/test/golden/native.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/native.jsonnet
@@ -0,0 +1,10 @@
+local concat = std.native("concat");
+local add = std.native("add");
+local nonexistent = std.native("nonexistent");
+
+{
+  string_test: concat("hello ", "world"),
+  number_test: add(20, 22),
+  missing_func_is_null: nonexistent == null,
+  curried_test: std.map(function(x) add(10, x), [1, 2, 3]),
+}
diff --git a/test/golden/obj-assert-fails-eq.golden b/test/golden/obj-assert-fails-eq.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/obj-assert-fails-eq.golden
@@ -0,0 +1,2 @@
+Runtime error: Assertion failed
+  obj-assert-fails-eq.jsonnet:4:1-5:1 
diff --git a/test/golden/obj-assert-fails-eq.jsonnet b/test/golden/obj-assert-fails-eq.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/obj-assert-fails-eq.jsonnet
@@ -0,0 +1,4 @@
+local x = 'foo';
+local y = 'bar';
+
+{ assert true, assert x == y, x: 1 } == { x: 1 }
diff --git a/test/golden/object.jsonnet b/test/golden/object.jsonnet
--- a/test/golden/object.jsonnet
+++ b/test/golden/object.jsonnet
@@ -31,7 +31,7 @@
 std.assertEqual({ x: 1, y: 2 } != { x: 1, y: 2, z: 3 }, true) &&
 
 std.assertEqual({ f(x, y, z): x, y: self.f(1, 2, 3) }.y, 1) &&
-//std.assertEqual({ ["f"](x, y, z):: x, "y"(x): self.f(x, 2, 3), z: self.y(4) }.z, 4) &&
+std.assertEqual({ ["f"](x, y, z):: x, "y"(x): self.f(x, 2, 3), z: self.y(4) }.z, 4) &&
 
 // Object Local
 
@@ -46,8 +46,8 @@
 
 // Comprehension object
 std.assertEqual(local x = 10; { ["" + x]: x for x in [x, x + 1, x + 2] }, { "10": 10, "11": 11, "12": 12 }) &&
-//std.assertEqual(local x = "foo"; { local x = "bar", [x]: 1 }, { foo: 1 }) &&
-//std.assertEqual({ [x + ""]: if x == 1 then 1 else x + $["1"] for x in [1, 2, 3] }, { "1": 1, "2": 3, "3": 4 }) &&
+std.assertEqual(local x = "foo"; { local x = "bar", [x]: 1 }, { foo: 1 }) &&
+std.assertEqual({ [x + ""]: if x == 1 then 1 else x + $["1"] for x in [1, 2, 3] }, { "1": 1, "2": 3, "3": 4 }) &&
 
 std.assertEqual(local x = "baz"; { local x = "bar", [x]: x for x in ["foo"] }, { foo: "bar" }) &&
 
@@ -80,26 +80,31 @@
 
 std.assertEqual(obj, { ["f" + x + y + z]: { x: x, y: y, z: z } for x in [1, 2, 3] for y in [1, 4, 6] if x + 2 < y for z in [true, false] }) &&
 
-//std.assertEqual({ f: { foo: 7, bar: 1 } { [self.name]+: 3, name:: "foo" }, name:: "bar" },
-//                { f: { foo: 7, bar: 4 } }) &&
+// Tests for #1111 - object comprehension fields should use "inherit" visibility.
+std.assertEqual(std.objectFields({ x: 1 } + { [k]: 2 for k in ['x'] }), ['x']) &&
+std.assertEqual(std.objectFields({ x:: 1 } + { [k]: 2 for k in ['x'] }), []) &&
+std.assertEqual(std.objectFields({ x::: 1 } + { [k]: 2 for k in ['x'] }), ['x']) &&
 
-//std.assertEqual({ name:: "supername" } { name:: "selfname", f: { wrongname: 7, supername: 1, name:: "wrongname" } { [super.name]+: 3 } },
-//                { f: { wrongname: 7, supername: 4 } }) &&
+std.assertEqual({ f: { foo: 7, bar: 1 } { [self.name]+: 3, name:: "foo" }, name:: "bar" },
+                { f: { foo: 7, bar: 4 } }) &&
 
+std.assertEqual({ name:: "supername" } { name:: "selfname", f: { wrongname: 7, supername: 1, name:: "wrongname" } { [super.name]+: 3 } },
+                { f: { wrongname: 7, supername: 4 } }) &&
+
 std.assertEqual({} + { f+: 3 }, { f: 3 }) &&
 std.assertEqual({} + { f+: { g+: "foo" } }, { f: { g: "foo" } }) &&
 std.assertEqual({} + { f+: [3] }, { f: [3] }) &&
 
-//std.assertEqual({ f+: 3 }, { f: 3 }) &&
-//std.assertEqual({ f+: { g+: "foo" } }, { f: { g: "foo" } }) &&
-//std.assertEqual({ f+: [3] }, { f: [3] }) &&
+std.assertEqual({ f+: 3 }, { f: 3 }) &&
+std.assertEqual({ f+: { g+: "foo" } }, { f: { g: "foo" } }) &&
+std.assertEqual({ f+: [3] }, { f: [3] }) &&
 
 // Ensure that e in super is handled correctly during the +: desugaring, because it moves
 // into a different object scope:
-//std.assertEqual(
-//    { opt:: true, f: { y: 5 } } + { f+: { [if "opt" in super then "x" else "y"]+: 3 } },
-//    { f: { x: 3, y: 5 } }
-//) &&
+std.assertEqual(
+    { opt:: true, f: { y: 5 } } + { f+: { [if "opt" in super then "x" else "y"]+: 3 } },
+    { f: { x: 3, y: 5 } }
+) &&
 
 std.assertEqual({ x: 1 } + { a: "x" in super, b: "y" in super }, { x: 1, a: true, b: false }) &&
 std.assertEqual({ x:: 1 } + { a: "x" in super, b: "y" in super }, { a: true, b: false }) &&
diff --git a/test/golden/recursive_import_ok.golden b/test/golden/recursive_import_ok.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/recursive_import_ok.golden
@@ -0,0 +1,1 @@
+true
diff --git a/test/golden/recursive_import_ok.jsonnet b/test/golden/recursive_import_ok.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/recursive_import_ok.jsonnet
@@ -0,0 +1,17 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+if 3 > 10 then import 'recursive_import_ok.jsonnet' else true
diff --git a/test/golden/stdlib.jsonnet b/test/golden/stdlib.jsonnet
--- a/test/golden/stdlib.jsonnet
+++ b/test/golden/stdlib.jsonnet
@@ -19,9 +19,9 @@
 // Can capture std from another file.
 std.assertEqual((import 'lib/capture_std_func.libsonnet')().sqrt(4), 2) &&
 
-// Each import has its own std. (not implemented in haskell-jsonnet)
+// Each import has its own std.
 std.assertEqual(
-  //local std = { sqrt: function(x) x };
+  local std = { sqrt: function(x) x };
   local lib = import 'lib/capture_std.libsonnet';
   lib.sqrt(4),
   2
@@ -168,17 +168,48 @@
 std.assertEqual(std.objectValues({ x::: 1 } { x:: 1 }), []) &&
 std.assertEqual(std.objectValues({ x::: 1 } { x::: 1 }), [1]) &&
 
+std.assertEqual(std.objectKeysValues({}), []) &&
+std.assertEqual(std.objectKeysValues({ x: 1, y: 2 }), [{ key: 'x', value: 1 }, { key: 'y', value: 2 }]) &&
+std.assertEqual(std.objectKeysValues({ x: 1 } { x: 1 }), [{ key: 'x', value: 1 }]) &&
+std.assertEqual(std.objectKeysValues({ x: 1 } { x:: 1 }), []) &&
+std.assertEqual(std.objectKeysValues({ x: 1 } { x::: 1 }), [{ key: 'x', value: 1 }]) &&
+std.assertEqual(std.objectKeysValues({ x:: 1 } { x: 1 }), []) &&
+std.assertEqual(std.objectKeysValues({ x:: 1 } { x:: 1 }), []) &&
+std.assertEqual(std.objectKeysValues({ x:: 1 } { x::: 1 }), [{ key: 'x', value: 1 }]) &&
+std.assertEqual(std.objectKeysValues({ x::: 1 } { x: 1 }), [{ key: 'x', value: 1 }]) &&
+std.assertEqual(std.objectKeysValues({ x::: 1 } { x:: 1 }), []) &&
+std.assertEqual(std.objectKeysValues({ x::: 1 } { x::: 1 }), [{ key: 'x', value: 1 }]) &&
 
-//std.assertEqual(std.toString({ a: 1, b: 2 }), '{"b":2,"a":1}') &&
-std.assertEqual(std.toString({}), '{}') &&
-std.assertEqual(std.toString([1, 2]), '[1,2]') &&
-std.assertEqual(std.toString([]), '[]') &&
+std.assertEqual(std.get({ x: 1, y: 2 }, 'x', 5), 1) &&
+std.assertEqual(std.get({ x: 1, y: 2 }, 'z', 5), 5) &&
+std.assertEqual(std.get({ x: 1, y: 2 }, 'z'), null) &&
+std.assertEqual(std.get({ x::: 1, y::: 2 }, 'x', 5), 1) &&
+std.assertEqual(std.get({ x::: 1, y::: 2 }, 'z', 5), 5) &&
+std.assertEqual(std.get({ x::: 1, y::: 2 }, 'z'), null) &&
+std.assertEqual(std.get({ x:: 1, y:: 2 }, 'x', 5), 1) &&
+std.assertEqual(std.get({ x:: 1, y:: 2 }, 'x'), 1) &&
+std.assertEqual(std.get({ x:: 1, y:: 2 }, 'z', 5), 5) &&
+std.assertEqual(std.get({ x:: 1, y:: 2 }, 'z'), null) &&
+std.assertEqual(std.get({}, 'z', 5), 5) &&
+std.assertEqual(std.get({}, 'z'), null) &&
+std.assertEqual(std.get({ x: 1, y: 2 }, 'x', 5, false), 1) &&
+std.assertEqual(std.get({ x: 1, y: 2 }, 'z', 5, false), 5) &&
+std.assertEqual(std.get({ x::: 1, y::: 2 }, 'x', 5, false), 1) &&
+std.assertEqual(std.get({ x::: 1, y::: 2 }, 'z', 5, false), 5) &&
+std.assertEqual(std.get({ x:: 1, y:: 2 }, 'x', 5, false), 5) &&
+std.assertEqual(std.get({ x:: 1, y:: 2 }, 'z', 5, false), 5) &&
+std.assertEqual(std.get({}, 'z', 5, false), 5) &&
+
+std.assertEqual(std.toString({ a: 1, b: 2 }), '{"a": 1, "b": 2}') &&
+std.assertEqual(std.toString({}), '{ }') &&
+std.assertEqual(std.toString([1, 2]), '[1, 2]') &&
+std.assertEqual(std.toString([]), '[ ]') &&
 std.assertEqual(std.toString(null), 'null') &&
 std.assertEqual(std.toString(true), 'true') &&
 std.assertEqual(std.toString(false), 'false') &&
 std.assertEqual(std.toString('str'), 'str') &&
 std.assertEqual(std.toString(''), '') &&
-std.assertEqual(std.toString([1, 2, 'foo']), '[1,2,"foo"]') &&
+std.assertEqual(std.toString([1, 2, 'foo']), '[1, 2, "foo"]') &&
 
 std.assertEqual(std.substr('cookie', 1, 3), 'ook') &&
 std.assertEqual(std.substr('cookie', 1, 0), '') &&
@@ -282,6 +313,11 @@
 
 std.assertEqual(std.flattenArrays([[1, 2, 3], [4, 5, 6], []]), [1, 2, 3, 4, 5, 6]) &&
 
+std.assertEqual(std.flattenDeepArray([]), []) &&
+std.assertEqual(std.flattenDeepArray([1, 2, 3]), [1, 2, 3]) &&
+std.assertEqual(std.flattenDeepArray([1, [2, 3]]), [1, 2, 3]) &&
+std.assertEqual(std.flattenDeepArray([[1], [2, 3], [[null]]]), [1, 2, 3, null]) &&
+
 std.assertEqual(
   std.manifestIni({
     main: { a: '1', b: '2' },
@@ -320,6 +356,11 @@
 std.assertEqual(std.escapeStringJson('he"llo'), '"he\\"llo"') &&
 std.assertEqual(std.escapeStringBash("he\"l'lo"), "'he\"l'\"'\"'lo'") &&
 std.assertEqual(std.escapeStringDollars('The path is ${PATH}.'), 'The path is $${PATH}.') &&
+std.assertEqual(std.escapeStringXML('2 < 3'), '2 &lt; 3') &&
+std.assertEqual(std.escapeStringXML('3 > 2'), '3 &gt; 2') &&
+std.assertEqual(std.escapeStringXML('"foo"'), '&quot;foo&quot;') &&
+std.assertEqual(std.escapeStringXML("don't believe the hype"), 'don&apos;t believe the hype') &&
+std.assertEqual(std.escapeStringXML('PB&J'), 'PB&amp;J') &&
 std.assertEqual(std.escapeStringJson('!~'), '"!~"') &&
 
 std.assertEqual(std.manifestPython({
@@ -387,20 +428,96 @@
 std.assertEqual(std.reverse([1, 2, 3]), [3, 2, 1]) &&
 std.assertEqual(std.reverse([[1, 2, 3]]), [[1, 2, 3]]) &&
 
-//(
-//  if std.thisFile == '<stdin>' then
-//    // This happens when testing the unparser.
-//    true
-//  else
-//    std.assertEqual(std.thisFile, 'stdlib.jsonnet')
-//) &&
+std.assertEqual(std.sort([]), []) &&
+std.assertEqual(std.sort([1]), [1]) &&
+std.assertEqual(std.sort([1, 2]), [1, 2]) &&
+std.assertEqual(std.sort([2, 1]), [1, 2]) &&
+std.assertEqual(std.sort(['1', '2']), ['1', '2']) &&
+std.assertEqual(std.sort(['2', '1']), ['1', '2']) &&
+std.assertEqual(
+  std.sort(['The', 'rain', 'in', 'spain', 'falls', 'mainly', 'on', 'the', 'plain.']),
+  ['The', 'falls', 'in', 'mainly', 'on', 'plain.', 'rain', 'spain', 'the']
+) &&
 
+std.assertEqual(std.uniq([]), []) &&
+std.assertEqual(std.uniq([1]), [1]) &&
+std.assertEqual(std.uniq([1, 2]), [1, 2]) &&
+std.assertEqual(std.uniq(['1', '2']), ['1', '2']) &&
+std.assertEqual(
+  std.uniq(['The', 'falls', 'in', 'mainly', 'on', 'plain.', 'rain', 'spain', 'the']),
+  ['The', 'falls', 'in', 'mainly', 'on', 'plain.', 'rain', 'spain', 'the']
+) &&
+
+local animal_set = ['ant', 'bat', 'cat', 'dog', 'elephant', 'fish', 'giraffe'];
+
+std.assertEqual(
+  std.uniq(['ant', 'bat', 'cat', 'dog', 'dog', 'elephant', 'fish', 'fish', 'giraffe']),
+  animal_set
+) &&
+
+std.assertEqual(
+  std.set(['dog', 'ant', 'bat', 'cat', 'dog', 'elephant', 'fish', 'giraffe', 'fish']),
+  animal_set
+) &&
+
+std.assertEqual(std.setUnion(animal_set, animal_set), animal_set) &&
+std.assertEqual(std.setUnion(animal_set, []), animal_set) &&
+std.assertEqual(std.setUnion([], animal_set), animal_set) &&
+std.assertEqual(std.setUnion([], []), []) &&
+std.assertEqual(std.setUnion(['a', 'b'], ['b', 'c']), ['a', 'b', 'c']) &&
+
+std.assertEqual(std.setInter(animal_set, animal_set), animal_set) &&
+std.assertEqual(std.setInter(animal_set, []), []) &&
+std.assertEqual(std.setInter([], animal_set), []) &&
+std.assertEqual(std.setInter([], []), []) &&
+std.assertEqual(std.setInter(['a', 'b'], ['b', 'c']), ['b']) &&
+
+std.assertEqual(std.setDiff(animal_set, animal_set), []) &&
+std.assertEqual(std.setDiff(animal_set, []), animal_set) &&
+std.assertEqual(std.setDiff([], animal_set), []) &&
+std.assertEqual(std.setDiff([], []), []) &&
+std.assertEqual(std.setDiff(['a', 'b'], ['b', 'c']), ['a']) &&
+
+std.assertEqual(std.setMember('a', ['a', 'b', 'c']), true) &&
+std.assertEqual(std.setMember('a', []), false) &&
+std.assertEqual(std.setMember('a', ['b', 'c']), false) &&
+
+(
+  if std.thisFile == '<stdin>' then
+    // This happens when testing the unparser.
+    true
+  else
+    // std.assertEqual(std.thisFile, 'stdlib.jsonnet')
+    true
+) &&
+
+//std.assertEqual(import 'this_file/a.libsonnet', 'this_file/a.libsonnet') &&
+//std.assertEqual(import 'this_file/b.libsonnet', 'this_file/a.libsonnet') &&
+
+
 std.assertEqual(std.extVar('var1'), 'test') &&
 
+std.assertEqual(std.toString(std.extVar('var2')), '{"x": 1, "y": 2}') &&
 std.assertEqual(std.extVar('var2'), { x: 1, y: 2 }) &&
-// std.assertEqual(std.toString(std.extVar('var2')), '{"x": 1, "y": 2}') &&
-// std.assertEqual(std.extVar('var2') { x+: 2 }.x, 3) &&
+std.assertEqual(std.extVar('var2') { x+: 2 }.x, 3) &&
 
+std.assertEqual(std.split('foo/bar', '/'), ['foo', 'bar']) &&
+std.assertEqual(std.split('/foo/', '/'), ['', 'foo', '']) &&
+std.assertEqual(std.split('foo/_bar', '/_'), ['foo', 'bar']) &&
+std.assertEqual(std.split('/_foo/_', '/_'), ['', 'foo', '']) &&
+
+std.assertEqual(std.splitLimit('foo/bar', '/', 1), ['foo', 'bar']) &&
+std.assertEqual(std.splitLimit('/foo/', '/', 1), ['', 'foo/']) &&
+std.assertEqual(std.splitLimit('foo/_bar', '/_', 1), ['foo', 'bar']) &&
+std.assertEqual(std.splitLimit('/_foo/_', '/_', 1), ['', 'foo/_']) &&
+
+std.assertEqual(std.splitLimitR('foo/bar', '/', 1), ['foo', 'bar']) &&
+std.assertEqual(std.splitLimitR('/foo/', '/', 1), ['/foo', '']) &&
+std.assertEqual(std.splitLimitR('/foo/', '/', -1), ['', 'foo', '']) &&
+std.assertEqual(std.splitLimitR('foo/_bar', '/_', 1), ['foo', 'bar']) &&
+std.assertEqual(std.splitLimitR('/_foo/_', '/_', 1), ['/_foo', '']) &&
+std.assertEqual(std.splitLimitR('/_foo/_', '/_', -1), ['', 'foo', '']) &&
+
 local some_toml = {
   key: 'value',
   simple: { t: 5 },
@@ -432,61 +549,61 @@
   '"': 4,
 };
 
-//std.assertEqual(
-//  std.manifestTomlEx(some_toml, '  ') + '\n',
-//  |||
-//    "\"" = 4
-//    array = [
-//      "s",
-//      1,
-//      [ 2, 3 ],
-//      { a = [ "0", "z" ], r = 6 }
-//    ]
-//    bool = true
-//    emptyArray = []
-//    key = "value"
-//    notBool = false
-//    number = 7
-//
-//    [[arraySection]]
-//      q = 1
-//
-//    [[arraySection]]
-//      w = 2
-//
-//    [[emptyArraySection]]
-//
-//    [emptySection]
-//
-//    ["escaped\"Section"]
-//      z = "q"
-//
-//    [section]
-//      a = 1
-//
-//      [[section.array]]
-//        c = 3
-//
-//      [[section.array]]
-//        d = 4
-//
-//      [section."e$caped"]
-//        q = "t"
-//
-//      [section.nested]
-//        b = 2
-//
-//      [[section.nestedArray]]
-//        k = "v"
-//
-//        [section.nestedArray.nested]
-//          e = 5
-//
-//    [simple]
-//      t = 5
-//  |||
-//) &&
+std.assertEqual(
+  std.manifestTomlEx(some_toml, '  ') + '\n',
+  |||
+    "\"" = 4
+    array = [
+      "s",
+      1,
+      [ 2, 3 ],
+      { a = [ "0", "z" ], r = 6 }
+    ]
+    bool = true
+    emptyArray = []
+    key = "value"
+    notBool = false
+    number = 7
 
+    [[arraySection]]
+      q = 1
+
+    [[arraySection]]
+      w = 2
+
+    [[emptyArraySection]]
+
+    [emptySection]
+
+    ["escaped\"Section"]
+      z = "q"
+
+    [section]
+      a = 1
+
+      [[section.array]]
+        c = 3
+
+      [[section.array]]
+        d = 4
+
+      [section."e$caped"]
+        q = "t"
+
+      [section.nested]
+        b = 2
+
+      [[section.nestedArray]]
+        k = "v"
+
+        [section.nestedArray.nested]
+          e = 5
+
+    [simple]
+      t = 5
+  |||
+) &&
+
 local some_json = {
   x: [1, 2, 3, true, false, null, 'string\nstring\n'],
   arr: [[[]]],
@@ -497,6 +614,73 @@
   '"': null,
 };
 
+local bare_yaml_quoted = {
+  '685230': 'canonical',
+  '+685_230': 'decimal',
+  '02472256': 'octal',
+  '-1_0': 'negative integer',
+  '-0.1_0_0': 'negative float',
+  '0x_0A_74_AE': 'hexadecimal',
+  '-0x_0A_74_AE': 'negative hexadecimal',
+  '0b1010_0111_0100_1010_1110': 'binary',
+  '-0b1010_0111_0100_1010_1110': 'binary',
+  '190:20:30': 'sexagesimal',
+  '-190:20:30': 'negative sexagesimal',
+  '6.8523015e+5': 'canonical',
+  '6.8523015e-5': 'canonical',
+  '-6.8523015e+5': 'negative canonical',
+  '685.230_15e+03': 'exponential',
+  '-685.230_15e+03': 'negative exponential',
+  '-685.230_15e-03': 'negative w/ negative exponential',
+  '-685.230_15E-03': 'negative w/ negative exponential',
+  '685_230.15': 'fixed',
+  '-685_230.15': 'negative fixed',
+  '190:20:30.15': 'sexagesimal',
+  '-190:20:30.15': 'negative sexagesimal',
+  '-.inf': 'negative infinity',
+  '.inf': 'positive infinity',
+  '+.inf': 'positive infinity',
+  '.NaN': 'not a number',
+  y: 'boolean true',
+  yes: 'boolean true',
+  Yes: 'boolean true',
+  True: 'boolean true',
+  'true': 'boolean true',
+  on: 'boolean true',
+  On: 'boolean true',
+  NO: 'boolean false',
+  n: 'boolean false',
+  N: 'boolean false',
+  off: 'boolean false',
+  OFF: 'boolean false',
+  'null': 'null word',
+  NULL: 'null word capital',
+  Null: 'null word',
+  '~': 'null key',
+  '': 'empty key',
+  '-': 'invalid bare key',
+  '---': 'triple dash key',
+  '2001-12-15T02:59:43.1Z': 'canonical',
+  '2001-12-14t21:59:43.10-05:00': 'valid iso8601',
+  '2001-12-14 21:59:43.10 -5': 'space separated',
+  '2001-12-15 2:59:43.10': 'no time zone (Z)',
+  '2002-12-14': 'date',
+};
+local bare_yaml_unquoted = {
+  '0X_0a_74_ae': 'BARE_KEY',
+  '__-0X_0a_74_ae': 'BARE_KEY',
+  '-0B1010_0111_0100_1010_1110': 'BARE_KEY',
+  '__-0B1010_0111_0100_1010_1110': 'BARE_KEY',
+  x: 'BARE_KEY',
+  b: 'BARE_KEY',
+  just_letters_underscores: 'BARE_KEY',
+  'just-letters-dashes': 'BARE_KEY',
+  'jsonnet.org/k8s-label-like': 'BARE_KEY',
+  '192.168.0.1': 'BARE_KEY',
+  '1-234-567-8901': 'BARE_KEY',
+};
+local bare_yaml_test = bare_yaml_quoted + bare_yaml_unquoted;
+
 std.assertEqual(
   std.manifestJsonEx(some_json, '    ') + '\n',
   |||
@@ -556,6 +740,16 @@
 ) &&
 
 std.assertEqual(
+  std.manifestYamlDoc([{ x: [1, 2, 3] }], quote_keys=false) + '\n',
+  |||
+    - x:
+      - 1
+      - 2
+      - 3
+  |||
+) &&
+
+std.assertEqual(
   std.manifestYamlDoc([{ x: [1, 2, 3] }]) + '\n',
   |||
     - "x":
@@ -617,6 +811,21 @@
 ) &&
 
 std.assertEqual(
+  std.manifestYamlDoc({ x: [[[1, { f: 3, g: [1, 2] }, 1]]] }, quote_keys=false) + '\n',
+  |||
+    x:
+    -
+      -
+        - 1
+        - f: 3
+          g:
+          - 1
+          - 2
+        - 1
+  |||
+) &&
+
+std.assertEqual(
   std.manifestYamlDoc('hello\nworld\n') + '\n',
   |||
     |
@@ -644,6 +853,15 @@
 ) &&
 
 std.assertEqual(
+  std.manifestYamlDoc({ f: 'hello\nworld\n' }, quote_keys=false) + '\n',
+  |||
+    f: |
+      hello
+      world
+  |||
+) &&
+
+std.assertEqual(
   std.manifestYamlDoc(some_json) + '\n',
   |||
     "\"": null
@@ -674,6 +892,36 @@
 ) &&
 
 std.assertEqual(
+  std.manifestYamlDoc(some_json, quote_keys=false) + '\n',
+  |||
+    "\"": null
+    arr:
+    -
+      - []
+    emptyArray: []
+    emptyObject: {}
+    objectInArray:
+    - f: 3
+    x:
+    - 1
+    - 2
+    - 3
+    - true
+    - false
+    - null
+    - |
+      string
+      string
+    "y":
+      a: 1
+      b: 2
+      c:
+      - 1
+      - 2
+  |||
+) &&
+
+std.assertEqual(
   std.manifestYamlDoc([{ x: [1, 2, 3] }], indent_array_in_object=true) + '\n',
   |||
     - "x":
@@ -684,6 +932,16 @@
 ) &&
 
 std.assertEqual(
+  std.manifestYamlDoc([{ x: [1, 2, 3] }], indent_array_in_object=true, quote_keys=false) + '\n',
+  |||
+    - x:
+        - 1
+        - 2
+        - 3
+  |||
+) &&
+
+std.assertEqual(
   std.manifestYamlDoc({ x: [1, 2, 3] }, indent_array_in_object=true) + '\n',
   |||
     "x":
@@ -792,6 +1050,173 @@
 ) &&
 
 std.assertEqual(
+  std.manifestYamlDoc(some_json, indent_array_in_object=true, quote_keys=false) + '\n',
+  |||
+    "\"": null
+    arr:
+      -
+        - []
+    emptyArray: []
+    emptyObject: {}
+    objectInArray:
+      - f: 3
+    x:
+      - 1
+      - 2
+      - 3
+      - true
+      - false
+      - null
+      - |
+        string
+        string
+    "y":
+      a: 1
+      b: 2
+      c:
+        - 1
+        - 2
+  |||
+) &&
+
+std.assertEqual(
+  std.manifestYamlDoc(bare_yaml_test, quote_keys=false) + '\n',
+  |||
+    "": "empty key"
+    "+.inf": "positive infinity"
+    "+685_230": "decimal"
+    "-": "invalid bare key"
+    "---": "triple dash key"
+    "-.inf": "negative infinity"
+    "-0.1_0_0": "negative float"
+    -0B1010_0111_0100_1010_1110: "BARE_KEY"
+    "-0b1010_0111_0100_1010_1110": "binary"
+    "-0x_0A_74_AE": "negative hexadecimal"
+    "-190:20:30": "negative sexagesimal"
+    "-190:20:30.15": "negative sexagesimal"
+    "-1_0": "negative integer"
+    "-6.8523015e+5": "negative canonical"
+    "-685.230_15E-03": "negative w/ negative exponential"
+    "-685.230_15e+03": "negative exponential"
+    "-685.230_15e-03": "negative w/ negative exponential"
+    "-685_230.15": "negative fixed"
+    ".NaN": "not a number"
+    ".inf": "positive infinity"
+    "02472256": "octal"
+    0X_0a_74_ae: "BARE_KEY"
+    "0b1010_0111_0100_1010_1110": "binary"
+    "0x_0A_74_AE": "hexadecimal"
+    1-234-567-8901: "BARE_KEY"
+    "190:20:30": "sexagesimal"
+    "190:20:30.15": "sexagesimal"
+    192.168.0.1: "BARE_KEY"
+    "2001-12-14 21:59:43.10 -5": "space separated"
+    "2001-12-14t21:59:43.10-05:00": "valid iso8601"
+    "2001-12-15 2:59:43.10": "no time zone (Z)"
+    "2001-12-15T02:59:43.1Z": "canonical"
+    "2002-12-14": "date"
+    "6.8523015e+5": "canonical"
+    "6.8523015e-5": "canonical"
+    "685.230_15e+03": "exponential"
+    "685230": "canonical"
+    "685_230.15": "fixed"
+    "N": "boolean false"
+    "NO": "boolean false"
+    "NULL": "null word capital"
+    "Null": "null word"
+    "OFF": "boolean false"
+    "On": "boolean true"
+    "True": "boolean true"
+    "Yes": "boolean true"
+    __-0B1010_0111_0100_1010_1110: "BARE_KEY"
+    __-0X_0a_74_ae: "BARE_KEY"
+    b: "BARE_KEY"
+    jsonnet.org/k8s-label-like: "BARE_KEY"
+    just-letters-dashes: "BARE_KEY"
+    just_letters_underscores: "BARE_KEY"
+    "n": "boolean false"
+    "null": "null word"
+    "off": "boolean false"
+    "on": "boolean true"
+    "true": "boolean true"
+    x: "BARE_KEY"
+    "y": "boolean true"
+    "yes": "boolean true"
+    "~": "null key"
+  |||
+) &&
+
+std.assertEqual(
+  std.manifestYamlStream([bare_yaml_quoted, bare_yaml_unquoted], quote_keys=false),
+  |||
+    ---
+    "": "empty key"
+    "+.inf": "positive infinity"
+    "+685_230": "decimal"
+    "-": "invalid bare key"
+    "---": "triple dash key"
+    "-.inf": "negative infinity"
+    "-0.1_0_0": "negative float"
+    "-0b1010_0111_0100_1010_1110": "binary"
+    "-0x_0A_74_AE": "negative hexadecimal"
+    "-190:20:30": "negative sexagesimal"
+    "-190:20:30.15": "negative sexagesimal"
+    "-1_0": "negative integer"
+    "-6.8523015e+5": "negative canonical"
+    "-685.230_15E-03": "negative w/ negative exponential"
+    "-685.230_15e+03": "negative exponential"
+    "-685.230_15e-03": "negative w/ negative exponential"
+    "-685_230.15": "negative fixed"
+    ".NaN": "not a number"
+    ".inf": "positive infinity"
+    "02472256": "octal"
+    "0b1010_0111_0100_1010_1110": "binary"
+    "0x_0A_74_AE": "hexadecimal"
+    "190:20:30": "sexagesimal"
+    "190:20:30.15": "sexagesimal"
+    "2001-12-14 21:59:43.10 -5": "space separated"
+    "2001-12-14t21:59:43.10-05:00": "valid iso8601"
+    "2001-12-15 2:59:43.10": "no time zone (Z)"
+    "2001-12-15T02:59:43.1Z": "canonical"
+    "2002-12-14": "date"
+    "6.8523015e+5": "canonical"
+    "6.8523015e-5": "canonical"
+    "685.230_15e+03": "exponential"
+    "685230": "canonical"
+    "685_230.15": "fixed"
+    "N": "boolean false"
+    "NO": "boolean false"
+    "NULL": "null word capital"
+    "Null": "null word"
+    "OFF": "boolean false"
+    "On": "boolean true"
+    "True": "boolean true"
+    "Yes": "boolean true"
+    "n": "boolean false"
+    "null": "null word"
+    "off": "boolean false"
+    "on": "boolean true"
+    "true": "boolean true"
+    "y": "boolean true"
+    "yes": "boolean true"
+    "~": "null key"
+    ---
+    -0B1010_0111_0100_1010_1110: "BARE_KEY"
+    0X_0a_74_ae: "BARE_KEY"
+    1-234-567-8901: "BARE_KEY"
+    192.168.0.1: "BARE_KEY"
+    __-0B1010_0111_0100_1010_1110: "BARE_KEY"
+    __-0X_0a_74_ae: "BARE_KEY"
+    b: "BARE_KEY"
+    jsonnet.org/k8s-label-like: "BARE_KEY"
+    just-letters-dashes: "BARE_KEY"
+    just_letters_underscores: "BARE_KEY"
+    x: "BARE_KEY"
+    ...
+  |||
+) &&
+
+std.assertEqual(
   std.manifestYamlStream([some_json, some_json, {}, [], 3, '"']),
   |||
     ---
@@ -857,6 +1282,71 @@
 ) &&
 
 std.assertEqual(
+  std.manifestYamlStream([some_json, some_json, {}, [], 3, '"'], quote_keys=false),
+  |||
+    ---
+    "\"": null
+    arr:
+    -
+      - []
+    emptyArray: []
+    emptyObject: {}
+    objectInArray:
+    - f: 3
+    x:
+    - 1
+    - 2
+    - 3
+    - true
+    - false
+    - null
+    - |
+      string
+      string
+    "y":
+      a: 1
+      b: 2
+      c:
+      - 1
+      - 2
+    ---
+    "\"": null
+    arr:
+    -
+      - []
+    emptyArray: []
+    emptyObject: {}
+    objectInArray:
+    - f: 3
+    x:
+    - 1
+    - 2
+    - 3
+    - true
+    - false
+    - null
+    - |
+      string
+      string
+    "y":
+      a: 1
+      b: 2
+      c:
+      - 1
+      - 2
+    ---
+    {}
+    ---
+    []
+    ---
+    3
+    ---
+    "\""
+    ...
+  |||
+) &&
+
+std.assertEqual(
   std.manifestYamlStream([some_json, some_json, {}, [], 3, '"'], indent_array_in_object=true),
   |||
     ---
@@ -948,10 +1438,10 @@
 std.assertEqual(std.parseHex('4a'), 74) &&
 
 // verified by running md5 -s value
-//std.assertEqual(std.md5(''), 'd41d8cd98f00b204e9800998ecf8427e') &&
-//std.assertEqual(std.md5('grape'), 'b781cbb29054db12f88f08c6e161c199') &&
-//std.assertEqual(std.md5("{}[]01234567890\"'+=-_/<>?,.!@#$%^&*|\\:;`~"), 'a680db28332f0c9647376e5b2aeb4b3d') &&
-//std.assertEqual(std.md5('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim. Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. Cras metus. Sed aliquet risus a tortor. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante. Nulla quam. Aenean laoreet. Vestibulum nisi lectus, commodo ac, facilisis ac, ultricies eu, pede. Ut orci risus, accumsan porttitor, cursus quis, aliquet eget, justo. Sed pretium blandit orci. Ut eu diam at pede suscipit sodales. Aenean lectus elit, fermentum non, convallis id, sagittis at, neque. Nullam mauris orci, aliquet et, iaculis et, viverra vitae, ligula. Nulla ut felis in purus aliquam imperdiet. Maecenas aliquet mollis lectus. Vivamus consectetuer risus et tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim. Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. Cras metus. Sed aliquet risus a tortor. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante. Nulla quam. Aenean laoreet. Vestibulum nisi lectus, commodo ac, facilisis ac, ultricies eu, pede. Ut orci risus, accumsan porttitor, cursus quis, aliquet eget, justo. Sed pretium blandit orci. Ut eu diam at pede suscipit sodales. Aenean lectus elit, fermentum non, convallis id, sagittis at, neque. Nullam mauris orci, aliquet et, iaculis et, viverra vitae, ligula. Nulla ut felis in purus aliquam imperdiet. Maecenas aliquet mollis lectus. Vivamus consectetuer risus et tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum si.'), '3496bb633e830e7679ce53700d42de1e') &&
+std.assertEqual(std.md5(''), 'd41d8cd98f00b204e9800998ecf8427e') &&
+std.assertEqual(std.md5('grape'), 'b781cbb29054db12f88f08c6e161c199') &&
+std.assertEqual(std.md5("{}[]01234567890\"'+=-_/<>?,.!@#$%^&*|\\:;`~"), 'a680db28332f0c9647376e5b2aeb4b3d') &&
+std.assertEqual(std.md5('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim. Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. Cras metus. Sed aliquet risus a tortor. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante. Nulla quam. Aenean laoreet. Vestibulum nisi lectus, commodo ac, facilisis ac, ultricies eu, pede. Ut orci risus, accumsan porttitor, cursus quis, aliquet eget, justo. Sed pretium blandit orci. Ut eu diam at pede suscipit sodales. Aenean lectus elit, fermentum non, convallis id, sagittis at, neque. Nullam mauris orci, aliquet et, iaculis et, viverra vitae, ligula. Nulla ut felis in purus aliquam imperdiet. Maecenas aliquet mollis lectus. Vivamus consectetuer risus et tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec, blandit vel, egestas et, augue. Vestibulum tincidunt malesuada tellus. Ut ultrices ultrices enim. Curabitur sit amet mauris. Morbi in dui quis est pulvinar ullamcorper. Nulla facilisi. Integer lacinia sollicitudin massa. Cras metus. Sed aliquet risus a tortor. Integer id quam. Morbi mi. Quisque nisl felis, venenatis tristique, dignissim in, ultrices sit amet, augue. Proin sodales libero eget ante. Nulla quam. Aenean laoreet. Vestibulum nisi lectus, commodo ac, facilisis ac, ultricies eu, pede. Ut orci risus, accumsan porttitor, cursus quis, aliquet eget, justo. Sed pretium blandit orci. Ut eu diam at pede suscipit sodales. Aenean lectus elit, fermentum non, convallis id, sagittis at, neque. Nullam mauris orci, aliquet et, iaculis et, viverra vitae, ligula. Nulla ut felis in purus aliquam imperdiet. Maecenas aliquet mollis lectus. Vivamus consectetuer risus et tortor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum si.'), '3496bb633e830e7679ce53700d42de1e') &&
 std.assertEqual(std.parseInt('-01234567890'), -1234567890) &&
 
 std.assertEqual(std.prune({}), {}) &&
@@ -971,6 +1461,61 @@
 std.assertEqual(std.parseJson('12.123'), 12.123) &&
 std.assertEqual(std.parseJson('{"a": {"b": ["c", 42]}}'), { a: { b: ['c', 42] } }) &&
 
+std.assertEqual(std.parseYaml('{}'), {}) &&
+std.assertEqual(std.parseYaml('[]'), []) &&
+std.assertEqual(
+  std.parseYaml(
+    |||
+      foo:
+        bar:
+        - true
+        - 42
+        - 1.0
+    |||
+  ), { foo: { bar: [true, 42, 1] } }
+) &&
+std.assertEqual(
+  std.parseYaml(
+    |||
+      ---
+      foo:
+        bar:
+        - true
+        - 42
+        - 1.0
+      ---
+      wibble:
+        wobble:
+        - true
+        - 42
+        - 1.0
+    |||
+  ), [{ foo: { bar: [true, 42, 1] } }, { wibble: { wobble: [true, 42, 1] } }]
+) &&
+std.assertEqual(
+  std.parseYaml(
+    |||
+      - 1
+      - 2
+      - 3
+    |||
+  ), [1, 2, 3]
+) &&
+std.assertEqual(
+  std.parseYaml(
+    |||
+      f1: |
+        a
+        b
+      f2: "a\nb\n"
+    |||
+  ), { f1: 'a\nb\n', f2: 'a\nb\n' }
+) &&
+// Issue https://github.com/google/jsonnet/issues/1014
+std.assertEqual(std.parseYaml('version: 1.2.3'), { version: '1.2.3' }) &&
+// Issue https://github.com/google/jsonnet/issues/1050
+std.assertEqual(std.type(std.parseYaml('id: "12345"').id), 'string') &&
+
 std.assertEqual(std.asciiUpper('!@#$%&*()asdfghFGHJKL09876 '), '!@#$%&*()ASDFGHFGHJKL09876 ') &&
 std.assertEqual(std.asciiLower('!@#$%&*()asdfghFGHJKL09876 '), '!@#$%&*()asdfghfghjkl09876 ') &&
 
@@ -1007,5 +1552,68 @@
 std.assertEqual(std.decodeUTF8([65 + 1 - 1]), 'A') &&
 std.assertEqual(std.decodeUTF8([90, 97, 197, 188, 195, 179, 197, 130, 196, 135, 32, 103, 196, 153, 197, 155, 108, 196, 133, 32, 106, 97, 197, 186, 197, 132]), 'Zażółć gęślą jaźń') &&
 std.assertEqual(std.decodeUTF8([240, 159, 152, 131]), '😃') &&
+
+
+std.assertEqual(std.any([true, false]), true) &&
+std.assertEqual(std.any([false, false]), false) &&
+std.assertEqual(std.any([]), false) &&
+
+std.assertEqual(std.all([true, false]), false) &&
+std.assertEqual(std.all([true, true]), true) &&
+std.assertEqual(std.all([]), true) &&
+
+std.assertEqual(std.sum([1, 2, 3]), 6) &&
+
+std.assertEqual(std.avg([1, 2, 3]), 2) &&
+std.assertEqual(std.avg([0, 0, 0]), 0) &&
+std.assertEqual(std.avg([1, 1, 2.5]), 1.5) &&
+
+std.assertEqual(std.minArray([1, 2, 3]), 1) &&
+std.assertEqual(std.minArray(['1', '2', '3']), '1') &&
+
+std.assertEqual(std.maxArray([1, 2, 3]), 3) &&
+std.assertEqual(std.maxArray(['1', '2', '3']), '3') &&
+std.assertEqual(std.maxArray(['a', 'x', 'z']), 'z') &&
+
+
+std.assertEqual(std.xor(true, false), true) &&
+std.assertEqual(std.xor(true, true), false) &&
+
+std.assertEqual(std.xnor(true, false), false) &&
+std.assertEqual(std.xnor(true, true), true) &&
+
+std.assertEqual(std.round(1.2), 1) &&
+std.assertEqual(std.round(1.5), 2) &&
+
+std.assertEqual(std.isEmpty(''), true) &&
+std.assertEqual(std.isEmpty('non-empty string'), false) &&
+
+std.assertEqual(std.contains([1, 2, 3], 2), true) &&
+std.assertEqual(std.contains([1, 2, 3], 'foo'), false) &&
+
+std.assertEqual(std.equalsIgnoreCase('foo', 'FOO'), true) &&
+std.assertEqual(std.equalsIgnoreCase('foo', 'bar'), false) &&
+
+std.assertEqual(std.isEven(10), true) &&
+std.assertEqual(std.isEven(5), false) &&
+std.assertEqual(std.isOdd(5), true) &&
+std.assertEqual(std.isOdd(10), false) &&
+std.assertEqual(std.isInteger(1), true) &&
+std.assertEqual(std.isInteger(1.1), false) &&
+std.assertEqual(std.isDecimal(1.1), true) &&
+std.assertEqual(std.isDecimal(1), false) &&
+
+std.assertEqual(std.remove([1, 2, 3], 2), [1, 3]) &&
+std.assertEqual(std.removeAt([1, 2, 3], 1), [1, 3]) &&
+
+std.assertEqual(std.objectRemoveKey({ foo: 1, bar: 2, baz: 3 }, 'foo'), { bar: 2, baz: 3 }) &&
+
+std.assertEqual(std.trim('already trimmed string'), 'already trimmed string') &&
+std.assertEqual(std.trim('    string with spaces on both ends     '), 'string with spaces on both ends') &&
+std.assertEqual(std.trim('string with newline character at end\n'), 'string with newline character at end') &&
+std.assertEqual(std.trim('string with tabs at end\t\t'), 'string with tabs at end') &&
+// The last character here was previously expressed as \u00A0, but this is rewritten by jsonnetfmt.
+// To avoid ambiguity but allow the code to pass unchanged through jsonnetfmt, this now uses a std.char() call.
+std.assertEqual(std.trim('string with other special whitespaces at end\f\r\u0085' + std.char(160)), 'string with other special whitespaces at end') &&
 
 true
diff --git a/test/golden/this_file/a.libsonnet b/test/golden/this_file/a.libsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/this_file/a.libsonnet
@@ -0,0 +1,1 @@
+std.thisFile
diff --git a/test/golden/this_file/b.libsonnet b/test/golden/this_file/b.libsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/this_file/b.libsonnet
@@ -0,0 +1,1 @@
+import "a.libsonnet"
diff --git a/test/golden/trace.golden b/test/golden/trace.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/trace.golden
@@ -0,0 +1,1 @@
+true
diff --git a/test/golden/trace.jsonnet b/test/golden/trace.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/trace.jsonnet
@@ -0,0 +1,29 @@
+/*
+Copyright 2015 Google Inc. All rights reserved.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+std.assertEqual(std.trace('', null), null) &&
+std.assertEqual(std.trace('', true), true) &&
+std.assertEqual(std.trace('', 77), 77) &&
+std.assertEqual(std.trace('', 77.88), 77.88) &&
+std.assertEqual(std.trace('', 'word'), 'word') &&
+std.assertEqual(std.foldl(std.trace('', function(acc, i) acc + i), [1, 2, 3], 0), 6) &&
+std.assertEqual(std.trace('', {}), {}) &&
+std.assertEqual(std.trace('', { a: {} }), { a: {} }) &&
+std.assertEqual(std.trace('', []), []) &&
+std.assertEqual(std.trace('', [{ a: 'b' }, { a: 'b' }]), [{ a: 'b' }, { a: 'b' }]) &&
+std.assertEqual(std.trace('Some Trace Message', { a: {} }), { a: {} }) &&
+
+true
diff --git a/test/golden/trivial-obj-assert.golden b/test/golden/trivial-obj-assert.golden
new file mode 100644
--- /dev/null
+++ b/test/golden/trivial-obj-assert.golden
@@ -0,0 +1,1 @@
+true
diff --git a/test/golden/trivial-obj-assert.jsonnet b/test/golden/trivial-obj-assert.jsonnet
new file mode 100644
--- /dev/null
+++ b/test/golden/trivial-obj-assert.jsonnet
@@ -0,0 +1,1 @@
+{ assert true, x: 1 } == { x: 1 }
