1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//! # jsonnet bindings for Rust
//!
//! This library contains bindings to the [jsonnet][1] C library,
//! a template language that generates JSON and YAML.
//!
//! Almost all interaction with this module will be via the
//! `JsonnetVm` type.
//!
//! [1]: https://jsonnet.org/
//!
//! # Examples
//!
//! ```
//! use jsonnet::JsonnetVm;
//!
//! let mut vm = JsonnetVm::new();
//! let output = vm.evaluate_snippet("example", "'Hello ' + 'World'").unwrap();
//! assert_eq!(output.to_string(), "\"Hello World\"\n");
//! ```

#![deny(missing_docs)]
#![allow(trivial_casts)]

extern crate libc;
extern crate jsonnet_sys;

use std::ffi::{CStr, CString, OsStr};
use std::path::{Path,PathBuf};
use std::{error,iter,ptr,fmt};
use std::ops::Deref;
use libc::{c_int, c_uint, c_char, c_void};

mod string;
mod value;

pub use string::JsonnetString;
use string::JsonnetStringIter;
pub use value::{JsonVal, JsonValue};
use jsonnet_sys::JsonnetJsonValue;

/// Error returned from jsonnet routines on failure.
#[derive(Debug,PartialEq,Eq)]
pub struct Error<'a>(JsonnetString<'a>);

impl<'a> From<JsonnetString<'a>> for Error<'a> {
    fn from(s: JsonnetString<'a>) -> Self { Error(s) }
}

impl<'a> From<Error<'a>> for JsonnetString<'a> {
    fn from(e: Error<'a>) -> Self { e.0 }
}

impl<'a> Deref for Error<'a> {
    type Target = JsonnetString<'a>;
    fn deref(&self) -> &Self::Target { &self.0 }
}

impl<'a> fmt::Display for Error<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl<'a> error::Error for Error<'a> {
    fn description(&self) -> &str { "jsonnet error" }
}

/// Result from "multi" eval methods.
///
/// Contains a list of (&str, &str) pairs.
pub struct EvalMap<'a>(JsonnetString<'a>);
impl<'a> EvalMap<'a> {
    /// Returns an iterator over the contained values.
    pub fn iter<'b>(&'b self) -> EvalMapIter<'b,'a> {
        EvalMapIter(unsafe { JsonnetStringIter::new(&self.0) })
    }
}

impl<'a,'b> IntoIterator for &'b EvalMap<'a> {
    type Item = (&'b str, &'b str);
    type IntoIter = EvalMapIter<'b,'a>;
    fn into_iter(self) -> Self::IntoIter { self.iter() }
}

/// Iterator returned from "multi" eval methods.
///
/// Yields (&str, &str) pairs.
#[derive(Debug)]
pub struct EvalMapIter<'a,'b:'a>(JsonnetStringIter<'a,'b>);

impl<'a,'b> Iterator for EvalMapIter<'a,'b> {
    type Item = (&'a str, &'a str);
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
            .map(|first| {
                let second = self.0.next().unwrap();
                (first, second)
            })
    }
}

/// Result from "stream" eval methods.
///
/// Contains a list of &str.
pub struct EvalList<'a>(JsonnetString<'a>);
impl<'a> EvalList<'a> {
    /// Returns an iterator over the contained values.
    pub fn iter<'b>(&'b self) -> EvalListIter<'b,'a> {
        EvalListIter(unsafe { JsonnetStringIter::new(&self.0) })
    }
}

/// Iterator returned from "stream" eval methods.
///
/// Yields &str items.
pub struct EvalListIter<'a,'b:'a>(JsonnetStringIter<'a,'b>);

impl<'a,'b> Iterator for EvalListIter<'a,'b> {
    type Item = &'a str;
    fn next(&mut self) -> Option<Self::Item> { self.0.next() }
}

impl<'a,'b> IntoIterator for &'b EvalList<'a> {
    type Item = &'b str;
    type IntoIter = EvalListIter<'b,'a>;
    fn into_iter(self) -> Self::IntoIter { self.iter() }
}

/// String literal style
#[derive(Debug,PartialEq,Eq)]
pub enum FmtString {
    /// Double quoted `"foo"`.
    Double,
    /// Single quoted `'foo'`.
    Single,
    /// Leave quoting as-is.
    Leave,
}

impl FmtString {
    fn to_char(self) -> c_int {
        let c = match self {
            FmtString::Double => 'd',
            FmtString::Single => 's',
            FmtString::Leave => 'l',
        };
        c as c_int
    }
}

impl Default for FmtString {
    fn default() -> FmtString { FmtString::Leave }
}

/// Comment style
#[derive(Debug,PartialEq,Eq)]
pub enum FmtComment {
    /// Hash comments (like shell).
    Hash,
    /// Double slash comments (like C++).
    Slash,
    /// Leave comments as-is.
    Leave,
}

impl FmtComment {
    fn to_char(self) -> c_int {
        let c = match self {
            FmtComment::Hash => 'h',
            FmtComment::Slash => 's',
            FmtComment::Leave => 'l',
        };
        c as c_int
    }
}

impl Default for FmtComment {
    fn default() -> FmtComment { FmtComment::Leave }
}

/// Return the version string of the Jsonnet interpreter.  Conforms to
/// [semantic versioning][1].
///
/// [1]: http://semver.org/
pub fn jsonnet_version() -> &'static str {
    let s = unsafe { CStr::from_ptr(jsonnet_sys::jsonnet_version()) };
    s.to_str().unwrap()
}

#[test]
fn test_version() {
    let s = jsonnet_version();
    println!("Got version: {}", s);
    // Should be 1.2.3 semver format
    assert_eq!(s.split('.').count(), 3);
}

/// Callback used to load imports.
pub type ImportCallback<'a> = fn(vm: &'a JsonnetVm, base: &Path, rel: &Path) -> Result<(PathBuf, String), String>;

struct ImportContext<'a> {
    vm: &'a JsonnetVm,
    cb: ImportCallback<'a>,
}

#[cfg(unix)]
fn bytes2osstr(b: &[u8]) -> &OsStr {
    use std::os::unix::ffi::OsStrExt;
    OsStr::from_bytes(b)
}

/// Panics if os contains invalid utf8!
#[cfg(windows)]
fn bytes2osstr(b: &[u8]) -> &OsStr {
    let s = std::str::from_utf8(b).unwrap();
    OsStr::new(s)
}

fn cstr2osstr(cstr: &CStr) -> &OsStr {
    bytes2osstr(cstr.to_bytes())
}

#[cfg(unix)]
fn osstr2bytes(os: &OsStr) -> &[u8] {
    use std::os::unix::ffi::OsStrExt;
    os.as_bytes()
}

/// Panics if os contains invalid utf8!
#[cfg(windows)]
fn osstr2bytes(os: &OsStr) -> &[u8] {
    os.to_str().unwrap().as_bytes()
}

fn osstr2cstring<T: AsRef<OsStr>>(os: T) -> CString {
    let b = osstr2bytes(os.as_ref());
    CString::new(b).unwrap()
}

// `jsonnet_sys::JsonnetImportCallback`-compatible function that
// interprets `ctx` as an `ImportContext` and converts arguments
// appropriately.
extern fn import_callback(ctx: *mut c_void, base: &c_char, rel: &c_char, found_here: &mut *mut c_char, success: &mut c_int) -> *mut c_char {
    let ctx = unsafe { &*(ctx as *mut ImportContext) };
    let vm = ctx.vm;
    let callback = ctx.cb;
    let base_path = Path::new(cstr2osstr(unsafe { CStr::from_ptr(base) }));
    let rel_path = Path::new(cstr2osstr(unsafe { CStr::from_ptr(rel) }));
    match callback(vm, base_path, rel_path) {
        Ok((found_here_path, contents)) => {
            *success = 1;

            let v = {
                // Note: PathBuf may not be valid utf8.
                let b = osstr2bytes(found_here_path.as_os_str());
                JsonnetString::from_bytes(vm, b)
            };
            *found_here = v.into_raw();

            JsonnetString::new(vm, &contents).into_raw()
        },
        Err(err) => {
            *success = 0;
            JsonnetString::new(vm, &err).into_raw()
        }
    }
}

/// Callback to provide native extensions to Jsonnet.
///
/// This callback should not have side-effects!  Jsonnet is a lazy
/// functional language and will call your function when you least
/// expect it, more times than you expect, or not at all.
// TODO: Convert to closure
pub type NativeCallback<'a> = fn(vm: &'a JsonnetVm, argv: &[JsonVal<'a>]) -> Result<JsonValue<'a>, String>;

struct NativeContext<'a> {
    vm: &'a JsonnetVm,
    argc: usize,
    cb: NativeCallback<'a>,
}

// `jsonnet_sys::JsonnetNativeCallback`-compatible function that
// interprets `ctx` as a `NativeContext` and converts arguments
// appropriately.
extern fn native_callback(ctx: *mut libc::c_void, argv: *const *const JsonnetJsonValue, success: &mut c_int) -> *mut JsonnetJsonValue {
    let ctx = unsafe { &*(ctx as *mut NativeContext) };
    let vm = ctx.vm;
    let callback = ctx.cb;
    let args: Vec<_> = (0..ctx.argc)
        .map(|i| unsafe { JsonVal::from_ptr(vm, *argv.offset(i as isize)) })
        .collect();
    match callback(vm, &args) {
        Ok(v) => {
            *success = 1;
            v.into_raw()
        },
        Err(err) => {
            *success = 0;
            let ret = JsonValue::from_str(vm, &err);
            ret.into_raw()
        }
    }
}

/// Jsonnet virtual machine context.
pub struct JsonnetVm(*mut jsonnet_sys::JsonnetVm);

impl JsonnetVm {
    /// Create a new Jsonnet virtual machine.
    pub fn new() -> Self {
        let vm = unsafe { jsonnet_sys::jsonnet_make() };
        JsonnetVm(vm)
    }

    fn as_ptr(&self) -> *mut jsonnet_sys::JsonnetVm { self.0 }

    /// Set the maximum stack depth.
    pub fn max_stack(&mut self, v: u32) {
        unsafe { jsonnet_sys::jsonnet_max_stack(self.0, v as c_uint) }
    }

    /// Set the number of objects required before a garbage collection
    /// cycle is allowed.
    pub fn gc_min_objects(&mut self, v: u32) {
        unsafe { jsonnet_sys::jsonnet_gc_min_objects(self.0, v as c_uint) }
    }

    /// Run the garbage collector after this amount of growth in the
    /// number of objects.
    pub fn gc_growth_trigger(&mut self, v: f64) {
        unsafe { jsonnet_sys::jsonnet_gc_growth_trigger(self.0, v) }
    }

    /// Expect a string as output and don't JSON encode it.
    pub fn string_output(&mut self, v: bool) {
        unsafe { jsonnet_sys::jsonnet_string_output(self.0, v as c_int) }
    }


    /// Override the callback used to locate imports.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::path::{Path,PathBuf};
    /// use std::ffi::OsStr;
    /// use jsonnet::JsonnetVm;
    ///
    /// fn myimport<'a>(_vm: &'a JsonnetVm, base: &Path, rel: &Path) -> Result<(PathBuf, String), String> {
    ///    if rel.file_stem() == Some(OsStr::new("bar")) {
    ///       let newbase = base.into();
    ///       let contents = "2 + 3".to_owned();
    ///       Ok((newbase, contents))
    ///    } else {
    ///       Err("not found".to_owned())
    ///    }
    /// }
    ///
    /// let mut vm = JsonnetVm::new();
    /// vm.import_callback(myimport);
    /// {
    ///    let output = vm.evaluate_snippet("myimport", "import 'x/bar.jsonnet'").unwrap();
    ///    assert_eq!(output.to_string(), "5\n");
    /// }
    ///
    /// {
    ///    let result = vm.evaluate_snippet("myimport", "import 'x/foo.jsonnet'");
    ///    assert!(result.is_err());
    /// }
    /// ```
    pub fn import_callback<'a>(&'a mut self, cb: ImportCallback<'a>) {
        let ctx = ImportContext {
            vm: self,
            cb: cb,
        };
        unsafe {
            jsonnet_sys::jsonnet_import_callback(self.as_ptr(),
                                                 import_callback as *const _,
                                                 // TODO: ctx is leaked :(
                                                 Box::into_raw(Box::new(ctx)) as *mut _);
        }
    }

    /// Register a native extension.
    ///
    /// This will appear in Jsonnet as a function type and can be
    /// accessed from `std.native("foo")`.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonnet::{JsonnetVm, JsonVal, JsonValue};
    ///
    /// fn myadd<'a>(vm: &'a JsonnetVm, args: &[JsonVal<'a>]) -> Result<JsonValue<'a>, String> {
    ///    let a = try!(args[0].as_num().ok_or("Expected a number"));
    ///    let b = try!(args[1].as_num().ok_or("Expected a number"));
    ///    Ok(JsonValue::from_num(vm, a + b))
    /// }
    ///
    /// let mut vm = JsonnetVm::new();
    /// vm.native_callback("myadd", myadd, &["a", "b"]);
    ///
    /// {
    ///    let result = vm.evaluate_snippet("nativetest",
    ///       "std.native('myadd')(2, 3)");
    ///    assert_eq!(result.unwrap().as_str(), "5\n");
    /// }
    ///
    /// {
    ///    let result = vm.evaluate_snippet("nativefail",
    ///       "std.native('myadd')('foo', 'bar')");
    ///    assert!(result.is_err());
    /// }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if `name` or `params` contain any embedded nul characters.
    pub fn native_callback<'a>(&'a mut self, name: &str, cb: NativeCallback<'a>, params: &[&'a str]) {
        let ctx = NativeContext {
            vm: self,
            argc: params.len(),
            cb: cb,
        };
        let cname = CString::new(name).unwrap();
        let cparams: Vec<_> = params.into_iter()
            .map(|&p| CString::new(p).unwrap())
            .collect();
        let cptrs: Vec<_> = cparams.iter()
            .map(|p| p.as_ptr())
            .chain(iter::once(ptr::null()))
            .collect();
        unsafe {
            jsonnet_sys::jsonnet_native_callback(self.as_ptr(),
                                                 cname.as_ptr(),
                                                 native_callback as *const _,
                                                 // TODO: ctx is leaked :(
                                                 Box::into_raw(Box::new(ctx)) as *mut _,
                                                 cptrs.as_slice().as_ptr());
        }
    }

    /// Bind a Jsonnet external var to the given string.
    ///
    /// # Panics
    ///
    /// Panics if `key` or `val` contain embedded nul characters.
    pub fn ext_var(&mut self, key: &str, val: &str) {
        let ckey = CString::new(key).unwrap();
        let cval = CString::new(val).unwrap();
        unsafe {
            jsonnet_sys::jsonnet_ext_var(self.0, ckey.as_ptr(), cval.as_ptr());
        }
    }

    /// Bind a Jsonnet external var to the given code.
    ///
    /// # Panics
    ///
    /// Panics if `key` or `code` contain embedded nul characters.
    pub fn ext_code(&mut self, key: &str, code: &str) {
        let ckey = CString::new(key).unwrap();
        let ccode = CString::new(code).unwrap();
        unsafe {
            jsonnet_sys::jsonnet_ext_code(self.0, ckey.as_ptr(), ccode.as_ptr());
        }
    }

    /// Bind a string top-level argument for a top-level parameter.
    ///
    /// # Panics
    ///
    /// Panics if `key` or `val` contain embedded nul characters.
    pub fn tla_var(&mut self, key: &str, val: &str) {
        let ckey = CString::new(key).unwrap();
        let cval = CString::new(val).unwrap();
        unsafe {
            jsonnet_sys::jsonnet_tla_var(self.0, ckey.as_ptr(), cval.as_ptr());
        }
    }

    /// Bind a code top-level argument for a top-level parameter.
    ///
    /// # Panics
    ///
    /// Panics if `key` or `code` contain embedded nul characters.
    pub fn tla_code(&mut self, key: &str, code: &str) {
        let ckey = CString::new(key).unwrap();
        let ccode = CString::new(code).unwrap();
        unsafe {
            jsonnet_sys::jsonnet_tla_code(self.0, ckey.as_ptr(), ccode.as_ptr());
        }
    }

    /// Indentation level when reformatting (number of spaces).
    pub fn fmt_indent(&mut self, n: u32) {
        unsafe {
            jsonnet_sys::jsonnet_fmt_indent(self.0, n as c_int);
        }
    }

    /// Maximum number of blank lines when reformatting.
    pub fn fmt_max_blank_lines(&mut self, n: u32) {
        unsafe {
            jsonnet_sys::jsonnet_fmt_max_blank_lines(self.0, n as c_int);
        }
    }

    /// Preferred style for string literals (`""` or `''`).
    pub fn fmt_string(&mut self, fmt: FmtString) {
        unsafe {
            jsonnet_sys::jsonnet_fmt_string(self.0, fmt.to_char());
        }
    }

    /// Preferred style for line comments (# or //).
    pub fn fmt_comment(&mut self, fmt: FmtComment) {
        unsafe {
            jsonnet_sys::jsonnet_fmt_comment(self.0, fmt.to_char());
        }
    }

    /// Whether to add an extra space on the inside of arrays.
    pub fn fmt_pad_arrays(&mut self, pad: bool) {
        unsafe {
            jsonnet_sys::jsonnet_fmt_pad_arrays(self.0, pad as c_int);
        }
    }

    /// Whether to add an extra space on the inside of objects.
    pub fn fmt_pad_objects(&mut self, pad: bool) {
        unsafe {
            jsonnet_sys::jsonnet_fmt_pad_objects(self.0, pad as c_int);
        }
    }

    /// Use syntax sugar where possible with field names.
    pub fn fmt_pretty_field_names(&mut self, sugar: bool) {
        unsafe {
            jsonnet_sys::jsonnet_fmt_pretty_field_names(self.0, sugar as c_int);
        }
    }

    /// Sort top-level imports in alphabetical order
    pub fn fmt_sort_import(&mut self, sort: bool) {
        unsafe {
            jsonnet_sys::jsonnet_fmt_sort_imports(self.0, sort as c_int);
        }
    }

    /// Reformat the Jsonnet input after desugaring.
    pub fn fmt_debug_desugaring(&mut self, reformat: bool) {
        unsafe {
            jsonnet_sys::jsonnet_fmt_debug_desugaring(self.0, reformat as c_int);
        }
    }

    /// Reformat a file containing Jsonnet code, return a Jsonnet string.
    ///
    /// # Panics
    ///
    /// Panics if `filename` contains embedded nul characters.
    pub fn fmt_file<'a,P>(&'a mut self, filename: P) -> Result<JsonnetString<'a>, Error<'a>>
        where P: AsRef<OsStr>
    {
        let fname = osstr2cstring(filename);
        let mut error = 1;
        let output = unsafe {
            let v = jsonnet_sys::jsonnet_fmt_file(self.0, fname.as_ptr(), &mut error);
            JsonnetString::from_ptr(self, v)
        };
        match error {
            0 => Ok(output),
            _ => Err(Error(output)),
        }
    }

    /// Reformat a string containing Jsonnet code, return a Jsonnet string.
    ///
    /// # Panics
    ///
    /// Panics if `filename` or `snippet` contain embedded nul characters.
    pub fn fmt_snippet<'a,P>(&'a mut self, filename: P, snippet: &str) -> Result<JsonnetString<'a>, Error<'a>>
        where P: AsRef<OsStr>
    {
        let fname = osstr2cstring(filename);
        let snippet = CString::new(snippet).unwrap();
        let mut error = 1;
        let output = unsafe {
            let v = jsonnet_sys::jsonnet_fmt_snippet(self.0, fname.as_ptr(), snippet.as_ptr(), &mut error);
            JsonnetString::from_ptr(self, v)
        };
        match error {
            0 => Ok(output),
            _ => Err(Error(output)),
        }
    }

    /// Set the number of lines of stack trace to display (None for unlimited).
    pub fn max_trace(&mut self, limit: Option<u32>) {
        let v = limit.unwrap_or(0);
        unsafe {
            jsonnet_sys::jsonnet_max_trace(self.0, v);
        }
    }

    /// Add to the default import callback's library search path.
    ///
    /// Search order is last to first, so more recently appended paths
    /// take precedence.
    ///
    /// # Panics
    ///
    /// Panics if `path` contains embedded nul characters.
    pub fn jpath_add<P>(&mut self, path: P)
        where P: AsRef<OsStr>
    {
        let v = osstr2cstring(path);
        unsafe {
            jsonnet_sys::jsonnet_jpath_add(self.0, v.as_ptr());
        }
    }

    /// Evaluate a file containing Jsonnet code, returning a JSON string.
    ///
    /// # Errors
    ///
    /// Returns any jsonnet error during evaluation.
    ///
    /// # Panics
    ///
    /// Panics if `filename` contains embedded nul characters.
    pub fn evaluate_file<'a,P>(&'a mut self, filename: P) -> Result<JsonnetString<'a>, Error<'a>>
        where P: AsRef<OsStr>
    {
        let fname = osstr2cstring(filename);
        let mut error = 1;
        let output = unsafe {
            let v = jsonnet_sys::jsonnet_evaluate_file(self.0, fname.as_ptr(), &mut error);
            JsonnetString::from_ptr(self, v)
        };
        match error {
            0 => Ok(output),
            _ => Err(Error(output)),
        }
    }

    /// Evaluate a string containing Jsonnet code, returning a JSON string.
    ///
    /// The `filename` argument is only used in error messages.
    ///
    /// # Errors
    ///
    /// Returns any jsonnet error during evaluation.
    ///
    /// # Panics
    ///
    /// Panics if `filename` or `snippet` contain embedded nul characters.
    pub fn evaluate_snippet<'a,P>(&'a mut self, filename: P, snippet: &str) -> Result<JsonnetString<'a>, Error<'a>>
        where P: AsRef<OsStr>
    {
        let fname = osstr2cstring(filename);
        let snip = CString::new(snippet).unwrap();
        let mut error = 1;
        let output = unsafe {
            let v = jsonnet_sys::jsonnet_evaluate_snippet(self.0, fname.as_ptr(), snip.as_ptr(), &mut error);
            JsonnetString::from_ptr(self, v)
        };
        match error {
            0 => Ok(output),
            _ => Err(Error(output)),
        }
    }

    /// Evaluate a file containing Jsonnet code, returning a number of
    /// named JSON files.
    ///
    /// # Errors
    ///
    /// Returns any jsonnet error during evaluation.
    ///
    /// # Panics
    ///
    /// Panics if `filename` contains embedded nul characters.
    pub fn evaluate_file_multi<'a,P>(&'a mut self, filename: P) -> Result<EvalMap<'a>, Error<'a>>
        where P: AsRef<OsStr>
    {
        let fname = osstr2cstring(filename);
        let mut error = 1;
        let output = unsafe {
            let v = jsonnet_sys::jsonnet_evaluate_file_multi(self.0, fname.as_ptr(), &mut error);
            JsonnetString::from_ptr(self, v)
        };
        match error {
            0 => Ok(EvalMap(output)),
            _ => Err(Error(output)),
        }
    }

    /// Evaluate a file containing Jsonnet code, returning a number of
    /// named JSON files.
    ///
    /// # Errors
    ///
    /// Returns any jsonnet error during evaluation.
    ///
    /// # Panics
    ///
    /// Panics if `filename` or `snippet` contain embedded nul characters.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use jsonnet::JsonnetVm;
    ///
    /// let mut vm = JsonnetVm::new();
    /// let output = vm.evaluate_snippet_multi("multi",
    ///    "{'foo.json': 'foo', 'bar.json': 'bar'}").unwrap();
    ///
    /// let map: HashMap<_,_> = output.iter().collect();
    /// assert_eq!(*map.get("bar.json").unwrap(), "\"bar\"\n");
    /// ```
    pub fn evaluate_snippet_multi<'a,P>(&'a mut self, filename: P, snippet: &str) -> Result<EvalMap<'a>, Error<'a>>
        where P: AsRef<OsStr>
    {
        let fname = osstr2cstring(filename);
        let snippet = CString::new(snippet).unwrap();
        let mut error = 1;
        let output = unsafe {
            let v = jsonnet_sys::jsonnet_evaluate_snippet_multi(self.0, fname.as_ptr(), snippet.as_ptr(), &mut error);
            JsonnetString::from_ptr(self, v)
        };
        match error {
            0 => Ok(EvalMap(output)),
            _ => Err(Error(output)),
        }
    }

    /// Evaluate a file containing Jsonnet code, returning a number of
    /// JSON files.
    ///
    /// # Errors
    ///
    /// Returns any jsonnet error during evaluation.
    ///
    /// # Panics
    ///
    /// Panics if `filename` contains embedded nul characters.
    pub fn evaluate_file_stream<'a,P>(&'a mut self, filename: P) -> Result<EvalList<'a>, Error<'a>>
        where P: AsRef<OsStr>
    {
        let fname = osstr2cstring(filename);
        let mut error = 1;
        let output = unsafe {
            let v = jsonnet_sys::jsonnet_evaluate_file_stream(self.0, fname.as_ptr(), &mut error);
            JsonnetString::from_ptr(self, v)
        };
        match error {
            0 => Ok(EvalList(output)),
            _ => Err(Error(output)),
        }
    }

    /// Evaluate a string containing Jsonnet code, returning a number
    /// of JSON files.
    ///
    /// # Errors
    ///
    /// Returns any jsonnet error during evaluation.
    ///
    /// # Panics
    ///
    /// Panics if `filename` or `snippet` contain embedded nul characters.
    ///
    /// # Examples
    ///
    /// ```
    /// use jsonnet::JsonnetVm;
    ///
    /// let mut vm = JsonnetVm::new();
    /// let output = vm.evaluate_snippet_stream("stream",
    ///    "['foo', 'bar']").unwrap();
    ///
    /// let list: Vec<_> = output.iter().collect();
    /// assert_eq!(list, vec!["\"foo\"\n", "\"bar\"\n"]);
    /// ```
    pub fn evaluate_snippet_stream<'a,P>(&'a mut self, filename: P, snippet: &str) -> Result<EvalList<'a>, Error<'a>>
        where P: AsRef<OsStr>
    {
        let fname = osstr2cstring(filename);
        let snippet = CString::new(snippet).unwrap();
        let mut error = 1;
        let output = unsafe {
            let v = jsonnet_sys::jsonnet_evaluate_snippet_stream(self.0, fname.as_ptr(), snippet.as_ptr(), &mut error);
            JsonnetString::from_ptr(self, v)
        };
        match error {
            0 => Ok(EvalList(output)),
            _ => Err(Error(output)),
        }
    }
}

impl Drop for JsonnetVm {
    fn drop(&mut self) {
        assert!(!self.0.is_null());
        unsafe { jsonnet_sys::jsonnet_destroy(self.0) }
    }
}

#[test]
fn basic_eval() {
    let mut vm = JsonnetVm::new();
    let result = vm.evaluate_snippet("example", "'Hello ' + 'World'");
    println!("result is {:?}", result);
    assert!(result.is_ok());
    assert_eq!(result.unwrap().to_string(), "\"Hello World\"\n");
}

#[test]
fn basic_eval_err() {
    let mut vm = JsonnetVm::new();
    let result = vm.evaluate_snippet("example", "bogus");
    println!("result is {:?}", result);
    assert!(result.is_err());
    assert!(result.unwrap_err().contains("Unknown variable: bogus"));
}