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

ICE: len_without_is_empty #7186

Closed
lopopolo opened this issue May 7, 2021 · 5 comments
Closed

ICE: len_without_is_empty #7186

lopopolo opened this issue May 7, 2021 · 5 comments
Labels
C-bug Category: Clippy is not doing the correct thing I-ICE Issue: Clippy panicked, giving an Internal Compilation Error (ICE) ❄️

Comments

@lopopolo
Copy link

lopopolo commented May 7, 2021

I can't figure out how to get this to reproduce so I'm not sure how to minimize.

$ rustc -Vv
rustc 1.52.0 (88f19c6da 2021-05-03)
binary: rustc
commit-hash: 88f19c6dab716c6281af7602e30f413e809c5974
commit-date: 2021-05-03
host: x86_64-apple-darwin
release: 1.52.0
LLVM version: 12.0.0
$ cargo clippy -V
clippy 0.1.52 (88f19c6d 2021-05-03)
thread 'rustc' panicked at 'found unstable fingerprints for predicates_of(core[7cda]::marker::Sized): GenericPredicates { parent: None, predicates: [(Binder(TraitPredicate(<Self as core::marker::Sized>)), /Users/lopopolo/.rustup/toolchains/1.52.0-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/marker.rs:92:1: 92:16 (#0))] }', /rustc/88f19c6dab716c6281af7602e30f413e809c5974/compiler/rustc_query_system/src/query/plumbing.rs:593:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

error: internal compiler error: unexpected panic

note: the compiler unexpectedly panicked. this is a bug.

note: we would appreciate a bug report: https://github.com/rust-lang/rust-clippy/issues/new

note: Clippy version: clippy 0.1.52 (88f19c6d 2021-05-03)

query stack during panic:
#0 [predicates_of] computing predicates of `core::marker::Sized`
#1 [check_impl_item_well_formed] checking that `<impl at spinoso-symbol/src/lib.rs:196:1: 324:2>::len` is well-formed
end of query stack
error: could not compile `spinoso-symbol`

To learn more, run the command again with --verbose.

Source: spinso-symbol/src/lib.rs

#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![warn(clippy::needless_borrow)]
// https://github.com/rust-lang/rust-clippy/pull/5998#issuecomment-731855891
#![allow(clippy::map_err_ignore)]
#![allow(clippy::option_if_let_else)]
#![cfg_attr(test, allow(clippy::non_ascii_literal))]
#![allow(unknown_lints)]
#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![warn(missing_copy_implementations)]
#![warn(rust_2018_idioms)]
#![warn(trivial_casts, trivial_numeric_casts)]
#![warn(unused_qualifications)]
#![warn(variant_size_differences)]
#![forbid(unsafe_code)]
// Enable feature callouts in generated documentation:
// https://doc.rust-lang.org/beta/unstable-book/language-features/doc-cfg.html
//
// This approach is borrowed from tokio.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_alias))]

//! Identifier for interned bytestrings and routines for manipulating the
//! underlying bytestrings.
//!
//! `Symbol` is a `Copy` type based on `u32`. `Symbol` is cheap to copy, store,
//! and compare. It is suitable for representing indexes into a string interner.
//!
//! # Artichoke integration
//!
//! This crate has an `artichoke` Cargo feature. When this feature is active,
//! this crate implements [the `Symbol` API from Ruby Core]. These APIs require
//! resolving the underlying bytes associated with the `Symbol` via a type that
//! implements `Intern` from `artichoke-core`.
//!
//! APIs that require this feature to be active are highlighted in the
//! documentation.
//!
//! This crate provides an `AllSymbols` iterator for walking all symbols stored
//! in an [`Intern`]er and an extension trait for constructing it which is
//! suitable for implementing [`Symbol::all_symbols`] from Ruby Core.
//!
//! This crate provides an `Inspect` iterator for converting `Symbol` byte
//! content to a debug representation suitable for implementing
//! [`Symbol#inspect`] from Ruby Core.
//!
//! # `no_std`
//!
//! This crate is `no_std` compatible when built without the `std` feature. This
//! crate does not depend on [`alloc`].
//!
//! # Crate features
//!
//! All features are enabled by default.
//!
//! - **artichoke** - Enables additional methods, functions, and types for
//!   implementing APIs from Ruby Core. Dropping this feature removes the
//!   `artichoke-core` and `focaccia` dependencies. Activating this feature also
//!   activates the **inspect** feature.
//! - **inspect** - Enables an iterator for generating debug output of a symbol
//!   bytestring. Activating this feature also activates the **ident-parser**
//!   feature.
//! - **ident-parser** - Enables a parser to determing the Ruby identifier type,
//!   if any, for a bytestring. Dropping this feature removes the `bstr` and
//!   `scolapasta-string-escape` dependencies.
//! - **std** - Enables a dependency on the Rust Standard Library. Activating
//!   this feature enables [`std::error::Error`] impls on error types in this
//!   crate.
//!
//! [the `Symbol` API from Ruby Core]: https://ruby-doc.org/core-2.6.3/Symbol.html
//! [`Symbol::all_symbols`]: https://ruby-doc.org/core-2.6.3/Symbol.html#method-c-all_symbols
//! [`Symbol#inspect`]: https://ruby-doc.org/core-2.6.3/Symbol.html#method-i-inspect
//! [`alloc`]: https://doc.rust-lang.org/alloc/
//! [`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html

#![no_std]

#[cfg(any(feature = "std", test, doctest))]
extern crate std;

// Ensure code blocks in README.md compile
#[cfg(doctest)]
macro_rules! readme {
    ($x:expr) => {
        #[doc = $x]
        mod readme {}
    };
    () => {
        readme!(include_str!("../README.md"));
    };
}
#[cfg(all(feature = "inspect", doctest))]
readme!();

#[cfg(feature = "artichoke")]
use artichoke_core::intern::Intern;
use core::borrow::Borrow;
use core::fmt;
use core::mem::size_of;
use core::num::TryFromIntError;

#[doc(inline)]
#[cfg(feature = "artichoke")]
#[cfg_attr(docsrs, doc(cfg(feature = "artichoke")))]
pub use focaccia::{CaseFold, NoSuchCaseFoldingScheme};

// Spinoso symbol assumes symbols are `u32` and requires `usize` to be at least
// as big as `u32`.
//
// This const-evaluated expression will fail to compile if this invariant does
// not hold.
const _: () = [()][!(size_of::<usize>() >= size_of::<u32>()) as usize];

#[cfg(feature = "artichoke")]
mod all_symbols;
#[cfg(feature = "artichoke")]
mod casecmp;
mod convert;
mod eq;
#[cfg(feature = "ident-parser")]
mod ident;
#[cfg(feature = "inspect")]
mod inspect;

#[cfg(test)]
mod fixtures;

#[cfg(feature = "artichoke")]
pub use all_symbols::{AllSymbols, InternerAllSymbols};
#[cfg(feature = "artichoke")]
pub use casecmp::{ascii_casecmp, unicode_case_eq};
#[cfg(feature = "ident-parser")]
pub use ident::{IdentifierType, ParseIdentifierError};
#[cfg(feature = "inspect")]
pub use inspect::Inspect;

/// Error returned when a symbol identifier overflows.
///
/// Spinoso symbol uses `u32` identifiers for symbols to save space. If more
/// than `u32::MAX` symbols are stored in the underlying table, no more
/// identifiers can be generated.
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct SymbolOverflowError {
    _private: (),
}

impl SymbolOverflowError {
    /// The maximum identifier of a `Symbol`.
    pub const MAX_IDENTIFIER: usize = u32::MAX as usize;

    /// Construct a new, default `SymbolOverflowError`.
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self { _private: () }
    }
}

impl From<TryFromIntError> for SymbolOverflowError {
    #[inline]
    fn from(err: TryFromIntError) -> Self {
        let _ = err;
        Self::new()
    }
}

impl fmt::Display for SymbolOverflowError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Symbol overflow")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for SymbolOverflowError {}

/// Identifier bound to an interned bytestring.
///
/// A `Symbol` allows retrieving a reference to the original interned
/// bytestring.  Equivalent `Symbol`s will resolve to an identical bytestring.
///
/// `Symbol`s are based on a `u32` index. They are cheap to compare and cheap to
/// copy.
///
/// `Symbol`s are not constrained to the interner which created them.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Symbol(u32);

impl Borrow<u32> for Symbol {
    fn borrow(&self) -> &u32 {
        &self.0
    }
}

impl Symbol {
    /// Construct a new `Symbol` from the given `u32`.
    ///
    /// `Symbol`s constructed manually may fail to resolve to an underlying
    /// bytesstring.
    ///
    /// `Symbol`s are not constrained to the interner which created them.
    /// No runtime checks ensure that the underlying interner is called with a
    /// `Symbol` that the interner itself issued.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_symbol::Symbol;
    /// let sym = Symbol::new(263);
    /// assert_eq!(sym.id(), 263);
    /// ```
    #[inline]
    #[must_use]
    pub const fn new(id: u32) -> Self {
        Self(id)
    }

    /// Return the `u32` identifier from this `Symbol`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_symbol::Symbol;
    /// let sym = Symbol::new(263);
    /// assert_eq!(sym.id(), 263);
    /// assert_eq!(u32::from(sym), 263);
    /// ```
    #[inline]
    #[must_use]
    pub const fn id(self) -> u32 {
        self.0
    }

    /// Returns whether the symbol is the empty byteslice `b""` in the
    /// underlying interner.
    ///
    /// If there symbol does not exist in the underlying interner or there is an
    /// error looking up the symbol in the underlying interner, `true` is
    /// returned.
    #[inline]
    #[must_use]
    #[cfg(feature = "artichoke")]
    #[cfg_attr(docsrs, doc(cfg(feature = "artichoke")))]
    pub fn is_empty<T, U>(self, interner: &T) -> bool
    where
        T: Intern<Symbol = U>,
        U: Copy + From<Symbol>,
    {
        if let Ok(Some(bytes)) = interner.lookup_symbol(self.into()) {
            bytes.is_empty()
        } else {
            true
        }
    }

    /// Returns the length of the byteslice associated with the symbol in the
    /// underlying interner.
    ///
    /// If there symbol does not exist in the underlying interner or there is an
    /// error looking up the symbol in the underlying interner, `0` is returned.
    #[inline]
    #[must_use]
    #[cfg(feature = "artichoke")]
    #[cfg_attr(docsrs, doc(cfg(feature = "artichoke")))]
    #[allow(clippy::len_without_is_empty)]
    pub fn len<T, U>(self, interner: &T) -> usize
    where
        T: Intern<Symbol = U>,
        U: Copy + From<Symbol>,
    {
        if let Ok(Some(bytes)) = interner.lookup_symbol(self.into()) {
            bytes.len()
        } else {
            0_usize
        }
    }

    /// Returns the interned byteslice associated with the symbol in the
    /// underlying interner.
    ///
    /// If there symbol does not exist in the underlying interner or there is an
    /// error looking up the symbol in the underlying interner, `&[]` is
    /// returned.
    #[inline]
    #[must_use]
    #[cfg(feature = "artichoke")]
    #[cfg_attr(docsrs, doc(cfg(feature = "artichoke")))]
    pub fn bytes<T, U>(self, interner: &T) -> &[u8]
    where
        T: Intern<Symbol = U>,
        U: Copy + From<Symbol>,
    {
        if let Ok(Some(bytes)) = interner.lookup_symbol(self.into()) {
            bytes
        } else {
            &[]
        }
    }

    /// Returns an iterator that yields a debug representation of the interned
    /// byteslice associated with the symbol in the underlying interner.
    ///
    /// This iterator produces [`char`] sequences like `:spinoso` and
    /// `:"invalid-\xFF-utf8"`.
    ///
    /// If there symbol does not exist in the underlying interner or there is an
    /// error looking up the symbol in the underlying interner, a default
    /// iterator is returned.
    #[inline]
    #[cfg(feature = "artichoke")]
    #[cfg_attr(docsrs, doc(cfg(feature = "artichoke")))]
    pub fn inspect<T, U>(self, interner: &T) -> Inspect<'_>
    where
        T: Intern<Symbol = U>,
        U: Copy + From<Symbol>,
    {
        if let Ok(Some(bytes)) = interner.lookup_symbol(self.into()) {
            Inspect::from(bytes)
        } else {
            Inspect::default()
        }
    }
}
@lopopolo
Copy link
Author

lopopolo commented May 7, 2021

This might be a dupe of rust-lang/rust#84002?

@fujiapple852
Copy link

Similar issue on 1.52:

$ rustc -Vv
rustc 1.52.0 (88f19c6da 2021-05-03)
binary: rustc
commit-hash: 88f19c6dab716c6281af7602e30f413e809c5974
commit-date: 2021-05-03
host: x86_64-apple-darwin
release: 1.52.0
LLVM version: 12.0.0
$ cargo clippy -V
clippy 0.1.52 (88f19c6d 2021-05-03)

Intermittent panic, haven't been able to minimise so far:

thread 'rustc' panicked at 'found unstable fingerprints for evaluate_obligation(b1919c1468ce032d-ea24d1dfc1f54c05): Ok(EvaluatedToOkModuloRegions)', /rustc/88f19c6dab716c6281af7602e30f413e809c5974/compiler/rustc_query_system/src/query/plumbing.rs:593:5
stack backtrace:
   0: _rust_begin_unwind
   1: std::panicking::begin_panic_fmt
   2: rustc_query_system::query::plumbing::incremental_verify_ich
   3: rustc_query_system::query::plumbing::load_from_disk_and_cache_in_memory
   4: rustc_data_structures::stack::ensure_sufficient_stack
   5: rustc_query_system::query::plumbing::get_query_impl
   6: <rustc_query_impl::Queries as rustc_middle::ty::query::QueryEngine>::evaluate_obligation
   7: <rustc_infer::infer::InferCtxt as rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt>::evaluate_obligation
   8: <rustc_infer::infer::InferCtxt as rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt>::evaluate_obligation_no_overflow
   9: rustc_trait_selection::traits::fulfill::FulfillProcessor::process_trait_obligation
  10: rustc_trait_selection::traits::fulfill::FulfillProcessor::progress_changed_obligations
  11: rustc_data_structures::obligation_forest::ObligationForest<O>::process_obligations
  12: <rustc_trait_selection::traits::fulfill::FulfillmentContext as rustc_infer::traits::engine::TraitEngine>::select_where_possible
  13: <rustc_trait_selection::traits::fulfill::FulfillmentContext as rustc_infer::traits::engine::TraitEngine>::select_all_or_error
  14: rustc_infer::infer::InferCtxtBuilder::enter
  15: <clippy_lints::future_not_send::FutureNotSend as rustc_lint::passes::LateLintPass>::check_fn
  16: <rustc_lint::late::LateLintPassObjects as rustc_lint::passes::LateLintPass>::check_fn
  17: <rustc_lint::late::LateContextAndPass<T> as rustc_hir::intravisit::Visitor>::visit_fn
  18: rustc_hir::intravisit::walk_impl_item
  19: rustc_hir::intravisit::Visitor::visit_nested_impl_item
  20: rustc_hir::intravisit::walk_item
  21: rustc_hir::intravisit::Visitor::visit_nested_item
  22: rustc_hir::intravisit::walk_item
  23: rustc_hir::intravisit::Visitor::visit_nested_item
  24: rustc_hir::intravisit::walk_item
  25: rustc_hir::intravisit::Visitor::visit_nested_item
  26: rustc_hir::intravisit::walk_crate
  27: rustc_lint::late::late_lint_pass_crate
  28: rustc_lint::late::late_lint_crate
  29: rustc_data_structures::sync::join
  30: <std::panic::AssertUnwindSafe<F> as core::ops::function::FnOnce<()>>::call_once
  31: rustc_session::utils::<impl rustc_session::session::Session>::time
  32: rustc_interface::passes::analysis
  33: rustc_middle::dep_graph::<impl rustc_query_system::dep_graph::DepKind for rustc_middle::dep_graph::dep_node::DepKind>::with_deps
  34: rustc_query_system::dep_graph::graph::DepGraph<K>::with_task_impl
  35: rustc_data_structures::stack::ensure_sufficient_stack
  36: rustc_query_system::query::plumbing::force_query_with_job
  37: rustc_query_system::query::plumbing::get_query_impl
  38: <rustc_query_impl::Queries as rustc_middle::ty::query::QueryEngine>::analysis
  39: rustc_interface::passes::QueryContext::enter
  40: rustc_interface::queries::<impl rustc_interface::interface::Compiler>::enter
  41: rustc_span::with_source_map
  42: rustc_interface::interface::create_compiler_and_run
  43: scoped_tls::ScopedKey<T>::set
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

error: internal compiler error: unexpected panic

note: the compiler unexpectedly panicked. this is a bug.

note: we would appreciate a bug report: https://github.com/rust-lang/rust-clippy/issues/new

note: Clippy version: clippy 0.1.52 (88f19c6d 2021-05-03)

query stack during panic:
#0 [evaluate_obligation] evaluating trait selection obligation `std::boxed::Box<dyn std::error::Error + std::marker::Send + std::marker::Sync>: std::convert::Into<std::boxed::Box<dyn std::error::Error + std::marker::Send + std::marker::Sync>>`
#1 [analysis] running analysis passes on this crate
end of query stack

@xFrednet
Copy link
Member

xFrednet commented May 8, 2021

I can't reproduce the ICE in a playground. Could you maybe add the features you had enabled during the Clippy run?

@rustbot label +I-ICE +C-bug

@rustbot rustbot added C-bug Category: Clippy is not doing the correct thing I-ICE Issue: Clippy panicked, giving an Internal Compilation Error (ICE) ❄️ labels May 8, 2021
@lopopolo
Copy link
Author

lopopolo commented May 8, 2021

The bug appears to be related to incremental compilation. There are several other similar issues in rust-lang/rust issue tracker,

@giraffate
Copy link
Contributor

I'm closing this because of rust-lang/rust#84002 (comment).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: Clippy is not doing the correct thing I-ICE Issue: Clippy panicked, giving an Internal Compilation Error (ICE) ❄️
Projects
None yet
Development

No branches or pull requests

5 participants