]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/intrinsic.rs
Update compiler error 0093 to use new error format
[rust.git] / src / librustc_typeck / check / intrinsic.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Type-checking for the rust-intrinsic and platform-intrinsic
12 //! intrinsics that the compiler exposes.
13
14 use intrinsics;
15 use rustc::infer::TypeOrigin;
16 use rustc::ty::subst::{self, Substs};
17 use rustc::ty::FnSig;
18 use rustc::ty::{self, Ty};
19 use {CrateCtxt, require_same_types};
20
21 use std::collections::{HashMap};
22 use syntax::abi::Abi;
23 use syntax::ast;
24 use syntax::parse::token;
25 use syntax_pos::Span;
26
27 use rustc::hir;
28
29 fn equate_intrinsic_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
30                                    it: &hir::ForeignItem,
31                                    n_tps: usize,
32                                    abi: Abi,
33                                    inputs: Vec<ty::Ty<'tcx>>,
34                                    output: ty::FnOutput<'tcx>) {
35     let tcx = ccx.tcx;
36     let def_id = tcx.map.local_def_id(it.id);
37     let i_ty = tcx.lookup_item_type(def_id);
38
39     let mut substs = Substs::empty();
40     substs.types = i_ty.generics.types.map(|def| tcx.mk_param_from_def(def));
41
42     let fty = tcx.mk_fn_def(def_id, tcx.mk_substs(substs),
43                             tcx.mk_bare_fn(ty::BareFnTy {
44         unsafety: hir::Unsafety::Unsafe,
45         abi: abi,
46         sig: ty::Binder(FnSig {
47             inputs: inputs,
48             output: output,
49             variadic: false,
50         }),
51     }));
52     let i_n_tps = i_ty.generics.types.len(subst::FnSpace);
53     if i_n_tps != n_tps {
54         span_err!(tcx.sess, it.span, E0094,
55             "intrinsic has wrong number of type \
56              parameters: found {}, expected {}",
57              i_n_tps, n_tps);
58     } else {
59         require_same_types(ccx,
60                            TypeOrigin::IntrinsicType(it.span),
61                            i_ty.ty,
62                            fty);
63     }
64 }
65
66 /// Remember to add all intrinsics here, in librustc_trans/trans/intrinsic.rs,
67 /// and in libcore/intrinsics.rs
68 pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) {
69     fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> {
70         let name = token::intern(&format!("P{}", n));
71         ccx.tcx.mk_param(subst::FnSpace, n, name)
72     }
73
74     let tcx = ccx.tcx;
75     let name = it.name.as_str();
76     let (n_tps, inputs, output) = if name.starts_with("atomic_") {
77         let split : Vec<&str> = name.split('_').collect();
78         assert!(split.len() >= 2, "Atomic intrinsic not correct format");
79
80         //We only care about the operation here
81         let (n_tps, inputs, output) = match split[1] {
82             "cxchg" | "cxchgweak" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)),
83                                               param(ccx, 0),
84                                               param(ccx, 0)),
85                                       tcx.mk_tup(vec!(param(ccx, 0), tcx.types.bool))),
86             "load" => (1, vec!(tcx.mk_imm_ptr(param(ccx, 0))),
87                        param(ccx, 0)),
88             "store" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)),
89                         tcx.mk_nil()),
90
91             "xchg" | "xadd" | "xsub" | "and"  | "nand" | "or" | "xor" | "max" |
92             "min"  | "umax" | "umin" => {
93                 (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)),
94                  param(ccx, 0))
95             }
96             "fence" | "singlethreadfence" => {
97                 (0, Vec::new(), tcx.mk_nil())
98             }
99             op => {
100                 span_err!(tcx.sess, it.span, E0092,
101                     "unrecognized atomic operation function: `{}`", op);
102                 return;
103             }
104         };
105         (n_tps, inputs, ty::FnConverging(output))
106     } else if &name[..] == "abort" || &name[..] == "unreachable" {
107         (0, Vec::new(), ty::FnDiverging)
108     } else {
109         let (n_tps, inputs, output) = match &name[..] {
110             "breakpoint" => (0, Vec::new(), tcx.mk_nil()),
111             "size_of" |
112             "pref_align_of" | "min_align_of" => (1, Vec::new(), ccx.tcx.types.usize),
113             "size_of_val" |  "min_align_of_val" => {
114                 (1, vec![
115                     tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
116                                                                   ty::BrAnon(0))),
117                                     param(ccx, 0))
118                  ], ccx.tcx.types.usize)
119             }
120             "rustc_peek" => (1, vec![param(ccx, 0)], param(ccx, 0)),
121             "init" | "init_dropped" => (1, Vec::new(), param(ccx, 0)),
122             "uninit" => (1, Vec::new(), param(ccx, 0)),
123             "forget" => (1, vec!( param(ccx, 0) ), tcx.mk_nil()),
124             "transmute" => (2, vec!( param(ccx, 0) ), param(ccx, 1)),
125             "move_val_init" => {
126                 (1,
127                  vec!(
128                     tcx.mk_mut_ptr(param(ccx, 0)),
129                     param(ccx, 0)
130                   ),
131                tcx.mk_nil())
132             }
133             "drop_in_place" => {
134                 (1, vec![tcx.mk_mut_ptr(param(ccx, 0))], tcx.mk_nil())
135             }
136             "needs_drop" => (1, Vec::new(), ccx.tcx.types.bool),
137
138             "type_name" => (1, Vec::new(), tcx.mk_static_str()),
139             "type_id" => (1, Vec::new(), ccx.tcx.types.u64),
140             "offset" | "arith_offset" => {
141               (1,
142                vec!(
143                   tcx.mk_ptr(ty::TypeAndMut {
144                       ty: param(ccx, 0),
145                       mutbl: hir::MutImmutable
146                   }),
147                   ccx.tcx.types.isize
148                ),
149                tcx.mk_ptr(ty::TypeAndMut {
150                    ty: param(ccx, 0),
151                    mutbl: hir::MutImmutable
152                }))
153             }
154             "copy" | "copy_nonoverlapping" => {
155               (1,
156                vec!(
157                   tcx.mk_ptr(ty::TypeAndMut {
158                       ty: param(ccx, 0),
159                       mutbl: hir::MutImmutable
160                   }),
161                   tcx.mk_ptr(ty::TypeAndMut {
162                       ty: param(ccx, 0),
163                       mutbl: hir::MutMutable
164                   }),
165                   tcx.types.usize,
166                ),
167                tcx.mk_nil())
168             }
169             "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
170               (1,
171                vec!(
172                   tcx.mk_ptr(ty::TypeAndMut {
173                       ty: param(ccx, 0),
174                       mutbl: hir::MutMutable
175                   }),
176                   tcx.mk_ptr(ty::TypeAndMut {
177                       ty: param(ccx, 0),
178                       mutbl: hir::MutImmutable
179                   }),
180                   tcx.types.usize,
181                ),
182                tcx.mk_nil())
183             }
184             "write_bytes" | "volatile_set_memory" => {
185               (1,
186                vec!(
187                   tcx.mk_ptr(ty::TypeAndMut {
188                       ty: param(ccx, 0),
189                       mutbl: hir::MutMutable
190                   }),
191                   tcx.types.u8,
192                   tcx.types.usize,
193                ),
194                tcx.mk_nil())
195             }
196             "sqrtf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
197             "sqrtf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
198             "powif32" => {
199                (0,
200                 vec!( tcx.types.f32, tcx.types.i32 ),
201                 tcx.types.f32)
202             }
203             "powif64" => {
204                (0,
205                 vec!( tcx.types.f64, tcx.types.i32 ),
206                 tcx.types.f64)
207             }
208             "sinf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
209             "sinf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
210             "cosf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
211             "cosf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
212             "powf32" => {
213                (0,
214                 vec!( tcx.types.f32, tcx.types.f32 ),
215                 tcx.types.f32)
216             }
217             "powf64" => {
218                (0,
219                 vec!( tcx.types.f64, tcx.types.f64 ),
220                 tcx.types.f64)
221             }
222             "expf32"   => (0, vec!( tcx.types.f32 ), tcx.types.f32),
223             "expf64"   => (0, vec!( tcx.types.f64 ), tcx.types.f64),
224             "exp2f32"  => (0, vec!( tcx.types.f32 ), tcx.types.f32),
225             "exp2f64"  => (0, vec!( tcx.types.f64 ), tcx.types.f64),
226             "logf32"   => (0, vec!( tcx.types.f32 ), tcx.types.f32),
227             "logf64"   => (0, vec!( tcx.types.f64 ), tcx.types.f64),
228             "log10f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
229             "log10f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
230             "log2f32"  => (0, vec!( tcx.types.f32 ), tcx.types.f32),
231             "log2f64"  => (0, vec!( tcx.types.f64 ), tcx.types.f64),
232             "fmaf32" => {
233                 (0,
234                  vec!( tcx.types.f32, tcx.types.f32, tcx.types.f32 ),
235                  tcx.types.f32)
236             }
237             "fmaf64" => {
238                 (0,
239                  vec!( tcx.types.f64, tcx.types.f64, tcx.types.f64 ),
240                  tcx.types.f64)
241             }
242             "fabsf32"      => (0, vec!( tcx.types.f32 ), tcx.types.f32),
243             "fabsf64"      => (0, vec!( tcx.types.f64 ), tcx.types.f64),
244             "copysignf32"  => (0, vec!( tcx.types.f32, tcx.types.f32 ), tcx.types.f32),
245             "copysignf64"  => (0, vec!( tcx.types.f64, tcx.types.f64 ), tcx.types.f64),
246             "floorf32"     => (0, vec!( tcx.types.f32 ), tcx.types.f32),
247             "floorf64"     => (0, vec!( tcx.types.f64 ), tcx.types.f64),
248             "ceilf32"      => (0, vec!( tcx.types.f32 ), tcx.types.f32),
249             "ceilf64"      => (0, vec!( tcx.types.f64 ), tcx.types.f64),
250             "truncf32"     => (0, vec!( tcx.types.f32 ), tcx.types.f32),
251             "truncf64"     => (0, vec!( tcx.types.f64 ), tcx.types.f64),
252             "rintf32"      => (0, vec!( tcx.types.f32 ), tcx.types.f32),
253             "rintf64"      => (0, vec!( tcx.types.f64 ), tcx.types.f64),
254             "nearbyintf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
255             "nearbyintf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
256             "roundf32"     => (0, vec!( tcx.types.f32 ), tcx.types.f32),
257             "roundf64"     => (0, vec!( tcx.types.f64 ), tcx.types.f64),
258
259             "volatile_load" =>
260                 (1, vec!( tcx.mk_imm_ptr(param(ccx, 0)) ), param(ccx, 0)),
261             "volatile_store" =>
262                 (1, vec!( tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0) ), tcx.mk_nil()),
263
264             "ctpop" | "ctlz" | "cttz" | "bswap" => (1, vec!(param(ccx, 0)), param(ccx, 0)),
265
266             "add_with_overflow" | "sub_with_overflow"  | "mul_with_overflow" =>
267                 (1, vec!(param(ccx, 0), param(ccx, 0)),
268                 tcx.mk_tup(vec!(param(ccx, 0), tcx.types.bool))),
269
270             "unchecked_div" | "unchecked_rem" =>
271                 (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)),
272
273             "overflowing_add" | "overflowing_sub" | "overflowing_mul" =>
274                 (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)),
275             "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" =>
276                 (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)),
277
278             "assume" => (0, vec![tcx.types.bool], tcx.mk_nil()),
279
280             "discriminant_value" => (1, vec![
281                     tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
282                                                                   ty::BrAnon(0))),
283                                    param(ccx, 0))], tcx.types.u64),
284
285             "try" => {
286                 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
287                 let fn_ty = tcx.mk_bare_fn(ty::BareFnTy {
288                     unsafety: hir::Unsafety::Normal,
289                     abi: Abi::Rust,
290                     sig: ty::Binder(FnSig {
291                         inputs: vec![mut_u8],
292                         output: ty::FnOutput::FnConverging(tcx.mk_nil()),
293                         variadic: false,
294                     }),
295                 });
296                 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
297             }
298
299             ref other => {
300                 struct_span_err!(tcx.sess, it.span, E0093,
301                                 "unrecognized intrinsic function: `{}`",
302                                 *other)
303                                 .span_label(it.span, &format!("unrecognized intrinsic"))
304                                 .emit();
305                 return;
306             }
307         };
308         (n_tps, inputs, ty::FnConverging(output))
309     };
310     equate_intrinsic_type(ccx, it, n_tps, Abi::RustIntrinsic, inputs, output)
311 }
312
313 /// Type-check `extern "platform-intrinsic" { ... }` functions.
314 pub fn check_platform_intrinsic_type(ccx: &CrateCtxt,
315                                      it: &hir::ForeignItem) {
316     let param = |n| {
317         let name = token::intern(&format!("P{}", n));
318         ccx.tcx.mk_param(subst::FnSpace, n, name)
319     };
320
321     let tcx = ccx.tcx;
322     let i_ty = tcx.lookup_item_type(tcx.map.local_def_id(it.id));
323     let i_n_tps = i_ty.generics.types.len(subst::FnSpace);
324     let name = it.name.as_str();
325
326     let (n_tps, inputs, output) = match &*name {
327         "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
328             (2, vec![param(0), param(0)], param(1))
329         }
330         "simd_add" | "simd_sub" | "simd_mul" |
331         "simd_div" | "simd_shl" | "simd_shr" |
332         "simd_and" | "simd_or" | "simd_xor" => {
333             (1, vec![param(0), param(0)], param(0))
334         }
335         "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
336         "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
337         "simd_cast" => (2, vec![param(0)], param(1)),
338         name if name.starts_with("simd_shuffle") => {
339             match name["simd_shuffle".len()..].parse() {
340                 Ok(n) => {
341                     let params = vec![param(0), param(0),
342                                       tcx.mk_ty(ty::TyArray(tcx.types.u32, n))];
343                     (2, params, param(1))
344                 }
345                 Err(_) => {
346                     span_err!(tcx.sess, it.span, E0439,
347                               "invalid `simd_shuffle`, needs length: `{}`", name);
348                     return
349                 }
350             }
351         }
352         _ => {
353             match intrinsics::Intrinsic::find(&name) {
354                 Some(intr) => {
355                     // this function is a platform specific intrinsic
356                     if i_n_tps != 0 {
357                         span_err!(tcx.sess, it.span, E0440,
358                                   "platform-specific intrinsic has wrong number of type \
359                                    parameters: found {}, expected 0",
360                                   i_n_tps);
361                         return
362                     }
363
364                     let mut structural_to_nomimal = HashMap::new();
365
366                     let sig = tcx.no_late_bound_regions(i_ty.ty.fn_sig()).unwrap();
367                     if intr.inputs.len() != sig.inputs.len() {
368                         span_err!(tcx.sess, it.span, E0444,
369                                   "platform-specific intrinsic has invalid number of \
370                                    arguments: found {}, expected {}",
371                                   intr.inputs.len(), sig.inputs.len());
372                         return
373                     }
374                     let input_pairs = intr.inputs.iter().zip(&sig.inputs);
375                     for (i, (expected_arg, arg)) in input_pairs.enumerate() {
376                         match_intrinsic_type_to_type(ccx, &format!("argument {}", i + 1), it.span,
377                                                      &mut structural_to_nomimal, expected_arg, arg);
378                     }
379                     match_intrinsic_type_to_type(ccx, "return value", it.span,
380                                                  &mut structural_to_nomimal,
381                                                  &intr.output, sig.output.unwrap());
382                     return
383                 }
384                 None => {
385                     span_err!(tcx.sess, it.span, E0441,
386                               "unrecognized platform-specific intrinsic function: `{}`", name);
387                     return;
388                 }
389             }
390         }
391     };
392
393     equate_intrinsic_type(ccx, it, n_tps, Abi::PlatformIntrinsic,
394                           inputs, ty::FnConverging(output))
395 }
396
397 // walk the expected type and the actual type in lock step, checking they're
398 // the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with
399 // exactly the right element type
400 fn match_intrinsic_type_to_type<'tcx, 'a>(
401         ccx: &CrateCtxt<'a, 'tcx>,
402         position: &str,
403         span: Span,
404         structural_to_nominal: &mut HashMap<&'a intrinsics::Type, ty::Ty<'tcx>>,
405         expected: &'a intrinsics::Type, t: ty::Ty<'tcx>)
406 {
407     use intrinsics::Type::*;
408
409     let simple_error = |real: &str, expected: &str| {
410         span_err!(ccx.tcx.sess, span, E0442,
411                   "intrinsic {} has wrong type: found {}, expected {}",
412                   position, real, expected)
413     };
414
415     match *expected {
416         Void => match t.sty {
417             ty::TyTuple(ref v) if v.is_empty() => {},
418             _ => simple_error(&format!("`{}`", t), "()"),
419         },
420         // (The width we pass to LLVM doesn't concern the type checker.)
421         Integer(signed, bits, _llvm_width) => match (signed, bits, &t.sty) {
422             (true,  8,  &ty::TyInt(ast::IntTy::I8)) |
423             (false, 8,  &ty::TyUint(ast::UintTy::U8)) |
424             (true,  16, &ty::TyInt(ast::IntTy::I16)) |
425             (false, 16, &ty::TyUint(ast::UintTy::U16)) |
426             (true,  32, &ty::TyInt(ast::IntTy::I32)) |
427             (false, 32, &ty::TyUint(ast::UintTy::U32)) |
428             (true,  64, &ty::TyInt(ast::IntTy::I64)) |
429             (false, 64, &ty::TyUint(ast::UintTy::U64)) => {},
430             _ => simple_error(&format!("`{}`", t),
431                               &format!("`{}{n}`",
432                                        if signed {"i"} else {"u"},
433                                        n = bits)),
434         },
435         Float(bits) => match (bits, &t.sty) {
436             (32, &ty::TyFloat(ast::FloatTy::F32)) |
437             (64, &ty::TyFloat(ast::FloatTy::F64)) => {},
438             _ => simple_error(&format!("`{}`", t),
439                               &format!("`f{n}`", n = bits)),
440         },
441         Pointer(ref inner_expected, ref _llvm_type, const_) => {
442             match t.sty {
443                 ty::TyRawPtr(ty::TypeAndMut { ty, mutbl }) => {
444                     if (mutbl == hir::MutImmutable) != const_ {
445                         simple_error(&format!("`{}`", t),
446                                      if const_ {"const pointer"} else {"mut pointer"})
447                     }
448                     match_intrinsic_type_to_type(ccx, position, span, structural_to_nominal,
449                                                  inner_expected, ty)
450                 }
451                 _ => simple_error(&format!("`{}`", t), "raw pointer"),
452             }
453         }
454         Vector(ref inner_expected, ref _llvm_type, len) => {
455             if !t.is_simd() {
456                 simple_error(&format!("non-simd type `{}`", t), "simd type");
457                 return;
458             }
459             let t_len = t.simd_size(ccx.tcx);
460             if len as usize != t_len {
461                 simple_error(&format!("vector with length {}", t_len),
462                              &format!("length {}", len));
463                 return;
464             }
465             let t_ty = t.simd_type(ccx.tcx);
466             {
467                 // check that a given structural type always has the same an intrinsic definition
468                 let previous = structural_to_nominal.entry(expected).or_insert(t);
469                 if *previous != t {
470                     // this gets its own error code because it is non-trivial
471                     span_err!(ccx.tcx.sess, span, E0443,
472                               "intrinsic {} has wrong type: found `{}`, expected `{}` which \
473                                was used for this vector type previously in this signature",
474                               position,
475                               t,
476                               *previous);
477                     return;
478                 }
479             }
480             match_intrinsic_type_to_type(ccx,
481                                          position,
482                                          span,
483                                          structural_to_nominal,
484                                          inner_expected,
485                                          t_ty)
486         }
487         Aggregate(_flatten, ref expected_contents) => {
488             match t.sty {
489                 ty::TyTuple(contents) => {
490                     if contents.len() != expected_contents.len() {
491                         simple_error(&format!("tuple with length {}", contents.len()),
492                                      &format!("tuple with length {}", expected_contents.len()));
493                         return
494                     }
495                     for (e, c) in expected_contents.iter().zip(contents) {
496                         match_intrinsic_type_to_type(ccx, position, span, structural_to_nominal,
497                                                      e, c)
498                     }
499                 }
500                 _ => simple_error(&format!("`{}`", t),
501                                   &format!("tuple")),
502             }
503         }
504     }
505 }