From 6269791d3626b9a9e5ea6a11c15e14470c0809a0 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Sat, 27 Apr 2019 21:05:59 +0200 Subject: [PATCH 01/15] Add Ty::Bound variant for use in Chalk integration --- crates/ra_hir/src/ty.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index 12e10c75187..094de62a3e5 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs @@ -121,6 +121,10 @@ pub enum Ty { name: Name, }, + /// A bound type variable. Only used during trait resolution to represent + /// Chalk variables. + Bound(u32), + /// A type variable used during type checking. Not to be confused with a /// type parameter. Infer(InferTy), @@ -260,7 +264,7 @@ impl Ty { t.walk(f); } } - Ty::Param { .. } | Ty::Infer(_) | Ty::Unknown => {} + Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} } f(self); } @@ -270,7 +274,7 @@ impl Ty { Ty::Apply(a_ty) => { a_ty.parameters.walk_mut(f); } - Ty::Param { .. } | Ty::Infer(_) | Ty::Unknown => {} + Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} } f(self); } @@ -472,6 +476,7 @@ impl HirDisplay for Ty { match self { Ty::Apply(a_ty) => a_ty.hir_fmt(f)?, Ty::Param { name, .. } => write!(f, "{}", name)?, + Ty::Bound(idx) => write!(f, "?{}", idx)?, Ty::Unknown => write!(f, "{{unknown}}")?, Ty::Infer(..) => write!(f, "_")?, } From b9c0c2abb79769852119dc9a595e63ee74eeba03 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Sat, 20 Apr 2019 12:34:36 +0200 Subject: [PATCH 02/15] Chalk integration - add proper canonicalization logic - add conversions from/to Chalk IR --- Cargo.lock | 121 ++++++ crates/ra_hir/Cargo.toml | 9 +- crates/ra_hir/src/code_model_api.rs | 6 +- crates/ra_hir/src/db.rs | 26 +- crates/ra_hir/src/generics.rs | 11 +- crates/ra_hir/src/ids.rs | 54 +++ crates/ra_hir/src/resolve.rs | 3 +- crates/ra_hir/src/ty.rs | 49 ++- crates/ra_hir/src/ty/infer.rs | 31 +- crates/ra_hir/src/ty/infer/unify.rs | 81 ++++ crates/ra_hir/src/ty/lower.rs | 30 +- crates/ra_hir/src/ty/method_resolution.rs | 29 +- crates/ra_hir/src/ty/tests.rs | 2 +- crates/ra_hir/src/ty/traits.rs | 497 ++++++++++++++++++---- 14 files changed, 800 insertions(+), 149 deletions(-) create mode 100644 crates/ra_hir/src/ty/infer/unify.rs diff --git a/Cargo.lock b/Cargo.lock index de6e9ec9ab5..0bb62cb88da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -143,6 +143,61 @@ name = "cfg-if" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "chalk-engine" +version = "0.9.0" +source = "git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match#b508031b92c754a677d46236aae1dcd2fa2fd68a" +dependencies = [ + "chalk-macros 0.1.1 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "stacker 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "chalk-ir" +version = "0.1.0" +source = "git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match#b508031b92c754a677d46236aae1dcd2fa2fd68a" +dependencies = [ + "chalk-engine 0.9.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-macros 0.1.1 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "lalrpop-intern 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "chalk-macros" +version = "0.1.1" +source = "git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match#b508031b92c754a677d46236aae1dcd2fa2fd68a" +dependencies = [ + "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "chalk-rust-ir" +version = "0.1.0" +source = "git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match#b508031b92c754a677d46236aae1dcd2fa2fd68a" +dependencies = [ + "chalk-engine 0.9.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-macros 0.1.1 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", +] + +[[package]] +name = "chalk-solve" +version = "0.1.0" +source = "git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match#b508031b92c754a677d46236aae1dcd2fa2fd68a" +dependencies = [ + "chalk-engine 0.9.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-macros 0.1.1 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-rust-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "derive-new 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", + "ena 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", + "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", + "itertools 0.7.11 (registry+https://github.com/rust-lang/crates.io-index)", + "petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "chrono" version = "0.4.6" @@ -306,6 +361,14 @@ name = "either" version = "1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "ena" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "log 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "ena" version = "0.11.0" @@ -362,6 +425,11 @@ dependencies = [ "redox_syscall 0.1.54 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "fixedbitset" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "flexi_logger" version = "0.11.4" @@ -540,6 +608,14 @@ dependencies = [ "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "itertools" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "either 1.5.2 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "itertools" version = "0.8.0" @@ -595,6 +671,11 @@ dependencies = [ "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "lalrpop-intern" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "lazy_static" version = "1.3.0" @@ -789,6 +870,11 @@ name = "opaque-debug" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "ordermap" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "owning_ref" version = "0.4.0" @@ -862,6 +948,15 @@ dependencies = [ "sha-1 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "petgraph" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "fixedbitset 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "ordermap 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "proc-macro2" version = "0.4.28" @@ -979,6 +1074,9 @@ name = "ra_hir" version = "0.1.0" dependencies = [ "arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", + "chalk-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-rust-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-solve 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", "ena 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "flexi_logger 0.11.4 (registry+https://github.com/rust-lang/crates.io-index)", "insta 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1498,6 +1596,17 @@ name = "stable_deref_trait" version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "stacker" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "cc 1.0.35 (registry+https://github.com/rust-lang/crates.io-index)", + "cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "strsim" version = "0.8.0" @@ -1888,6 +1997,11 @@ dependencies = [ "checksum cargo_metadata 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)" = "178d62b240c34223f265a4c1e275e37d62da163d421fc8d7f7e3ee340f803c57" "checksum cc 1.0.35 (registry+https://github.com/rust-lang/crates.io-index)" = "5e5f3fee5eeb60324c2781f1e41286bdee933850fff9b3c672587fed5ec58c83" "checksum cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "11d43355396e872eefb45ce6342e4374ed7bc2b3a502d1b28e36d6e23c05d1f4" +"checksum chalk-engine 0.9.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)" = "" +"checksum chalk-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)" = "" +"checksum chalk-macros 0.1.1 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)" = "" +"checksum chalk-rust-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)" = "" +"checksum chalk-solve 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)" = "" "checksum chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "45912881121cb26fad7c38c17ba7daa18764771836b34fab7d3fbd93ed633878" "checksum ci_info 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e5e881307a989a3a5e20d52a32cc05950e3c2178cccfcc9428271a6cde09f902" "checksum clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" @@ -1907,6 +2021,7 @@ dependencies = [ "checksum drop_bomb 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "69b26e475fd29098530e709294e94e661974c851aed42512793f120fed4e199f" "checksum dtoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6d301140eb411af13d3115f9a562c85cc6b541ade9dfa314132244aaee7489dd" "checksum either 1.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "5527cfe0d098f36e3f8839852688e63c8fff1c90b2b405aef730615f9a7bcf7b" +"checksum ena 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "25b4e5febb25f08c49f1b07dc33a182729a6b21edfb562b5aef95f78e0dbe5bb" "checksum ena 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f56c93cc076508c549d9bb747f79aa9b4eb098be7b8cad8830c3137ef52d1e00" "checksum encode_unicode 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "90b2c9496c001e8cb61827acdefad780795c42264c137744cae6f7d9e3450abd" "checksum error-chain 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "07e791d3be96241c77c43846b665ef1384606da2cd2a48730abe606a12906e02" @@ -1914,6 +2029,7 @@ dependencies = [ "checksum failure_derive 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "ea1063915fd7ef4309e222a5a07cf9c319fb9c7836b1f89b85458672dbb127e1" "checksum fake-simd 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" "checksum filetime 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "2f8c63033fcba1f51ef744505b3cad42510432b904c062afa67ad7ece008429d" +"checksum fixedbitset 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "86d4de0081402f5e88cdac65c8dcdcc73118c1a7a465e2a05f0da05843a8ea33" "checksum flexi_logger 0.11.4 (registry+https://github.com/rust-lang/crates.io-index)" = "73de04baa435682b03677bb28f7b3e9d72b0489a551da5ba413c9b29f7979a19" "checksum fs_extra 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5f2a4a2034423744d2cc7ca2068453168dcdb82c438419e639a26bd87839c674" "checksum fsevent 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)" = "c4bbbf71584aeed076100b5665ac14e3d85eeb31fdbb45fbd41ef9a682b5ec05" @@ -1934,6 +2050,7 @@ dependencies = [ "checksum inotify-sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e74a1aa87c59aeff6ef2cc2fa62d41bc43f54952f55652656b18a02fd5e356c0" "checksum insta 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)" = "03e7d88a87d342ce8bd698516151be43e6eb2e84b683db528696cb4a382f734a" "checksum iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dbe6e417e7d0975db6512b90796e8ce223145ac4e33c377e4a42882a0e88bb08" +"checksum itertools 0.7.11 (registry+https://github.com/rust-lang/crates.io-index)" = "0d47946d458e94a1b7bcabbf6521ea7c037062c81f534615abcad76e84d4970d" "checksum itertools 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5b8467d9c1cebe26feb08c640139247fac215782d35371ade9a2136ed6085358" "checksum itoa 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "1306f3464951f30e30d12373d31c79fbd52d236e5e896fd92f96ec7babbbe60b" "checksum jemalloc-ctl 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4e93b0f37e7d735c6b610176d5b1bde8e1621ff3f6f7ac23cdfa4e7f7d0111b5" @@ -1941,6 +2058,7 @@ dependencies = [ "checksum jemallocator 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "9f0cd42ac65f758063fea55126b0148b1ce0a6354ff78e07a4d6806bc65c4ab3" "checksum join_to_string 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4dc7a5290e8c2606ce2be49f456d50f69173cb96d1541e4f66e34ac8b331a98f" "checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" +"checksum lalrpop-intern 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cc4fd87be4a815fd373e02773983940f0d75fb26fde8c098e9e45f7af03154c0" "checksum lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bc5729f27f159ddd61f4df6228e827e86643d4d3e7c32183cb30a1c08f604a14" "checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" "checksum libc 0.2.51 (registry+https://github.com/rust-lang/crates.io-index)" = "bedcc7a809076656486ffe045abeeac163da1b558e963a31e29fbfbeba916917" @@ -1965,6 +2083,7 @@ dependencies = [ "checksum number_prefix 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "dbf9993e59c894e3c08aa1c2712914e9e6bf1fcbfc6bef283e2183df345a4fee" "checksum numtoa 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b8f8bdf33df195859076e54ab11ee78a1b208382d3a26ec40d142ffc1ecc49ef" "checksum opaque-debug 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "93f5bb2e8e8dec81642920ccff6b61f1eb94fa3020c5a325c9851ff604152409" +"checksum ordermap 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "a86ed3f5f244b372d6b1a00b72ef7f8876d0bc6a78a4c9985c53614041512063" "checksum owning_ref 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "49a4b8ea2179e6a2e27411d3bca09ca6dd630821cf6894c6c7c8467a8ee7ef13" "checksum parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ab41b4aed082705d1056416ae4468b6ea99d52599ecf3169b00088d43113e337" "checksum parking_lot_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9" @@ -1973,6 +2092,7 @@ dependencies = [ "checksum pest_derive 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "833d1ae558dc601e9a60366421196a8d94bc0ac980476d0b67e1d0988d72b2d0" "checksum pest_generator 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "63120576c4efd69615b5537d3d052257328a4ca82876771d6944424ccfd9f646" "checksum pest_meta 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f249ea6de7c7b7aba92b4ff4376a994c6dbd98fd2166c89d5c4947397ecb574d" +"checksum petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)" = "9c3659d1ee90221741f65dd128d9998311b0e40c5d3c23a62445938214abce4f" "checksum proc-macro2 0.4.28 (registry+https://github.com/rust-lang/crates.io-index)" = "ba92c84f814b3f9a44c5cfca7d2ad77fa10710867d2bbb1b3d175ab5f47daa12" "checksum proptest 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)" = "24f5844db2f839e97e3021980975f6ebf8691d9b9b2ca67ed3feb38dc3edb52c" "checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0" @@ -2019,6 +2139,7 @@ dependencies = [ "checksum smallvec 0.6.9 (registry+https://github.com/rust-lang/crates.io-index)" = "c4488ae950c49d403731982257768f48fada354a5203fe81f9bb6f43ca9002be" "checksum smol_str 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "d077b3367211e9c6e2e012fb804c444e0d80ab5a51ae4137739b58e6446dcaef" "checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" +"checksum stacker 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "fb79482f57cf598af52094ec4cc3b3c42499d3ce5bd426f2ac41515b7e57404b" "checksum strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" "checksum superslice 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ab16ced94dbd8a46c82fd81e3ed9a8727dac2977ea869d217bcc4ea1f122e81f" "checksum syn 0.15.32 (registry+https://github.com/rust-lang/crates.io-index)" = "846620ec526c1599c070eff393bfeeeb88a93afa2513fc3b49f1fea84cf7b0ed" diff --git a/crates/ra_hir/Cargo.toml b/crates/ra_hir/Cargo.toml index a2858dad9dd..ae7e7df6237 100644 --- a/crates/ra_hir/Cargo.toml +++ b/crates/ra_hir/Cargo.toml @@ -19,7 +19,14 @@ ra_db = { path = "../ra_db" } mbe = { path = "../ra_mbe", package = "ra_mbe" } tt = { path = "../ra_tt", package = "ra_tt" } test_utils = { path = "../test_utils" } -ra_prof = {path = "../ra_prof" } +ra_prof = { path = "../ra_prof" } + +# chalk-solve = { git = "https://github.com/rust-lang/chalk.git" } +# chalk-rust-ir = { git = "https://github.com/rust-lang/chalk.git" } +# chalk-ir = { git = "https://github.com/rust-lang/chalk.git" } +chalk-solve = { git = "https://github.com/detrumi/chalk.git", branch = "program_clauses_that_could_match" } +chalk-rust-ir = { git = "https://github.com/detrumi/chalk.git", branch = "program_clauses_that_could_match" } +chalk-ir = { git = "https://github.com/detrumi/chalk.git", branch = "program_clauses_that_could_match" } [dev-dependencies] flexi_logger = "0.11.0" diff --git a/crates/ra_hir/src/code_model_api.rs b/crates/ra_hir/src/code_model_api.rs index 8f1ed1086c7..9dcae50a550 100644 --- a/crates/ra_hir/src/code_model_api.rs +++ b/crates/ra_hir/src/code_model_api.rs @@ -9,7 +9,7 @@ use crate::{ type_ref::TypeRef, nameres::{ModuleScope, Namespace, ImportId, CrateModuleId}, expr::{Body, BodySourceMap}, - ty::InferenceResult, + ty::{ TraitRef, InferenceResult}, adt::{EnumVariantId, StructFieldId, VariantDef}, generics::HasGenericParams, docs::{Documentation, Docs, docs_from_ast}, @@ -696,6 +696,10 @@ impl Trait { db.trait_data(self) } + pub fn trait_ref(self, db: &impl HirDatabase) -> TraitRef { + TraitRef::for_trait(db, self) + } + pub(crate) fn resolver(&self, db: &impl DefDatabase) -> Resolver { let r = self.module(db).resolver(db); // add generic params, if present diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index 398e00c42b4..b2c4fccf28f 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs @@ -1,4 +1,4 @@ -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use ra_syntax::{SyntaxNode, TreeArc, SourceFile, SmolStr, ast}; use ra_db::{SourceDatabase, salsa}; @@ -8,16 +8,16 @@ use crate::{ Function, FnSignature, ExprScopes, TypeAlias, Struct, Enum, StructField, Const, ConstSignature, Static, - DefWithBody, + DefWithBody, Trait, + ids, nameres::{Namespace, ImportSourceMap, RawItems, CrateDefMap}, - ty::{InferenceResult, Ty, method_resolution::CrateImplBlocks, TypableDef, CallableDef, FnSig}, + ty::{InferenceResult, Ty, method_resolution::CrateImplBlocks, TypableDef, CallableDef, FnSig, TypeCtor}, adt::{StructData, EnumData}, - impl_block::{ModuleImplBlocks, ImplSourceMap}, + impl_block::{ModuleImplBlocks, ImplSourceMap, ImplBlock}, generics::{GenericParams, GenericDef}, type_ref::TypeRef, - traits::TraitData, Trait, ty::TraitRef, + traits::TraitData, lang_item::{LangItems, LangItemTarget}, - ids }; #[salsa::query_group(DefDatabaseStorage)] @@ -39,6 +39,12 @@ pub trait DefDatabase: SourceDatabase { #[salsa::interned] fn intern_type_alias(&self, loc: ids::ItemLoc) -> ids::TypeAliasId; + // Interned IDs for Chalk integration + #[salsa::interned] + fn intern_type_ctor(&self, type_ctor: TypeCtor) -> ids::TypeCtorId; + #[salsa::interned] + fn intern_impl_block(&self, impl_block: ImplBlock) -> ids::GlobalImplId; + #[salsa::invoke(crate::ids::macro_def_query)] fn macro_def(&self, macro_id: MacroDefId) -> Option>; @@ -144,8 +150,12 @@ pub trait HirDatabase: DefDatabase { #[salsa::invoke(crate::ty::method_resolution::CrateImplBlocks::impls_in_crate_query)] fn impls_in_crate(&self, krate: Crate) -> Arc; - #[salsa::invoke(crate::ty::traits::implements)] - fn implements(&self, trait_ref: TraitRef) -> Option; + #[salsa::invoke(crate::ty::traits::impls_for_trait)] + fn impls_for_trait(&self, krate: Crate, trait_: Trait) -> Arc<[ImplBlock]>; + + #[salsa::invoke(crate::ty::traits::solver)] + #[salsa::volatile] + fn chalk_solver(&self, krate: Crate) -> Arc>; } #[test] diff --git a/crates/ra_hir/src/generics.rs b/crates/ra_hir/src/generics.rs index 1c71e21ea3c..2e52c587111 100644 --- a/crates/ra_hir/src/generics.rs +++ b/crates/ra_hir/src/generics.rs @@ -9,7 +9,7 @@ use ra_syntax::ast::{self, NameOwner, TypeParamsOwner, TypeBoundsOwner}; use crate::{ db::DefDatabase, - Name, AsName, Function, Struct, Enum, Trait, TypeAlias, ImplBlock, Container, path::Path, type_ref::TypeRef + Name, AsName, Function, Struct, Enum, Trait, TypeAlias, ImplBlock, Container, path::Path, type_ref::TypeRef, AdtDef }; /// Data about a generic parameter (to a function, struct, impl, ...). @@ -157,6 +157,15 @@ impl From for GenericDef { } } +impl From for GenericDef { + fn from(adt: crate::adt::AdtDef) -> Self { + match adt { + AdtDef::Struct(s) => s.into(), + AdtDef::Enum(e) => e.into(), + } + } +} + pub trait HasGenericParams { fn generic_params(self, db: &impl DefDatabase) -> Arc; } diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs index 4102951c954..6875b006d6c 100644 --- a/crates/ra_hir/src/ids.rs +++ b/crates/ra_hir/src/ids.rs @@ -323,6 +323,25 @@ impl AstItemDef for TraitId { } } +fn from_chalk(chalk_id: chalk_ir::RawId) -> T { + T::from_intern_id(salsa::InternId::from(chalk_id.index)) +} +fn to_chalk(salsa_id: T) -> chalk_ir::RawId { + chalk_ir::RawId { index: salsa_id.as_intern_id().as_u32() } +} + +impl From for TraitId { + fn from(trait_id: chalk_ir::TraitId) -> Self { + from_chalk(trait_id.0) + } +} + +impl From for chalk_ir::TraitId { + fn from(trait_id: TraitId) -> Self { + chalk_ir::TraitId(to_chalk(trait_id)) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct TypeAliasId(salsa::InternId); impl_intern_key!(TypeAliasId); @@ -354,3 +373,38 @@ impl MacroCallId { ) } } + +/// This exists just for chalk, because chalk doesn't differentiate between +/// enums and structs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct TypeCtorId(salsa::InternId); +impl_intern_key!(TypeCtorId); + +impl From for TypeCtorId { + fn from(struct_id: chalk_ir::StructId) -> Self { + from_chalk(struct_id.0) + } +} + +impl From for chalk_ir::StructId { + fn from(adt_id: TypeCtorId) -> Self { + chalk_ir::StructId(to_chalk(adt_id)) + } +} + +/// This exists just for chalk, because our ImplIds are only unique per module. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct GlobalImplId(salsa::InternId); +impl_intern_key!(GlobalImplId); + +impl From for GlobalImplId { + fn from(impl_id: chalk_ir::ImplId) -> Self { + from_chalk(impl_id.0) + } +} + +impl From for chalk_ir::ImplId { + fn from(impl_id: GlobalImplId) -> Self { + chalk_ir::ImplId(to_chalk(impl_id)) + } +} diff --git a/crates/ra_hir/src/resolve.rs b/crates/ra_hir/src/resolve.rs index bc9170cdc12..707556ef842 100644 --- a/crates/ra_hir/src/resolve.rs +++ b/crates/ra_hir/src/resolve.rs @@ -6,7 +6,7 @@ use ra_syntax::ast; use rustc_hash::FxHashMap; use crate::{ - ModuleDef, + ModuleDef, Trait, code_model_api::Crate, MacroCallId, MacroCallLoc, @@ -18,7 +18,6 @@ use crate::{ expr::{scope::{ExprScopes, ScopeId}, PatId}, impl_block::ImplBlock, path::Path, - Trait, }; #[derive(Debug, Clone, Default)] diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index 094de62a3e5..538148956a8 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs @@ -15,7 +15,7 @@ pub(crate) mod display; use std::sync::Arc; use std::{fmt, mem}; -use crate::{Name, AdtDef, type_ref::Mutability, db::HirDatabase, Trait}; +use crate::{Name, AdtDef, type_ref::Mutability, db::HirDatabase, Trait, GenericParams}; use display::{HirDisplay, HirFormatter}; pub(crate) use lower::{TypableDef, type_for_def, type_for_field, callable_item_sig}; @@ -118,6 +118,7 @@ pub enum Ty { /// surrounding impl, then the current function). idx: u32, /// The name of the parameter, for displaying. + // FIXME get rid of this name: Name, }, @@ -177,6 +178,30 @@ impl Substs { } &self.0[0] } + + /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). + pub fn identity(generic_params: &GenericParams) -> Substs { + Substs( + generic_params + .params_including_parent() + .into_iter() + .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() }) + .collect::>() + .into(), + ) + } + + /// Return Substs that replace each parameter by a bound variable. + pub fn bound_vars(generic_params: &GenericParams) -> Substs { + Substs( + generic_params + .params_including_parent() + .into_iter() + .map(|p| Ty::Bound(p.idx)) + .collect::>() + .into(), + ) + } } impl From> for Substs { @@ -198,6 +223,14 @@ impl TraitRef { pub fn self_ty(&self) -> &Ty { &self.substs.0[0] } + + pub fn subst(mut self, substs: &Substs) -> TraitRef { + self.substs.walk_mut(&mut |ty_mut| { + let ty = mem::replace(ty_mut, Ty::Unknown); + *ty_mut = ty.subst(substs); + }); + self + } } /// A function signature as seen by type inference: Several parameter types and @@ -376,6 +409,20 @@ impl Ty { }) } + /// Substitutes `Ty::Bound` vars (as opposed to type parameters). + pub fn subst_bound_vars(self, substs: &Substs) -> Ty { + self.fold(&mut |ty| match ty { + Ty::Bound(idx) => { + if (idx as usize) < substs.0.len() { + substs.0[idx as usize].clone() + } else { + Ty::Bound(idx) + } + } + ty => ty, + }) + } + /// Returns the type parameters of this type if it has some (i.e. is an ADT /// or function); so if `self` is `Option`, this returns the `u32`. fn substs(&self) -> Option { diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs index c7772a7f6d0..a6d08dbcbf6 100644 --- a/crates/ra_hir/src/ty/infer.rs +++ b/crates/ra_hir/src/ty/infer.rs @@ -44,9 +44,13 @@ use crate::{ }; use super::{ Ty, TypableDef, Substs, primitive, op, ApplicationTy, TypeCtor, CallableDef, TraitRef, - traits::{ Solution, Obligation, Guidance}, + traits::{Solution, Obligation, Guidance}, }; +mod unify; + +pub(super) use unify::Canonical; + /// The entry point of type inference. pub fn infer(db: &impl HirDatabase, def: DefWithBody) -> Arc { db.check_canceled(); @@ -321,30 +325,27 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { fn resolve_obligations_as_possible(&mut self) { let obligations = mem::replace(&mut self.obligations, Vec::new()); for obligation in obligations { - // FIXME resolve types in the obligation first - let (solution, var_mapping) = match &obligation { + let mut canonicalizer = self.canonicalizer(); + let solution = match &obligation { Obligation::Trait(tr) => { - let (tr, var_mapping) = super::traits::canonicalize(tr.clone()); - (self.db.implements(tr), var_mapping) + let canonical = canonicalizer.canonicalize_trait_ref(tr.clone()); + super::traits::implements( + canonicalizer.ctx.db, + canonicalizer.ctx.resolver.krate().unwrap(), + canonical, + ) } }; match solution { Some(Solution::Unique(substs)) => { - for (i, subst) in substs.0.iter().enumerate() { - let uncanonical = var_mapping[i]; - // FIXME the subst may contain type variables, which would need to be mapped back as well - self.unify(&Ty::Infer(InferTy::TypeVar(uncanonical)), subst); - } + canonicalizer.apply_solution(substs.0); } Some(Solution::Ambig(Guidance::Definite(substs))) => { - for (i, subst) in substs.0.iter().enumerate() { - let uncanonical = var_mapping[i]; - // FIXME the subst may contain type variables, which would need to be mapped back as well - self.unify(&Ty::Infer(InferTy::TypeVar(uncanonical)), subst); - } + canonicalizer.apply_solution(substs.0); self.obligations.push(obligation); } Some(_) => { + // FIXME use this when trying to resolve everything at the end self.obligations.push(obligation); } None => { diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs new file mode 100644 index 00000000000..7918b007b6d --- /dev/null +++ b/crates/ra_hir/src/ty/infer/unify.rs @@ -0,0 +1,81 @@ +//! Unification and canonicalization logic. + +use super::{InferenceContext, Ty, TraitRef, InferTy, HirDatabase}; + +impl<'a, D: HirDatabase> InferenceContext<'a, D> { + pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D> + where + 'a: 'b, + { + Canonicalizer { ctx: self, free_vars: Vec::new() } + } +} + +// TODO improve the interface of this + +// TODO move further up? +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(crate) struct Canonical { + pub value: T, + pub num_vars: usize, +} + +pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase> +where + 'a: 'b, +{ + pub ctx: &'b mut InferenceContext<'a, D>, + pub free_vars: Vec, +} + +impl<'a, 'b, D: HirDatabase> Canonicalizer<'a, 'b, D> +where + 'a: 'b, +{ + fn add(&mut self, free_var: InferTy) -> usize { + self.free_vars.iter().position(|&v| v == free_var).unwrap_or_else(|| { + let next_index = self.free_vars.len(); + self.free_vars.push(free_var); + next_index + }) + } + + pub fn canonicalize_ty(&mut self, ty: Ty) -> Canonical { + let value = ty.fold(&mut |ty| match ty { + Ty::Infer(tv) => { + let inner = tv.to_inner(); + // TODO prevent infinite loops? => keep var stack + if let Some(known_ty) = self.ctx.var_unification_table.probe_value(inner).known() { + self.canonicalize_ty(known_ty.clone()).value + } else { + let free_var = InferTy::TypeVar(self.ctx.var_unification_table.find(inner)); + let position = self.add(free_var); + Ty::Bound(position as u32) + } + } + _ => ty, + }); + Canonical { value, num_vars: self.free_vars.len() } + } + + pub fn canonicalize_trait_ref(&mut self, trait_ref: TraitRef) -> Canonical { + let substs = trait_ref + .substs + .0 + .iter() + .map(|ty| self.canonicalize_ty(ty.clone()).value) + .collect::>(); + let value = TraitRef { trait_: trait_ref.trait_, substs: substs.into() }; + Canonical { value, num_vars: self.free_vars.len() } + } + + pub fn apply_solution(&mut self, solution: Canonical>) { + // the solution may contain new variables, which we need to convert to new inference vars + let new_vars = + (0..solution.num_vars).map(|_| self.ctx.new_type_var()).collect::>().into(); + for (i, ty) in solution.value.into_iter().enumerate() { + let var = self.free_vars[i].clone(); + self.ctx.unify(&Ty::Infer(var), &ty.subst_bound_vars(&new_vars)); + } + } +} diff --git a/crates/ra_hir/src/ty/lower.rs b/crates/ra_hir/src/ty/lower.rs index 7fac084ce14..2bbd1706878 100644 --- a/crates/ra_hir/src/ty/lower.rs +++ b/crates/ra_hir/src/ty/lower.rs @@ -238,6 +238,11 @@ impl TraitRef { let segment = path.segments.last().expect("path should have at least one segment"); substs_from_path_segment(db, resolver, segment, &resolved.generic_params(db), true) } + + pub(crate) fn for_trait(db: &impl HirDatabase, trait_: Trait) -> TraitRef { + let substs = Substs::identity(&trait_.generic_params(db)); + TraitRef { trait_, substs } + } } /// Build the declared type of an item. This depends on the namespace; e.g. for @@ -299,7 +304,7 @@ fn fn_sig_for_fn(db: &impl HirDatabase, def: Function) -> FnSig { /// function body. fn type_for_fn(db: &impl HirDatabase, def: Function) -> Ty { let generics = def.generic_params(db); - let substs = make_substs(&generics); + let substs = Substs::identity(&generics); Ty::apply(TypeCtor::FnDef(def.into()), substs) } @@ -341,7 +346,7 @@ fn type_for_struct_constructor(db: &impl HirDatabase, def: Struct) -> Ty { return type_for_struct(db, def); // Unit struct } let generics = def.generic_params(db); - let substs = make_substs(&generics); + let substs = Substs::identity(&generics); Ty::apply(TypeCtor::FnDef(def.into()), substs) } @@ -357,7 +362,7 @@ fn fn_sig_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariant) .map(|(_, field)| Ty::from_hir(db, &resolver, &field.type_ref)) .collect::>(); let generics = def.parent_enum(db).generic_params(db); - let substs = make_substs(&generics); + let substs = Substs::identity(&generics); let ret = type_for_enum(db, def.parent_enum(db)).subst(&substs); FnSig::from_params_and_return(params, ret) } @@ -369,36 +374,25 @@ fn type_for_enum_variant_constructor(db: &impl HirDatabase, def: EnumVariant) -> return type_for_enum(db, def.parent_enum(db)); // Unit variant } let generics = def.parent_enum(db).generic_params(db); - let substs = make_substs(&generics); + let substs = Substs::identity(&generics); Ty::apply(TypeCtor::FnDef(def.into()), substs) } -fn make_substs(generics: &GenericParams) -> Substs { - Substs( - generics - .params_including_parent() - .into_iter() - .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() }) - .collect::>() - .into(), - ) -} - fn type_for_struct(db: &impl HirDatabase, s: Struct) -> Ty { let generics = s.generic_params(db); - Ty::apply(TypeCtor::Adt(s.into()), make_substs(&generics)) + Ty::apply(TypeCtor::Adt(s.into()), Substs::identity(&generics)) } fn type_for_enum(db: &impl HirDatabase, s: Enum) -> Ty { let generics = s.generic_params(db); - Ty::apply(TypeCtor::Adt(s.into()), make_substs(&generics)) + Ty::apply(TypeCtor::Adt(s.into()), Substs::identity(&generics)) } fn type_for_type_alias(db: &impl HirDatabase, t: TypeAlias) -> Ty { let generics = t.generic_params(db); let resolver = t.resolver(db); let type_ref = t.type_ref(db); - let substs = make_substs(&generics); + let substs = Substs::identity(&generics); let inner = Ty::from_hir(db, &resolver, &type_ref); inner.subst(&substs) } diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir/src/ty/method_resolution.rs index ea6e0dc0f7a..ea7da0b6293 100644 --- a/crates/ra_hir/src/ty/method_resolution.rs +++ b/crates/ra_hir/src/ty/method_resolution.rs @@ -16,7 +16,7 @@ use crate::{ generics::HasGenericParams, ty::primitive::{UncertainIntTy, UncertainFloatTy} }; -use super::{TraitRef, Substs}; +use super::{TraitRef, infer::Canonical, Substs}; /// This is used as a key for indexing impls. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] @@ -183,6 +183,7 @@ impl Ty { name: Option<&Name>, mut callback: impl FnMut(&Ty, Function) -> Option, ) -> Option { + let krate = resolver.krate()?; 'traits: for t in resolver.traits_in_scope() { let data = t.trait_data(db); // we'll be lazy about checking whether the type implements the @@ -195,12 +196,19 @@ impl Ty { let sig = m.signature(db); if name.map_or(true, |name| sig.name() == name) && sig.has_self_param() { if !known_implemented { + // TODO the self type may contain type + // variables, so we need to do proper + // canonicalization here let trait_ref = TraitRef { trait_: t, substs: fresh_substs_for_trait(db, t, self.clone()), }; - let (trait_ref, _) = super::traits::canonicalize(trait_ref); - if db.implements(trait_ref).is_none() { + let canonical = Canonical { + num_vars: trait_ref.substs.len(), + value: trait_ref, + }; + // FIXME cache this implements check (without solution) in a query? + if super::traits::implements(db, krate, canonical).is_none() { continue 'traits; } } @@ -271,15 +279,18 @@ impl Ty { } /// This creates Substs for a trait with the given Self type and type variables -/// for all other parameters. This is kind of a hack since these aren't 'real' -/// type variables; the resulting trait reference is just used for the -/// preliminary method candidate check. +/// for all other parameters, to query Chalk with it. fn fresh_substs_for_trait(db: &impl HirDatabase, tr: Trait, self_ty: Ty) -> Substs { let mut substs = Vec::new(); let generics = tr.generic_params(db); substs.push(self_ty); - substs.extend(generics.params_including_parent().into_iter().skip(1).enumerate().map( - |(i, _p)| Ty::Infer(super::infer::InferTy::TypeVar(super::infer::TypeVarId(i as u32))), - )); + substs.extend( + generics + .params_including_parent() + .into_iter() + .skip(1) + .enumerate() + .map(|(i, _p)| Ty::Bound(i as u32)), + ); substs.into() } diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs index c76a5012f07..0aecde37c4d 100644 --- a/crates/ra_hir/src/ty/tests.rs +++ b/crates/ra_hir/src/ty/tests.rs @@ -2140,7 +2140,7 @@ fn test() { [102; 127) '{ ...d(); }': () [108; 109) 'S': S(T) -> S [108; 115) 'S(1u32)': S -[108; 124) 'S(1u32...thod()': {unknown} +[108; 124) 'S(1u32...thod()': u32 [110; 114) '1u32': u32"### ); } diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index 06f48389970..367322ed293 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs @@ -1,47 +1,329 @@ -//! Stuff that will probably mostly replaced by Chalk. -use std::collections::HashMap; +//! Chalk integration. +use std::sync::{Arc, Mutex}; -use crate::{db::HirDatabase, generics::HasGenericParams}; -use super::{TraitRef, Substs, infer::{TypeVarId, InferTy}, Ty}; +use chalk_ir::{TypeId, TraitId, StructId, ImplId, TypeKindId, ProjectionTy, Parameter, Identifier, cast::Cast}; +use chalk_rust_ir::{AssociatedTyDatum, TraitDatum, StructDatum, ImplDatum}; -// Copied (and simplified) from Chalk +use crate::{Crate, Trait, db::HirDatabase, HasGenericParams, ImplBlock}; +use super::{TraitRef, Ty, ApplicationTy, TypeCtor, Substs, infer::Canonical}; -#[derive(Clone, Debug, PartialEq, Eq)] -/// A (possible) solution for a proposed goal. Usually packaged in a `Result`, -/// where `Err` represents definite *failure* to prove a goal. -pub enum Solution { - /// The goal indeed holds, and there is a unique value for all existential - /// variables. - Unique(Substs), - - /// The goal may be provable in multiple ways, but regardless we may have some guidance - /// for type inference. - Ambig(Guidance), +#[derive(Debug, Copy, Clone)] +struct ChalkContext<'a, DB> { + db: &'a DB, + krate: Crate, } -#[derive(Clone, Debug, PartialEq, Eq)] -/// When a goal holds ambiguously (e.g., because there are multiple possible -/// solutions), we issue a set of *guidance* back to type inference. -pub enum Guidance { - /// The existential variables *must* have the given values if the goal is - /// ever to hold, but that alone isn't enough to guarantee the goal will - /// actually hold. - Definite(Substs), +pub(crate) trait ToChalk { + type Chalk; + fn to_chalk(self, db: &impl HirDatabase) -> Self::Chalk; + fn from_chalk(db: &impl HirDatabase, chalk: Self::Chalk) -> Self; +} - /// There are multiple plausible values for the existentials, but the ones - /// here are suggested as the preferred choice heuristically. These should - /// be used for inference fallback only. - Suggested(Substs), +pub(crate) fn from_chalk(db: &impl HirDatabase, chalk: ChalkT) -> T +where + T: ToChalk, +{ + T::from_chalk(db, chalk) +} - /// There's no useful information to feed back to type inference - Unknown, +impl ToChalk for Ty { + type Chalk = chalk_ir::Ty; + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty { + match self { + Ty::Apply(apply_ty) => chalk_ir::Ty::Apply(apply_ty.to_chalk(db)), + Ty::Param { idx, .. } => { + chalk_ir::PlaceholderIndex { ui: chalk_ir::UniverseIndex::ROOT, idx: idx as usize } + .to_ty() + } + Ty::Bound(idx) => chalk_ir::Ty::BoundVar(idx as usize), + Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), + Ty::Unknown => unimplemented!(), // TODO turn into placeholder? + } + } + fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty) -> Self { + match chalk { + chalk_ir::Ty::Apply(apply_ty) => { + match apply_ty.name { + // FIXME handle TypeKindId::Trait/Type here + chalk_ir::TypeName::TypeKindId(_) => Ty::Apply(from_chalk(db, apply_ty)), + chalk_ir::TypeName::AssociatedType(_) => unimplemented!(), + chalk_ir::TypeName::Placeholder(idx) => { + assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT); + Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() } + } + } + } + chalk_ir::Ty::Projection(_) => unimplemented!(), + chalk_ir::Ty::UnselectedProjection(_) => unimplemented!(), + chalk_ir::Ty::ForAll(_) => unimplemented!(), + chalk_ir::Ty::BoundVar(idx) => Ty::Bound(idx as u32), + chalk_ir::Ty::InferenceVar(_iv) => panic!("unexpected chalk infer ty"), + } + } +} + +impl ToChalk for ApplicationTy { + type Chalk = chalk_ir::ApplicationTy; + + fn to_chalk(self: ApplicationTy, db: &impl HirDatabase) -> chalk_ir::ApplicationTy { + let struct_id = self.ctor.to_chalk(db); + let name = chalk_ir::TypeName::TypeKindId(struct_id.into()); + let parameters = self.parameters.to_chalk(db); + chalk_ir::ApplicationTy { name, parameters } + } + + fn from_chalk(db: &impl HirDatabase, apply_ty: chalk_ir::ApplicationTy) -> ApplicationTy { + let ctor = match apply_ty.name { + chalk_ir::TypeName::TypeKindId(chalk_ir::TypeKindId::StructId(struct_id)) => { + from_chalk(db, struct_id) + } + chalk_ir::TypeName::TypeKindId(_) => unimplemented!(), + chalk_ir::TypeName::Placeholder(_) => unimplemented!(), + chalk_ir::TypeName::AssociatedType(_) => unimplemented!(), + }; + let parameters = from_chalk(db, apply_ty.parameters); + ApplicationTy { ctor, parameters } + } +} + +impl ToChalk for Substs { + type Chalk = Vec; + + fn to_chalk(self, db: &impl HirDatabase) -> Vec { + self.iter().map(|ty| ty.clone().to_chalk(db).cast()).collect() + } + + fn from_chalk(db: &impl HirDatabase, parameters: Vec) -> Substs { + parameters + .into_iter() + .map(|p| match p { + chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty), + chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(), + }) + .collect::>() + .into() + } +} + +impl ToChalk for TraitRef { + type Chalk = chalk_ir::TraitRef; + + fn to_chalk(self: TraitRef, db: &impl HirDatabase) -> chalk_ir::TraitRef { + let trait_id = self.trait_.to_chalk(db); + let parameters = self.substs.to_chalk(db); + chalk_ir::TraitRef { trait_id, parameters } + } + + fn from_chalk(db: &impl HirDatabase, trait_ref: chalk_ir::TraitRef) -> Self { + let trait_ = from_chalk(db, trait_ref.trait_id); + let substs = from_chalk(db, trait_ref.parameters); + TraitRef { trait_, substs } + } +} + +impl ToChalk for Trait { + type Chalk = TraitId; + + fn to_chalk(self, _db: &impl HirDatabase) -> TraitId { + self.id.into() + } + + fn from_chalk(_db: &impl HirDatabase, trait_id: TraitId) -> Trait { + Trait { id: trait_id.into() } + } +} + +impl ToChalk for TypeCtor { + type Chalk = chalk_ir::StructId; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::StructId { + db.intern_type_ctor(self).into() + } + + fn from_chalk(db: &impl HirDatabase, struct_id: chalk_ir::StructId) -> TypeCtor { + db.lookup_intern_type_ctor(struct_id.into()) + } +} + +impl ToChalk for ImplBlock { + type Chalk = chalk_ir::ImplId; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ImplId { + db.intern_impl_block(self).into() + } + + fn from_chalk(db: &impl HirDatabase, impl_id: chalk_ir::ImplId) -> ImplBlock { + db.lookup_intern_impl_block(impl_id.into()) + } +} + +fn make_binders(value: T, num_vars: usize) -> chalk_ir::Binders { + chalk_ir::Binders { + value, + binders: std::iter::repeat(chalk_ir::ParameterKind::Ty(())).take(num_vars).collect(), + } +} + +impl<'a, DB> chalk_solve::RustIrDatabase for ChalkContext<'a, DB> +where + DB: HirDatabase, +{ + fn associated_ty_data(&self, _ty: TypeId) -> Arc { + unimplemented!() + } + fn trait_datum(&self, trait_id: TraitId) -> Arc { + eprintln!("trait_datum {:?}", trait_id); + let trait_: Trait = from_chalk(self.db, trait_id); + let generic_params = trait_.generic_params(self.db); + let bound_vars = Substs::bound_vars(&generic_params); + let trait_ref = trait_.trait_ref(self.db).subst(&bound_vars).to_chalk(self.db); + let flags = chalk_rust_ir::TraitFlags { + // FIXME set these flags correctly + auto: false, + marker: false, + upstream: trait_.module(self.db).krate(self.db) != Some(self.krate), + fundamental: false, + }; + let where_clauses = Vec::new(); // FIXME add where clauses + let trait_datum_bound = chalk_rust_ir::TraitDatumBound { trait_ref, where_clauses, flags }; + let trait_datum = TraitDatum { binders: make_binders(trait_datum_bound, bound_vars.len()) }; + Arc::new(trait_datum) + } + fn struct_datum(&self, struct_id: StructId) -> Arc { + eprintln!("struct_datum {:?}", struct_id); + let type_ctor = from_chalk(self.db, struct_id); + // TODO might be nicer if we can create a fake GenericParams for the TypeCtor + let (num_params, upstream) = match type_ctor { + TypeCtor::Bool + | TypeCtor::Char + | TypeCtor::Int(_) + | TypeCtor::Float(_) + | TypeCtor::Never + | TypeCtor::Str => (0, true), + TypeCtor::Slice | TypeCtor::Array | TypeCtor::RawPtr(_) | TypeCtor::Ref(_) => (1, true), + TypeCtor::FnPtr | TypeCtor::Tuple => unimplemented!(), // FIXME tuples and FnPtr are currently variadic... we need to make the parameter number explicit + TypeCtor::FnDef(_) => unimplemented!(), + TypeCtor::Adt(adt) => { + let generic_params = adt.generic_params(self.db); + ( + generic_params.count_params_including_parent(), + adt.krate(self.db) != Some(self.krate), + ) + } + }; + let flags = chalk_rust_ir::StructFlags { + upstream, + // FIXME set fundamental flag correctly + fundamental: false, + }; + let where_clauses = Vec::new(); // FIXME add where clauses + let ty = ApplicationTy { + ctor: type_ctor, + parameters: (0..num_params).map(|i| Ty::Bound(i as u32)).collect::>().into(), + }; + let struct_datum_bound = chalk_rust_ir::StructDatumBound { + self_ty: ty.to_chalk(self.db), + fields: Vec::new(), // FIXME add fields (only relevant for auto traits) + where_clauses, + flags, + }; + let struct_datum = StructDatum { binders: make_binders(struct_datum_bound, num_params) }; + Arc::new(struct_datum) + } + fn impl_datum(&self, impl_id: ImplId) -> Arc { + eprintln!("impl_datum {:?}", impl_id); + let impl_block: ImplBlock = from_chalk(self.db, impl_id); + let generic_params = impl_block.generic_params(self.db); + let bound_vars = Substs::bound_vars(&generic_params); + let trait_ref = impl_block + .target_trait_ref(self.db) + .expect("FIXME handle unresolved impl block trait ref") + .subst(&bound_vars); + let impl_type = if impl_block.module().krate(self.db) == Some(self.krate) { + chalk_rust_ir::ImplType::Local + } else { + chalk_rust_ir::ImplType::External + }; + let impl_datum_bound = chalk_rust_ir::ImplDatumBound { + // FIXME handle negative impls (impl !Sync for Foo) + trait_ref: chalk_rust_ir::PolarizedTraitRef::Positive(trait_ref.to_chalk(self.db)), + where_clauses: Vec::new(), // FIXME add where clauses + associated_ty_values: Vec::new(), // FIXME add associated type values + impl_type, + }; + let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, bound_vars.len()) }; + Arc::new(impl_datum) + } + fn impls_for_trait(&self, trait_id: TraitId) -> Vec { + eprintln!("impls_for_trait {:?}", trait_id); + let trait_ = from_chalk(self.db, trait_id); + self.db + .impls_for_trait(self.krate, trait_) + .iter() + // FIXME temporary hack -- as long as we're not lowering where clauses + // correctly, ignore impls with them completely so as to not treat + // impl Trait for T where T: ... as a blanket impl on all types + .filter(|impl_block| impl_block.generic_params(self.db).where_predicates.is_empty()) + .map(|impl_block| impl_block.to_chalk(self.db)) + .collect() + } + fn impl_provided_for(&self, auto_trait_id: TraitId, struct_id: StructId) -> bool { + eprintln!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id); + false // FIXME + } + fn type_name(&self, _id: TypeKindId) -> Identifier { + unimplemented!() + } + fn split_projection<'p>( + &self, + projection: &'p ProjectionTy, + ) -> (Arc, &'p [Parameter], &'p [Parameter]) { + eprintln!("split_projection {:?}", projection); + unimplemented!() + } +} + +pub(crate) fn solver(_db: &impl HirDatabase, _krate: Crate) -> Arc> { + // krate parameter is just so we cache a unique solver per crate + let solver_choice = chalk_solve::SolverChoice::SLG { max_size: 10 }; + Arc::new(Mutex::new(solver_choice.into_solver())) +} + +/// Collects impls for the given trait in the whole dependency tree of `krate`. +pub(crate) fn impls_for_trait( + db: &impl HirDatabase, + krate: Crate, + trait_: Trait, +) -> Arc<[ImplBlock]> { + let mut impls = Vec::new(); + // We call the query recursively here. On the one hand, this means we can + // reuse results from queries for different crates; on the other hand, this + // will only ever get called for a few crates near the root of the tree (the + // ones the user is editing), so this may actually be a waste of memory. I'm + // doing it like this mainly for simplicity for now. + for dep in krate.dependencies(db) { + impls.extend(db.impls_for_trait(dep.krate, trait_).iter()); + } + let crate_impl_blocks = db.impls_in_crate(krate); + impls.extend(crate_impl_blocks.lookup_impl_blocks_for_trait(&trait_)); + impls.into() +} + +fn solve( + db: &impl HirDatabase, + krate: Crate, + goal: &chalk_ir::UCanonical>, +) -> Option { + let context = ChalkContext { db, krate }; + let solver = db.chalk_solver(krate); + let solution = solver.lock().unwrap().solve(&context, goal); + eprintln!("solve({:?}) => {:?}", goal, solution); + solution } /// Something that needs to be proven (by Chalk) during type checking, e.g. that /// a certain type implements a certain trait. Proving the Obligation might /// result in additional information about inference variables. -/// -/// This might be handled by Chalk when we integrate it? #[derive(Clone, Debug, PartialEq, Eq)] pub enum Obligation { /// Prove that a certain type implements a trait (the type is the `Self` type @@ -49,67 +331,98 @@ pub enum Obligation { Trait(TraitRef), } -/// Rudimentary check whether an impl exists for a given type and trait; this -/// will actually be done by chalk. -pub(crate) fn implements(db: &impl HirDatabase, trait_ref: TraitRef) -> Option { - // FIXME use all trait impls in the whole crate graph - let krate = trait_ref.trait_.module(db).krate(db); - let krate = match krate { - Some(krate) => krate, - None => return None, +/// Check using Chalk whether trait is implemented for given parameters including `Self` type. +pub(crate) fn implements( + db: &impl HirDatabase, + krate: Crate, + trait_ref: Canonical, +) -> Option { + let goal: chalk_ir::Goal = trait_ref.value.to_chalk(db).cast(); + eprintln!("goal: {:?}", goal); + let env = chalk_ir::Environment::new(); + let in_env = chalk_ir::InEnvironment::new(&env, goal); + let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT); + let canonical = + chalk_ir::Canonical { value: in_env, binders: vec![parameter; trait_ref.num_vars] }; + // We currently don't deal with universes (I think / hope they're not yet + // relevant for our use cases?) + let u_canonical = chalk_ir::UCanonical { canonical, universes: 1 }; + let solution = solve(db, krate, &u_canonical); + solution_from_chalk(db, solution) +} + +fn solution_from_chalk( + db: &impl HirDatabase, + solution: Option, +) -> Option { + let convert_subst = |subst: chalk_ir::Canonical| { + let value = subst + .value + .parameters + .into_iter() + .map(|p| { + let ty = match p { + chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty), + chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(), + }; + ty + }) + .collect(); + let result = Canonical { value, num_vars: subst.binders.len() }; + SolutionVariables(result) }; - let crate_impl_blocks = db.impls_in_crate(krate); - let mut impl_blocks = crate_impl_blocks - .lookup_impl_blocks_for_trait(&trait_ref.trait_) - // we don't handle where clauses at all, waiting for Chalk for that - .filter(|impl_block| impl_block.generic_params(db).where_predicates.is_empty()); - impl_blocks - .find_map(|impl_block| unify_trait_refs(&trait_ref, &impl_block.target_trait_ref(db)?)) -} - -pub(super) fn canonicalize(trait_ref: TraitRef) -> (TraitRef, Vec) { - let mut canonical = HashMap::new(); // mapping uncanonical -> canonical - let mut uncanonical = Vec::new(); // mapping canonical -> uncanonical (which is dense) - let mut substs = trait_ref.substs.0.to_vec(); - for ty in &mut substs { - ty.walk_mut(&mut |ty| match ty { - Ty::Infer(InferTy::TypeVar(tv)) => { - let tv: &mut TypeVarId = tv; - *tv = *canonical.entry(*tv).or_insert_with(|| { - let i = uncanonical.len(); - uncanonical.push(*tv); - TypeVarId(i as u32) - }); - } - _ => {} - }); - } - (TraitRef { substs: substs.into(), ..trait_ref }, uncanonical) -} - -fn unify_trait_refs(tr1: &TraitRef, tr2: &TraitRef) -> Option { - if tr1.trait_ != tr2.trait_ { - return None; - } - let mut solution_substs = Vec::new(); - for (t1, t2) in tr1.substs.0.iter().zip(tr2.substs.0.iter()) { - // this is very bad / hacky 'unification' logic, just enough to make the simple tests pass - match (t1, t2) { - (_, Ty::Infer(InferTy::TypeVar(_))) | (_, Ty::Unknown) | (_, Ty::Param { .. }) => { - // type variable (or similar) in the impl, we just assume it works - } - (Ty::Infer(InferTy::TypeVar(v1)), _) => { - // type variable in the query and fixed type in the impl, record its value - solution_substs.resize_with(v1.0 as usize + 1, || Ty::Unknown); - solution_substs[v1.0 as usize] = t2.clone(); - } - _ => { - // check that they're equal (actually we'd have to recurse etc.) - if t1 != t2 { - return None; - } - } + match solution { + Some(chalk_solve::Solution::Unique(constr_subst)) => { + let subst = chalk_ir::Canonical { + value: constr_subst.value.subst, + binders: constr_subst.binders, + }; + Some(Solution::Unique(convert_subst(subst))) } + Some(chalk_solve::Solution::Ambig(chalk_solve::Guidance::Definite(subst))) => { + Some(Solution::Ambig(Guidance::Definite(convert_subst(subst)))) + } + Some(chalk_solve::Solution::Ambig(chalk_solve::Guidance::Suggested(subst))) => { + Some(Solution::Ambig(Guidance::Suggested(convert_subst(subst)))) + } + Some(chalk_solve::Solution::Ambig(chalk_solve::Guidance::Unknown)) => { + Some(Solution::Ambig(Guidance::Unknown)) + } + None => None, } - Some(Solution::Unique(solution_substs.into())) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct SolutionVariables(pub Canonical>); + +#[derive(Clone, Debug, PartialEq, Eq)] +/// A (possible) solution for a proposed goal. +pub(crate) enum Solution { + /// The goal indeed holds, and there is a unique value for all existential + /// variables. + Unique(SolutionVariables), + + /// The goal may be provable in multiple ways, but regardless we may have some guidance + /// for type inference. In this case, we don't return any lifetime + /// constraints, since we have not "committed" to any particular solution + /// yet. + Ambig(Guidance), +} + +#[derive(Clone, Debug, PartialEq, Eq)] +/// When a goal holds ambiguously (e.g., because there are multiple possible +/// solutions), we issue a set of *guidance* back to type inference. +pub(crate) enum Guidance { + /// The existential variables *must* have the given values if the goal is + /// ever to hold, but that alone isn't enough to guarantee the goal will + /// actually hold. + Definite(SolutionVariables), + + /// There are multiple plausible values for the existentials, but the ones + /// here are suggested as the preferred choice heuristically. These should + /// be used for inference fallback only. + Suggested(SolutionVariables), + + /// There's no useful information to feed back to type inference + Unknown, } From 6c3ee834d6452c5caa244c3c58504992de38baa4 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Wed, 1 May 2019 16:37:52 +0200 Subject: [PATCH 03/15] Simplify solution_from_chalk --- crates/ra_hir/src/ty/traits.rs | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index 367322ed293..e1193c402a3 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs @@ -348,13 +348,13 @@ pub(crate) fn implements( // relevant for our use cases?) let u_canonical = chalk_ir::UCanonical { canonical, universes: 1 }; let solution = solve(db, krate, &u_canonical); - solution_from_chalk(db, solution) + solution.map(|solution| solution_from_chalk(db, solution)) } fn solution_from_chalk( db: &impl HirDatabase, - solution: Option, -) -> Option { + solution: chalk_solve::Solution, +) -> Solution { let convert_subst = |subst: chalk_ir::Canonical| { let value = subst .value @@ -372,23 +372,22 @@ fn solution_from_chalk( SolutionVariables(result) }; match solution { - Some(chalk_solve::Solution::Unique(constr_subst)) => { + chalk_solve::Solution::Unique(constr_subst) => { let subst = chalk_ir::Canonical { value: constr_subst.value.subst, binders: constr_subst.binders, }; - Some(Solution::Unique(convert_subst(subst))) + Solution::Unique(convert_subst(subst)) } - Some(chalk_solve::Solution::Ambig(chalk_solve::Guidance::Definite(subst))) => { - Some(Solution::Ambig(Guidance::Definite(convert_subst(subst)))) + chalk_solve::Solution::Ambig(chalk_solve::Guidance::Definite(subst)) => { + Solution::Ambig(Guidance::Definite(convert_subst(subst))) } - Some(chalk_solve::Solution::Ambig(chalk_solve::Guidance::Suggested(subst))) => { - Some(Solution::Ambig(Guidance::Suggested(convert_subst(subst)))) + chalk_solve::Solution::Ambig(chalk_solve::Guidance::Suggested(subst)) => { + Solution::Ambig(Guidance::Suggested(convert_subst(subst))) } - Some(chalk_solve::Solution::Ambig(chalk_solve::Guidance::Unknown)) => { - Some(Solution::Ambig(Guidance::Unknown)) + chalk_solve::Solution::Ambig(chalk_solve::Guidance::Unknown) => { + Solution::Ambig(Guidance::Unknown) } - None => None, } } From 99492278ac8c8a9caf3981b4406dcac6724a6a93 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Wed, 1 May 2019 16:48:05 +0200 Subject: [PATCH 04/15] Implement Deref for Substs --- crates/ra_hir/src/ty.rs | 35 +++++++++++++++-------------- crates/ra_hir/src/ty/infer/unify.rs | 1 - 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index 538148956a8..e7c39487d52 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs @@ -13,6 +13,7 @@ mod infer; pub(crate) mod display; use std::sync::Arc; +use std::ops::Deref; use std::{fmt, mem}; use crate::{Name, AdtDef, type_ref::Mutability, db::HirDatabase, Trait, GenericParams}; @@ -155,14 +156,6 @@ impl Substs { Substs(self.0.iter().cloned().take(n).collect::>().into()) } - pub fn iter(&self) -> impl Iterator { - self.0.iter() - } - - pub fn len(&self) -> usize { - self.0.len() - } - pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { // Without an Arc::make_mut_slice, we can't avoid the clone here: let mut v: Vec<_> = self.0.iter().cloned().collect(); @@ -210,6 +203,14 @@ impl From> for Substs { } } +impl Deref for Substs { + type Target = [Ty]; + + fn deref(&self) -> &[Ty] { + &self.0 + } +} + /// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait. /// Name to be bikeshedded: TraitBound? TraitImplements? #[derive(Clone, PartialEq, Eq, Debug, Hash)] @@ -221,7 +222,7 @@ pub struct TraitRef { impl TraitRef { pub fn self_ty(&self) -> &Ty { - &self.substs.0[0] + &self.substs[0] } pub fn subst(mut self, substs: &Substs) -> TraitRef { @@ -399,8 +400,8 @@ impl Ty { pub fn subst(self, substs: &Substs) -> Ty { self.fold(&mut |ty| match ty { Ty::Param { idx, name } => { - if (idx as usize) < substs.0.len() { - substs.0[idx as usize].clone() + if (idx as usize) < substs.len() { + substs[idx as usize].clone() } else { Ty::Param { idx, name } } @@ -413,8 +414,8 @@ impl Ty { pub fn subst_bound_vars(self, substs: &Substs) -> Ty { self.fold(&mut |ty| match ty { Ty::Bound(idx) => { - if (idx as usize) < substs.0.len() { - substs.0[idx as usize].clone() + if (idx as usize) < substs.len() { + substs[idx as usize].clone() } else { Ty::Bound(idx) } @@ -466,8 +467,8 @@ impl HirDisplay for ApplicationTy { TypeCtor::Never => write!(f, "!")?, TypeCtor::Tuple => { let ts = &self.parameters; - if ts.0.len() == 1 { - write!(f, "({},)", ts.0[0].display(f.db))?; + if ts.len() == 1 { + write!(f, "({},)", ts[0].display(f.db))?; } else { write!(f, "(")?; f.write_joined(&*ts.0, ", ")?; @@ -491,7 +492,7 @@ impl HirDisplay for ApplicationTy { CallableDef::Function(_) => write!(f, "fn {}", name)?, CallableDef::Struct(_) | CallableDef::EnumVariant(_) => write!(f, "{}", name)?, } - if self.parameters.0.len() > 0 { + if self.parameters.len() > 0 { write!(f, "<")?; f.write_joined(&*self.parameters.0, ", ")?; write!(f, ">")?; @@ -507,7 +508,7 @@ impl HirDisplay for ApplicationTy { } .unwrap_or_else(Name::missing); write!(f, "{}", name)?; - if self.parameters.0.len() > 0 { + if self.parameters.len() > 0 { write!(f, "<")?; f.write_joined(&*self.parameters.0, ", ")?; write!(f, ">")?; diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs index 7918b007b6d..5edb95c315d 100644 --- a/crates/ra_hir/src/ty/infer/unify.rs +++ b/crates/ra_hir/src/ty/infer/unify.rs @@ -61,7 +61,6 @@ where pub fn canonicalize_trait_ref(&mut self, trait_ref: TraitRef) -> Canonical { let substs = trait_ref .substs - .0 .iter() .map(|ty| self.canonicalize_ty(ty.clone()).value) .collect::>(); From c8a643f090ed88289c7bc17b48078e39b932c8a4 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Wed, 1 May 2019 17:06:11 +0200 Subject: [PATCH 05/15] Move Chalk conversion code to its own module --- crates/ra_hir/src/ids.rs | 50 +--- crates/ra_hir/src/ty/traits.rs | 283 +---------------------- crates/ra_hir/src/ty/traits/chalk.rs | 327 +++++++++++++++++++++++++++ 3 files changed, 339 insertions(+), 321 deletions(-) create mode 100644 crates/ra_hir/src/ty/traits/chalk.rs diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs index 6875b006d6c..ff4a81e59bf 100644 --- a/crates/ra_hir/src/ids.rs +++ b/crates/ra_hir/src/ids.rs @@ -323,25 +323,6 @@ impl AstItemDef for TraitId { } } -fn from_chalk(chalk_id: chalk_ir::RawId) -> T { - T::from_intern_id(salsa::InternId::from(chalk_id.index)) -} -fn to_chalk(salsa_id: T) -> chalk_ir::RawId { - chalk_ir::RawId { index: salsa_id.as_intern_id().as_u32() } -} - -impl From for TraitId { - fn from(trait_id: chalk_ir::TraitId) -> Self { - from_chalk(trait_id.0) - } -} - -impl From for chalk_ir::TraitId { - fn from(trait_id: TraitId) -> Self { - chalk_ir::TraitId(to_chalk(trait_id)) - } -} - #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct TypeAliasId(salsa::InternId); impl_intern_key!(TypeAliasId); @@ -374,37 +355,14 @@ impl MacroCallId { } } -/// This exists just for chalk, because chalk doesn't differentiate between -/// enums and structs. +/// This exists just for Chalk, because Chalk just has a single `StructId` where +/// we have different kinds of ADTs, primitive types and special type +/// constructors like tuples and function pointers. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct TypeCtorId(salsa::InternId); impl_intern_key!(TypeCtorId); -impl From for TypeCtorId { - fn from(struct_id: chalk_ir::StructId) -> Self { - from_chalk(struct_id.0) - } -} - -impl From for chalk_ir::StructId { - fn from(adt_id: TypeCtorId) -> Self { - chalk_ir::StructId(to_chalk(adt_id)) - } -} - -/// This exists just for chalk, because our ImplIds are only unique per module. +/// This exists just for Chalk, because our ImplIds are only unique per module. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct GlobalImplId(salsa::InternId); impl_intern_key!(GlobalImplId); - -impl From for GlobalImplId { - fn from(impl_id: chalk_ir::ImplId) -> Self { - from_chalk(impl_id.0) - } -} - -impl From for chalk_ir::ImplId { - fn from(impl_id: GlobalImplId) -> Self { - chalk_ir::ImplId(to_chalk(impl_id)) - } -} diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index e1193c402a3..acb69683cbd 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs @@ -1,11 +1,14 @@ -//! Chalk integration. +//! Trait solving using Chalk. use std::sync::{Arc, Mutex}; -use chalk_ir::{TypeId, TraitId, StructId, ImplId, TypeKindId, ProjectionTy, Parameter, Identifier, cast::Cast}; -use chalk_rust_ir::{AssociatedTyDatum, TraitDatum, StructDatum, ImplDatum}; +use chalk_ir::cast::Cast; -use crate::{Crate, Trait, db::HirDatabase, HasGenericParams, ImplBlock}; -use super::{TraitRef, Ty, ApplicationTy, TypeCtor, Substs, infer::Canonical}; +use crate::{Crate, Trait, db::HirDatabase, ImplBlock}; +use super::{TraitRef, Ty, infer::Canonical}; + +use self::chalk::{ToChalk, from_chalk}; + +mod chalk; #[derive(Debug, Copy, Clone)] struct ChalkContext<'a, DB> { @@ -13,276 +16,6 @@ struct ChalkContext<'a, DB> { krate: Crate, } -pub(crate) trait ToChalk { - type Chalk; - fn to_chalk(self, db: &impl HirDatabase) -> Self::Chalk; - fn from_chalk(db: &impl HirDatabase, chalk: Self::Chalk) -> Self; -} - -pub(crate) fn from_chalk(db: &impl HirDatabase, chalk: ChalkT) -> T -where - T: ToChalk, -{ - T::from_chalk(db, chalk) -} - -impl ToChalk for Ty { - type Chalk = chalk_ir::Ty; - fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty { - match self { - Ty::Apply(apply_ty) => chalk_ir::Ty::Apply(apply_ty.to_chalk(db)), - Ty::Param { idx, .. } => { - chalk_ir::PlaceholderIndex { ui: chalk_ir::UniverseIndex::ROOT, idx: idx as usize } - .to_ty() - } - Ty::Bound(idx) => chalk_ir::Ty::BoundVar(idx as usize), - Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), - Ty::Unknown => unimplemented!(), // TODO turn into placeholder? - } - } - fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty) -> Self { - match chalk { - chalk_ir::Ty::Apply(apply_ty) => { - match apply_ty.name { - // FIXME handle TypeKindId::Trait/Type here - chalk_ir::TypeName::TypeKindId(_) => Ty::Apply(from_chalk(db, apply_ty)), - chalk_ir::TypeName::AssociatedType(_) => unimplemented!(), - chalk_ir::TypeName::Placeholder(idx) => { - assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT); - Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() } - } - } - } - chalk_ir::Ty::Projection(_) => unimplemented!(), - chalk_ir::Ty::UnselectedProjection(_) => unimplemented!(), - chalk_ir::Ty::ForAll(_) => unimplemented!(), - chalk_ir::Ty::BoundVar(idx) => Ty::Bound(idx as u32), - chalk_ir::Ty::InferenceVar(_iv) => panic!("unexpected chalk infer ty"), - } - } -} - -impl ToChalk for ApplicationTy { - type Chalk = chalk_ir::ApplicationTy; - - fn to_chalk(self: ApplicationTy, db: &impl HirDatabase) -> chalk_ir::ApplicationTy { - let struct_id = self.ctor.to_chalk(db); - let name = chalk_ir::TypeName::TypeKindId(struct_id.into()); - let parameters = self.parameters.to_chalk(db); - chalk_ir::ApplicationTy { name, parameters } - } - - fn from_chalk(db: &impl HirDatabase, apply_ty: chalk_ir::ApplicationTy) -> ApplicationTy { - let ctor = match apply_ty.name { - chalk_ir::TypeName::TypeKindId(chalk_ir::TypeKindId::StructId(struct_id)) => { - from_chalk(db, struct_id) - } - chalk_ir::TypeName::TypeKindId(_) => unimplemented!(), - chalk_ir::TypeName::Placeholder(_) => unimplemented!(), - chalk_ir::TypeName::AssociatedType(_) => unimplemented!(), - }; - let parameters = from_chalk(db, apply_ty.parameters); - ApplicationTy { ctor, parameters } - } -} - -impl ToChalk for Substs { - type Chalk = Vec; - - fn to_chalk(self, db: &impl HirDatabase) -> Vec { - self.iter().map(|ty| ty.clone().to_chalk(db).cast()).collect() - } - - fn from_chalk(db: &impl HirDatabase, parameters: Vec) -> Substs { - parameters - .into_iter() - .map(|p| match p { - chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty), - chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(), - }) - .collect::>() - .into() - } -} - -impl ToChalk for TraitRef { - type Chalk = chalk_ir::TraitRef; - - fn to_chalk(self: TraitRef, db: &impl HirDatabase) -> chalk_ir::TraitRef { - let trait_id = self.trait_.to_chalk(db); - let parameters = self.substs.to_chalk(db); - chalk_ir::TraitRef { trait_id, parameters } - } - - fn from_chalk(db: &impl HirDatabase, trait_ref: chalk_ir::TraitRef) -> Self { - let trait_ = from_chalk(db, trait_ref.trait_id); - let substs = from_chalk(db, trait_ref.parameters); - TraitRef { trait_, substs } - } -} - -impl ToChalk for Trait { - type Chalk = TraitId; - - fn to_chalk(self, _db: &impl HirDatabase) -> TraitId { - self.id.into() - } - - fn from_chalk(_db: &impl HirDatabase, trait_id: TraitId) -> Trait { - Trait { id: trait_id.into() } - } -} - -impl ToChalk for TypeCtor { - type Chalk = chalk_ir::StructId; - - fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::StructId { - db.intern_type_ctor(self).into() - } - - fn from_chalk(db: &impl HirDatabase, struct_id: chalk_ir::StructId) -> TypeCtor { - db.lookup_intern_type_ctor(struct_id.into()) - } -} - -impl ToChalk for ImplBlock { - type Chalk = chalk_ir::ImplId; - - fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ImplId { - db.intern_impl_block(self).into() - } - - fn from_chalk(db: &impl HirDatabase, impl_id: chalk_ir::ImplId) -> ImplBlock { - db.lookup_intern_impl_block(impl_id.into()) - } -} - -fn make_binders(value: T, num_vars: usize) -> chalk_ir::Binders { - chalk_ir::Binders { - value, - binders: std::iter::repeat(chalk_ir::ParameterKind::Ty(())).take(num_vars).collect(), - } -} - -impl<'a, DB> chalk_solve::RustIrDatabase for ChalkContext<'a, DB> -where - DB: HirDatabase, -{ - fn associated_ty_data(&self, _ty: TypeId) -> Arc { - unimplemented!() - } - fn trait_datum(&self, trait_id: TraitId) -> Arc { - eprintln!("trait_datum {:?}", trait_id); - let trait_: Trait = from_chalk(self.db, trait_id); - let generic_params = trait_.generic_params(self.db); - let bound_vars = Substs::bound_vars(&generic_params); - let trait_ref = trait_.trait_ref(self.db).subst(&bound_vars).to_chalk(self.db); - let flags = chalk_rust_ir::TraitFlags { - // FIXME set these flags correctly - auto: false, - marker: false, - upstream: trait_.module(self.db).krate(self.db) != Some(self.krate), - fundamental: false, - }; - let where_clauses = Vec::new(); // FIXME add where clauses - let trait_datum_bound = chalk_rust_ir::TraitDatumBound { trait_ref, where_clauses, flags }; - let trait_datum = TraitDatum { binders: make_binders(trait_datum_bound, bound_vars.len()) }; - Arc::new(trait_datum) - } - fn struct_datum(&self, struct_id: StructId) -> Arc { - eprintln!("struct_datum {:?}", struct_id); - let type_ctor = from_chalk(self.db, struct_id); - // TODO might be nicer if we can create a fake GenericParams for the TypeCtor - let (num_params, upstream) = match type_ctor { - TypeCtor::Bool - | TypeCtor::Char - | TypeCtor::Int(_) - | TypeCtor::Float(_) - | TypeCtor::Never - | TypeCtor::Str => (0, true), - TypeCtor::Slice | TypeCtor::Array | TypeCtor::RawPtr(_) | TypeCtor::Ref(_) => (1, true), - TypeCtor::FnPtr | TypeCtor::Tuple => unimplemented!(), // FIXME tuples and FnPtr are currently variadic... we need to make the parameter number explicit - TypeCtor::FnDef(_) => unimplemented!(), - TypeCtor::Adt(adt) => { - let generic_params = adt.generic_params(self.db); - ( - generic_params.count_params_including_parent(), - adt.krate(self.db) != Some(self.krate), - ) - } - }; - let flags = chalk_rust_ir::StructFlags { - upstream, - // FIXME set fundamental flag correctly - fundamental: false, - }; - let where_clauses = Vec::new(); // FIXME add where clauses - let ty = ApplicationTy { - ctor: type_ctor, - parameters: (0..num_params).map(|i| Ty::Bound(i as u32)).collect::>().into(), - }; - let struct_datum_bound = chalk_rust_ir::StructDatumBound { - self_ty: ty.to_chalk(self.db), - fields: Vec::new(), // FIXME add fields (only relevant for auto traits) - where_clauses, - flags, - }; - let struct_datum = StructDatum { binders: make_binders(struct_datum_bound, num_params) }; - Arc::new(struct_datum) - } - fn impl_datum(&self, impl_id: ImplId) -> Arc { - eprintln!("impl_datum {:?}", impl_id); - let impl_block: ImplBlock = from_chalk(self.db, impl_id); - let generic_params = impl_block.generic_params(self.db); - let bound_vars = Substs::bound_vars(&generic_params); - let trait_ref = impl_block - .target_trait_ref(self.db) - .expect("FIXME handle unresolved impl block trait ref") - .subst(&bound_vars); - let impl_type = if impl_block.module().krate(self.db) == Some(self.krate) { - chalk_rust_ir::ImplType::Local - } else { - chalk_rust_ir::ImplType::External - }; - let impl_datum_bound = chalk_rust_ir::ImplDatumBound { - // FIXME handle negative impls (impl !Sync for Foo) - trait_ref: chalk_rust_ir::PolarizedTraitRef::Positive(trait_ref.to_chalk(self.db)), - where_clauses: Vec::new(), // FIXME add where clauses - associated_ty_values: Vec::new(), // FIXME add associated type values - impl_type, - }; - let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, bound_vars.len()) }; - Arc::new(impl_datum) - } - fn impls_for_trait(&self, trait_id: TraitId) -> Vec { - eprintln!("impls_for_trait {:?}", trait_id); - let trait_ = from_chalk(self.db, trait_id); - self.db - .impls_for_trait(self.krate, trait_) - .iter() - // FIXME temporary hack -- as long as we're not lowering where clauses - // correctly, ignore impls with them completely so as to not treat - // impl Trait for T where T: ... as a blanket impl on all types - .filter(|impl_block| impl_block.generic_params(self.db).where_predicates.is_empty()) - .map(|impl_block| impl_block.to_chalk(self.db)) - .collect() - } - fn impl_provided_for(&self, auto_trait_id: TraitId, struct_id: StructId) -> bool { - eprintln!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id); - false // FIXME - } - fn type_name(&self, _id: TypeKindId) -> Identifier { - unimplemented!() - } - fn split_projection<'p>( - &self, - projection: &'p ProjectionTy, - ) -> (Arc, &'p [Parameter], &'p [Parameter]) { - eprintln!("split_projection {:?}", projection); - unimplemented!() - } -} - pub(crate) fn solver(_db: &impl HirDatabase, _krate: Crate) -> Arc> { // krate parameter is just so we cache a unique solver per crate let solver_choice = chalk_solve::SolverChoice::SLG { max_size: 10 }; diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs new file mode 100644 index 00000000000..36cc5270452 --- /dev/null +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -0,0 +1,327 @@ +//! Conversion code from/to Chalk. +use std::sync::Arc; + +use chalk_ir::{TypeId, ImplId, TypeKindId, ProjectionTy, Parameter, Identifier, cast::Cast, PlaceholderIndex, UniverseIndex, TypeName}; +use chalk_rust_ir::{AssociatedTyDatum, TraitDatum, StructDatum, ImplDatum}; + +use ra_db::salsa::{InternId, InternKey}; + +use crate::{ + Trait, HasGenericParams, ImplBlock, + db::HirDatabase, + ty::{TraitRef, Ty, ApplicationTy, TypeCtor, Substs}, +}; +use super::ChalkContext; + +pub(super) trait ToChalk { + type Chalk; + fn to_chalk(self, db: &impl HirDatabase) -> Self::Chalk; + fn from_chalk(db: &impl HirDatabase, chalk: Self::Chalk) -> Self; +} + +pub(super) fn from_chalk(db: &impl HirDatabase, chalk: ChalkT) -> T +where + T: ToChalk, +{ + T::from_chalk(db, chalk) +} + +impl ToChalk for Ty { + type Chalk = chalk_ir::Ty; + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty { + match self { + Ty::Apply(apply_ty) => chalk_ir::Ty::Apply(apply_ty.to_chalk(db)), + Ty::Param { idx, .. } => { + PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize } + .to_ty() + } + Ty::Bound(idx) => chalk_ir::Ty::BoundVar(idx as usize), + Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), + Ty::Unknown => unimplemented!(), // TODO turn into placeholder? + } + } + fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty) -> Self { + match chalk { + chalk_ir::Ty::Apply(apply_ty) => { + match apply_ty.name { + // FIXME handle TypeKindId::Trait/Type here + TypeName::TypeKindId(_) => Ty::Apply(from_chalk(db, apply_ty)), + TypeName::AssociatedType(_) => unimplemented!(), + TypeName::Placeholder(idx) => { + assert_eq!(idx.ui, UniverseIndex::ROOT); + Ty::Param { idx: idx.idx as u32, name: crate::Name::missing() } + } + } + } + chalk_ir::Ty::Projection(_) => unimplemented!(), + chalk_ir::Ty::UnselectedProjection(_) => unimplemented!(), + chalk_ir::Ty::ForAll(_) => unimplemented!(), + chalk_ir::Ty::BoundVar(idx) => Ty::Bound(idx as u32), + chalk_ir::Ty::InferenceVar(_iv) => panic!("unexpected chalk infer ty"), + } + } +} + +impl ToChalk for ApplicationTy { + type Chalk = chalk_ir::ApplicationTy; + + fn to_chalk(self: ApplicationTy, db: &impl HirDatabase) -> chalk_ir::ApplicationTy { + let struct_id = self.ctor.to_chalk(db); + let name = TypeName::TypeKindId(struct_id.into()); + let parameters = self.parameters.to_chalk(db); + chalk_ir::ApplicationTy { name, parameters } + } + + fn from_chalk(db: &impl HirDatabase, apply_ty: chalk_ir::ApplicationTy) -> ApplicationTy { + let ctor = match apply_ty.name { + TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => { + from_chalk(db, struct_id) + } + TypeName::TypeKindId(_) => unimplemented!(), + TypeName::Placeholder(_) => unimplemented!(), + TypeName::AssociatedType(_) => unimplemented!(), + }; + let parameters = from_chalk(db, apply_ty.parameters); + ApplicationTy { ctor, parameters } + } +} + +impl ToChalk for Substs { + type Chalk = Vec; + + fn to_chalk(self, db: &impl HirDatabase) -> Vec { + self.iter().map(|ty| ty.clone().to_chalk(db).cast()).collect() + } + + fn from_chalk(db: &impl HirDatabase, parameters: Vec) -> Substs { + parameters + .into_iter() + .map(|p| match p { + chalk_ir::Parameter(chalk_ir::ParameterKind::Ty(ty)) => from_chalk(db, ty), + chalk_ir::Parameter(chalk_ir::ParameterKind::Lifetime(_)) => unimplemented!(), + }) + .collect::>() + .into() + } +} + +impl ToChalk for TraitRef { + type Chalk = chalk_ir::TraitRef; + + fn to_chalk(self: TraitRef, db: &impl HirDatabase) -> chalk_ir::TraitRef { + let trait_id = self.trait_.to_chalk(db); + let parameters = self.substs.to_chalk(db); + chalk_ir::TraitRef { trait_id, parameters } + } + + fn from_chalk(db: &impl HirDatabase, trait_ref: chalk_ir::TraitRef) -> Self { + let trait_ = from_chalk(db, trait_ref.trait_id); + let substs = from_chalk(db, trait_ref.parameters); + TraitRef { trait_, substs } + } +} + +impl ToChalk for Trait { + type Chalk = chalk_ir::TraitId; + + fn to_chalk(self, _db: &impl HirDatabase) -> chalk_ir::TraitId { + self.id.into() + } + + fn from_chalk(_db: &impl HirDatabase, trait_id: chalk_ir::TraitId) -> Trait { + Trait { id: trait_id.into() } + } +} + +impl ToChalk for TypeCtor { + type Chalk = chalk_ir::StructId; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::StructId { + db.intern_type_ctor(self).into() + } + + fn from_chalk(db: &impl HirDatabase, struct_id: chalk_ir::StructId) -> TypeCtor { + db.lookup_intern_type_ctor(struct_id.into()) + } +} + +impl ToChalk for ImplBlock { + type Chalk = chalk_ir::ImplId; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::ImplId { + db.intern_impl_block(self).into() + } + + fn from_chalk(db: &impl HirDatabase, impl_id: chalk_ir::ImplId) -> ImplBlock { + db.lookup_intern_impl_block(impl_id.into()) + } +} + +fn make_binders(value: T, num_vars: usize) -> chalk_ir::Binders { + chalk_ir::Binders { + value, + binders: std::iter::repeat(chalk_ir::ParameterKind::Ty(())).take(num_vars).collect(), + } +} + +impl<'a, DB> chalk_solve::RustIrDatabase for ChalkContext<'a, DB> +where + DB: HirDatabase, +{ + fn associated_ty_data(&self, _ty: TypeId) -> Arc { + unimplemented!() + } + fn trait_datum(&self, trait_id: chalk_ir::TraitId) -> Arc { + eprintln!("trait_datum {:?}", trait_id); + let trait_: Trait = from_chalk(self.db, trait_id); + let generic_params = trait_.generic_params(self.db); + let bound_vars = Substs::bound_vars(&generic_params); + let trait_ref = trait_.trait_ref(self.db).subst(&bound_vars).to_chalk(self.db); + let flags = chalk_rust_ir::TraitFlags { + // FIXME set these flags correctly + auto: false, + marker: false, + upstream: trait_.module(self.db).krate(self.db) != Some(self.krate), + fundamental: false, + }; + let where_clauses = Vec::new(); // FIXME add where clauses + let trait_datum_bound = chalk_rust_ir::TraitDatumBound { trait_ref, where_clauses, flags }; + let trait_datum = TraitDatum { binders: make_binders(trait_datum_bound, bound_vars.len()) }; + Arc::new(trait_datum) + } + fn struct_datum(&self, struct_id: chalk_ir::StructId) -> Arc { + eprintln!("struct_datum {:?}", struct_id); + let type_ctor = from_chalk(self.db, struct_id); + // TODO might be nicer if we can create a fake GenericParams for the TypeCtor + let (num_params, upstream) = match type_ctor { + TypeCtor::Bool + | TypeCtor::Char + | TypeCtor::Int(_) + | TypeCtor::Float(_) + | TypeCtor::Never + | TypeCtor::Str => (0, true), + TypeCtor::Slice | TypeCtor::Array | TypeCtor::RawPtr(_) | TypeCtor::Ref(_) => (1, true), + TypeCtor::FnPtr | TypeCtor::Tuple => unimplemented!(), // FIXME tuples and FnPtr are currently variadic... we need to make the parameter number explicit + TypeCtor::FnDef(_) => unimplemented!(), + TypeCtor::Adt(adt) => { + let generic_params = adt.generic_params(self.db); + ( + generic_params.count_params_including_parent(), + adt.krate(self.db) != Some(self.krate), + ) + } + }; + let flags = chalk_rust_ir::StructFlags { + upstream, + // FIXME set fundamental flag correctly + fundamental: false, + }; + let where_clauses = Vec::new(); // FIXME add where clauses + let ty = ApplicationTy { + ctor: type_ctor, + parameters: (0..num_params).map(|i| Ty::Bound(i as u32)).collect::>().into(), + }; + let struct_datum_bound = chalk_rust_ir::StructDatumBound { + self_ty: ty.to_chalk(self.db), + fields: Vec::new(), // FIXME add fields (only relevant for auto traits) + where_clauses, + flags, + }; + let struct_datum = StructDatum { binders: make_binders(struct_datum_bound, num_params) }; + Arc::new(struct_datum) + } + fn impl_datum(&self, impl_id: ImplId) -> Arc { + eprintln!("impl_datum {:?}", impl_id); + let impl_block: ImplBlock = from_chalk(self.db, impl_id); + let generic_params = impl_block.generic_params(self.db); + let bound_vars = Substs::bound_vars(&generic_params); + let trait_ref = impl_block + .target_trait_ref(self.db) + .expect("FIXME handle unresolved impl block trait ref") + .subst(&bound_vars); + let impl_type = if impl_block.module().krate(self.db) == Some(self.krate) { + chalk_rust_ir::ImplType::Local + } else { + chalk_rust_ir::ImplType::External + }; + let impl_datum_bound = chalk_rust_ir::ImplDatumBound { + // FIXME handle negative impls (impl !Sync for Foo) + trait_ref: chalk_rust_ir::PolarizedTraitRef::Positive(trait_ref.to_chalk(self.db)), + where_clauses: Vec::new(), // FIXME add where clauses + associated_ty_values: Vec::new(), // FIXME add associated type values + impl_type, + }; + let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, bound_vars.len()) }; + Arc::new(impl_datum) + } + fn impls_for_trait(&self, trait_id: chalk_ir::TraitId) -> Vec { + eprintln!("impls_for_trait {:?}", trait_id); + let trait_ = from_chalk(self.db, trait_id); + self.db + .impls_for_trait(self.krate, trait_) + .iter() + // FIXME temporary hack -- as long as we're not lowering where clauses + // correctly, ignore impls with them completely so as to not treat + // impl Trait for T where T: ... as a blanket impl on all types + .filter(|impl_block| impl_block.generic_params(self.db).where_predicates.is_empty()) + .map(|impl_block| impl_block.to_chalk(self.db)) + .collect() + } + fn impl_provided_for(&self, auto_trait_id: chalk_ir::TraitId, struct_id: chalk_ir::StructId) -> bool { + eprintln!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id); + false // FIXME + } + fn type_name(&self, _id: TypeKindId) -> Identifier { + unimplemented!() + } + fn split_projection<'p>( + &self, + projection: &'p ProjectionTy, + ) -> (Arc, &'p [Parameter], &'p [Parameter]) { + eprintln!("split_projection {:?}", projection); + unimplemented!() + } +} + +fn id_from_chalk(chalk_id: chalk_ir::RawId) -> T { + T::from_intern_id(InternId::from(chalk_id.index)) +} +fn id_to_chalk(salsa_id: T) -> chalk_ir::RawId { + chalk_ir::RawId { index: salsa_id.as_intern_id().as_u32() } +} + +impl From for crate::ids::TraitId { + fn from(trait_id: chalk_ir::TraitId) -> Self { + id_from_chalk(trait_id.0) + } +} + +impl From for chalk_ir::TraitId { + fn from(trait_id: crate::ids::TraitId) -> Self { + chalk_ir::TraitId(id_to_chalk(trait_id)) + } +} + +impl From for crate::ids::TypeCtorId { + fn from(struct_id: chalk_ir::StructId) -> Self { + id_from_chalk(struct_id.0) + } +} + +impl From for chalk_ir::StructId { + fn from(type_ctor_id: crate::ids::TypeCtorId) -> Self { + chalk_ir::StructId(id_to_chalk(type_ctor_id)) + } +} + +impl From for crate::ids::GlobalImplId { + fn from(impl_id: chalk_ir::ImplId) -> Self { + id_from_chalk(impl_id.0) + } +} + +impl From for chalk_ir::ImplId { + fn from(impl_id: crate::ids::GlobalImplId) -> Self { + chalk_ir::ImplId(id_to_chalk(impl_id)) + } +} From ef77d8375130d12678d4b2316cc1708c90349dad Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Wed, 1 May 2019 17:13:33 +0200 Subject: [PATCH 06/15] Document the peculiarity of the solver query a bit Also remove the only remaining mention of chalk outside of the ty::traits module. --- crates/ra_hir/src/db.rs | 7 ++++++- crates/ra_hir/src/ty/traits.rs | 6 ++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index b2c4fccf28f..8aaf0375a15 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs @@ -153,9 +153,14 @@ pub trait HirDatabase: DefDatabase { #[salsa::invoke(crate::ty::traits::impls_for_trait)] fn impls_for_trait(&self, krate: Crate, trait_: Trait) -> Arc<[ImplBlock]>; + /// This provides the Chalk trait solver instance. Because Chalk always + /// works from a specific crate, this query is keyed on the crate; and + /// because Chalk does its own internal caching, the solver is wrapped in a + /// Mutex and the query is marked volatile, to make sure the cached state is + /// thrown away when input facts change. #[salsa::invoke(crate::ty::traits::solver)] #[salsa::volatile] - fn chalk_solver(&self, krate: Crate) -> Arc>; + fn solver(&self, krate: Crate) -> Arc>; } #[test] diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index acb69683cbd..ac31ca2f6e3 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs @@ -10,13 +10,15 @@ use self::chalk::{ToChalk, from_chalk}; mod chalk; +pub(crate) type Solver = chalk_solve::Solver; + #[derive(Debug, Copy, Clone)] struct ChalkContext<'a, DB> { db: &'a DB, krate: Crate, } -pub(crate) fn solver(_db: &impl HirDatabase, _krate: Crate) -> Arc> { +pub(crate) fn solver(_db: &impl HirDatabase, _krate: Crate) -> Arc> { // krate parameter is just so we cache a unique solver per crate let solver_choice = chalk_solve::SolverChoice::SLG { max_size: 10 }; Arc::new(Mutex::new(solver_choice.into_solver())) @@ -48,7 +50,7 @@ fn solve( goal: &chalk_ir::UCanonical>, ) -> Option { let context = ChalkContext { db, krate }; - let solver = db.chalk_solver(krate); + let solver = db.solver(krate); let solution = solver.lock().unwrap().solve(&context, goal); eprintln!("solve({:?}) => {:?}", goal, solution); solution From 0ad7317b24dc90c3787482f9ec563e7830d499fc Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Wed, 1 May 2019 17:57:56 +0200 Subject: [PATCH 07/15] Canonicalize before doing method resolution --- crates/ra_hir/src/source_binder.rs | 11 +- crates/ra_hir/src/ty.rs | 11 + crates/ra_hir/src/ty/infer.rs | 13 +- crates/ra_hir/src/ty/infer/unify.rs | 24 +- crates/ra_hir/src/ty/method_resolution.rs | 261 +++++++++++----------- crates/ra_hir/src/ty/traits.rs | 7 +- crates/ra_hir/src/ty/traits/chalk.rs | 13 +- 7 files changed, 186 insertions(+), 154 deletions(-) diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 2959e3eca29..24350bda7e6 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -350,7 +350,16 @@ impl SourceAnalyzer { name: Option<&Name>, callback: impl FnMut(&Ty, Function) -> Option, ) -> Option { - ty.iterate_method_candidates(db, &self.resolver, name, callback) + // There should be no inference vars in types passed here + // TODO check that? + let canonical = crate::ty::Canonical { value: ty, num_vars: 0 }; + crate::ty::method_resolution::iterate_method_candidates( + &canonical, + db, + &self.resolver, + name, + callback, + ) } #[cfg(test)] diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index e7c39487d52..6a79af35b91 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs @@ -234,6 +234,17 @@ impl TraitRef { } } +/// Basically a claim (currently not validated / checked) that the contained +/// type / trait ref contains no inference variables; any inference variables it +/// contained have been replaced by bound variables, and `num_vars` tells us how +/// many there are. This is used to erase irrelevant differences between types +/// before using them in queries. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(crate) struct Canonical { + pub value: T, + pub num_vars: usize, +} + /// A function signature as seen by type inference: Several parameter types and /// one return type. #[derive(Clone, PartialEq, Eq, Debug)] diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs index a6d08dbcbf6..41ae569f7b6 100644 --- a/crates/ra_hir/src/ty/infer.rs +++ b/crates/ra_hir/src/ty/infer.rs @@ -45,12 +45,11 @@ use crate::{ use super::{ Ty, TypableDef, Substs, primitive, op, ApplicationTy, TypeCtor, CallableDef, TraitRef, traits::{Solution, Obligation, Guidance}, + method_resolution, }; mod unify; -pub(super) use unify::Canonical; - /// The entry point of type inference. pub fn infer(db: &impl HirDatabase, def: DefWithBody) -> Arc { db.check_canceled(); @@ -878,9 +877,17 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { generic_args: Option<&GenericArgs>, ) -> Ty { let receiver_ty = self.infer_expr(receiver, &Expectation::none()); - let resolved = receiver_ty.clone().lookup_method(self.db, method_name, &self.resolver); + let mut canonicalizer = self.canonicalizer(); + let canonical_receiver = canonicalizer.canonicalize_ty(receiver_ty.clone()); + let resolved = method_resolution::lookup_method( + &canonical_receiver, + canonicalizer.ctx.db, + method_name, + &canonicalizer.ctx.resolver, + ); let (derefed_receiver_ty, method_ty, def_generics) = match resolved { Some((ty, func)) => { + let ty = canonicalizer.decanonicalize_ty(ty); self.write_method_resolution(tgt_expr, func); ( ty, diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs index 5edb95c315d..820a6478952 100644 --- a/crates/ra_hir/src/ty/infer/unify.rs +++ b/crates/ra_hir/src/ty/infer/unify.rs @@ -1,6 +1,8 @@ //! Unification and canonicalization logic. -use super::{InferenceContext, Ty, TraitRef, InferTy, HirDatabase}; +use crate::db::HirDatabase; +use crate::ty::{Ty, Canonical, TraitRef, InferTy}; +use super::InferenceContext; impl<'a, D: HirDatabase> InferenceContext<'a, D> { pub(super) fn canonicalizer<'b>(&'b mut self) -> Canonicalizer<'a, 'b, D> @@ -13,13 +15,6 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { // TODO improve the interface of this -// TODO move further up? -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub(crate) struct Canonical { - pub value: T, - pub num_vars: usize, -} - pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase> where 'a: 'b, @@ -68,6 +63,19 @@ where Canonical { value, num_vars: self.free_vars.len() } } + pub fn decanonicalize_ty(&self, ty: Ty) -> Ty { + ty.fold(&mut |ty| match ty { + Ty::Bound(idx) => { + if (idx as usize) < self.free_vars.len() { + Ty::Infer(self.free_vars[idx as usize].clone()) + } else { + Ty::Bound(idx) + } + } + ty => ty, + }) + } + pub fn apply_solution(&mut self, solution: Canonical>) { // the solution may contain new variables, which we need to convert to new inference vars let new_vars = diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir/src/ty/method_resolution.rs index ea7da0b6293..bc5033be6cc 100644 --- a/crates/ra_hir/src/ty/method_resolution.rs +++ b/crates/ra_hir/src/ty/method_resolution.rs @@ -16,7 +16,7 @@ use crate::{ generics::HasGenericParams, ty::primitive::{UncertainIntTy, UncertainFloatTy} }; -use super::{TraitRef, infer::Canonical, Substs}; +use super::{TraitRef, Canonical}; /// This is used as a key for indexing impls. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] @@ -130,132 +130,123 @@ fn def_crate(db: &impl HirDatabase, cur_crate: Crate, ty: &Ty) -> Option } } +/// Look up the method with the given name, returning the actual autoderefed +/// receiver type (but without autoref applied yet). +pub(crate) fn lookup_method( + ty: &Canonical, + db: &impl HirDatabase, + name: &Name, + resolver: &Resolver, +) -> Option<(Ty, Function)> { + iterate_method_candidates(ty, db, resolver, Some(name), |ty, f| Some((ty.clone(), f))) +} + +// This would be nicer if it just returned an iterator, but that runs into +// lifetime problems, because we need to borrow temp `CrateImplBlocks`. +pub(crate) fn iterate_method_candidates( + ty: &Canonical, + db: &impl HirDatabase, + resolver: &Resolver, + name: Option<&Name>, + mut callback: impl FnMut(&Ty, Function) -> Option, +) -> Option { + // For method calls, rust first does any number of autoderef, and then one + // autoref (i.e. when the method takes &self or &mut self). We just ignore + // the autoref currently -- when we find a method matching the given name, + // we assume it fits. + + // Also note that when we've got a receiver like &S, even if the method we + // find in the end takes &self, we still do the autoderef step (just as + // rustc does an autoderef and then autoref again). + + let krate = resolver.krate()?; + for derefed_ty in ty.value.clone().autoderef(db) { + let derefed_ty = Canonical { value: derefed_ty, num_vars: ty.num_vars }; + if let Some(result) = iterate_inherent_methods(&derefed_ty, db, name, krate, &mut callback) + { + return Some(result); + } + if let Some(result) = + iterate_trait_method_candidates(&derefed_ty, db, resolver, name, &mut callback) + { + return Some(result); + } + } + None +} + +fn iterate_trait_method_candidates( + ty: &Canonical, + db: &impl HirDatabase, + resolver: &Resolver, + name: Option<&Name>, + mut callback: impl FnMut(&Ty, Function) -> Option, +) -> Option { + let krate = resolver.krate()?; + 'traits: for t in resolver.traits_in_scope() { + let data = t.trait_data(db); + // we'll be lazy about checking whether the type implements the + // trait, but if we find out it doesn't, we'll skip the rest of the + // iteration + let mut known_implemented = false; + for item in data.items() { + match item { + &TraitItem::Function(m) => { + let sig = m.signature(db); + if name.map_or(true, |name| sig.name() == name) && sig.has_self_param() { + if !known_implemented { + let trait_ref = canonical_trait_ref(db, t, ty.clone()); + // FIXME cache this implements check (without solution) in a query? + if super::traits::implements(db, krate, trait_ref).is_none() { + continue 'traits; + } + } + known_implemented = true; + // TODO the self type is now canonicalized... + if let Some(result) = callback(&ty.value, m) { + return Some(result); + } + } + } + _ => {} + } + } + } + None +} + +fn iterate_inherent_methods( + ty: &Canonical, + db: &impl HirDatabase, + name: Option<&Name>, + krate: Crate, + mut callback: impl FnMut(&Ty, Function) -> Option, +) -> Option { + let krate = match def_crate(db, krate, &ty.value) { + Some(krate) => krate, + None => return None, + }; + let impls = db.impls_in_crate(krate); + + for impl_block in impls.lookup_impl_blocks(&ty.value) { + for item in impl_block.items(db) { + match item { + ImplItem::Method(f) => { + let sig = f.signature(db); + if name.map_or(true, |name| sig.name() == name) && sig.has_self_param() { + if let Some(result) = callback(&ty.value, f) { + return Some(result); + } + } + } + _ => {} + } + } + } + None +} + impl Ty { - /// Look up the method with the given name, returning the actual autoderefed - /// receiver type (but without autoref applied yet). - pub(crate) fn lookup_method( - self, - db: &impl HirDatabase, - name: &Name, - resolver: &Resolver, - ) -> Option<(Ty, Function)> { - self.iterate_method_candidates(db, resolver, Some(name), |ty, f| Some((ty.clone(), f))) - } - - // This would be nicer if it just returned an iterator, but that runs into - // lifetime problems, because we need to borrow temp `CrateImplBlocks`. - pub(crate) fn iterate_method_candidates( - self, - db: &impl HirDatabase, - resolver: &Resolver, - name: Option<&Name>, - mut callback: impl FnMut(&Ty, Function) -> Option, - ) -> Option { - // For method calls, rust first does any number of autoderef, and then one - // autoref (i.e. when the method takes &self or &mut self). We just ignore - // the autoref currently -- when we find a method matching the given name, - // we assume it fits. - - // Also note that when we've got a receiver like &S, even if the method we - // find in the end takes &self, we still do the autoderef step (just as - // rustc does an autoderef and then autoref again). - - let krate = resolver.krate()?; - for derefed_ty in self.autoderef(db) { - if let Some(result) = - derefed_ty.iterate_inherent_methods(db, name, krate, &mut callback) - { - return Some(result); - } - if let Some(result) = - derefed_ty.iterate_trait_method_candidates(db, resolver, name, &mut callback) - { - return Some(result); - } - } - None - } - - fn iterate_trait_method_candidates( - &self, - db: &impl HirDatabase, - resolver: &Resolver, - name: Option<&Name>, - mut callback: impl FnMut(&Ty, Function) -> Option, - ) -> Option { - let krate = resolver.krate()?; - 'traits: for t in resolver.traits_in_scope() { - let data = t.trait_data(db); - // we'll be lazy about checking whether the type implements the - // trait, but if we find out it doesn't, we'll skip the rest of the - // iteration - let mut known_implemented = false; - for item in data.items() { - match item { - &TraitItem::Function(m) => { - let sig = m.signature(db); - if name.map_or(true, |name| sig.name() == name) && sig.has_self_param() { - if !known_implemented { - // TODO the self type may contain type - // variables, so we need to do proper - // canonicalization here - let trait_ref = TraitRef { - trait_: t, - substs: fresh_substs_for_trait(db, t, self.clone()), - }; - let canonical = Canonical { - num_vars: trait_ref.substs.len(), - value: trait_ref, - }; - // FIXME cache this implements check (without solution) in a query? - if super::traits::implements(db, krate, canonical).is_none() { - continue 'traits; - } - } - known_implemented = true; - if let Some(result) = callback(self, m) { - return Some(result); - } - } - } - _ => {} - } - } - } - None - } - - fn iterate_inherent_methods( - &self, - db: &impl HirDatabase, - name: Option<&Name>, - krate: Crate, - mut callback: impl FnMut(&Ty, Function) -> Option, - ) -> Option { - let krate = match def_crate(db, krate, self) { - Some(krate) => krate, - None => return None, - }; - let impls = db.impls_in_crate(krate); - - for impl_block in impls.lookup_impl_blocks(self) { - for item in impl_block.items(db) { - match item { - ImplItem::Method(f) => { - let sig = f.signature(db); - if name.map_or(true, |name| sig.name() == name) && sig.has_self_param() { - if let Some(result) = callback(self, f) { - return Some(result); - } - } - } - _ => {} - } - } - } - None - } - // This would be nicer if it just returned an iterator, but that runs into // lifetime problems, because we need to borrow temp `CrateImplBlocks`. pub fn iterate_impl_items( @@ -280,17 +271,25 @@ impl Ty { /// This creates Substs for a trait with the given Self type and type variables /// for all other parameters, to query Chalk with it. -fn fresh_substs_for_trait(db: &impl HirDatabase, tr: Trait, self_ty: Ty) -> Substs { +fn canonical_trait_ref( + db: &impl HirDatabase, + trait_: Trait, + self_ty: Canonical, +) -> Canonical { let mut substs = Vec::new(); - let generics = tr.generic_params(db); - substs.push(self_ty); + let generics = trait_.generic_params(db); + let num_vars = self_ty.num_vars; + substs.push(self_ty.value); substs.extend( generics .params_including_parent() .into_iter() .skip(1) .enumerate() - .map(|(i, _p)| Ty::Bound(i as u32)), + .map(|(i, _p)| Ty::Bound((i + num_vars) as u32)), ); - substs.into() + Canonical { + num_vars: substs.len() - 1 + self_ty.num_vars, + value: TraitRef { trait_, substs: substs.into() }, + } } diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index ac31ca2f6e3..c707110ad98 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs @@ -4,7 +4,7 @@ use std::sync::{Arc, Mutex}; use chalk_ir::cast::Cast; use crate::{Crate, Trait, db::HirDatabase, ImplBlock}; -use super::{TraitRef, Ty, infer::Canonical}; +use super::{TraitRef, Ty, Canonical}; use self::chalk::{ToChalk, from_chalk}; @@ -86,10 +86,7 @@ pub(crate) fn implements( solution.map(|solution| solution_from_chalk(db, solution)) } -fn solution_from_chalk( - db: &impl HirDatabase, - solution: chalk_solve::Solution, -) -> Solution { +fn solution_from_chalk(db: &impl HirDatabase, solution: chalk_solve::Solution) -> Solution { let convert_subst = |subst: chalk_ir::Canonical| { let value = subst .value diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 36cc5270452..18f3017899a 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -32,8 +32,7 @@ impl ToChalk for Ty { match self { Ty::Apply(apply_ty) => chalk_ir::Ty::Apply(apply_ty.to_chalk(db)), Ty::Param { idx, .. } => { - PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize } - .to_ty() + PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }.to_ty() } Ty::Bound(idx) => chalk_ir::Ty::BoundVar(idx as usize), Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), @@ -74,9 +73,7 @@ impl ToChalk for ApplicationTy { fn from_chalk(db: &impl HirDatabase, apply_ty: chalk_ir::ApplicationTy) -> ApplicationTy { let ctor = match apply_ty.name { - TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => { - from_chalk(db, struct_id) - } + TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => from_chalk(db, struct_id), TypeName::TypeKindId(_) => unimplemented!(), TypeName::Placeholder(_) => unimplemented!(), TypeName::AssociatedType(_) => unimplemented!(), @@ -267,7 +264,11 @@ where .map(|impl_block| impl_block.to_chalk(self.db)) .collect() } - fn impl_provided_for(&self, auto_trait_id: chalk_ir::TraitId, struct_id: chalk_ir::StructId) -> bool { + fn impl_provided_for( + &self, + auto_trait_id: chalk_ir::TraitId, + struct_id: chalk_ir::StructId, + ) -> bool { eprintln!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id); false // FIXME } From 7310f3f801a8dff37503dd4ed3e3e2ecbf6bac2e Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Wed, 1 May 2019 20:50:11 +0200 Subject: [PATCH 08/15] Handle Ty::Unknown in Chalk conversion Badly, but at least it doesn't crash. --- crates/ra_hir/src/ty/traits/chalk.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 18f3017899a..02df5a4fa9d 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -36,7 +36,11 @@ impl ToChalk for Ty { } Ty::Bound(idx) => chalk_ir::Ty::BoundVar(idx as usize), Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), - Ty::Unknown => unimplemented!(), // TODO turn into placeholder? + // FIXME this is clearly incorrect, but probably not too incorrect + // and I'm not sure what to actually do with Ty::Unknown + Ty::Unknown => { + PlaceholderIndex { ui: UniverseIndex::ROOT, idx: 0 }.to_ty() + }, } } fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty) -> Self { From 0f34568924019caf1ed63c84143c12156b963abf Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Wed, 1 May 2019 20:50:49 +0200 Subject: [PATCH 09/15] Turn eprintln!s into debug!s --- crates/ra_hir/src/ty/traits.rs | 5 +++-- crates/ra_hir/src/ty/traits/chalk.rs | 15 +++++++++------ 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index c707110ad98..a1ed0c02820 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs @@ -1,6 +1,7 @@ //! Trait solving using Chalk. use std::sync::{Arc, Mutex}; +use log::debug; use chalk_ir::cast::Cast; use crate::{Crate, Trait, db::HirDatabase, ImplBlock}; @@ -52,7 +53,7 @@ fn solve( let context = ChalkContext { db, krate }; let solver = db.solver(krate); let solution = solver.lock().unwrap().solve(&context, goal); - eprintln!("solve({:?}) => {:?}", goal, solution); + debug!("solve({:?}) => {:?}", goal, solution); solution } @@ -73,7 +74,7 @@ pub(crate) fn implements( trait_ref: Canonical, ) -> Option { let goal: chalk_ir::Goal = trait_ref.value.to_chalk(db).cast(); - eprintln!("goal: {:?}", goal); + debug!("goal: {:?}", goal); let env = chalk_ir::Environment::new(); let in_env = chalk_ir::InEnvironment::new(&env, goal); let parameter = chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::ROOT); diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 02df5a4fa9d..1adc1d60140 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -1,6 +1,8 @@ //! Conversion code from/to Chalk. use std::sync::Arc; +use log::debug; + use chalk_ir::{TypeId, ImplId, TypeKindId, ProjectionTy, Parameter, Identifier, cast::Cast, PlaceholderIndex, UniverseIndex, TypeName}; use chalk_rust_ir::{AssociatedTyDatum, TraitDatum, StructDatum, ImplDatum}; @@ -65,6 +67,7 @@ impl ToChalk for Ty { } } +// TODO merge this into the ToChalk implementation for Ty impl ToChalk for ApplicationTy { type Chalk = chalk_ir::ApplicationTy; @@ -173,7 +176,7 @@ where unimplemented!() } fn trait_datum(&self, trait_id: chalk_ir::TraitId) -> Arc { - eprintln!("trait_datum {:?}", trait_id); + debug!("trait_datum {:?}", trait_id); let trait_: Trait = from_chalk(self.db, trait_id); let generic_params = trait_.generic_params(self.db); let bound_vars = Substs::bound_vars(&generic_params); @@ -191,7 +194,7 @@ where Arc::new(trait_datum) } fn struct_datum(&self, struct_id: chalk_ir::StructId) -> Arc { - eprintln!("struct_datum {:?}", struct_id); + debug!("struct_datum {:?}", struct_id); let type_ctor = from_chalk(self.db, struct_id); // TODO might be nicer if we can create a fake GenericParams for the TypeCtor let (num_params, upstream) = match type_ctor { @@ -232,7 +235,7 @@ where Arc::new(struct_datum) } fn impl_datum(&self, impl_id: ImplId) -> Arc { - eprintln!("impl_datum {:?}", impl_id); + debug!("impl_datum {:?}", impl_id); let impl_block: ImplBlock = from_chalk(self.db, impl_id); let generic_params = impl_block.generic_params(self.db); let bound_vars = Substs::bound_vars(&generic_params); @@ -256,7 +259,7 @@ where Arc::new(impl_datum) } fn impls_for_trait(&self, trait_id: chalk_ir::TraitId) -> Vec { - eprintln!("impls_for_trait {:?}", trait_id); + debug!("impls_for_trait {:?}", trait_id); let trait_ = from_chalk(self.db, trait_id); self.db .impls_for_trait(self.krate, trait_) @@ -273,7 +276,7 @@ where auto_trait_id: chalk_ir::TraitId, struct_id: chalk_ir::StructId, ) -> bool { - eprintln!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id); + debug!("impl_provided_for {:?}, {:?}", auto_trait_id, struct_id); false // FIXME } fn type_name(&self, _id: TypeKindId) -> Identifier { @@ -283,7 +286,7 @@ where &self, projection: &'p ProjectionTy, ) -> (Arc, &'p [Parameter], &'p [Parameter]) { - eprintln!("split_projection {:?}", projection); + debug!("split_projection {:?}", projection); unimplemented!() } } From 0bcf47b22b01f66c2f2056f5871e32071ba95b01 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Wed, 1 May 2019 23:26:42 +0200 Subject: [PATCH 10/15] Update Chalk --- Cargo.lock | 46 +++++++++++------------ crates/ra_hir/Cargo.toml | 9 ++--- crates/ra_hir/src/ty/method_resolution.rs | 1 - crates/ra_hir/src/ty/traits/chalk.rs | 17 +++++++-- 4 files changed, 39 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0bb62cb88da..98c349dec41 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -146,9 +146,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "chalk-engine" version = "0.9.0" -source = "git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match#b508031b92c754a677d46236aae1dcd2fa2fd68a" +source = "git+https://github.com/rust-lang/chalk.git#17fb07e43b23d721f9c1adba289eac71b25f38ef" dependencies = [ - "chalk-macros 0.1.1 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git)", "rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "stacker 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -156,17 +156,17 @@ dependencies = [ [[package]] name = "chalk-ir" version = "0.1.0" -source = "git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match#b508031b92c754a677d46236aae1dcd2fa2fd68a" +source = "git+https://github.com/rust-lang/chalk.git#17fb07e43b23d721f9c1adba289eac71b25f38ef" dependencies = [ - "chalk-engine 0.9.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", - "chalk-macros 0.1.1 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git)", + "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git)", "lalrpop-intern 0.15.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "chalk-macros" version = "0.1.1" -source = "git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match#b508031b92c754a677d46236aae1dcd2fa2fd68a" +source = "git+https://github.com/rust-lang/chalk.git#17fb07e43b23d721f9c1adba289eac71b25f38ef" dependencies = [ "lazy_static 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -174,22 +174,22 @@ dependencies = [ [[package]] name = "chalk-rust-ir" version = "0.1.0" -source = "git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match#b508031b92c754a677d46236aae1dcd2fa2fd68a" +source = "git+https://github.com/rust-lang/chalk.git#17fb07e43b23d721f9c1adba289eac71b25f38ef" dependencies = [ - "chalk-engine 0.9.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", - "chalk-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", - "chalk-macros 0.1.1 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git)", + "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)", + "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git)", ] [[package]] name = "chalk-solve" version = "0.1.0" -source = "git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match#b508031b92c754a677d46236aae1dcd2fa2fd68a" +source = "git+https://github.com/rust-lang/chalk.git#17fb07e43b23d721f9c1adba289eac71b25f38ef" dependencies = [ - "chalk-engine 0.9.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", - "chalk-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", - "chalk-macros 0.1.1 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", - "chalk-rust-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git)", + "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)", + "chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git)", + "chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)", "derive-new 0.5.6 (registry+https://github.com/rust-lang/crates.io-index)", "ena 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", "failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1074,9 +1074,9 @@ name = "ra_hir" version = "0.1.0" dependencies = [ "arrayvec 0.4.10 (registry+https://github.com/rust-lang/crates.io-index)", - "chalk-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", - "chalk-rust-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", - "chalk-solve 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)", + "chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)", + "chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)", + "chalk-solve 0.1.0 (git+https://github.com/rust-lang/chalk.git)", "ena 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "flexi_logger 0.11.4 (registry+https://github.com/rust-lang/crates.io-index)", "insta 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1997,11 +1997,11 @@ dependencies = [ "checksum cargo_metadata 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)" = "178d62b240c34223f265a4c1e275e37d62da163d421fc8d7f7e3ee340f803c57" "checksum cc 1.0.35 (registry+https://github.com/rust-lang/crates.io-index)" = "5e5f3fee5eeb60324c2781f1e41286bdee933850fff9b3c672587fed5ec58c83" "checksum cfg-if 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "11d43355396e872eefb45ce6342e4374ed7bc2b3a502d1b28e36d6e23c05d1f4" -"checksum chalk-engine 0.9.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)" = "" -"checksum chalk-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)" = "" -"checksum chalk-macros 0.1.1 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)" = "" -"checksum chalk-rust-ir 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)" = "" -"checksum chalk-solve 0.1.0 (git+https://github.com/detrumi/chalk.git?branch=program_clauses_that_could_match)" = "" +"checksum chalk-engine 0.9.0 (git+https://github.com/rust-lang/chalk.git)" = "" +"checksum chalk-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)" = "" +"checksum chalk-macros 0.1.1 (git+https://github.com/rust-lang/chalk.git)" = "" +"checksum chalk-rust-ir 0.1.0 (git+https://github.com/rust-lang/chalk.git)" = "" +"checksum chalk-solve 0.1.0 (git+https://github.com/rust-lang/chalk.git)" = "" "checksum chrono 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "45912881121cb26fad7c38c17ba7daa18764771836b34fab7d3fbd93ed633878" "checksum ci_info 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e5e881307a989a3a5e20d52a32cc05950e3c2178cccfcc9428271a6cde09f902" "checksum clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" diff --git a/crates/ra_hir/Cargo.toml b/crates/ra_hir/Cargo.toml index ae7e7df6237..68ffcb2e975 100644 --- a/crates/ra_hir/Cargo.toml +++ b/crates/ra_hir/Cargo.toml @@ -21,12 +21,9 @@ tt = { path = "../ra_tt", package = "ra_tt" } test_utils = { path = "../test_utils" } ra_prof = { path = "../ra_prof" } -# chalk-solve = { git = "https://github.com/rust-lang/chalk.git" } -# chalk-rust-ir = { git = "https://github.com/rust-lang/chalk.git" } -# chalk-ir = { git = "https://github.com/rust-lang/chalk.git" } -chalk-solve = { git = "https://github.com/detrumi/chalk.git", branch = "program_clauses_that_could_match" } -chalk-rust-ir = { git = "https://github.com/detrumi/chalk.git", branch = "program_clauses_that_could_match" } -chalk-ir = { git = "https://github.com/detrumi/chalk.git", branch = "program_clauses_that_could_match" } +chalk-solve = { git = "https://github.com/rust-lang/chalk.git" } +chalk-rust-ir = { git = "https://github.com/rust-lang/chalk.git" } +chalk-ir = { git = "https://github.com/rust-lang/chalk.git" } [dev-dependencies] flexi_logger = "0.11.0" diff --git a/crates/ra_hir/src/ty/method_resolution.rs b/crates/ra_hir/src/ty/method_resolution.rs index bc5033be6cc..607e9ba7933 100644 --- a/crates/ra_hir/src/ty/method_resolution.rs +++ b/crates/ra_hir/src/ty/method_resolution.rs @@ -202,7 +202,6 @@ fn iterate_trait_method_candidates( } } known_implemented = true; - // TODO the self type is now canonicalized... if let Some(result) = callback(&ty.value, m) { return Some(result); } diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 1adc1d60140..c77db92029a 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -40,9 +40,7 @@ impl ToChalk for Ty { Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), // FIXME this is clearly incorrect, but probably not too incorrect // and I'm not sure what to actually do with Ty::Unknown - Ty::Unknown => { - PlaceholderIndex { ui: UniverseIndex::ROOT, idx: 0 }.to_ty() - }, + Ty::Unknown => PlaceholderIndex { ui: UniverseIndex::ROOT, idx: 0 }.to_ty(), } } fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty) -> Self { @@ -189,7 +187,9 @@ where fundamental: false, }; let where_clauses = Vec::new(); // FIXME add where clauses - let trait_datum_bound = chalk_rust_ir::TraitDatumBound { trait_ref, where_clauses, flags }; + let associated_ty_ids = Vec::new(); // FIXME add associated tys + let trait_datum_bound = + chalk_rust_ir::TraitDatumBound { trait_ref, where_clauses, flags, associated_ty_ids }; let trait_datum = TraitDatum { binders: make_binders(trait_datum_bound, bound_vars.len()) }; Arc::new(trait_datum) } @@ -289,6 +289,15 @@ where debug!("split_projection {:?}", projection); unimplemented!() } + fn custom_clauses(&self) -> Vec { + debug!("custom_clauses"); + vec![] + } + fn all_structs(&self) -> Vec { + debug!("all_structs"); + // FIXME + vec![] + } } fn id_from_chalk(chalk_id: chalk_ir::RawId) -> T { From 621864319f8e3149c08d4d0f99b975407ba00ffd Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Sat, 4 May 2019 15:42:00 +0200 Subject: [PATCH 11/15] Make canonicalization API a bit nicer --- crates/ra_hir/src/ty/infer.rs | 31 ++++++++-------- crates/ra_hir/src/ty/infer/unify.rs | 56 ++++++++++++++++++++--------- 2 files changed, 56 insertions(+), 31 deletions(-) diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs index 41ae569f7b6..cc74c632215 100644 --- a/crates/ra_hir/src/ty/infer.rs +++ b/crates/ra_hir/src/ty/infer.rs @@ -324,23 +324,25 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { fn resolve_obligations_as_possible(&mut self) { let obligations = mem::replace(&mut self.obligations, Vec::new()); for obligation in obligations { - let mut canonicalizer = self.canonicalizer(); - let solution = match &obligation { + let (solution, canonicalized) = match &obligation { Obligation::Trait(tr) => { - let canonical = canonicalizer.canonicalize_trait_ref(tr.clone()); - super::traits::implements( - canonicalizer.ctx.db, - canonicalizer.ctx.resolver.krate().unwrap(), - canonical, + let canonicalized = self.canonicalizer().canonicalize_trait_ref(tr.clone()); + ( + super::traits::implements( + self.db, + self.resolver.krate().unwrap(), + canonicalized.value.clone(), + ), + canonicalized, ) } }; match solution { Some(Solution::Unique(substs)) => { - canonicalizer.apply_solution(substs.0); + canonicalized.apply_solution(self, substs.0); } Some(Solution::Ambig(Guidance::Definite(substs))) => { - canonicalizer.apply_solution(substs.0); + canonicalized.apply_solution(self, substs.0); self.obligations.push(obligation); } Some(_) => { @@ -877,17 +879,16 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { generic_args: Option<&GenericArgs>, ) -> Ty { let receiver_ty = self.infer_expr(receiver, &Expectation::none()); - let mut canonicalizer = self.canonicalizer(); - let canonical_receiver = canonicalizer.canonicalize_ty(receiver_ty.clone()); + let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone()); let resolved = method_resolution::lookup_method( - &canonical_receiver, - canonicalizer.ctx.db, + &canonicalized_receiver.value, + self.db, method_name, - &canonicalizer.ctx.resolver, + &self.resolver, ); let (derefed_receiver_ty, method_ty, def_generics) = match resolved { Some((ty, func)) => { - let ty = canonicalizer.decanonicalize_ty(ty); + let ty = canonicalized_receiver.decanonicalize_ty(ty); self.write_method_resolution(tgt_expr, func); ( ty, diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs index 820a6478952..c9c8959c4a8 100644 --- a/crates/ra_hir/src/ty/infer/unify.rs +++ b/crates/ra_hir/src/ty/infer/unify.rs @@ -13,14 +13,17 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { } } -// TODO improve the interface of this - pub(super) struct Canonicalizer<'a, 'b, D: HirDatabase> where 'a: 'b, { - pub ctx: &'b mut InferenceContext<'a, D>, - pub free_vars: Vec, + ctx: &'b mut InferenceContext<'a, D>, + free_vars: Vec, +} + +pub(super) struct Canonicalized { + pub value: Canonical, + free_vars: Vec, } impl<'a, 'b, D: HirDatabase> Canonicalizer<'a, 'b, D> @@ -35,13 +38,13 @@ where }) } - pub fn canonicalize_ty(&mut self, ty: Ty) -> Canonical { - let value = ty.fold(&mut |ty| match ty { + fn do_canonicalize_ty(&mut self, ty: Ty) -> Ty { + ty.fold(&mut |ty| match ty { Ty::Infer(tv) => { let inner = tv.to_inner(); // TODO prevent infinite loops? => keep var stack if let Some(known_ty) = self.ctx.var_unification_table.probe_value(inner).known() { - self.canonicalize_ty(known_ty.clone()).value + self.do_canonicalize_ty(known_ty.clone()) } else { let free_var = InferTy::TypeVar(self.ctx.var_unification_table.find(inner)); let position = self.add(free_var); @@ -49,20 +52,37 @@ where } } _ => ty, - }); - Canonical { value, num_vars: self.free_vars.len() } + }) } - pub fn canonicalize_trait_ref(&mut self, trait_ref: TraitRef) -> Canonical { + fn do_canonicalize_trait_ref(&mut self, trait_ref: TraitRef) -> TraitRef { let substs = trait_ref .substs .iter() - .map(|ty| self.canonicalize_ty(ty.clone()).value) + .map(|ty| self.do_canonicalize_ty(ty.clone())) .collect::>(); - let value = TraitRef { trait_: trait_ref.trait_, substs: substs.into() }; - Canonical { value, num_vars: self.free_vars.len() } + TraitRef { trait_: trait_ref.trait_, substs: substs.into() } } + fn into_canonicalized(self, result: T) -> Canonicalized { + Canonicalized { + value: Canonical { value: result, num_vars: self.free_vars.len() }, + free_vars: self.free_vars, + } + } + + pub fn canonicalize_ty(mut self, ty: Ty) -> Canonicalized { + let result = self.do_canonicalize_ty(ty); + self.into_canonicalized(result) + } + + pub fn canonicalize_trait_ref(mut self, trait_ref: TraitRef) -> Canonicalized { + let result = self.do_canonicalize_trait_ref(trait_ref); + self.into_canonicalized(result) + } +} + +impl Canonicalized { pub fn decanonicalize_ty(&self, ty: Ty) -> Ty { ty.fold(&mut |ty| match ty { Ty::Bound(idx) => { @@ -76,13 +96,17 @@ where }) } - pub fn apply_solution(&mut self, solution: Canonical>) { + pub fn apply_solution( + &self, + ctx: &mut InferenceContext<'_, impl HirDatabase>, + solution: Canonical>, + ) { // the solution may contain new variables, which we need to convert to new inference vars let new_vars = - (0..solution.num_vars).map(|_| self.ctx.new_type_var()).collect::>().into(); + (0..solution.num_vars).map(|_| ctx.new_type_var()).collect::>().into(); for (i, ty) in solution.value.into_iter().enumerate() { let var = self.free_vars[i].clone(); - self.ctx.unify(&Ty::Infer(var), &ty.subst_bound_vars(&new_vars)); + ctx.unify(&Ty::Infer(var), &ty.subst_bound_vars(&new_vars)); } } } From 5795d773dbcce67577851da02e4d659f0daf1a12 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Sat, 4 May 2019 15:53:23 +0200 Subject: [PATCH 12/15] Remove ToChalk implementation for ApplicationTy --- crates/ra_hir/src/ty/traits/chalk.rs | 45 ++++++++++------------------ 1 file changed, 16 insertions(+), 29 deletions(-) diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index c77db92029a..0c6e5a4f508 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -32,7 +32,12 @@ impl ToChalk for Ty { type Chalk = chalk_ir::Ty; fn to_chalk(self, db: &impl HirDatabase) -> chalk_ir::Ty { match self { - Ty::Apply(apply_ty) => chalk_ir::Ty::Apply(apply_ty.to_chalk(db)), + Ty::Apply(apply_ty) => { + let struct_id = apply_ty.ctor.to_chalk(db); + let name = TypeName::TypeKindId(struct_id.into()); + let parameters = apply_ty.parameters.to_chalk(db); + chalk_ir::ApplicationTy { name, parameters }.cast() + } Ty::Param { idx, .. } => { PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }.to_ty() } @@ -47,8 +52,13 @@ impl ToChalk for Ty { match chalk { chalk_ir::Ty::Apply(apply_ty) => { match apply_ty.name { + TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => { + let ctor = from_chalk(db, struct_id); + let parameters = from_chalk(db, apply_ty.parameters); + Ty::Apply(ApplicationTy { ctor, parameters }) + } // FIXME handle TypeKindId::Trait/Type here - TypeName::TypeKindId(_) => Ty::Apply(from_chalk(db, apply_ty)), + TypeName::TypeKindId(_) => unimplemented!(), TypeName::AssociatedType(_) => unimplemented!(), TypeName::Placeholder(idx) => { assert_eq!(idx.ui, UniverseIndex::ROOT); @@ -65,29 +75,6 @@ impl ToChalk for Ty { } } -// TODO merge this into the ToChalk implementation for Ty -impl ToChalk for ApplicationTy { - type Chalk = chalk_ir::ApplicationTy; - - fn to_chalk(self: ApplicationTy, db: &impl HirDatabase) -> chalk_ir::ApplicationTy { - let struct_id = self.ctor.to_chalk(db); - let name = TypeName::TypeKindId(struct_id.into()); - let parameters = self.parameters.to_chalk(db); - chalk_ir::ApplicationTy { name, parameters } - } - - fn from_chalk(db: &impl HirDatabase, apply_ty: chalk_ir::ApplicationTy) -> ApplicationTy { - let ctor = match apply_ty.name { - TypeName::TypeKindId(TypeKindId::StructId(struct_id)) => from_chalk(db, struct_id), - TypeName::TypeKindId(_) => unimplemented!(), - TypeName::Placeholder(_) => unimplemented!(), - TypeName::AssociatedType(_) => unimplemented!(), - }; - let parameters = from_chalk(db, apply_ty.parameters); - ApplicationTy { ctor, parameters } - } -} - impl ToChalk for Substs { type Chalk = Vec; @@ -221,12 +208,12 @@ where fundamental: false, }; let where_clauses = Vec::new(); // FIXME add where clauses - let ty = ApplicationTy { - ctor: type_ctor, - parameters: (0..num_params).map(|i| Ty::Bound(i as u32)).collect::>().into(), + let self_ty = chalk_ir::ApplicationTy { + name: TypeName::TypeKindId(type_ctor.to_chalk(self.db).into()), + parameters: (0..num_params).map(|i| chalk_ir::Ty::BoundVar(i).cast()).collect(), }; let struct_datum_bound = chalk_rust_ir::StructDatumBound { - self_ty: ty.to_chalk(self.db), + self_ty, fields: Vec::new(), // FIXME add fields (only relevant for auto traits) where_clauses, flags, From f43e69a64eea0caf8b9f5ced31e7f77dc0d33d65 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Sat, 4 May 2019 18:25:07 +0200 Subject: [PATCH 13/15] Handle recursive types in canonicalization --- crates/ra_hir/src/source_binder.rs | 2 +- crates/ra_hir/src/ty/infer/unify.rs | 16 +++++++++++++--- crates/ra_hir/src/ty/traits/chalk.rs | 2 +- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 24350bda7e6..2ec1a769284 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs @@ -351,7 +351,7 @@ impl SourceAnalyzer { callback: impl FnMut(&Ty, Function) -> Option, ) -> Option { // There should be no inference vars in types passed here - // TODO check that? + // FIXME check that? let canonical = crate::ty::Canonical { value: ty, num_vars: 0 }; crate::ty::method_resolution::iterate_method_candidates( &canonical, diff --git a/crates/ra_hir/src/ty/infer/unify.rs b/crates/ra_hir/src/ty/infer/unify.rs index c9c8959c4a8..8ca7e957d33 100644 --- a/crates/ra_hir/src/ty/infer/unify.rs +++ b/crates/ra_hir/src/ty/infer/unify.rs @@ -9,7 +9,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { where 'a: 'b, { - Canonicalizer { ctx: self, free_vars: Vec::new() } + Canonicalizer { ctx: self, free_vars: Vec::new(), var_stack: Vec::new() } } } @@ -19,6 +19,10 @@ where { ctx: &'b mut InferenceContext<'a, D>, free_vars: Vec, + /// A stack of type variables that is used to detect recursive types (which + /// are an error, but we need to protect against them to avoid stack + /// overflows). + var_stack: Vec, } pub(super) struct Canonicalized { @@ -42,9 +46,15 @@ where ty.fold(&mut |ty| match ty { Ty::Infer(tv) => { let inner = tv.to_inner(); - // TODO prevent infinite loops? => keep var stack + if self.var_stack.contains(&inner) { + // recursive type + return tv.fallback_value(); + } if let Some(known_ty) = self.ctx.var_unification_table.probe_value(inner).known() { - self.do_canonicalize_ty(known_ty.clone()) + self.var_stack.push(inner); + let result = self.do_canonicalize_ty(known_ty.clone()); + self.var_stack.pop(); + result } else { let free_var = InferTy::TypeVar(self.ctx.var_unification_table.find(inner)); let position = self.add(free_var); diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 0c6e5a4f508..74370bae973 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -183,7 +183,7 @@ where fn struct_datum(&self, struct_id: chalk_ir::StructId) -> Arc { debug!("struct_datum {:?}", struct_id); let type_ctor = from_chalk(self.db, struct_id); - // TODO might be nicer if we can create a fake GenericParams for the TypeCtor + // FIXME might be nicer if we can create a fake GenericParams for the TypeCtor let (num_params, upstream) = match type_ctor { TypeCtor::Bool | TypeCtor::Char From 19fbd919986e99287168f40aa11003a11aa43d3a Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Sat, 4 May 2019 18:41:48 +0200 Subject: [PATCH 14/15] Simplify subst / subst_bound_vars a bit --- crates/ra_hir/src/ty.rs | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index 6a79af35b91..f2b37b20829 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs @@ -411,11 +411,7 @@ impl Ty { pub fn subst(self, substs: &Substs) -> Ty { self.fold(&mut |ty| match ty { Ty::Param { idx, name } => { - if (idx as usize) < substs.len() { - substs[idx as usize].clone() - } else { - Ty::Param { idx, name } - } + substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name }) } ty => ty, }) @@ -424,13 +420,7 @@ impl Ty { /// Substitutes `Ty::Bound` vars (as opposed to type parameters). pub fn subst_bound_vars(self, substs: &Substs) -> Ty { self.fold(&mut |ty| match ty { - Ty::Bound(idx) => { - if (idx as usize) < substs.len() { - substs[idx as usize].clone() - } else { - Ty::Bound(idx) - } - } + Ty::Bound(idx) => substs.get(idx as usize).cloned().unwrap_or(Ty::Bound(idx)), ty => ty, }) } From a4eb1a546c7623f65823c5e249cd3c6d8c90fd8c Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Sat, 4 May 2019 19:07:25 +0200 Subject: [PATCH 15/15] Differentiate Tuple / FnPtr type constructors by cardinality This is necessary because Chalk (reasonably) expects each 'struct' to know how many type parameters it takes. --- crates/ra_hir/src/ty.rs | 16 +++++++++------- crates/ra_hir/src/ty/infer.rs | 11 +++++++---- crates/ra_hir/src/ty/lower.rs | 7 +++++-- crates/ra_hir/src/ty/traits/chalk.rs | 4 +++- crates/ra_ide_api/src/completion/complete_dot.rs | 2 +- 5 files changed, 25 insertions(+), 15 deletions(-) diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index f2b37b20829..f4eee835f27 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs @@ -82,13 +82,13 @@ pub enum TypeCtor { /// fn foo() -> i32 { 1 } /// let bar: fn() -> i32 = foo; /// ``` - FnPtr, + FnPtr { num_args: u16 }, /// The never type `!`. Never, /// A tuple type. For example, `(i32, bool)`. - Tuple, + Tuple { cardinality: u16 }, } /// A nominal type with (maybe 0) type parameters. This might be a primitive @@ -299,7 +299,7 @@ impl Ty { Ty::Apply(ApplicationTy { ctor, parameters }) } pub fn unit() -> Self { - Ty::apply(TypeCtor::Tuple, Substs::empty()) + Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty()) } pub fn walk(&self, f: &mut impl FnMut(&Ty)) { @@ -352,7 +352,9 @@ impl Ty { pub fn as_tuple(&self) -> Option<&Substs> { match self { - Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple, parameters }) => Some(parameters), + Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => { + Some(parameters) + } _ => None, } } @@ -380,7 +382,7 @@ impl Ty { fn callable_sig(&self, db: &impl HirDatabase) -> Option { match self { Ty::Apply(a_ty) => match a_ty.ctor { - TypeCtor::FnPtr => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)), + TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)), TypeCtor::FnDef(def) => { let sig = db.callable_item_signature(def); Some(sig.subst(&a_ty.parameters)) @@ -466,7 +468,7 @@ impl HirDisplay for ApplicationTy { write!(f, "&{}{}", m.as_keyword_for_ref(), t.display(f.db))?; } TypeCtor::Never => write!(f, "!")?, - TypeCtor::Tuple => { + TypeCtor::Tuple { .. } => { let ts = &self.parameters; if ts.len() == 1 { write!(f, "({},)", ts[0].display(f.db))?; @@ -476,7 +478,7 @@ impl HirDisplay for ApplicationTy { write!(f, ")")?; } } - TypeCtor::FnPtr => { + TypeCtor::FnPtr { .. } => { let sig = FnSig::from_fn_ptr_substs(&self.parameters); write!(f, "fn(")?; f.write_joined(sig.params(), ", ")?; diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs index cc74c632215..edce1afe7f0 100644 --- a/crates/ra_hir/src/ty/infer.rs +++ b/crates/ra_hir/src/ty/infer.rs @@ -739,14 +739,14 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { }; let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); - let inner_tys = args + let inner_tys: Substs = args .iter() .zip(expectations_iter) .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm)) .collect::>() .into(); - Ty::apply(TypeCtor::Tuple, Substs(inner_tys)) + Ty::apply(TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, inner_tys) } Pat::Ref { pat, mutability } => { let expectation = match expected.as_reference() { @@ -1073,7 +1073,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { .autoderef(self.db) .find_map(|derefed_ty| match derefed_ty { Ty::Apply(a_ty) => match a_ty.ctor { - TypeCtor::Tuple => { + TypeCtor::Tuple { .. } => { let i = name.to_string().parse::().ok(); i.and_then(|i| a_ty.parameters.0.get(i).cloned()) } @@ -1184,7 +1184,10 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { ty_vec.push(self.infer_expr(*arg, &Expectation::none())); } - Ty::apply(TypeCtor::Tuple, Substs(ty_vec.into())) + Ty::apply( + TypeCtor::Tuple { cardinality: ty_vec.len() as u16 }, + Substs(ty_vec.into()), + ) } Expr::Array(array) => { let elem_ty = match &expected.ty { diff --git a/crates/ra_hir/src/ty/lower.rs b/crates/ra_hir/src/ty/lower.rs index 2bbd1706878..8bab7e54b89 100644 --- a/crates/ra_hir/src/ty/lower.rs +++ b/crates/ra_hir/src/ty/lower.rs @@ -29,7 +29,10 @@ impl Ty { TypeRef::Tuple(inner) => { let inner_tys = inner.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect::>(); - Ty::apply(TypeCtor::Tuple, Substs(inner_tys.into())) + Ty::apply( + TypeCtor::Tuple { cardinality: inner_tys.len() as u16 }, + Substs(inner_tys.into()), + ) } TypeRef::Path(path) => Ty::from_hir_path(db, resolver, path), TypeRef::RawPtr(inner, mutability) => { @@ -53,7 +56,7 @@ impl Ty { let inner_tys = params.iter().map(|tr| Ty::from_hir(db, resolver, tr)).collect::>(); let sig = Substs(inner_tys.into()); - Ty::apply(TypeCtor::FnPtr, sig) + Ty::apply(TypeCtor::FnPtr { num_args: sig.len() as u16 - 1 }, sig) } TypeRef::Error => Ty::Unknown, } diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 74370bae973..8b77d21b4a3 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -184,6 +184,7 @@ where debug!("struct_datum {:?}", struct_id); let type_ctor = from_chalk(self.db, struct_id); // FIXME might be nicer if we can create a fake GenericParams for the TypeCtor + // FIXME extract this to a method on Ty let (num_params, upstream) = match type_ctor { TypeCtor::Bool | TypeCtor::Char @@ -192,7 +193,8 @@ where | TypeCtor::Never | TypeCtor::Str => (0, true), TypeCtor::Slice | TypeCtor::Array | TypeCtor::RawPtr(_) | TypeCtor::Ref(_) => (1, true), - TypeCtor::FnPtr | TypeCtor::Tuple => unimplemented!(), // FIXME tuples and FnPtr are currently variadic... we need to make the parameter number explicit + TypeCtor::FnPtr { num_args } => (num_args as usize + 1, true), + TypeCtor::Tuple { cardinality } => (cardinality as usize, true), TypeCtor::FnDef(_) => unimplemented!(), TypeCtor::Adt(adt) => { let generic_params = adt.generic_params(self.db); diff --git a/crates/ra_ide_api/src/completion/complete_dot.rs b/crates/ra_ide_api/src/completion/complete_dot.rs index e34ddf24af4..2e808469915 100644 --- a/crates/ra_ide_api/src/completion/complete_dot.rs +++ b/crates/ra_ide_api/src/completion/complete_dot.rs @@ -24,7 +24,7 @@ fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty) } } // FIXME unions - TypeCtor::Tuple => { + TypeCtor::Tuple { .. } => { for (i, ty) in a_ty.parameters.iter().enumerate() { acc.add_pos_field(ctx, i, ty); }