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
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
//! Implements a virtual machine which interprets bytecode functions.
//!
//! The virtual machine consists of:
//!
//!  * A value stack, containing values stored or passed into functions
//!  * A single value register into which values can be loaded from the stack
//!    and from which values can be pushed onto the stack.
//!  * A call stack, containing for each successive function:
//!    * an index into the bytecode ("instruction pointer")
//!    * an index into the value stack ("stack pointer")
//!    * any constant values referenced by bytecode instructions
//!    * any enclosed values referenced by bytecode instructions
//!
//! Bytecode instructions may modify or consume the value register, push values
//! onto the stack, modify the instruction pointer, add a function call to the
//! call stack, or return from the function currently being executed.
//!
//! When a bytecode function is added to the stack, its stack pointer will be set
//! to the position of the first argument which is passed to the function. It may
//! load or modify these values. When the function returns, all values after the
//! stack pointer will be automatically removed from the stack before
//! returning control to the previous function execution. Every function
//! returns a value, which is available to the calling function through the
//! value register.

use std::cell::Cell;
use std::error::Error as StdError;
use std::fmt;
use std::mem::replace;
use std::rc::Rc;
use std::time::Instant;
use std::vec::Drain;

use bytecode::{Code, CodeReader};
use error::Error;
use function::{Arity, Function, Lambda, SystemFn, first, last, init, tail};
use integer::{Integer, Ratio};
use lexer::{highlight_span, Span};
use restrict::{RestrictConfig, RestrictError};
use scope::{MasterScope, Scope};
use string_fmt::FormatError;
use name::{debug_names, display_names, get_standard_name, get_system_fn,
    Name, NameDisplay, NameStore};
use trace::{Trace, TraceItem, set_traceback};
use value::{FromValueRef, Value};

/// Interval, in instructions run, between checking time limit
const TIME_CHECK_INTERVAL: u32 = 100;

/// Represents an execution context
#[derive(Clone)]
pub struct Context {
    scope: Scope,
    restrict: RestrictConfig,
    // In limited circumstances, a Machine may be created during execution
    // to execute a program within a program. Therefore, start time must be
    // carried along with the context rather than attached to a particular
    // Machine.
    //
    // These values are copied when a Context is cloned, but that doesn't
    // create a problem because updates need not be carried back into
    // prior existing Machines.
    run_start: Cell<Option<Instant>>,
    run_level: Cell<u32>,
    memory_held: Cell<usize>,
}

impl Context {
    /// Creates a new execution context.
    pub fn new(scope: Scope, restrict: RestrictConfig) -> Context {
        Context{
            scope: scope,
            restrict: restrict,
            run_start: Cell::new(None),
            run_level: Cell::new(0),
            memory_held: Cell::new(0),
        }
    }

    /// Returns a reference to the contained scope.
    pub fn scope(&self) -> &Scope { &self.scope }

    /// Creates a new execution context with the given scope.
    pub fn with_scope(&self, scope: Scope) -> Context {
        Context::new(scope, self.restrict.clone())
    }

    /// Returns a reference to the contained restriction configuration.
    pub fn restrict(&self) -> &RestrictConfig { &self.restrict }

    fn dec_run_level(&self) {
        let n = self.run_level.get() - 1;
        self.run_level.set(n);
        if n == 0 {
            self.run_start.set(None);
        }
    }

    fn inc_run_level(&self) {
        let n = self.run_level.get();
        self.run_level.set(n + 1);
        if n == 0 {
            self.run_start.set(Some(Instant::now()));
        }
    }

    fn start_time(&self) -> Instant {
        self.run_start.get().expect("context missing start time")
    }

    fn set_memory<F>(&self, f: F) -> usize
            where F: FnOnce(usize) -> usize {
        let old = self.memory_held.get();
        let new = f(old);
        self.memory_held.set(new);
        new
    }
}

/// Represents an error generated while executing bytecode.
#[derive(Debug)]
pub enum ExecError {
    /// Error in arity to function call
    ArityError{
        /// Name of function, if available
        name: Option<Name>,
        /// Expected count or range of arguments
        expected: Arity,
        /// Number of arguments present
        found: u32,
    },
    /// Attempt to compare with a `NaN` `Float` value.
    CompareNaN,
    /// Type does not support ordered comparison
    CannotCompare(&'static str),
    /// Attempt to redefine a name in master scope
    CannotDefine(Name),
    /// Attempt to divide by a number equal to zero.
    DivideByZero,
    /// Duplicate field name in struct definition
    DuplicateField(Name),
    /// Duplicate keyword argument to function
    DuplicateKeyword(Name),
    /// Duplicate struct definition
    DuplicateStructDef(Name),
    /// No such field name in struct
    FieldError{
        /// Name of struct type
        struct_name: Name,
        /// Field name
        field: Name,
    },
    /// Type error assigning value to field
    FieldTypeError{
        /// Name of struct type
        struct_name: Name,
        /// Name of field
        field: Name,
        /// Expected type name
        expected: Name,
        /// Name of type received
        found: &'static str,
        /// Value received
        value: Option<Value>,
    },
    /// Error in `format` call
    FormatError{
        /// Supplied format string
        fmt: Box<str>,
        /// Span within format string
        span: Span,
        /// Formatting error produced
        err: FormatError,
    },
    /// Invalid index into closure values
    InvalidClosureValue(u32),
    /// Invalid const index
    InvalidConst(u32),
    /// Invalid (zero) depth value to `Quote`, `Quasiquote`, or `Comma` instruction
    InvalidDepth,
    /// Invalid jump label
    InvalidJump(u32),
    /// Slice indices out of order
    InvalidSlice(usize, usize),
    /// Invalid stack index
    InvalidStack(u32),
    /// Invalid system function
    InvalidSystemFn(u32),
    /// `CallSys` instruction for system function which requires argument count
    MissingArgCount(Name),
    /// Attempt to construct a `Struct` without the given field
    MissingField{
        /// Struct type name
        struct_name: Name,
        /// Field name
        field: Name,
    },
    /// Attempt to lookup a name that did not exist in scope.
    NameError(Name),
    /// Attempt to slice a string not along UTF-8 code point boundaries.
    NotCharBoundary(usize),
    /// Odd number of parameters when keyword-value pairs expected
    OddKeywordParams,
    /// Attempt to access an element in a list that is out of bounds.
    OutOfBounds(usize),
    /// Integer overflow during certain arithmetic operations.
    Overflow,
    /// Code called `panic`
    Panic(Option<Value>),
    /// Struct definition not found
    StructDefError(Name),
    /// Operation performed on unexpected type
    TypeError{
        /// Name of the type expected
        expected: &'static str,
        /// Name of the type received
        found: &'static str,
        /// Value received
        value: Option<Value>,
    },
    /// Function received a value of incorrect type
    StructMismatch{
        /// Type of left-hand side value
        lhs: Name,
        /// Type of right-hand side value
        rhs: Name,
    },
    /// Attempt to operate on two values of incompatible types
    TypeMismatch{
        /// Type of left-hand side value
        lhs: &'static str,
        /// Type of right-hand side value
        rhs: &'static str,
    },
    /// Unexpected end in bytecode
    UnexpectedEnd,
    /// Unrecognized keyword passed to function
    UnrecognizedKeyword(Name),
    /// Unrecognized opcode
    UnrecognizedOpCode(u8),
}

impl StdError for ExecError {
    fn description(&self) -> &str { "execution error" }
}

/// Returns a `Panic` error with the given value.
///
/// This is equivalent to `(panic value)`.
pub fn panic<T, E>(value: T) -> E
        where T: Into<Value>, E: From<ExecError> {
    From::from(ExecError::Panic(Some(value.into())))
}

/// Returns a `Panic` error with no value.
///
/// This is equivalent to `(panic)`.
pub fn panic_none<E>() -> E
        where E: From<ExecError> {
    From::from(ExecError::Panic(None))
}

impl ExecError {
    /// Convenience function to return a `TypeError` value when `expected`
    /// type is expected, but some other type of value is found.
    pub fn expected(expected: &'static str, v: &Value) -> ExecError {
        ExecError::TypeError{
            expected: expected,
            found: v.type_name(),
            value: Some(v.clone()),
        }
    }

    /// Convenience function to return a `FieldTypeError` value when a struct
    /// field of the incorrect type is received.
    pub fn expected_field(struct_name: Name, field: Name,
            expected: Name, v: &Value) -> ExecError {
        ExecError::FieldTypeError{
            struct_name: struct_name,
            field: field,
            expected: expected,
            found: v.type_name(),
            value: Some(v.clone()),
        }
    }
}

impl fmt::Display for ExecError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use self::ExecError::*;

        match *self {
            ArityError{expected, found, ..} =>
                write!(f, "expected {}; found {}", expected, found),
            CannotCompare(ty) => write!(f, "cannot compare values of type {}", ty),
            CannotDefine(_) =>
                f.write_str("cannot define name of standard value or operator"),
            CompareNaN => f.write_str("attempt to compare NaN value"),
            DivideByZero => f.write_str("attempt to divide by zero"),
            DuplicateField(_) => f.write_str("duplicate field"),
            DuplicateKeyword(_) => f.write_str("duplicate keyword"),
            DuplicateStructDef(_) => f.write_str("duplicate struct definition"),
            FieldError{..} => f.write_str("no such field in struct"),
            FieldTypeError{..} => f.write_str("incorrect field type"),
            FormatError{ref err, ..} =>
                write!(f, "error in string formatting: {}", err),
            InvalidClosureValue(n) => write!(f, "invalid closure value: {}", n),
            InvalidConst(n) => write!(f, "invalid const: {}", n),
            InvalidDepth => f.write_str("invalid depth operand"),
            InvalidJump(label) => write!(f, "invalid jump label: {}", label),
            InvalidSlice(begin, end) => write!(f, "invalid slice {}..{}", begin, end),
            InvalidStack(n) => write!(f, "invalid stack index: {}", n),
            InvalidSystemFn(n) => write!(f, "invalid system function: {}", n),
            MissingArgCount(_) =>
                write!(f, "system function requires argument count"),
            MissingField{..} => f.write_str("missing field in struct"),
            NameError(_) => f.write_str("name not found in global scope"),
            StructDefError(_) => f.write_str("struct definition not found"),
            NotCharBoundary(n) => write!(f, "index not on char boundary: {}", n),
            OddKeywordParams => f.write_str("expected keyword-value pairs"),
            OutOfBounds(n) => write!(f, "index out of bounds: {}", n),
            Overflow => f.write_str("integer overflow"),
            Panic(_) => f.write_str("panic"),
            TypeError{expected, found, ..} =>
                write!(f, "type error: expected {}; found {}", expected, found),
            StructMismatch{..} => f.write_str("incorrect struct type"),
            TypeMismatch{lhs, rhs} =>
                write!(f, "type mismatch; {} and {}", lhs, rhs),
            UnexpectedEnd => f.write_str("unexpected end of bytecode"),
            UnrecognizedKeyword(_) => f.write_str("unrecognized keyword argument"),
            UnrecognizedOpCode(n) => write!(f, "unrecognized opcode {} ({:x})", n, n),
        }
    }
}

impl NameDisplay for ExecError {
    fn fmt(&self, names: &NameStore, f: &mut fmt::Formatter) -> fmt::Result {
        use self::ExecError::*;

        match *self {
            ArityError{name: Some(name), ..} =>
                write!(f, "`{}` {}", names.get(name), self),
            CannotDefine(name) |
            DuplicateField(name) |
            DuplicateKeyword(name) |
            DuplicateStructDef(name) |
            NameError(name) |
            StructDefError(name) |
            UnrecognizedKeyword(name) =>
                write!(f, "{}: {}", self, names.get(name)),
            FieldError{struct_name, field} =>
                write!(f, "no such field `{}` in struct `{}`",
                    names.get(field),
                    names.get(struct_name)),
            FieldTypeError{struct_name, field, expected, found, ref value} => {
                if let Some(ref value) = *value {
                    write!(f, "type error for field `{}` of struct `{}`: \
                            expected {}; found {}: {}",
                        names.get(field),
                        names.get(struct_name),
                        names.get(expected),
                        found,
                        debug_names(names, value))
                } else {
                    write!(f, "type error for field `{}` of struct `{}`: \
                            expected {}; found {}",
                        names.get(field),
                        names.get(struct_name),
                        names.get(expected),
                        found)
                }
            }
            FormatError{ref fmt, span, ref err} => {
                let hi = highlight_span(fmt, span);

                try!(f.write_str("error in string formatting:\n"));
                try!(writeln!(f, "{}:{}:error: {}", hi.line, hi.col, err));
                try!(writeln!(f, "    {}", hi.source));
                try!(writeln!(f, "    {}", hi.highlight));
                Ok(())
            }
            MissingArgCount(name) =>
                write!(f, "system function `{}` requires argument count",
                    names.get(name)),
            MissingField{struct_name, field} =>
                write!(f, "missing field `{}` in struct `{}`",
                    names.get(field),
                    names.get(struct_name)),
            Panic(ref value) => match *value {
                Some(ref v) => write!(f, "panic: {}", display_names(names, v)),
                None => f.write_str("explicit panic"),
            },
            StructMismatch{lhs, rhs} =>
                write!(f, "struct type mismatch: `{}` and `{}`",
                    names.get(lhs),
                    names.get(rhs)),
            TypeError{expected, found, ref value} => {
                if let Some(ref value) = *value {
                    write!(f, "type error: expected {}; found {}: {}",
                        expected, found, debug_names(names, value))
                } else {
                    write!(f, "type error: expected {}; found {}",
                        expected, found)
                }
            }
            _ => fmt::Display::fmt(self, f)
        }
    }
}

/// Executes a code object and returns the value.
pub fn execute(ctx: &Context, code: Rc<Code>) -> Result<Value, Error> {
    let mut mach = Machine::new(ctx);

    mach.execute(ctx.scope(), code)
        .map_err(|e| { set_traceback(mach.build_trace()); e })
}

/// Calls a function or lambda in the given scope with the given arguments.
pub fn call_function(ctx: &Context, fun: Value, args: Vec<Value>) -> Result<Value, Error> {
    match fun {
        Value::Function(fun) => execute_function(ctx, fun, args)
            .map_err(|e| { set_traceback(
                Trace::single(TraceItem::CallSys(fun.name), None)); e }),
        Value::Lambda(l) => execute_lambda(ctx, l, args),
        ref v => Err(From::from(ExecError::expected("function", v)))
    }
}

/// Executes a `Function` in the given scope and returns the value.
pub fn execute_function(ctx: &Context, fun: Function, mut args: Vec<Value>)
        -> Result<Value, Error> {
    let n_args = args.len() as u32;

    if !fun.sys_fn.arity.accepts(n_args) {
        Err(From::from(ExecError::ArityError{
            name: Some(fun.name),
            expected: fun.sys_fn.arity,
            found: n_args,
        }))
    } else {
        (fun.sys_fn.callback)(ctx, &mut args)
    }
}

/// Executes a `Lambda` in the given scope and returns the value.
pub fn execute_lambda(ctx: &Context, lambda: Lambda, args: Vec<Value>) -> Result<Value, Error> {
    let mut mach = Machine::new(ctx);

    mach.execute_lambda(lambda, args)
        .map_err(|e| { set_traceback(mach.build_trace()); e })
}

struct StackFrame {
    /// Code object
    code: Rc<Code>,
    /// Code scope
    scope: Scope,
    /// Closure values
    // TODO: When Rc<[T]> is possible for non-static [T], change this.
    values: Option<Rc<Box<[Value]>>>,
    /// Instruction pointer
    iptr: u32,
    /// Stack pointer
    sptr: u32,
    /// Whether the function value was on the stack
    fn_on_stack: bool,
}

struct Machine {
    context: Context,
    stack: Vec<Value>,
    call_stack: Vec<StackFrame>,
    value: Value,
    sys_fn_call: Option<Name>,
}

impl Machine {
    fn new(ctx: &Context) -> Machine {
        Machine{
            context: ctx.clone(),
            stack: Vec::with_capacity(ctx.restrict().value_stack_size),
            call_stack: Vec::with_capacity(ctx.restrict().call_stack_size),
            value: Value::Unit,
            sys_fn_call: None,
        }
    }

    fn build_trace(&self) -> Trace {
        let mut trace = Vec::new();

        for frame in &self.call_stack {
            let mod_name = frame.scope.name();

            let item = match frame.code.name {
                Some(fn_name) => TraceItem::CallCode(mod_name, fn_name),
                None => TraceItem::CallLambda(mod_name),
            };

            trace.push(item);
        }

        if let Some(name) = self.sys_fn_call {
            trace.push(TraceItem::CallSys(name));
        }

        Trace::new(trace, None)
    }

    fn execute(&mut self, scope: &Scope, code: Rc<Code>) -> Result<Value, Error> {
        let arity = code.arity();

        if arity != Arity::Exact(0) {
            return Err(From::from(ExecError::ArityError{
                name: code.name,
                expected: arity,
                found: 0,
            }));
        }

        self.start(StackFrame{
            code: code,
            scope: scope.clone(),
            values: None,
            iptr: 0,
            sptr: 0,
            fn_on_stack: false,
        })
    }

    fn execute_lambda(&mut self, lambda: Lambda, args: Vec<Value>)
            -> Result<Value, Error> {
        let scope = lambda.scope.upgrade()
            .expect("Lambda scope has been destroyed");

        try!(self.push_iter(args));

        let n_args = self.stack.len() as u32;
        let arity = lambda.code.arity();

        if !arity.accepts(n_args) {
            return Err(From::from(ExecError::ArityError{
                name: lambda.code.name,
                expected: arity,
                found: n_args,
            }));
        }

        let n_params = lambda.code.n_params;

        if n_params > n_args {
            try!(self.push_unbound(lambda.code.n_params - n_args));
        }
        if !lambda.code.kw_params.is_empty() {
            try!(self.push_unbound(lambda.code.kw_params.len() as u32));
        }
        if lambda.code.has_rest_params() {
            if n_params >= n_args {
                try!(self.push(Value::Unit));
            } else {
                try!(self.build_list(n_args - n_params));
                try!(self.push_value());
            }
        }

        self.start(StackFrame{
            code: lambda.code,
            scope: scope,
            values: lambda.values,
            iptr: 0,
            sptr: 0,
            fn_on_stack: false,
        })
    }

    fn start(&mut self, mut frame: StackFrame) -> Result<Value, Error> {
        self.context.inc_run_level();

        let res = self.run(&mut frame);

        self.context.dec_run_level();

        if let Err(e) = res {
            // Save the frame for stack traces
            self.call_stack.push(frame);
            return Err(e);
        }

        Ok(self.value.take())
    }

    fn run(&mut self, frame: &mut StackFrame) -> Result<(), Error> {
        use bytecode::Instruction::*;

        let mut n_instructions = 0;

        loop {
            let instr = {
                let mut r = CodeReader::new(&frame.code.code, frame.iptr as usize);
                let instr = try!(r.read_instruction());
                frame.iptr = r.offset() as u32;
                instr
            };

            n_instructions += 1;

            if n_instructions % TIME_CHECK_INTERVAL == 0 {
                try!(self.check_time());
            }

            match instr {
                Load(n) => try!(self.load(frame.sptr + n)),
                LoadC(n) => try!(self.load_c(frame, n)),
                UnboundToUnit(n) => try!(self.unbound_to_unit(frame.sptr + n)),
                GetDef(n) => try!(self.get_def(frame, n)),
                Push => try!(self.push_value()),
                Unit => self.value = Value::Unit,
                True => self.value = Value::Bool(true),
                False => self.value = Value::Bool(false),
                Const(n) => try!(self.load_const(&frame.code, n)),
                Store(n) => try!(self.store(frame.sptr + n)),
                LoadPush(n) => try!(self.load_push(frame.sptr + n)),
                LoadCPush(n) => try!(self.load_c_push(frame, n)),
                GetDefPush(n) => try!(self.get_def_push(frame, n)),
                UnitPush => try!(self.push(Value::Unit)),
                TruePush => try!(self.push(Value::Bool(true))),
                FalsePush => try!(self.push(Value::Bool(false))),
                ConstPush(n) => try!(self.push_const(&frame.code, n)),
                SetDef(n) => try!(self.set_def(frame, n)),
                List(n) => try!(self.build_list(n)),
                Quote(n) => try!(self.quote_value(n)),
                Quasiquote(n) => try!(self.quasiquote_value(n)),
                Comma(n) => try!(self.comma_value(n)),
                CommaAt(n) => try!(self.comma_at_value(n)),
                BuildClosure(n_const, n_values) =>
                    try!(self.build_closure(&frame.code, n_const, n_values)),
                Jump(label) => try!(self.jump(frame, label)),
                JumpIf(label) => try!(self.jump_if(frame, label)),
                JumpIfBound(label, n) => {
                    let n = frame.sptr + n;
                    try!(self.jump_if_bound(frame, label, n))
                }
                JumpIfNot(label) => try!(self.jump_if_not(frame, label)),
                JumpIfEq(label) => try!(self.jump_if_eq(frame, label)),
                JumpIfNotEq(label) => try!(self.jump_if_not_eq(frame, label)),
                JumpIfNull(label) => try!(self.jump_if_null(frame, label)),
                JumpIfNotNull(label) => try!(self.jump_if_not_null(frame, label)),
                JumpIfEqConst(label, n) =>
                    try!(self.jump_if_eq_const(frame, label, n)),
                JumpIfNotEqConst(label, n) =>
                    try!(self.jump_if_not_eq_const(frame, label, n)),
                Null => self.is_null(),
                NotNull => self.is_not_null(),
                Eq => try!(self.equal()),
                NotEq => try!(self.not_equal()),
                EqConst(n) => try!(self.equal_const(&frame.code, n)),
                NotEqConst(n) => try!(self.not_equal_const(&frame.code, n)),
                Not => try!(self.negate()),
                Inc => try!(self.increment()),
                Dec => try!(self.decrement()),
                Append => try!(self.append_value()),
                First => try!(self.first()),
                Tail => try!(self.tail()),
                Init => try!(self.init()),
                Last => try!(self.last()),
                FirstPush => try!(self.first_push()),
                TailPush => try!(self.tail_push()),
                InitPush => try!(self.init_push()),
                LastPush => try!(self.last_push()),
                CallSys(n) => try!(self.call_sys(frame, n)),
                CallSysArgs(n, n_args) =>
                    try!(self.call_sys_args(frame, n, n_args)),
                CallConst(n, n_args) =>
                    try!(self.call_const(frame, n, n_args)),
                Call(n) => try!(self.call_function(frame, n)),
                Apply(n) => try!(self.apply(frame, n)),
                ApplyConst(n, n_args) => try!(self.apply_const(frame, n, n_args)),
                ApplySelf(n) => try!(self.apply_self(frame, n)),
                TailApplySelf(n) => try!(self.tail_apply_self(frame, n)),
                CallSelf(n) => try!(self.call_self(frame, n)),
                TailCallSelf(n) => try!(self.tail_call(frame, n)),
                Skip(n) => try!(self.skip_stack(n as usize)),
                Return => {
                    match self.call_stack.pop() {
                        None => break,
                        Some(call) => {
                            self.clean_stack(frame.sptr as usize);
                            if frame.fn_on_stack {
                                // Pop one more value for the function
                                try!(self.pop());
                            }
                            *frame = call;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    fn build_closure(&mut self, code: &Code, n_const: u32, n_values: u32)
            -> Result<(), ExecError> {
        let (code, scope) = match *try!(get_const(code, n_const)) {
            Value::Lambda(ref l) => (l.code.clone(), l.scope.clone()),
            ref v => return Err(ExecError::expected("lambda", v))
        };

        let values = try!(self.drain_stack_top(n_values))
            .collect::<Vec<_>>().into_boxed_slice();

        self.value = Value::Lambda(Lambda::new_closure(code, scope, values));
        Ok(())
    }

    fn build_list(&mut self, n: u32) -> Result<(), ExecError> {
        let v = try!(self.drain_stack_top(n)).collect::<Vec<_>>().into();
        self.value = v;
        Ok(())
    }

    fn check_memory(&self, n: usize) -> Result<(), RestrictError> {
        if n > self.context.restrict().memory_limit {
            return Err(RestrictError::MemoryLimitExceeded);
        }
        Ok(())
    }

    fn check_time(&self) -> Result<(), RestrictError> {
        if let Some(time_limit) = self.context.restrict().execution_time {
            let start = self.context.start_time();

            if start.elapsed() >= time_limit {
                return Err(RestrictError::ExecutionTimeExceeded);
            }
        }

        Ok(())
    }

    fn get_sys_fn(&self, n: u32) -> Result<(Name, &'static SystemFn), ExecError> {
        get_standard_name(n).and_then(|n| get_system_fn(n).map(|f| (n, f)))
            .ok_or(ExecError::InvalidSystemFn(n))
    }

    fn call_sys(&mut self, frame: &mut StackFrame, n: u32) -> Result<(), Error> {
        let (name, sys_fn) = try!(self.get_sys_fn(n));

        let n_args = match sys_fn.arity {
            Arity::Exact(n) => n,
            _ => return Err(From::from(ExecError::MissingArgCount(name)))
        };

        self.call_sys_args(frame, n, n_args)
    }

    fn call_sys_args(&mut self, frame: &mut StackFrame, sys_fn: u32, n_args: u32)
            -> Result<(), Error> {
        let (name, sys_fn) = try!(self.get_sys_fn(sys_fn));
        self.call_sys_fn(frame, name, sys_fn, n_args, false)
    }

    fn call_sys_fn(&mut self, frame: &mut StackFrame, name: Name,
            sys_fn: &SystemFn, n_args: u32, fn_on_stack: bool)
            -> Result<(), Error> {
        if !sys_fn.arity.accepts(n_args) {
            Err(From::from(ExecError::ArityError{
                name: Some(name),
                expected: sys_fn.arity,
                found: n_args,
            }))
        } else {
                let mut args = try!(self.drain_stack_top(n_args))
                    .collect::<Vec<_>>();

                if fn_on_stack {
                    try!(self.pop());
                }

                // Store the name for traceback if an error is generated
                self.sys_fn_call = Some(name);

                let ctx = self.context.with_scope(frame.scope.clone());

                let v = try!((sys_fn.callback)(&ctx, &mut args));
                self.value = v;

                self.sys_fn_call = None;

                Ok(())
        }
    }

    fn call_const(&mut self, frame: &mut StackFrame,
            n: u32, n_args: u32) -> Result<(), Error> {
        let name = try!(get_const_name(&frame.code, n));
        let v = try!(self.get_value(frame, name));

        self.value = Value::Unit;
        self.call_value(frame, v, n_args, false)
    }

    /// Calls a function on the stack with `n_args` arguments.
    /// The callable value must be on the stack before the given arguments.
    fn call_function(&mut self, frame: &mut StackFrame, n_args: u32)
            -> Result<(), Error> {
        let v = try!(self.get_stack_top(n_args)).clone();
        self.call_value(frame, v, n_args, true)
    }

    fn call_value(&mut self, frame: &mut StackFrame, value: Value,
            n_args: u32, fn_on_stack: bool) -> Result<(), Error> {
        match value {
            Value::Function(fun) =>
                self.call_sys_fn(frame, fun.name, &fun.sys_fn, n_args, fn_on_stack),
            Value::Lambda(fun) =>
                self.call_lambda(frame, fun, n_args, fn_on_stack),
            Value::Foreign(ref fv) => {
                let mut args = try!(self.drain_stack_top(n_args))
                    .collect::<Vec<_>>();

                if fn_on_stack {
                    try!(self.pop());
                }

                let ctx = self.context.with_scope(frame.scope.clone());
                let v = try!(fv.call_value(&ctx, &mut args));
                self.value = v;

                Ok(())
            }
            ref v => Err(From::from(ExecError::expected("function", v)))
        }
    }

    fn call_lambda(&mut self, frame: &mut StackFrame, lambda: Lambda,
            n_args: u32, fn_on_stack: bool) -> Result<(), Error> {
        let scope = lambda.scope.upgrade()
            .expect("Lambda scope has been destroyed");

        if self.stack.len() < n_args as usize {
            return Err(From::from(RestrictError::ValueStackExceeded));
        }

        let n_args = try!(self.setup_call(&lambda.code, n_args));

        let old_frame = replace(frame, StackFrame{
            code: lambda.code,
            scope: scope,
            values: lambda.values,
            iptr: 0,
            sptr: self.stack.len() as u32 - n_args,
            fn_on_stack: fn_on_stack,
        });

        try!(self.save_frame(old_frame));
        Ok(())
    }

    /// Sets up a call to a `Code` object, ensuring that the incoming argument
    /// count is valid for the given code object being called.
    /// Keyword and rest arguments are processed and `Unbound` values
    /// are pushed to the stack, if necessary.
    ///
    /// Returns the final count of stack argument values.
    fn setup_call(&mut self, code: &Code, mut n_args: u32) -> Result<u32, Error> {
        if n_args < code.req_params {
            return Err(From::from(ExecError::ArityError{
                name: code.name,
                expected: code.arity(),
                found: n_args,
            }));
        }

        if n_args < code.n_params {
            try!(self.push_unbound(code.n_params - n_args));
            n_args = code.n_params;
        }

        if code.has_rest_params() {
            if n_args > code.n_params {
                try!(self.build_list(n_args - code.n_params));
                try!(self.push_value());
                n_args = code.n_params + 1;
            } else {
                try!(self.push(Value::Unit));
                n_args += 1;
            };
        } else if code.has_kw_params() {
            let mut kw_values = vec![Value::Unbound; code.kw_params.len()];

            if n_args > code.n_params {
                let n_kw_args = n_args - code.n_params;
                let mut iter = try!(self.drain_stack_top(n_kw_args));

                while let Some(kw) = iter.next() {
                    let kw = try!(get_keyword(&kw));
                    let v = match iter.next() {
                        Some(v) => v,
                        None => return Err(From::from(ExecError::OddKeywordParams))
                    };

                    match code.kw_params.iter().position(|&n| n == kw) {
                        Some(pos) => {
                            if let Value::Unbound = kw_values[pos] {
                                kw_values[pos] = v;
                            } else {
                                return Err(From::from(ExecError::DuplicateKeyword(kw)));
                            }
                        }
                        None => return Err(From::from(ExecError::UnrecognizedKeyword(kw)))
                    }
                }
            }

            n_args = code.n_params + kw_values.len() as u32;
            for v in kw_values {
                try!(self.push(v));
            }
        } else if n_args != code.n_params {
            return Err(From::from(ExecError::ArityError{
                name: code.name,
                expected: code.arity(),
                found: n_args,
            }));
        }

        Ok(n_args)
    }

    /// Consumes value, which must be `Unit` or `List`,
    /// and pushes each contained value to the top of the stack,
    /// returning the number of values pushed.
    fn expand_value(&mut self) -> Result<usize, Error> {
        let v = self.value.take();

        match v {
            Value::Unit => Ok(0),
            Value::List(li) => {
                let n = li.len();
                try!(self.push_iter(li.to_vec()));
                Ok(n)
            }
            ref v => return Err(From::from(ExecError::expected("list", v)))
        }
    }

    fn apply(&mut self, frame: &mut StackFrame, n_args: u32) -> Result<(), Error> {
        let n = try!(self.expand_value());

        self.call_function(frame, n_args + n as u32)
    }

    fn apply_const(&mut self, frame: &mut StackFrame, n: u32, n_args: u32) -> Result<(), Error> {
        let n_push = try!(self.expand_value());

        self.call_const(frame, n, n_args + n_push as u32)
    }

    fn apply_self(&mut self, frame: &mut StackFrame, n_args: u32) -> Result<(), Error> {
        let n = try!(self.expand_value());

        self.call_self(frame, n_args + n as u32)
    }

    fn tail_apply_self(&mut self, frame: &mut StackFrame, n_args: u32) -> Result<(), Error> {
        let n = try!(self.expand_value());

        self.tail_call(frame, n_args + n as u32)
    }

    fn call_self(&mut self, frame: &mut StackFrame, n: u32) -> Result<(), Error> {
        let lambda = Lambda{
            code: frame.code.clone(),
            scope: Rc::downgrade(&frame.scope),
            values: frame.values.clone(),
        };

        self.call_lambda(frame, lambda, n, false)
    }

    fn tail_call(&mut self, frame: &mut StackFrame, n_args: u32) -> Result<(), Error> {
        let len = self.stack.len();

        if len < n_args as usize {
            return Err(From::from(ExecError::InvalidStack(len as u32)));
        }

        let start = frame.sptr as usize;
        let end = len - n_args as usize;

        let n = self.stack[start..end].iter()
            .map(|v| v.size()).fold(0, |a, b| a + b);
        self.context.set_memory(|m| m.saturating_sub(n));

        let _ = self.stack.drain(start..end);
        frame.iptr = 0;

        try!(self.setup_call(&frame.code, n_args));

        Ok(())
    }

    /// Cleans the stack when returning from a function.
    /// All values `stack[pos..]` are removed.
    fn clean_stack(&mut self, pos: usize) {
        let n = self.stack[pos..].iter()
            .map(|v| v.size()).fold(0, |a, b| a + b);
        self.context.set_memory(|m| m.saturating_sub(n));

        let _ = self.stack.drain(pos..);
    }

    /// Removes the top `n` elements from the stack.
    fn skip_stack(&mut self, n: usize) -> Result<(), ExecError> {
        let len = self.stack.len();

        if n <= len {
            self.clean_stack(len - n);
            Ok(())
        } else {
            Err(ExecError::InvalidStack(len as u32))
        }
    }

    /// Saves the current call state to the call stack.
    fn save_frame(&mut self, frame: StackFrame) -> Result<(), Error> {
        if self.call_stack.len() == self.call_stack.capacity() {
            return Err(From::from(RestrictError::CallStackExceeded));
        }

        self.call_stack.push(frame);
        Ok(())
    }

    /// Load a value from the stack.
    fn load(&mut self, n: u32) -> Result<(), ExecError> {
        self.value = try!(self.get_stack(n)).clone();
        Ok(())
    }

    /// Load an enclosed value.
    fn load_c(&mut self, frame: &StackFrame, n: u32) -> Result<(), ExecError> {
        self.value = try!(self.get_closure_value(frame, n)).clone();
        Ok(())
    }

    fn quote_value(&mut self, n: u32) -> Result<(), ExecError> {
        if n == 0 {
            Err(ExecError::InvalidDepth)
        } else {
            let v = self.value.take();
            self.value = v.quote(n);
            Ok(())
        }
    }

    fn quasiquote_value(&mut self, n: u32) -> Result<(), ExecError> {
        if n == 0 {
            Err(ExecError::InvalidDepth)
        } else {
            let v = self.value.take();
            self.value = v.quasiquote(n);
            Ok(())
        }
    }

    fn comma_value(&mut self, n: u32) -> Result<(), ExecError> {
        if n == 0 {
            Err(ExecError::InvalidDepth)
        } else {
            let v = self.value.take();
            self.value = v.comma(n);
            Ok(())
        }
    }

    fn comma_at_value(&mut self, n: u32) -> Result<(), ExecError> {
        if n == 0 {
            Err(ExecError::InvalidDepth)
        } else {
            let v = self.value.take();
            self.value = v.comma_at(n);
            Ok(())
        }
    }

    /// Replace an unbound value on the stack with `()`.
    fn unbound_to_unit(&mut self, n: u32) -> Result<(), ExecError> {
        let v = try!(self.get_stack_mut(n));
        if let Value::Unbound = *v {
            *v = Value::Unit;
        }
        Ok(())
    }

    /// Store value on the stack.
    fn store(&mut self, n: u32) -> Result<(), ExecError> {
        let v = self.value.take();
        let p = try!(self.get_stack_mut(n));
        *p = v;
        Ok(())
    }

    /// Load a value from the global scope named by a const value.
    fn get_def(&mut self, frame: &StackFrame, n: u32) -> Result<(), ExecError> {
        let name = try!(get_const_name(&frame.code, n));
        self.value = try!(self.get_value(frame, name));

        Ok(())
    }

    /// Returns a named value from global or master scope.
    fn get_value(&self, frame: &StackFrame, name: Name) -> Result<Value, ExecError> {
        MasterScope::get(name)
            .or_else(|| frame.scope.get_value(name))
            .ok_or(ExecError::NameError(name))
    }

    fn get_def_push(&mut self, frame: &StackFrame, n: u32) -> Result<(), Error> {
        let name = try!(get_const_name(&frame.code, n));
        let v = try!(self.get_value(frame, name));
        self.push(v)
    }

    fn set_def(&mut self, frame: &StackFrame, n: u32) -> Result<(), Error> {
        let name = try!(get_const_name(&frame.code, n));

        if !MasterScope::can_define(name) {
            return Err(From::from(ExecError::CannotDefine(name)));
        }

        if !frame.scope.contains_value(name) {
            if frame.scope.num_values() >= self.context.restrict().namespace_size {
                return Err(From::from(RestrictError::NamespaceSizeExceeded));
            }
        }

        // Resulting value is the definition name
        let v = replace(&mut self.value, Value::Name(name));

        frame.scope.add_value(name, v);
        Ok(())
    }

    /// Pop from the top of the stack and return the value.
    fn pop(&mut self) -> Result<Value, ExecError> {
        let v = try!(self.stack.pop().ok_or(ExecError::InvalidStack(0)));
        self.context.set_memory(|m| m.saturating_sub(v.size()));

        Ok(v)
    }

    /// Push values onto the stack from an iterator.
    ///
    /// # Note
    ///
    /// If `ExactSizeIterator::len` misrepresents the number of items in the
    /// iterator, the stack's capacity may be exceeded without causing an error.
    fn push_iter<I>(&mut self, iter: I) -> Result<(), Error>
            where I: IntoIterator<Item=Value>, I::IntoIter: ExactSizeIterator {
        let iter = iter.into_iter();

        if self.stack.len() + iter.len() > self.stack.capacity() {
            return Err(From::from(RestrictError::ValueStackExceeded));
        }

        let mut size = 0;

        self.stack.extend(iter
            .inspect(|v| size += v.size()));

        let total = self.context.set_memory(|m| m.saturating_add(size));

        try!(self.check_memory(total));

        Ok(())
    }

    fn push(&mut self, v: Value) -> Result<(), Error> {
        if self.stack.len() == self.stack.capacity() {
            Err(From::from(RestrictError::ValueStackExceeded))
        } else {
            let n = v.size();
            let total = self.context.set_memory(|m| m.saturating_add(n));
            try!(self.check_memory(total));

            self.stack.push(v);
            Ok(())
        }
    }

    fn push_const(&mut self, code: &Code, n: u32) -> Result<(), Error> {
        self.push(try!(get_const(code, n)).clone())
    }

    fn push_unbound(&mut self, n: u32) -> Result<(), Error> {
        for _ in 0..n {
            try!(self.push(Value::Unbound));
        }
        Ok(())
    }

    fn push_value(&mut self) -> Result<(), Error> {
        let v = self.value.take();
        self.push(v)
    }

    fn load_const(&mut self, code: &Code, n: u32) -> Result<(), ExecError> {
        self.value = try!(get_const(code, n)).clone();
        Ok(())
    }

    fn drain_stack_top(&mut self, n: u32) -> Result<Drain<Value>, ExecError> {
        let len = self.stack.len();

        if n as usize <= len {
            let start = len - n as usize;

            let n = self.stack[start..].iter()
                .map(|v| v.size()).fold(0, |a, b| a + b);
            self.context.set_memory(|m| m.saturating_sub(n));

            Ok(self.stack.drain(start..))
        } else {
            Err(ExecError::InvalidStack(len as u32))
        }
    }

    fn get_stack(&self, n: u32) -> Result<&Value, ExecError> {
        self.stack.get(n as usize).ok_or(ExecError::InvalidStack(n))
    }

    /// Returns a reference to an enclosed value.
    fn get_closure_value<'f>(&self, frame: &'f StackFrame, n: u32)
            -> Result<&'f Value, ExecError> {
        frame.values.as_ref().and_then(|v| v.get(n as usize))
            .ok_or(ExecError::InvalidClosureValue(n))
    }

    fn get_stack_mut(&mut self, n: u32) -> Result<&mut Value, ExecError> {
        self.stack.get_mut(n as usize).ok_or(ExecError::InvalidStack(n))
    }

    /// Returns a value from the stack `n` values from the top.
    /// `0` returns the top value.
    fn get_stack_top(&self, n: u32) -> Result<&Value, ExecError> {
        let len = self.stack.len();

        if n as usize <= len {
            self.stack.get(len - 1 - n as usize)
                .ok_or(ExecError::InvalidStack(len as u32))
        } else {
            Err(ExecError::InvalidStack(n))
        }
    }

    fn load_push(&mut self, n: u32) -> Result<(), Error> {
        let v = try!(self.get_stack(n)).clone();
        self.push(v)
    }

    fn load_c_push(&mut self, frame: &StackFrame, n: u32) -> Result<(), Error> {
        let v = try!(self.get_closure_value(frame, n)).clone();
        self.push(v)
    }

    fn jump(&mut self, frame: &mut StackFrame, label: u32) -> Result<(), ExecError> {
        if label as usize >= frame.code.code.len() {
            Err(ExecError::InvalidJump(label))
        } else {
            frame.iptr = label;
            Ok(())
        }
    }

    fn jump_if(&mut self, frame: &mut StackFrame, label: u32) -> Result<(), ExecError> {
        if try!(get_bool(&self.value)) {
            self.jump(frame, label)
        } else {
            Ok(())
        }
    }

    fn jump_if_bound(&mut self, frame: &mut StackFrame, label: u32, n: u32) -> Result<(), ExecError> {
        match *try!(self.get_stack(n)) {
            Value::Unbound => Ok(()),
            _ => self.jump(frame, label)
        }
    }

    fn jump_if_null(&mut self, frame: &mut StackFrame, label: u32) -> Result<(), ExecError> {
        match self.value {
            Value::Unit => self.jump(frame, label),
            _ => Ok(())
        }
    }

    fn jump_if_not_null(&mut self, frame: &mut StackFrame, label: u32) -> Result<(), ExecError> {
        match self.value {
            Value::Unit => Ok(()),
            _ => self.jump(frame, label)
        }
    }

    fn jump_if_not(&mut self, frame: &mut StackFrame, label: u32) -> Result<(), ExecError> {
        if try!(get_bool(&self.value)) {
            Ok(())
        } else {
            self.jump(frame, label)
        }
    }

    fn jump_if_eq(&mut self, frame: &mut StackFrame, label: u32) -> Result<(), ExecError> {
        let v = try!(self.pop());
        if try!(self.value.is_equal(&v)) {
            self.jump(frame, label)
        } else {
            Ok(())
        }
    }

    fn jump_if_not_eq(&mut self, frame: &mut StackFrame, label: u32) -> Result<(), ExecError> {
        let v = try!(self.pop());
        if try!(self.value.is_equal(&v)) {
            Ok(())
        } else {
            self.jump(frame, label)
        }
    }

    fn jump_if_eq_const(&mut self, frame: &mut StackFrame, label: u32, n: u32) -> Result<(), ExecError> {
        let eq = try!(get_const(&frame.code, n).and_then(|v| self.value.is_equal(v)));

        if eq {
            self.jump(frame, label)
        } else {
            Ok(())
        }
    }

    fn jump_if_not_eq_const(&mut self, frame: &mut StackFrame, label: u32, n: u32) -> Result<(), ExecError> {
        let eq = try!(get_const(&frame.code, n)
            .and_then(|v| self.value.is_equal(v)));

        if !eq {
            self.jump(frame, label)
        } else {
            Ok(())
        }
    }

    fn is_null(&mut self) {
        let null = match self.value {
            Value::Unit => true,
            _ => false
        };

        self.value = null.into();
    }

    fn is_not_null(&mut self) {
        let null = match self.value {
            Value::Unit => true,
            _ => false
        };

        self.value = (!null).into();
    }

    fn equal(&mut self) -> Result<(), ExecError> {
        let v = try!(self.pop());
        let r = try!(v.is_equal(&self.value));
        self.value = r.into();
        Ok(())
    }

    fn not_equal(&mut self) -> Result<(), ExecError> {
        let v = try!(self.pop());
        let r = try!(v.is_equal(&self.value));
        self.value = (!r).into();
        Ok(())
    }

    fn equal_const(&mut self, code: &Code, n: u32) -> Result<(), ExecError> {
        let c = try!(get_const(code, n));
        let r = try!(self.value.is_equal(&c));
        self.value = r.into();
        Ok(())
    }

    fn not_equal_const(&mut self, code: &Code, n: u32) -> Result<(), ExecError> {
        let c = try!(get_const(code, n));
        let r = try!(self.value.is_equal(&c));
        self.value = (!r).into();
        Ok(())
    }

    fn negate(&mut self) -> Result<(), ExecError> {
        match self.value {
            Value::Bool(ref mut v) => *v = !*v,
            ref v => return Err(ExecError::expected("bool", v))
        }
        Ok(())
    }

    fn increment(&mut self) -> Result<(), ExecError> {
        match self.value {
            Value::Float(ref mut f) => *f += 1.0,
            Value::Integer(ref mut i) => *i = i.clone() + Integer::one(),
            Value::Ratio(ref mut r) => *r = r.clone() + Ratio::one(),
            ref v => return Err(ExecError::expected("number", v))
        }
        Ok(())
    }

    fn decrement(&mut self) -> Result<(), ExecError> {
        match self.value {
            Value::Float(ref mut f) => *f -= 1.0,
            Value::Integer(ref mut i) => *i = i.clone() - Integer::one(),
            Value::Ratio(ref mut r) => *r = r.clone() - Ratio::one(),
            ref v => return Err(ExecError::expected("number", v))
        }
        Ok(())
    }

    fn append_value(&mut self) -> Result<(), ExecError> {
        let mut li = try!(self.pop());
        let v = self.value.take();

        match li {
            Value::Unit => li = vec![v].into(),
            Value::List(ref mut li) => li.push(v),
            ref v => return Err(ExecError::expected("list", v))
        }

        self.value = li;
        Ok(())
    }

    fn first(&mut self) -> Result<(), Error> {
        let v = try!(first(&self.value));

        self.value = v;
        Ok(())
    }

    fn tail(&mut self) -> Result<(), Error> {
        let v = try!(tail(&self.value));

        self.value = v;
        Ok(())
    }

    fn init(&mut self) -> Result<(), Error> {
        let v = try!(init(&self.value));

        self.value = v;
        Ok(())
    }

    fn last(&mut self) -> Result<(), Error> {
        let v = try!(last(&self.value));

        self.value = v;
        Ok(())
    }

    fn first_push(&mut self) -> Result<(), Error> {
        let v = try!(first(&self.value));
        self.push(v)
    }

    fn tail_push(&mut self) -> Result<(), Error> {
        let v = try!(tail(&self.value));
        self.push(v)
    }

    fn init_push(&mut self) -> Result<(), Error> {
        let v = try!(init(&self.value));
        self.push(v)
    }

    fn last_push(&mut self) -> Result<(), Error> {
        let v = try!(last(&self.value));
        self.push(v)
    }
}

fn get_bool(v: &Value) -> Result<bool, ExecError> {
    FromValueRef::from_value_ref(v)
}

fn get_const(code: &Code, n: u32) -> Result<&Value, ExecError> {
    code.consts.get(n as usize).ok_or(ExecError::InvalidConst(n))
}

fn get_keyword(v: &Value) -> Result<Name, ExecError> {
    match *v {
        Value::Keyword(name) => Ok(name),
        ref v => Err(ExecError::expected("keyword", v))
    }
}

fn get_const_name(code: &Code, n: u32) -> Result<Name, ExecError> {
    match *try!(get_const(code, n)) {
        Value::Name(name) => Ok(name),
        ref v => Err(ExecError::expected("name", v))
    }
}

#[cfg(test)]
mod test {
    use super::{ExecError, panic, panic_none};
    use error::Error;
    use value::Value;

    #[test]
    fn test_panic_fn() {
        assert_matches!(panic_none(), ExecError::Panic(None));
        assert_matches!(panic_none(), Error::ExecError(ExecError::Panic(None)));

        assert_matches!(panic("foo"),
            ExecError::Panic(Some(Value::String(ref s)))
                if s == "foo");
        assert_matches!(panic("foo"),
            Error::ExecError(ExecError::Panic(Some(Value::String(ref s))))
                if s == "foo");
    }
}