@@ -17,8 +17,8 @@ use rustc_hir::def_id::{
1717 CrateNum , DefId , DefIndex , LocalDefId , CRATE_DEF_ID , CRATE_DEF_INDEX , LOCAL_CRATE ,
1818} ;
1919use rustc_hir:: definitions:: DefPathData ;
20- use rustc_hir:: intravisit;
2120use rustc_hir:: lang_items:: LangItem ;
21+ use rustc_hir_pretty:: id_to_string;
2222use rustc_middle:: middle:: debugger_visualizer:: DebuggerVisualizerFile ;
2323use rustc_middle:: middle:: dependency_format:: Linkage ;
2424use rustc_middle:: middle:: exported_symbols:: {
@@ -1614,7 +1614,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
16141614 record ! ( self . tables. mir_const_qualif[ def_id. to_def_id( ) ] <- qualifs) ;
16151615 let body_id = tcx. hir ( ) . maybe_body_owned_by ( def_id) ;
16161616 if let Some ( body_id) = body_id {
1617- let const_data = self . encode_rendered_const_for_body ( body_id) ;
1617+ let const_data = rendered_const ( self . tcx , body_id) ;
16181618 record ! ( self . tables. rendered_const[ def_id. to_def_id( ) ] <- const_data) ;
16191619 }
16201620 }
@@ -1682,14 +1682,6 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
16821682 }
16831683 }
16841684
1685- fn encode_rendered_const_for_body ( & mut self , body_id : hir:: BodyId ) -> String {
1686- let hir = self . tcx . hir ( ) ;
1687- let body = hir. body ( body_id) ;
1688- rustc_hir_pretty:: to_string ( & ( & hir as & dyn intravisit:: Map < ' _ > ) , |s| {
1689- s. print_expr ( & body. value )
1690- } )
1691- }
1692-
16931685 #[ instrument( level = "debug" , skip( self ) ) ]
16941686 fn encode_info_for_macro ( & mut self , def_id : LocalDefId ) {
16951687 let tcx = self . tcx ;
@@ -2291,3 +2283,97 @@ pub fn provide(providers: &mut Providers) {
22912283 ..* providers
22922284 }
22932285}
2286+
2287+ /// Build a textual representation of an unevaluated constant expression.
2288+ ///
2289+ /// If the const expression is too complex, an underscore `_` is returned.
2290+ /// For const arguments, it's `{ _ }` to be precise.
2291+ /// This means that the output is not necessarily valid Rust code.
2292+ ///
2293+ /// Currently, only
2294+ ///
2295+ /// * literals (optionally with a leading `-`)
2296+ /// * unit `()`
2297+ /// * blocks (`{ … }`) around simple expressions and
2298+ /// * paths without arguments
2299+ ///
2300+ /// are considered simple enough. Simple blocks are included since they are
2301+ /// necessary to disambiguate unit from the unit type.
2302+ /// This list might get extended in the future.
2303+ ///
2304+ /// Without this censoring, in a lot of cases the output would get too large
2305+ /// and verbose. Consider `match` expressions, blocks and deeply nested ADTs.
2306+ /// Further, private and `doc(hidden)` fields of structs would get leaked
2307+ /// since HIR datatypes like the `body` parameter do not contain enough
2308+ /// semantic information for this function to be able to hide them –
2309+ /// at least not without significant performance overhead.
2310+ ///
2311+ /// Whenever possible, prefer to evaluate the constant first and try to
2312+ /// use a different method for pretty-printing. Ideally this function
2313+ /// should only ever be used as a fallback.
2314+ pub fn rendered_const < ' tcx > ( tcx : TyCtxt < ' tcx > , body : hir:: BodyId ) -> String {
2315+ let hir = tcx. hir ( ) ;
2316+ let value = & hir. body ( body) . value ;
2317+
2318+ #[ derive( PartialEq , Eq ) ]
2319+ enum Classification {
2320+ Literal ,
2321+ Simple ,
2322+ Complex ,
2323+ }
2324+
2325+ use Classification :: * ;
2326+
2327+ fn classify ( expr : & hir:: Expr < ' _ > ) -> Classification {
2328+ match & expr. kind {
2329+ hir:: ExprKind :: Unary ( hir:: UnOp :: Neg , expr) => {
2330+ if matches ! ( expr. kind, hir:: ExprKind :: Lit ( _) ) { Literal } else { Complex }
2331+ }
2332+ hir:: ExprKind :: Lit ( _) => Literal ,
2333+ hir:: ExprKind :: Tup ( [ ] ) => Simple ,
2334+ hir:: ExprKind :: Block ( hir:: Block { stmts : [ ] , expr : Some ( expr) , .. } , _) => {
2335+ if classify ( expr) == Complex { Complex } else { Simple }
2336+ }
2337+ // Paths with a self-type or arguments are too “complex” following our measure since
2338+ // they may leak private fields of structs (with feature `adt_const_params`).
2339+ // Consider: `<Self as Trait<{ Struct { private: () } }>>::CONSTANT`.
2340+ // Paths without arguments are definitely harmless though.
2341+ hir:: ExprKind :: Path ( hir:: QPath :: Resolved ( _, hir:: Path { segments, .. } ) ) => {
2342+ if segments. iter ( ) . all ( |segment| segment. args . is_none ( ) ) { Simple } else { Complex }
2343+ }
2344+ // FIXME: Claiming that those kinds of QPaths are simple is probably not true if the Ty
2345+ // contains const arguments. Is there a *concise* way to check for this?
2346+ hir:: ExprKind :: Path ( hir:: QPath :: TypeRelative ( ..) ) => Simple ,
2347+ // FIXME: Can they contain const arguments and thus leak private struct fields?
2348+ hir:: ExprKind :: Path ( hir:: QPath :: LangItem ( ..) ) => Simple ,
2349+ _ => Complex ,
2350+ }
2351+ }
2352+
2353+ let classification = classify ( value) ;
2354+
2355+ if classification == Literal
2356+ && !value. span . from_expansion ( )
2357+ && let Ok ( snippet) = tcx. sess . source_map ( ) . span_to_snippet ( value. span ) {
2358+ // For literals, we avoid invoking the pretty-printer and use the source snippet instead to
2359+ // preserve certain stylistic choices the user likely made for the sake legibility like
2360+ //
2361+ // * hexadecimal notation
2362+ // * underscores
2363+ // * character escapes
2364+ //
2365+ // FIXME: This passes through `-/*spacer*/0` verbatim.
2366+ snippet
2367+ } else if classification == Simple {
2368+ // Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and
2369+ // other formatting artifacts.
2370+ id_to_string ( & hir, body. hir_id )
2371+ } else if tcx. def_kind ( hir. body_owner_def_id ( body) . to_def_id ( ) ) == DefKind :: AnonConst {
2372+ // FIXME: Omit the curly braces if the enclosing expression is an array literal
2373+ // with a repeated element (an `ExprKind::Repeat`) as in such case it
2374+ // would not actually need any disambiguation.
2375+ "{ _ }" . to_owned ( )
2376+ } else {
2377+ "_" . to_owned ( )
2378+ }
2379+ }
0 commit comments