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
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use cstore;
use index::Index;
use schema::*;

use rustc::middle::cstore::{LinkMeta, LinkagePreference, NativeLibrary};
use rustc::hir::def;
use rustc::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefIndex, DefId};
use rustc::hir::map::definitions::DefPathTable;
use rustc::middle::dependency_format::Linkage;
use rustc::middle::lang_items;
use rustc::mir;
use rustc::traits::specialization_graph;
use rustc::ty::{self, Ty, TyCtxt, ReprOptions};

use rustc::session::config::{self, CrateTypeProcMacro};
use rustc::util::nodemap::{FxHashMap, NodeSet};

use rustc_serialize::{Encodable, Encoder, SpecializedEncoder, opaque};
use std::hash::Hash;
use std::intrinsics;
use std::io::prelude::*;
use std::io::Cursor;
use std::rc::Rc;
use std::u32;
use syntax::ast::{self, CRATE_NODE_ID};
use syntax::codemap::Spanned;
use syntax::attr;
use syntax::symbol::Symbol;
use syntax_pos::{self, DUMMY_SP};

use rustc::hir::{self, PatKind};
use rustc::hir::itemlikevisit::ItemLikeVisitor;
use rustc::hir::intravisit::{Visitor, NestedVisitorMap};
use rustc::hir::intravisit;

use super::index_builder::{FromId, IndexBuilder, Untracked};

pub struct EncodeContext<'a, 'tcx: 'a> {
    opaque: opaque::Encoder<'a>,
    pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
    reexports: &'a def::ExportMap,
    link_meta: &'a LinkMeta,
    cstore: &'a cstore::CStore,
    exported_symbols: &'a NodeSet,

    lazy_state: LazyState,
    type_shorthands: FxHashMap<Ty<'tcx>, usize>,
    predicate_shorthands: FxHashMap<ty::Predicate<'tcx>, usize>,
}

macro_rules! encoder_methods {
    ($($name:ident($ty:ty);)*) => {
        $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> {
            self.opaque.$name(value)
        })*
    }
}

impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> {
    type Error = <opaque::Encoder<'a> as Encoder>::Error;

    fn emit_nil(&mut self) -> Result<(), Self::Error> {
        Ok(())
    }

    encoder_methods! {
        emit_usize(usize);
        emit_u128(u128);
        emit_u64(u64);
        emit_u32(u32);
        emit_u16(u16);
        emit_u8(u8);

        emit_isize(isize);
        emit_i128(i128);
        emit_i64(i64);
        emit_i32(i32);
        emit_i16(i16);
        emit_i8(i8);

        emit_bool(bool);
        emit_f64(f64);
        emit_f32(f32);
        emit_char(char);
        emit_str(&str);
    }
}

impl<'a, 'tcx, T> SpecializedEncoder<Lazy<T>> for EncodeContext<'a, 'tcx> {
    fn specialized_encode(&mut self, lazy: &Lazy<T>) -> Result<(), Self::Error> {
        self.emit_lazy_distance(lazy.position, Lazy::<T>::min_size())
    }
}

impl<'a, 'tcx, T> SpecializedEncoder<LazySeq<T>> for EncodeContext<'a, 'tcx> {
    fn specialized_encode(&mut self, seq: &LazySeq<T>) -> Result<(), Self::Error> {
        self.emit_usize(seq.len)?;
        if seq.len == 0 {
            return Ok(());
        }
        self.emit_lazy_distance(seq.position, LazySeq::<T>::min_size(seq.len))
    }
}

impl<'a, 'tcx> SpecializedEncoder<Ty<'tcx>> for EncodeContext<'a, 'tcx> {
    fn specialized_encode(&mut self, ty: &Ty<'tcx>) -> Result<(), Self::Error> {
        self.encode_with_shorthand(ty, &ty.sty, |ecx| &mut ecx.type_shorthands)
    }
}

impl<'a, 'tcx> SpecializedEncoder<ty::GenericPredicates<'tcx>> for EncodeContext<'a, 'tcx> {
    fn specialized_encode(&mut self,
                          predicates: &ty::GenericPredicates<'tcx>)
                          -> Result<(), Self::Error> {
        predicates.parent.encode(self)?;
        predicates.predicates.len().encode(self)?;
        for predicate in &predicates.predicates {
            self.encode_with_shorthand(predicate, predicate, |ecx| &mut ecx.predicate_shorthands)?
        }
        Ok(())
    }
}

impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
    pub fn position(&self) -> usize {
        self.opaque.position()
    }

    fn emit_node<F: FnOnce(&mut Self, usize) -> R, R>(&mut self, f: F) -> R {
        assert_eq!(self.lazy_state, LazyState::NoNode);
        let pos = self.position();
        self.lazy_state = LazyState::NodeStart(pos);
        let r = f(self, pos);
        self.lazy_state = LazyState::NoNode;
        r
    }

    fn emit_lazy_distance(&mut self,
                          position: usize,
                          min_size: usize)
                          -> Result<(), <Self as Encoder>::Error> {
        let min_end = position + min_size;
        let distance = match self.lazy_state {
            LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"),
            LazyState::NodeStart(start) => {
                assert!(min_end <= start);
                start - min_end
            }
            LazyState::Previous(last_min_end) => {
                assert!(last_min_end <= position);
                position - last_min_end
            }
        };
        self.lazy_state = LazyState::Previous(min_end);
        self.emit_usize(distance)
    }

    pub fn lazy<T: Encodable>(&mut self, value: &T) -> Lazy<T> {
        self.emit_node(|ecx, pos| {
            value.encode(ecx).unwrap();

            assert!(pos + Lazy::<T>::min_size() <= ecx.position());
            Lazy::with_position(pos)
        })
    }

    fn lazy_seq<I, T>(&mut self, iter: I) -> LazySeq<T>
        where I: IntoIterator<Item = T>,
              T: Encodable
    {
        self.emit_node(|ecx, pos| {
            let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();

            assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
            LazySeq::with_position_and_length(pos, len)
        })
    }

    fn lazy_seq_ref<'b, I, T>(&mut self, iter: I) -> LazySeq<T>
        where I: IntoIterator<Item = &'b T>,
              T: 'b + Encodable
    {
        self.emit_node(|ecx, pos| {
            let len = iter.into_iter().map(|value| value.encode(ecx).unwrap()).count();

            assert!(pos + LazySeq::<T>::min_size(len) <= ecx.position());
            LazySeq::with_position_and_length(pos, len)
        })
    }

    /// Encode the given value or a previously cached shorthand.
    fn encode_with_shorthand<T, U, M>(&mut self,
                                      value: &T,
                                      variant: &U,
                                      map: M)
                                      -> Result<(), <Self as Encoder>::Error>
        where M: for<'b> Fn(&'b mut Self) -> &'b mut FxHashMap<T, usize>,
              T: Clone + Eq + Hash,
              U: Encodable
    {
        let existing_shorthand = map(self).get(value).cloned();
        if let Some(shorthand) = existing_shorthand {
            return self.emit_usize(shorthand);
        }

        let start = self.position();
        variant.encode(self)?;
        let len = self.position() - start;

        // The shorthand encoding uses the same usize as the
        // discriminant, with an offset so they can't conflict.
        let discriminant = unsafe { intrinsics::discriminant_value(variant) };
        assert!(discriminant < SHORTHAND_OFFSET as u64);
        let shorthand = start + SHORTHAND_OFFSET;

        // Get the number of bits that leb128 could fit
        // in the same space as the fully encoded type.
        let leb128_bits = len * 7;

        // Check that the shorthand is a not longer than the
        // full encoding itself, i.e. it's an obvious win.
        if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) {
            map(self).insert(value.clone(), shorthand);
        }

        Ok(())
    }

    fn encode_item_variances(&mut self, def_id: DefId) -> LazySeq<ty::Variance> {
        let tcx = self.tcx;
        self.lazy_seq(tcx.item_variances(def_id).iter().cloned())
    }

    fn encode_item_type(&mut self, def_id: DefId) -> Lazy<Ty<'tcx>> {
        let tcx = self.tcx;
        self.lazy(&tcx.item_type(def_id))
    }

    /// Encode data for the given variant of the given ADT. The
    /// index of the variant is untracked: this is ok because we
    /// will have to lookup the adt-def by its id, and that gives us
    /// the right to access any information in the adt-def (including,
    /// e.g., the length of the various vectors).
    fn encode_enum_variant_info(&mut self,
                                (enum_did, Untracked(index)): (DefId, Untracked<usize>))
                                -> Entry<'tcx> {
        let tcx = self.tcx;
        let def = tcx.lookup_adt_def(enum_did);
        let variant = &def.variants[index];
        let def_id = variant.did;

        let data = VariantData {
            ctor_kind: variant.ctor_kind,
            discr: variant.discr,
            evaluated_discr: match variant.discr {
                ty::VariantDiscr::Explicit(def_id) => {
                    ty::queries::monomorphic_const_eval::get(tcx, DUMMY_SP, def_id).ok()
                }
                ty::VariantDiscr::Relative(_) => None
            },
            struct_ctor: None,
        };

        let enum_id = tcx.hir.as_local_node_id(enum_did).unwrap();
        let enum_vis = &tcx.hir.expect_item(enum_id).vis;

        Entry {
            kind: EntryKind::Variant(self.lazy(&data)),
            visibility: self.lazy(&ty::Visibility::from_hir(enum_vis, enum_id, tcx)),
            span: self.lazy(&tcx.def_span(def_id)),
            attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
            children: self.lazy_seq(variant.fields.iter().map(|f| {
                assert!(f.did.is_local());
                f.did.index
            })),
            stability: self.encode_stability(def_id),
            deprecation: self.encode_deprecation(def_id),

            ty: Some(self.encode_item_type(def_id)),
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: Some(self.encode_generics(def_id)),
            predicates: Some(self.encode_predicates(def_id)),

            ast: None,
            mir: None,
        }
    }

    fn encode_info_for_mod(&mut self,
                           FromId(id, (md, attrs, vis)): FromId<(&hir::Mod,
                                                                 &[ast::Attribute],
                                                                 &hir::Visibility)>)
                           -> Entry<'tcx> {
        let tcx = self.tcx;
        let def_id = tcx.hir.local_def_id(id);

        let data = ModData {
            reexports: match self.reexports.get(&id) {
                Some(exports) if *vis == hir::Public => self.lazy_seq_ref(exports),
                _ => LazySeq::empty(),
            },
        };

        Entry {
            kind: EntryKind::Mod(self.lazy(&data)),
            visibility: self.lazy(&ty::Visibility::from_hir(vis, id, tcx)),
            span: self.lazy(&md.inner),
            attributes: self.encode_attributes(attrs),
            children: self.lazy_seq(md.item_ids.iter().map(|item_id| {
                tcx.hir.local_def_id(item_id.id).index
            })),
            stability: self.encode_stability(def_id),
            deprecation: self.encode_deprecation(def_id),

            ty: None,
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: None,
            predicates: None,

            ast: None,
            mir: None
        }
    }
}

impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
    fn encode_fields(&mut self, adt_def_id: DefId) {
        let def = self.tcx.lookup_adt_def(adt_def_id);
        for (variant_index, variant) in def.variants.iter().enumerate() {
            for (field_index, field) in variant.fields.iter().enumerate() {
                self.record(field.did,
                            EncodeContext::encode_field,
                            (adt_def_id, Untracked((variant_index, field_index))));
            }
        }
    }
}

impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
    /// Encode data for the given field of the given variant of the
    /// given ADT. The indices of the variant/field are untracked:
    /// this is ok because we will have to lookup the adt-def by its
    /// id, and that gives us the right to access any information in
    /// the adt-def (including, e.g., the length of the various
    /// vectors).
    fn encode_field(&mut self,
                    (adt_def_id, Untracked((variant_index, field_index))): (DefId,
                                                                            Untracked<(usize,
                                                                                       usize)>))
                    -> Entry<'tcx> {
        let tcx = self.tcx;
        let variant = &tcx.lookup_adt_def(adt_def_id).variants[variant_index];
        let field = &variant.fields[field_index];

        let def_id = field.did;
        let variant_id = tcx.hir.as_local_node_id(variant.did).unwrap();
        let variant_data = tcx.hir.expect_variant_data(variant_id);

        Entry {
            kind: EntryKind::Field,
            visibility: self.lazy(&field.vis),
            span: self.lazy(&tcx.def_span(def_id)),
            attributes: self.encode_attributes(&variant_data.fields()[field_index].attrs),
            children: LazySeq::empty(),
            stability: self.encode_stability(def_id),
            deprecation: self.encode_deprecation(def_id),

            ty: Some(self.encode_item_type(def_id)),
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: Some(self.encode_generics(def_id)),
            predicates: Some(self.encode_predicates(def_id)),

            ast: None,
            mir: None,
        }
    }

    fn encode_struct_ctor(&mut self, (adt_def_id, def_id): (DefId, DefId)) -> Entry<'tcx> {
        let tcx = self.tcx;
        let variant = tcx.lookup_adt_def(adt_def_id).struct_variant();

        let data = VariantData {
            ctor_kind: variant.ctor_kind,
            discr: variant.discr,
            evaluated_discr: None,
            struct_ctor: Some(def_id.index),
        };

        let struct_id = tcx.hir.as_local_node_id(adt_def_id).unwrap();
        let struct_vis = &tcx.hir.expect_item(struct_id).vis;
        let mut ctor_vis = ty::Visibility::from_hir(struct_vis, struct_id, tcx);
        for field in &variant.fields {
            if ctor_vis.is_at_least(field.vis, tcx) {
                ctor_vis = field.vis;
            }
        }

        let repr_options = get_repr_options(&tcx, adt_def_id);

        Entry {
            kind: EntryKind::Struct(self.lazy(&data), repr_options),
            visibility: self.lazy(&ctor_vis),
            span: self.lazy(&tcx.def_span(def_id)),
            attributes: LazySeq::empty(),
            children: LazySeq::empty(),
            stability: self.encode_stability(def_id),
            deprecation: self.encode_deprecation(def_id),

            ty: Some(self.encode_item_type(def_id)),
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: Some(self.encode_generics(def_id)),
            predicates: Some(self.encode_predicates(def_id)),

            ast: None,
            mir: None,
        }
    }

    fn encode_generics(&mut self, def_id: DefId) -> Lazy<ty::Generics> {
        let tcx = self.tcx;
        self.lazy(tcx.item_generics(def_id))
    }

    fn encode_predicates(&mut self, def_id: DefId) -> Lazy<ty::GenericPredicates<'tcx>> {
        let tcx = self.tcx;
        self.lazy(&tcx.item_predicates(def_id))
    }

    fn encode_info_for_trait_item(&mut self, def_id: DefId) -> Entry<'tcx> {
        let tcx = self.tcx;

        let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
        let ast_item = tcx.hir.expect_trait_item(node_id);
        let trait_item = tcx.associated_item(def_id);

        let container = match trait_item.defaultness {
            hir::Defaultness::Default { has_value: true } =>
                AssociatedContainer::TraitWithDefault,
            hir::Defaultness::Default { has_value: false } =>
                AssociatedContainer::TraitRequired,
            hir::Defaultness::Final =>
                span_bug!(ast_item.span, "traits cannot have final items"),
        };

        let kind = match trait_item.kind {
            ty::AssociatedKind::Const => {
                EntryKind::AssociatedConst(container, 0)
            }
            ty::AssociatedKind::Method => {
                let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node {
                    let arg_names = match *m {
                        hir::TraitMethod::Required(ref names) => {
                            self.encode_fn_arg_names(names)
                        }
                        hir::TraitMethod::Provided(body) => {
                            self.encode_fn_arg_names_for_body(body)
                        }
                    };
                    FnData {
                        constness: hir::Constness::NotConst,
                        arg_names: arg_names
                    }
                } else {
                    bug!()
                };
                EntryKind::Method(self.lazy(&MethodData {
                    fn_data: fn_data,
                    container: container,
                    has_self: trait_item.method_has_self_argument,
                }))
            }
            ty::AssociatedKind::Type => EntryKind::AssociatedType(container),
        };

        Entry {
            kind: kind,
            visibility: self.lazy(&trait_item.vis),
            span: self.lazy(&ast_item.span),
            attributes: self.encode_attributes(&ast_item.attrs),
            children: LazySeq::empty(),
            stability: self.encode_stability(def_id),
            deprecation: self.encode_deprecation(def_id),

            ty: match trait_item.kind {
                ty::AssociatedKind::Const |
                ty::AssociatedKind::Method => {
                    Some(self.encode_item_type(def_id))
                }
                ty::AssociatedKind::Type => {
                    if trait_item.defaultness.has_value() {
                        Some(self.encode_item_type(def_id))
                    } else {
                        None
                    }
                }
            },
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: Some(self.encode_generics(def_id)),
            predicates: Some(self.encode_predicates(def_id)),

            ast: if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node {
                Some(self.encode_body(body))
            } else {
                None
            },
            mir: self.encode_mir(def_id),
        }
    }

    fn encode_info_for_impl_item(&mut self, def_id: DefId) -> Entry<'tcx> {
        let node_id = self.tcx.hir.as_local_node_id(def_id).unwrap();
        let ast_item = self.tcx.hir.expect_impl_item(node_id);
        let impl_item = self.tcx.associated_item(def_id);

        let container = match impl_item.defaultness {
            hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault,
            hir::Defaultness::Final => AssociatedContainer::ImplFinal,
            hir::Defaultness::Default { has_value: false } =>
                span_bug!(ast_item.span, "impl items always have values (currently)"),
        };

        let kind = match impl_item.kind {
            ty::AssociatedKind::Const => {
                EntryKind::AssociatedConst(container,
                    ty::queries::mir_const_qualif::get(self.tcx, ast_item.span, def_id))
            }
            ty::AssociatedKind::Method => {
                let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
                    FnData {
                        constness: sig.constness,
                        arg_names: self.encode_fn_arg_names_for_body(body),
                    }
                } else {
                    bug!()
                };
                EntryKind::Method(self.lazy(&MethodData {
                    fn_data: fn_data,
                    container: container,
                    has_self: impl_item.method_has_self_argument,
                }))
            }
            ty::AssociatedKind::Type => EntryKind::AssociatedType(container)
        };

        let (ast, mir) = if let hir::ImplItemKind::Const(_, body) = ast_item.node {
            (Some(body), true)
        } else if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node {
            let generics = self.tcx.item_generics(def_id);
            let types = generics.parent_types as usize + generics.types.len();
            let needs_inline = types > 0 || attr::requests_inline(&ast_item.attrs);
            let is_const_fn = sig.constness == hir::Constness::Const;
            let ast = if is_const_fn { Some(body) } else { None };
            let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
            (ast, needs_inline || is_const_fn || always_encode_mir)
        } else {
            (None, false)
        };

        Entry {
            kind: kind,
            visibility: self.lazy(&impl_item.vis),
            span: self.lazy(&ast_item.span),
            attributes: self.encode_attributes(&ast_item.attrs),
            children: LazySeq::empty(),
            stability: self.encode_stability(def_id),
            deprecation: self.encode_deprecation(def_id),

            ty: Some(self.encode_item_type(def_id)),
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: Some(self.encode_generics(def_id)),
            predicates: Some(self.encode_predicates(def_id)),

            ast: ast.map(|body| self.encode_body(body)),
            mir: if mir { self.encode_mir(def_id) } else { None },
        }
    }

    fn encode_fn_arg_names_for_body(&mut self, body_id: hir::BodyId)
                                    -> LazySeq<ast::Name> {
        let _ignore = self.tcx.dep_graph.in_ignore();
        let body = self.tcx.hir.body(body_id);
        self.lazy_seq(body.arguments.iter().map(|arg| {
            match arg.pat.node {
                PatKind::Binding(_, _, name, _) => name.node,
                _ => Symbol::intern("")
            }
        }))
    }

    fn encode_fn_arg_names(&mut self, names: &[Spanned<ast::Name>])
                           -> LazySeq<ast::Name> {
        self.lazy_seq(names.iter().map(|name| name.node))
    }

    fn encode_mir(&mut self, def_id: DefId) -> Option<Lazy<mir::Mir<'tcx>>> {
        self.tcx.maps.mir.borrow().get(&def_id).map(|mir| self.lazy(&*mir.borrow()))
    }

    // Encodes the inherent implementations of a structure, enumeration, or trait.
    fn encode_inherent_implementations(&mut self, def_id: DefId) -> LazySeq<DefIndex> {
        match self.tcx.maps.inherent_impls.borrow().get(&def_id) {
            None => LazySeq::empty(),
            Some(implementations) => {
                self.lazy_seq(implementations.iter().map(|&def_id| {
                    assert!(def_id.is_local());
                    def_id.index
                }))
            }
        }
    }

    fn encode_stability(&mut self, def_id: DefId) -> Option<Lazy<attr::Stability>> {
        self.tcx.lookup_stability(def_id).map(|stab| self.lazy(stab))
    }

    fn encode_deprecation(&mut self, def_id: DefId) -> Option<Lazy<attr::Deprecation>> {
        self.tcx.lookup_deprecation(def_id).map(|depr| self.lazy(&depr))
    }

    fn encode_info_for_item(&mut self, (def_id, item): (DefId, &'tcx hir::Item)) -> Entry<'tcx> {
        let tcx = self.tcx;

        debug!("encoding info for item at {}",
               tcx.sess.codemap().span_to_string(item.span));

        let kind = match item.node {
            hir::ItemStatic(_, hir::MutMutable, _) => EntryKind::MutStatic,
            hir::ItemStatic(_, hir::MutImmutable, _) => EntryKind::ImmStatic,
            hir::ItemConst(..) => {
                EntryKind::Const(ty::queries::mir_const_qualif::get(tcx, item.span, def_id))
            }
            hir::ItemFn(_, _, constness, .., body) => {
                let data = FnData {
                    constness: constness,
                    arg_names: self.encode_fn_arg_names_for_body(body),
                };

                EntryKind::Fn(self.lazy(&data))
            }
            hir::ItemMod(ref m) => {
                return self.encode_info_for_mod(FromId(item.id, (m, &item.attrs, &item.vis)));
            }
            hir::ItemForeignMod(_) => EntryKind::ForeignMod,
            hir::ItemTy(..) => EntryKind::Type,
            hir::ItemEnum(..) => EntryKind::Enum(get_repr_options(&tcx, def_id)),
            hir::ItemStruct(ref struct_def, _) => {
                let variant = tcx.lookup_adt_def(def_id).struct_variant();

                // Encode def_ids for each field and method
                // for methods, write all the stuff get_trait_method
                // needs to know
                let struct_ctor = if !struct_def.is_struct() {
                    Some(tcx.hir.local_def_id(struct_def.id()).index)
                } else {
                    None
                };

                let repr_options = get_repr_options(&tcx, def_id);

                EntryKind::Struct(self.lazy(&VariantData {
                    ctor_kind: variant.ctor_kind,
                    discr: variant.discr,
                    evaluated_discr: None,
                    struct_ctor: struct_ctor,
                }), repr_options)
            }
            hir::ItemUnion(..) => {
                let variant = tcx.lookup_adt_def(def_id).struct_variant();
                let repr_options = get_repr_options(&tcx, def_id);

                EntryKind::Union(self.lazy(&VariantData {
                    ctor_kind: variant.ctor_kind,
                    discr: variant.discr,
                    evaluated_discr: None,
                    struct_ctor: None,
                }), repr_options)
            }
            hir::ItemDefaultImpl(..) => {
                let data = ImplData {
                    polarity: hir::ImplPolarity::Positive,
                    parent_impl: None,
                    coerce_unsized_kind: None,
                    trait_ref: tcx.impl_trait_ref(def_id).map(|trait_ref| self.lazy(&trait_ref)),
                };

                EntryKind::DefaultImpl(self.lazy(&data))
            }
            hir::ItemImpl(_, polarity, ..) => {
                let trait_ref = tcx.impl_trait_ref(def_id);
                let parent = if let Some(trait_ref) = trait_ref {
                    let trait_def = tcx.lookup_trait_def(trait_ref.def_id);
                    trait_def.ancestors(def_id).skip(1).next().and_then(|node| {
                        match node {
                            specialization_graph::Node::Impl(parent) => Some(parent),
                            _ => None,
                        }
                    })
                } else {
                    None
                };

                let data = ImplData {
                    polarity: polarity,
                    parent_impl: parent,
                    coerce_unsized_kind: tcx.maps.custom_coerce_unsized_kind
                        .borrow()
                        .get(&def_id)
                        .cloned(),
                    trait_ref: trait_ref.map(|trait_ref| self.lazy(&trait_ref)),
                };

                EntryKind::Impl(self.lazy(&data))
            }
            hir::ItemTrait(..) => {
                let trait_def = tcx.lookup_trait_def(def_id);
                let data = TraitData {
                    unsafety: trait_def.unsafety,
                    paren_sugar: trait_def.paren_sugar,
                    has_default_impl: tcx.trait_has_default_impl(def_id),
                    super_predicates: self.lazy(&tcx.item_super_predicates(def_id)),
                };

                EntryKind::Trait(self.lazy(&data))
            }
            hir::ItemExternCrate(_) |
            hir::ItemUse(..) => bug!("cannot encode info for item {:?}", item),
        };

        Entry {
            kind: kind,
            visibility: self.lazy(&ty::Visibility::from_hir(&item.vis, item.id, tcx)),
            span: self.lazy(&item.span),
            attributes: self.encode_attributes(&item.attrs),
            children: match item.node {
                hir::ItemForeignMod(ref fm) => {
                    self.lazy_seq(fm.items
                        .iter()
                        .map(|foreign_item| tcx.hir.local_def_id(foreign_item.id).index))
                }
                hir::ItemEnum(..) => {
                    let def = self.tcx.lookup_adt_def(def_id);
                    self.lazy_seq(def.variants.iter().map(|v| {
                        assert!(v.did.is_local());
                        v.did.index
                    }))
                }
                hir::ItemStruct(..) |
                hir::ItemUnion(..) => {
                    let def = self.tcx.lookup_adt_def(def_id);
                    self.lazy_seq(def.struct_variant().fields.iter().map(|f| {
                        assert!(f.did.is_local());
                        f.did.index
                    }))
                }
                hir::ItemImpl(..) |
                hir::ItemTrait(..) => {
                    self.lazy_seq(tcx.associated_item_def_ids(def_id).iter().map(|&def_id| {
                        assert!(def_id.is_local());
                        def_id.index
                    }))
                }
                _ => LazySeq::empty(),
            },
            stability: self.encode_stability(def_id),
            deprecation: self.encode_deprecation(def_id),

            ty: match item.node {
                hir::ItemStatic(..) |
                hir::ItemConst(..) |
                hir::ItemFn(..) |
                hir::ItemTy(..) |
                hir::ItemEnum(..) |
                hir::ItemStruct(..) |
                hir::ItemUnion(..) |
                hir::ItemImpl(..) => Some(self.encode_item_type(def_id)),
                _ => None,
            },
            inherent_impls: self.encode_inherent_implementations(def_id),
            variances: match item.node {
                hir::ItemEnum(..) |
                hir::ItemStruct(..) |
                hir::ItemUnion(..) |
                hir::ItemTrait(..) => self.encode_item_variances(def_id),
                _ => LazySeq::empty(),
            },
            generics: match item.node {
                hir::ItemStatic(..) |
                hir::ItemConst(..) |
                hir::ItemFn(..) |
                hir::ItemTy(..) |
                hir::ItemEnum(..) |
                hir::ItemStruct(..) |
                hir::ItemUnion(..) |
                hir::ItemImpl(..) |
                hir::ItemTrait(..) => Some(self.encode_generics(def_id)),
                _ => None,
            },
            predicates: match item.node {
                hir::ItemStatic(..) |
                hir::ItemConst(..) |
                hir::ItemFn(..) |
                hir::ItemTy(..) |
                hir::ItemEnum(..) |
                hir::ItemStruct(..) |
                hir::ItemUnion(..) |
                hir::ItemImpl(..) |
                hir::ItemTrait(..) => Some(self.encode_predicates(def_id)),
                _ => None,
            },

            ast: match item.node {
                hir::ItemConst(_, body) |
                hir::ItemFn(_, _, hir::Constness::Const, _, _, body) => {
                    Some(self.encode_body(body))
                }
                _ => None,
            },
            mir: match item.node {
                hir::ItemStatic(..) if self.tcx.sess.opts.debugging_opts.always_encode_mir => {
                    self.encode_mir(def_id)
                }
                hir::ItemConst(..) => self.encode_mir(def_id),
                hir::ItemFn(_, _, constness, _, ref generics, _) => {
                    let tps_len = generics.ty_params.len();
                    let needs_inline = tps_len > 0 || attr::requests_inline(&item.attrs);
                    let always_encode_mir = self.tcx.sess.opts.debugging_opts.always_encode_mir;
                    if needs_inline || constness == hir::Constness::Const || always_encode_mir {
                        self.encode_mir(def_id)
                    } else {
                        None
                    }
                }
                _ => None,
            },
        }
    }

    /// Serialize the text of exported macros
    fn encode_info_for_macro_def(&mut self, macro_def: &hir::MacroDef) -> Entry<'tcx> {
        use syntax::print::pprust;
        Entry {
            kind: EntryKind::MacroDef(self.lazy(&MacroDef {
                body: pprust::tts_to_string(&macro_def.body.trees().collect::<Vec<_>>()),
            })),
            visibility: self.lazy(&ty::Visibility::Public),
            span: self.lazy(&macro_def.span),

            attributes: self.encode_attributes(&macro_def.attrs),
            children: LazySeq::empty(),
            stability: None,
            deprecation: None,
            ty: None,
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: None,
            predicates: None,
            ast: None,
            mir: None,
        }
    }
}

impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
    /// In some cases, along with the item itself, we also
    /// encode some sub-items. Usually we want some info from the item
    /// so it's easier to do that here then to wait until we would encounter
    /// normally in the visitor walk.
    fn encode_addl_info_for_item(&mut self, item: &hir::Item) {
        let def_id = self.tcx.hir.local_def_id(item.id);
        match item.node {
            hir::ItemStatic(..) |
            hir::ItemConst(..) |
            hir::ItemFn(..) |
            hir::ItemMod(..) |
            hir::ItemForeignMod(..) |
            hir::ItemExternCrate(..) |
            hir::ItemUse(..) |
            hir::ItemDefaultImpl(..) |
            hir::ItemTy(..) => {
                // no sub-item recording needed in these cases
            }
            hir::ItemEnum(..) => {
                self.encode_fields(def_id);

                let def = self.tcx.lookup_adt_def(def_id);
                for (i, variant) in def.variants.iter().enumerate() {
                    self.record(variant.did,
                                EncodeContext::encode_enum_variant_info,
                                (def_id, Untracked(i)));
                }
            }
            hir::ItemStruct(ref struct_def, _) => {
                self.encode_fields(def_id);

                // If the struct has a constructor, encode it.
                if !struct_def.is_struct() {
                    let ctor_def_id = self.tcx.hir.local_def_id(struct_def.id());
                    self.record(ctor_def_id,
                                EncodeContext::encode_struct_ctor,
                                (def_id, ctor_def_id));
                }
            }
            hir::ItemUnion(..) => {
                self.encode_fields(def_id);
            }
            hir::ItemImpl(..) => {
                for &trait_item_def_id in &self.tcx.associated_item_def_ids(def_id)[..] {
                    self.record(trait_item_def_id,
                                EncodeContext::encode_info_for_impl_item,
                                trait_item_def_id);
                }
            }
            hir::ItemTrait(..) => {
                for &item_def_id in &self.tcx.associated_item_def_ids(def_id)[..] {
                    self.record(item_def_id,
                                EncodeContext::encode_info_for_trait_item,
                                item_def_id);
                }
            }
        }
    }
}

impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
    fn encode_info_for_foreign_item(&mut self,
                                    (def_id, nitem): (DefId, &hir::ForeignItem))
                                    -> Entry<'tcx> {
        let tcx = self.tcx;

        debug!("writing foreign item {}", tcx.node_path_str(nitem.id));

        let kind = match nitem.node {
            hir::ForeignItemFn(_, ref names, _) => {
                let data = FnData {
                    constness: hir::Constness::NotConst,
                    arg_names: self.encode_fn_arg_names(names),
                };
                EntryKind::ForeignFn(self.lazy(&data))
            }
            hir::ForeignItemStatic(_, true) => EntryKind::ForeignMutStatic,
            hir::ForeignItemStatic(_, false) => EntryKind::ForeignImmStatic,
        };

        Entry {
            kind: kind,
            visibility: self.lazy(&ty::Visibility::from_hir(&nitem.vis, nitem.id, tcx)),
            span: self.lazy(&nitem.span),
            attributes: self.encode_attributes(&nitem.attrs),
            children: LazySeq::empty(),
            stability: self.encode_stability(def_id),
            deprecation: self.encode_deprecation(def_id),

            ty: Some(self.encode_item_type(def_id)),
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: Some(self.encode_generics(def_id)),
            predicates: Some(self.encode_predicates(def_id)),

            ast: None,
            mir: None,
        }
    }
}

struct EncodeVisitor<'a, 'b: 'a, 'tcx: 'b> {
    index: IndexBuilder<'a, 'b, 'tcx>,
}

impl<'a, 'b, 'tcx> Visitor<'tcx> for EncodeVisitor<'a, 'b, 'tcx> {
    fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
        NestedVisitorMap::OnlyBodies(&self.index.tcx.hir)
    }
    fn visit_expr(&mut self, ex: &'tcx hir::Expr) {
        intravisit::walk_expr(self, ex);
        self.index.encode_info_for_expr(ex);
    }
    fn visit_item(&mut self, item: &'tcx hir::Item) {
        intravisit::walk_item(self, item);
        let def_id = self.index.tcx.hir.local_def_id(item.id);
        match item.node {
            hir::ItemExternCrate(_) |
            hir::ItemUse(..) => (), // ignore these
            _ => self.index.record(def_id, EncodeContext::encode_info_for_item, (def_id, item)),
        }
        self.index.encode_addl_info_for_item(item);
    }
    fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem) {
        intravisit::walk_foreign_item(self, ni);
        let def_id = self.index.tcx.hir.local_def_id(ni.id);
        self.index.record(def_id,
                          EncodeContext::encode_info_for_foreign_item,
                          (def_id, ni));
    }
    fn visit_generics(&mut self, generics: &'tcx hir::Generics) {
        intravisit::walk_generics(self, generics);
        self.index.encode_info_for_generics(generics);
    }
    fn visit_ty(&mut self, ty: &'tcx hir::Ty) {
        intravisit::walk_ty(self, ty);
        self.index.encode_info_for_ty(ty);
    }
    fn visit_macro_def(&mut self, macro_def: &'tcx hir::MacroDef) {
        let def_id = self.index.tcx.hir.local_def_id(macro_def.id);
        self.index.record(def_id, EncodeContext::encode_info_for_macro_def, macro_def);
    }
}

impl<'a, 'b, 'tcx> IndexBuilder<'a, 'b, 'tcx> {
    fn encode_info_for_generics(&mut self, generics: &hir::Generics) {
        for ty_param in &generics.ty_params {
            let def_id = self.tcx.hir.local_def_id(ty_param.id);
            let has_default = Untracked(ty_param.default.is_some());
            self.record(def_id, EncodeContext::encode_info_for_ty_param, (def_id, has_default));
        }
    }

    fn encode_info_for_ty(&mut self, ty: &hir::Ty) {
        if let hir::TyImplTrait(_) = ty.node {
            let def_id = self.tcx.hir.local_def_id(ty.id);
            self.record(def_id, EncodeContext::encode_info_for_anon_ty, def_id);
        }
    }

    fn encode_info_for_expr(&mut self, expr: &hir::Expr) {
        match expr.node {
            hir::ExprClosure(..) => {
                let def_id = self.tcx.hir.local_def_id(expr.id);
                self.record(def_id, EncodeContext::encode_info_for_closure, def_id);
            }
            _ => {}
        }
    }
}

impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
    fn encode_info_for_ty_param(&mut self,
                                (def_id, Untracked(has_default)): (DefId, Untracked<bool>))
                                -> Entry<'tcx> {
        let tcx = self.tcx;
        Entry {
            kind: EntryKind::Type,
            visibility: self.lazy(&ty::Visibility::Public),
            span: self.lazy(&tcx.def_span(def_id)),
            attributes: LazySeq::empty(),
            children: LazySeq::empty(),
            stability: None,
            deprecation: None,

            ty: if has_default {
                Some(self.encode_item_type(def_id))
            } else {
                None
            },
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: None,
            predicates: None,

            ast: None,
            mir: None,
        }
    }

    fn encode_info_for_anon_ty(&mut self, def_id: DefId) -> Entry<'tcx> {
        let tcx = self.tcx;
        Entry {
            kind: EntryKind::Type,
            visibility: self.lazy(&ty::Visibility::Public),
            span: self.lazy(&tcx.def_span(def_id)),
            attributes: LazySeq::empty(),
            children: LazySeq::empty(),
            stability: None,
            deprecation: None,

            ty: Some(self.encode_item_type(def_id)),
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: Some(self.encode_generics(def_id)),
            predicates: Some(self.encode_predicates(def_id)),

            ast: None,
            mir: None,
        }
    }

    fn encode_info_for_closure(&mut self, def_id: DefId) -> Entry<'tcx> {
        let tcx = self.tcx;

        let data = ClosureData {
            kind: tcx.closure_kind(def_id),
            ty: self.lazy(&tcx.closure_type(def_id)),
        };

        Entry {
            kind: EntryKind::Closure(self.lazy(&data)),
            visibility: self.lazy(&ty::Visibility::Public),
            span: self.lazy(&tcx.def_span(def_id)),
            attributes: self.encode_attributes(&tcx.get_attrs(def_id)),
            children: LazySeq::empty(),
            stability: None,
            deprecation: None,

            ty: Some(self.encode_item_type(def_id)),
            inherent_impls: LazySeq::empty(),
            variances: LazySeq::empty(),
            generics: Some(self.encode_generics(def_id)),
            predicates: None,

            ast: None,
            mir: self.encode_mir(def_id),
        }
    }

    fn encode_info_for_items(&mut self) -> Index {
        let krate = self.tcx.hir.krate();
        let mut index = IndexBuilder::new(self);
        index.record(DefId::local(CRATE_DEF_INDEX),
                     EncodeContext::encode_info_for_mod,
                     FromId(CRATE_NODE_ID, (&krate.module, &krate.attrs, &hir::Public)));
        let mut visitor = EncodeVisitor { index: index };
        krate.visit_all_item_likes(&mut visitor.as_deep_visitor());
        for macro_def in &krate.exported_macros {
            visitor.visit_macro_def(macro_def);
        }
        visitor.index.into_items()
    }

    fn encode_attributes(&mut self, attrs: &[ast::Attribute]) -> LazySeq<ast::Attribute> {
        self.lazy_seq_ref(attrs)
    }

    fn encode_crate_deps(&mut self) -> LazySeq<CrateDep> {
        fn get_ordered_deps(cstore: &cstore::CStore) -> Vec<(CrateNum, Rc<cstore::CrateMetadata>)> {
            // Pull the cnums and name,vers,hash out of cstore
            let mut deps = Vec::new();
            cstore.iter_crate_data(|cnum, val| {
                deps.push((cnum, val.clone()));
            });

            // Sort by cnum
            deps.sort_by(|kv1, kv2| kv1.0.cmp(&kv2.0));

            // Sanity-check the crate numbers
            let mut expected_cnum = 1;
            for &(n, _) in &deps {
                assert_eq!(n, CrateNum::new(expected_cnum));
                expected_cnum += 1;
            }

            deps
        }

        // We're just going to write a list of crate 'name-hash-version's, with
        // the assumption that they are numbered 1 to n.
        // FIXME (#2166): This is not nearly enough to support correct versioning
        // but is enough to get transitive crate dependencies working.
        let deps = get_ordered_deps(self.cstore);
        self.lazy_seq(deps.iter().map(|&(_, ref dep)| {
            CrateDep {
                name: dep.name(),
                hash: dep.hash(),
                kind: dep.dep_kind.get(),
            }
        }))
    }

    fn encode_lang_items(&mut self) -> (LazySeq<(DefIndex, usize)>, LazySeq<lang_items::LangItem>) {
        let tcx = self.tcx;
        let lang_items = tcx.lang_items.items().iter();
        (self.lazy_seq(lang_items.enumerate().filter_map(|(i, &opt_def_id)| {
            if let Some(def_id) = opt_def_id {
                if def_id.is_local() {
                    return Some((def_id.index, i));
                }
            }
            None
        })),
         self.lazy_seq_ref(&tcx.lang_items.missing))
    }

    fn encode_native_libraries(&mut self) -> LazySeq<NativeLibrary> {
        let used_libraries = self.tcx.sess.cstore.used_libraries();
        self.lazy_seq(used_libraries)
    }

    fn encode_codemap(&mut self) -> LazySeq<syntax_pos::FileMap> {
        let codemap = self.tcx.sess.codemap();
        let all_filemaps = codemap.files.borrow();
        self.lazy_seq_ref(all_filemaps.iter()
            .filter(|filemap| {
                // No need to re-export imported filemaps, as any downstream
                // crate will import them from their original source.
                !filemap.is_imported()
            })
            .map(|filemap| &**filemap))
    }

    fn encode_def_path_table(&mut self) -> Lazy<DefPathTable> {
        let definitions = self.tcx.hir.definitions();
        self.lazy(definitions.def_path_table())
    }
}

struct ImplVisitor<'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    impls: FxHashMap<DefId, Vec<DefIndex>>,
}

impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'a, 'tcx> {
    fn visit_item(&mut self, item: &hir::Item) {
        if let hir::ItemImpl(..) = item.node {
            let impl_id = self.tcx.hir.local_def_id(item.id);
            if let Some(trait_ref) = self.tcx.impl_trait_ref(impl_id) {
                self.impls
                    .entry(trait_ref.def_id)
                    .or_insert(vec![])
                    .push(impl_id.index);
            }
        }
    }

    fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem) {}

    fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem) {
        // handled in `visit_item` above
    }
}

impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
    /// Encodes an index, mapping each trait to its (local) implementations.
    fn encode_impls(&mut self) -> LazySeq<TraitImpls> {
        let mut visitor = ImplVisitor {
            tcx: self.tcx,
            impls: FxHashMap(),
        };
        self.tcx.hir.krate().visit_all_item_likes(&mut visitor);

        let all_impls: Vec<_> = visitor.impls
            .into_iter()
            .map(|(trait_def_id, impls)| {
                TraitImpls {
                    trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index),
                    impls: self.lazy_seq(impls),
                }
            })
            .collect();

        self.lazy_seq(all_impls)
    }

    // Encodes all symbols exported from this crate into the metadata.
    //
    // This pass is seeded off the reachability list calculated in the
    // middle::reachable module but filters out items that either don't have a
    // symbol associated with them (they weren't translated) or if they're an FFI
    // definition (as that's not defined in this crate).
    fn encode_exported_symbols(&mut self) -> LazySeq<DefIndex> {
        let exported_symbols = self.exported_symbols;
        let tcx = self.tcx;
        self.lazy_seq(exported_symbols.iter().map(|&id| tcx.hir.local_def_id(id).index))
    }

    fn encode_dylib_dependency_formats(&mut self) -> LazySeq<Option<LinkagePreference>> {
        match self.tcx.sess.dependency_formats.borrow().get(&config::CrateTypeDylib) {
            Some(arr) => {
                self.lazy_seq(arr.iter().map(|slot| {
                    match *slot {
                        Linkage::NotLinked |
                        Linkage::IncludedFromDylib => None,

                        Linkage::Dynamic => Some(LinkagePreference::RequireDynamic),
                        Linkage::Static => Some(LinkagePreference::RequireStatic),
                    }
                }))
            }
            None => LazySeq::empty(),
        }
    }

    fn encode_crate_root(&mut self) -> Lazy<CrateRoot> {
        let mut i = self.position();
        let crate_deps = self.encode_crate_deps();
        let dylib_dependency_formats = self.encode_dylib_dependency_formats();
        let dep_bytes = self.position() - i;

        // Encode the language items.
        i = self.position();
        let (lang_items, lang_items_missing) = self.encode_lang_items();
        let lang_item_bytes = self.position() - i;

        // Encode the native libraries used
        i = self.position();
        let native_libraries = self.encode_native_libraries();
        let native_lib_bytes = self.position() - i;

        // Encode codemap
        i = self.position();
        let codemap = self.encode_codemap();
        let codemap_bytes = self.position() - i;

        // Encode DefPathTable
        i = self.position();
        let def_path_table = self.encode_def_path_table();
        let def_path_table_bytes = self.position() - i;

        // Encode the def IDs of impls, for coherence checking.
        i = self.position();
        let impls = self.encode_impls();
        let impl_bytes = self.position() - i;

        // Encode exported symbols info.
        i = self.position();
        let exported_symbols = self.encode_exported_symbols();
        let exported_symbols_bytes = self.position() - i;

        // Encode and index the items.
        i = self.position();
        let items = self.encode_info_for_items();
        let item_bytes = self.position() - i;

        i = self.position();
        let index = items.write_index(&mut self.opaque.cursor);
        let index_bytes = self.position() - i;

        let tcx = self.tcx;
        let link_meta = self.link_meta;
        let is_proc_macro = tcx.sess.crate_types.borrow().contains(&CrateTypeProcMacro);
        let root = self.lazy(&CrateRoot {
            name: link_meta.crate_name,
            triple: tcx.sess.opts.target_triple.clone(),
            hash: link_meta.crate_hash,
            disambiguator: tcx.sess.local_crate_disambiguator(),
            panic_strategy: tcx.sess.panic_strategy(),
            plugin_registrar_fn: tcx.sess
                .plugin_registrar_fn
                .get()
                .map(|id| tcx.hir.local_def_id(id).index),
            macro_derive_registrar: if is_proc_macro {
                let id = tcx.sess.derive_registrar_fn.get().unwrap();
                Some(tcx.hir.local_def_id(id).index)
            } else {
                None
            },

            crate_deps: crate_deps,
            dylib_dependency_formats: dylib_dependency_formats,
            lang_items: lang_items,
            lang_items_missing: lang_items_missing,
            native_libraries: native_libraries,
            codemap: codemap,
            def_path_table: def_path_table,
            impls: impls,
            exported_symbols: exported_symbols,
            index: index,
        });

        let total_bytes = self.position();

        if self.tcx.sess.meta_stats() {
            let mut zero_bytes = 0;
            for e in self.opaque.cursor.get_ref() {
                if *e == 0 {
                    zero_bytes += 1;
                }
            }

            println!("metadata stats:");
            println!("             dep bytes: {}", dep_bytes);
            println!("       lang item bytes: {}", lang_item_bytes);
            println!("          native bytes: {}", native_lib_bytes);
            println!("         codemap bytes: {}", codemap_bytes);
            println!("            impl bytes: {}", impl_bytes);
            println!("    exp. symbols bytes: {}", exported_symbols_bytes);
            println!("  def-path table bytes: {}", def_path_table_bytes);
            println!("            item bytes: {}", item_bytes);
            println!("           index bytes: {}", index_bytes);
            println!("            zero bytes: {}", zero_bytes);
            println!("           total bytes: {}", total_bytes);
        }

        root
    }
}

// NOTE(eddyb) The following comment was preserved for posterity, even
// though it's no longer relevant as EBML (which uses nested & tagged
// "documents") was replaced with a scheme that can't go out of bounds.
//
// And here we run into yet another obscure archive bug: in which metadata
// loaded from archives may have trailing garbage bytes. Awhile back one of
// our tests was failing sporadically on the OSX 64-bit builders (both nopt
// and opt) by having ebml generate an out-of-bounds panic when looking at
// metadata.
//
// Upon investigation it turned out that the metadata file inside of an rlib
// (and ar archive) was being corrupted. Some compilations would generate a
// metadata file which would end in a few extra bytes, while other
// compilations would not have these extra bytes appended to the end. These
// extra bytes were interpreted by ebml as an extra tag, so they ended up
// being interpreted causing the out-of-bounds.
//
// The root cause of why these extra bytes were appearing was never
// discovered, and in the meantime the solution we're employing is to insert
// the length of the metadata to the start of the metadata. Later on this
// will allow us to slice the metadata to the precise length that we just
// generated regardless of trailing bytes that end up in it.

pub fn encode_metadata<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                 cstore: &cstore::CStore,
                                 reexports: &def::ExportMap,
                                 link_meta: &LinkMeta,
                                 exported_symbols: &NodeSet)
                                 -> Vec<u8> {
    let mut cursor = Cursor::new(vec![]);
    cursor.write_all(METADATA_HEADER).unwrap();

    // Will be filed with the root position after encoding everything.
    cursor.write_all(&[0, 0, 0, 0]).unwrap();

    let root = {
        let mut ecx = EncodeContext {
            opaque: opaque::Encoder::new(&mut cursor),
            tcx: tcx,
            reexports: reexports,
            link_meta: link_meta,
            cstore: cstore,
            exported_symbols: exported_symbols,
            lazy_state: LazyState::NoNode,
            type_shorthands: Default::default(),
            predicate_shorthands: Default::default(),
        };

        // Encode the rustc version string in a predictable location.
        rustc_version().encode(&mut ecx).unwrap();

        // Encode all the entries and extra information in the crate,
        // culminating in the `CrateRoot` which points to all of it.
        ecx.encode_crate_root()
    };
    let mut result = cursor.into_inner();

    // Encode the root position.
    let header = METADATA_HEADER.len();
    let pos = root.position;
    result[header + 0] = (pos >> 24) as u8;
    result[header + 1] = (pos >> 16) as u8;
    result[header + 2] = (pos >> 8) as u8;
    result[header + 3] = (pos >> 0) as u8;

    result
}

pub fn get_repr_options<'a, 'tcx, 'gcx>(tcx: &TyCtxt<'a, 'tcx, 'gcx>, did: DefId) -> ReprOptions {
    let ty = tcx.item_type(did);
    match ty.sty {
        ty::TyAdt(ref def, _) => return def.repr,
        _ => bug!("{} is not an ADT", ty),
    }
}