Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Encodable and Encoder infallible. #94732

Merged
merged 5 commits into from
Jun 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::thin_vec::ThinVec;
use rustc_macros::HashStable_Generic;
use rustc_serialize::{self, Decoder, Encoder};
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use rustc_span::source_map::{respan, Spanned};
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{Span, DUMMY_SP};
Expand Down Expand Up @@ -2472,13 +2472,11 @@ rustc_index::newtype_index! {
}
}

impl<S: Encoder> rustc_serialize::Encodable<S> for AttrId {
fn encode(&self, _s: &mut S) -> Result<(), S::Error> {
Ok(())
}
impl<S: Encoder> Encodable<S> for AttrId {
fn encode(&self, _s: &mut S) {}
}

impl<D: Decoder> rustc_serialize::Decodable<D> for AttrId {
impl<D: Decoder> Decodable<D> for AttrId {
fn decode(_: &mut D) -> AttrId {
crate::attr::mk_attr_id()
}
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_ast/src/ptr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ impl<D: Decoder, T: 'static + Decodable<D>> Decodable<D> for P<T> {
}

impl<S: Encoder, T: Encodable<S>> Encodable<S> for P<T> {
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
(**self).encode(s)
fn encode(&self, s: &mut S) {
(**self).encode(s);
}
}

Expand Down Expand Up @@ -191,8 +191,8 @@ impl<'a, T> IntoIterator for &'a P<[T]> {
}

impl<S: Encoder, T: Encodable<S>> Encodable<S> for P<[T]> {
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
Encodable::encode(&**self, s)
fn encode(&self, s: &mut S) {
Encodable::encode(&**self, s);
}
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_ast/src/tokenstream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,9 @@ impl fmt::Debug for LazyTokenStream {
}

impl<S: Encoder> Encodable<S> for LazyTokenStream {
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
fn encode(&self, s: &mut S) {
// Used by AST json printing.
Encodable::encode(&self.create_token_stream(), s)
Encodable::encode(&self.create_token_stream(), s);
}
}

Expand Down
19 changes: 9 additions & 10 deletions compiler/rustc_codegen_ssa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ use rustc_middle::dep_graph::WorkProduct;
use rustc_middle::middle::dependency_format::Dependencies;
use rustc_middle::middle::exported_symbols::SymbolExportKind;
use rustc_middle::ty::query::{ExternProviders, Providers};
use rustc_serialize::{opaque, Decodable, Decoder, Encoder};
use rustc_serialize::opaque::{MemDecoder, MemEncoder};
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use rustc_session::config::{CrateType, OutputFilenames, OutputType, RUST_CGU_EXT};
use rustc_session::cstore::{self, CrateSource};
use rustc_session::utils::NativeLibKind;
Expand Down Expand Up @@ -203,16 +204,14 @@ const RUSTC_VERSION: Option<&str> = option_env!("CFG_VERSION");

impl CodegenResults {
pub fn serialize_rlink(codegen_results: &CodegenResults) -> Vec<u8> {
let mut encoder = opaque::Encoder::new(vec![]);
encoder.emit_raw_bytes(RLINK_MAGIC).unwrap();
let mut encoder = MemEncoder::new();
encoder.emit_raw_bytes(RLINK_MAGIC);
// `emit_raw_bytes` is used to make sure that the version representation does not depend on
// Encoder's inner representation of `u32`.
encoder.emit_raw_bytes(&RLINK_VERSION.to_be_bytes()).unwrap();
encoder.emit_str(RUSTC_VERSION.unwrap()).unwrap();

let mut encoder = rustc_serialize::opaque::Encoder::new(encoder.into_inner());
rustc_serialize::Encodable::encode(codegen_results, &mut encoder).unwrap();
encoder.into_inner()
encoder.emit_raw_bytes(&RLINK_VERSION.to_be_bytes());
encoder.emit_str(RUSTC_VERSION.unwrap());
Encodable::encode(codegen_results, &mut encoder);
encoder.finish()
}

pub fn deserialize_rlink(data: Vec<u8>) -> Result<Self, String> {
Expand All @@ -232,7 +231,7 @@ impl CodegenResults {
return Err(".rlink file was produced with encoding version {version_array}, but the current version is {RLINK_VERSION}".to_string());
}

let mut decoder = opaque::Decoder::new(&data[4..], 0);
let mut decoder = MemDecoder::new(&data[4..], 0);
let rustc_version = decoder.read_str();
let current_version = RUSTC_VERSION.unwrap();
if rustc_version != current_version {
Expand Down
19 changes: 9 additions & 10 deletions compiler/rustc_data_structures/src/fingerprint.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::stable_hasher;
use rustc_serialize::{Decodable, Encodable};
use rustc_serialize::{Decodable, Decoder, Encodable, Encoder};
use std::convert::TryInto;
use std::hash::{Hash, Hasher};

Expand Down Expand Up @@ -142,15 +142,14 @@ impl stable_hasher::StableHasherResult for Fingerprint {

impl_stable_hash_via_hash!(Fingerprint);

impl<E: rustc_serialize::Encoder> Encodable<E> for Fingerprint {
impl<E: Encoder> Encodable<E> for Fingerprint {
#[inline]
fn encode(&self, s: &mut E) -> Result<(), E::Error> {
s.emit_raw_bytes(&self.to_le_bytes())?;
Ok(())
fn encode(&self, s: &mut E) {
s.emit_raw_bytes(&self.to_le_bytes());
}
}

impl<D: rustc_serialize::Decoder> Decodable<D> for Fingerprint {
impl<D: Decoder> Decodable<D> for Fingerprint {
#[inline]
fn decode(d: &mut D) -> Self {
Fingerprint::from_le_bytes(d.read_raw_bytes(16).try_into().unwrap())
Expand Down Expand Up @@ -185,16 +184,16 @@ impl std::fmt::Display for PackedFingerprint {
}
}

impl<E: rustc_serialize::Encoder> Encodable<E> for PackedFingerprint {
impl<E: Encoder> Encodable<E> for PackedFingerprint {
#[inline]
fn encode(&self, s: &mut E) -> Result<(), E::Error> {
fn encode(&self, s: &mut E) {
// Copy to avoid taking reference to packed field.
let copy = self.0;
copy.encode(s)
copy.encode(s);
}
}

impl<D: rustc_serialize::Decoder> Decodable<D> for PackedFingerprint {
impl<D: Decoder> Decodable<D> for PackedFingerprint {
#[inline]
fn decode(d: &mut D) -> Self {
Self(Fingerprint::decode(d))
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_data_structures/src/svh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ impl fmt::Display for Svh {
}

impl<S: Encoder> Encodable<S> for Svh {
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_u64(self.as_u64().to_le())
fn encode(&self, s: &mut S) {
s.emit_u64(self.as_u64().to_le());
}
}

Expand Down
49 changes: 20 additions & 29 deletions compiler/rustc_incremental/src/persist/file_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,20 @@ const HEADER_FORMAT_VERSION: u16 = 0;
/// the Git commit hash.
const RUSTC_VERSION: Option<&str> = option_env!("CFG_VERSION");

pub(crate) fn write_file_header(stream: &mut FileEncoder, nightly_build: bool) -> FileEncodeResult {
stream.emit_raw_bytes(FILE_MAGIC)?;
stream.emit_raw_bytes(&[
(HEADER_FORMAT_VERSION >> 0) as u8,
(HEADER_FORMAT_VERSION >> 8) as u8,
])?;
pub(crate) fn write_file_header(stream: &mut FileEncoder, nightly_build: bool) {
stream.emit_raw_bytes(FILE_MAGIC);
stream
.emit_raw_bytes(&[(HEADER_FORMAT_VERSION >> 0) as u8, (HEADER_FORMAT_VERSION >> 8) as u8]);

let rustc_version = rustc_version(nightly_build);
assert_eq!(rustc_version.len(), (rustc_version.len() as u8) as usize);
stream.emit_raw_bytes(&[rustc_version.len() as u8])?;
stream.emit_raw_bytes(rustc_version.as_bytes())
stream.emit_raw_bytes(&[rustc_version.len() as u8]);
stream.emit_raw_bytes(rustc_version.as_bytes());
}

pub(crate) fn save_in<F>(sess: &Session, path_buf: PathBuf, name: &str, encode: F)
where
F: FnOnce(&mut FileEncoder) -> FileEncodeResult,
F: FnOnce(FileEncoder) -> FileEncodeResult,
{
debug!("save: storing data in {}", path_buf.display());

Expand Down Expand Up @@ -80,28 +78,21 @@ where
}
};

if let Err(err) = write_file_header(&mut encoder, sess.is_nightly_build()) {
sess.err(&format!("failed to write {} header to `{}`: {}", name, path_buf.display(), err));
return;
}

if let Err(err) = encode(&mut encoder) {
sess.err(&format!("failed to write {} to `{}`: {}", name, path_buf.display(), err));
return;
}
write_file_header(&mut encoder, sess.is_nightly_build());

if let Err(err) = encoder.flush() {
sess.err(&format!("failed to flush {} to `{}`: {}", name, path_buf.display(), err));
return;
match encode(encoder) {
Ok(position) => {
sess.prof.artifact_size(
&name.replace(' ', "_"),
path_buf.file_name().unwrap().to_string_lossy(),
position as u64,
);
debug!("save: data written to disk successfully");
}
Err(err) => {
sess.err(&format!("failed to write {} to `{}`: {}", name, path_buf.display(), err));
}
}

sess.prof.artifact_size(
&name.replace(' ', "_"),
path_buf.file_name().unwrap().to_string_lossy(),
encoder.position() as u64,
);

debug!("save: data written to disk successfully");
}

/// Reads the contents of a file with a file header as defined in this module.
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_incremental/src/persist/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::memmap::Mmap;
use rustc_middle::dep_graph::{SerializedDepGraph, WorkProduct, WorkProductId};
use rustc_middle::ty::OnDiskCache;
use rustc_serialize::opaque::Decoder;
use rustc_serialize::opaque::MemDecoder;
use rustc_serialize::Decodable;
use rustc_session::config::IncrementalStateAssertion;
use rustc_session::Session;
Expand Down Expand Up @@ -156,7 +156,7 @@ pub fn load_dep_graph(sess: &Session) -> DepGraphFuture {

if let LoadResult::Ok { data: (work_products_data, start_pos) } = load_result {
// Decode the list of work_products
let mut work_product_decoder = Decoder::new(&work_products_data[..], start_pos);
let mut work_product_decoder = MemDecoder::new(&work_products_data[..], start_pos);
let work_products: Vec<SerializedWorkProduct> =
Decodable::decode(&mut work_product_decoder);

Expand Down Expand Up @@ -193,7 +193,7 @@ pub fn load_dep_graph(sess: &Session) -> DepGraphFuture {
LoadResult::DataOutOfDate => LoadResult::DataOutOfDate,
LoadResult::Error { message } => LoadResult::Error { message },
LoadResult::Ok { data: (bytes, start_pos) } => {
let mut decoder = Decoder::new(&bytes, start_pos);
let mut decoder = MemDecoder::new(&bytes, start_pos);
let prev_commandline_args_hash = u64::decode(&mut decoder);

if prev_commandline_args_hash != expected_hash {
Expand Down
29 changes: 8 additions & 21 deletions compiler/rustc_incremental/src/persist/save.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use rustc_data_structures::sync::join;
use rustc_middle::dep_graph::{DepGraph, SerializedDepGraph, WorkProduct, WorkProductId};
use rustc_middle::ty::TyCtxt;
use rustc_serialize::opaque::{FileEncodeResult, FileEncoder};
use rustc_serialize::Encodable as RustcEncodable;
use rustc_serialize::Encodable;
use rustc_session::Session;
use std::fs;

Expand Down Expand Up @@ -96,8 +96,9 @@ pub fn save_work_product_index(
debug!("save_work_product_index()");
dep_graph.assert_ignored();
let path = work_products_path(sess);
file_format::save_in(sess, path, "work product index", |e| {
encode_work_product_index(&new_work_products, e)
file_format::save_in(sess, path, "work product index", |mut e| {
encode_work_product_index(&new_work_products, &mut e);
e.finish()
});

// We also need to clean out old work-products, as not all of them are
Expand All @@ -123,7 +124,7 @@ pub fn save_work_product_index(
fn encode_work_product_index(
work_products: &FxHashMap<WorkProductId, WorkProduct>,
encoder: &mut FileEncoder,
) -> FileEncodeResult {
) {
let serialized_products: Vec<_> = work_products
.iter()
.map(|(id, work_product)| SerializedWorkProduct {
Expand All @@ -135,7 +136,7 @@ fn encode_work_product_index(
serialized_products.encode(encoder)
}

fn encode_query_cache(tcx: TyCtxt<'_>, encoder: &mut FileEncoder) -> FileEncodeResult {
fn encode_query_cache(tcx: TyCtxt<'_>, encoder: FileEncoder) -> FileEncodeResult {
tcx.sess.time("incr_comp_serialize_result_cache", || tcx.serialize_query_result_cache(encoder))
}

Expand Down Expand Up @@ -170,24 +171,10 @@ pub fn build_dep_graph(
}
};

if let Err(err) = file_format::write_file_header(&mut encoder, sess.is_nightly_build()) {
sess.err(&format!(
"failed to write dependency graph header to `{}`: {}",
path_buf.display(),
err
));
return None;
}
file_format::write_file_header(&mut encoder, sess.is_nightly_build());

// First encode the commandline arguments hash
if let Err(err) = sess.opts.dep_tracking_hash(false).encode(&mut encoder) {
sess.err(&format!(
"failed to write dependency graph hash `{}`: {}",
path_buf.display(),
err
));
return None;
}
sess.opts.dep_tracking_hash(false).encode(&mut encoder);

Some(DepGraph::new(
&sess.prof,
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_index/src/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ pub struct IndexVec<I: Idx, T> {
unsafe impl<I: Idx, T> Send for IndexVec<I, T> where T: Send {}

impl<S: Encoder, I: Idx, T: Encodable<S>> Encodable<S> for IndexVec<I, T> {
fn encode(&self, s: &mut S) -> Result<(), S::Error> {
Encodable::encode(&self.raw, s)
fn encode(&self, s: &mut S) {
Encodable::encode(&self.raw, s);
}
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_macros/src/newtype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,8 @@ impl Parse for Newtype {
}
}
impl<E: ::rustc_serialize::Encoder> ::rustc_serialize::Encodable<E> for #name {
fn encode(&self, e: &mut E) -> Result<(), E::Error> {
e.emit_u32(self.private)
fn encode(&self, e: &mut E) {
e.emit_u32(self.private);
}
}
}
Expand Down
Loading