]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/op.rs
Auto merge of #49313 - sgrif:sg-revert-stuff, r=nikomatsakis
[rust.git] / src / librustc_typeck / check / op.rs
1 // Copyright 2014 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 //! Code related to processing overloaded binary and unary operators.
12
13 use super::{FnCtxt, Needs};
14 use super::method::MethodCallee;
15 use rustc::ty::{self, Ty, TypeFoldable, TypeVariants};
16 use rustc::ty::TypeVariants::{TyStr, TyRef, TyAdt};
17 use rustc::ty::adjustment::{Adjustment, Adjust, AutoBorrow, AutoBorrowMutability};
18 use rustc::infer::type_variable::TypeVariableOrigin;
19 use errors;
20 use syntax_pos::Span;
21 use syntax::symbol::Symbol;
22 use rustc::hir;
23
24 impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
25     /// Check a `a <op>= b`
26     pub fn check_binop_assign(&self,
27                               expr: &'gcx hir::Expr,
28                               op: hir::BinOp,
29                               lhs_expr: &'gcx hir::Expr,
30                               rhs_expr: &'gcx hir::Expr) -> Ty<'tcx>
31     {
32         let (lhs_ty, rhs_ty, return_ty) =
33             self.check_overloaded_binop(expr, lhs_expr, rhs_expr, op, IsAssign::Yes);
34
35         let ty = if !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var()
36                     && is_builtin_binop(lhs_ty, rhs_ty, op) {
37             self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
38             self.tcx.mk_nil()
39         } else {
40             return_ty
41         };
42
43         if !self.is_place_expr(lhs_expr) {
44             struct_span_err!(
45                 self.tcx.sess, lhs_expr.span,
46                 E0067, "invalid left-hand side expression")
47             .span_label(
48                 lhs_expr.span,
49                 "invalid expression for left-hand side")
50             .emit();
51         }
52         ty
53     }
54
55     /// Check a potentially overloaded binary operator.
56     pub fn check_binop(&self,
57                        expr: &'gcx hir::Expr,
58                        op: hir::BinOp,
59                        lhs_expr: &'gcx hir::Expr,
60                        rhs_expr: &'gcx hir::Expr) -> Ty<'tcx>
61     {
62         let tcx = self.tcx;
63
64         debug!("check_binop(expr.id={}, expr={:?}, op={:?}, lhs_expr={:?}, rhs_expr={:?})",
65                expr.id,
66                expr,
67                op,
68                lhs_expr,
69                rhs_expr);
70
71         match BinOpCategory::from(op) {
72             BinOpCategory::Shortcircuit => {
73                 // && and || are a simple case.
74                 self.check_expr_coercable_to_type(lhs_expr, tcx.types.bool);
75                 let lhs_diverges = self.diverges.get();
76                 self.check_expr_coercable_to_type(rhs_expr, tcx.types.bool);
77
78                 // Depending on the LHS' value, the RHS can never execute.
79                 self.diverges.set(lhs_diverges);
80
81                 tcx.types.bool
82             }
83             _ => {
84                 // Otherwise, we always treat operators as if they are
85                 // overloaded. This is the way to be most flexible w/r/t
86                 // types that get inferred.
87                 let (lhs_ty, rhs_ty, return_ty) =
88                     self.check_overloaded_binop(expr, lhs_expr,
89                                                 rhs_expr, op, IsAssign::No);
90
91                 // Supply type inference hints if relevant. Probably these
92                 // hints should be enforced during select as part of the
93                 // `consider_unification_despite_ambiguity` routine, but this
94                 // more convenient for now.
95                 //
96                 // The basic idea is to help type inference by taking
97                 // advantage of things we know about how the impls for
98                 // scalar types are arranged. This is important in a
99                 // scenario like `1_u32 << 2`, because it lets us quickly
100                 // deduce that the result type should be `u32`, even
101                 // though we don't know yet what type 2 has and hence
102                 // can't pin this down to a specific impl.
103                 if
104                     !lhs_ty.is_ty_var() && !rhs_ty.is_ty_var() &&
105                     is_builtin_binop(lhs_ty, rhs_ty, op)
106                 {
107                     let builtin_return_ty =
108                         self.enforce_builtin_binop_types(lhs_expr, lhs_ty, rhs_expr, rhs_ty, op);
109                     self.demand_suptype(expr.span, builtin_return_ty, return_ty);
110                 }
111
112                 return_ty
113             }
114         }
115     }
116
117     fn enforce_builtin_binop_types(&self,
118                                    lhs_expr: &'gcx hir::Expr,
119                                    lhs_ty: Ty<'tcx>,
120                                    rhs_expr: &'gcx hir::Expr,
121                                    rhs_ty: Ty<'tcx>,
122                                    op: hir::BinOp)
123                                    -> Ty<'tcx>
124     {
125         debug_assert!(is_builtin_binop(lhs_ty, rhs_ty, op));
126
127         let tcx = self.tcx;
128         match BinOpCategory::from(op) {
129             BinOpCategory::Shortcircuit => {
130                 self.demand_suptype(lhs_expr.span, tcx.mk_bool(), lhs_ty);
131                 self.demand_suptype(rhs_expr.span, tcx.mk_bool(), rhs_ty);
132                 tcx.mk_bool()
133             }
134
135             BinOpCategory::Shift => {
136                 // result type is same as LHS always
137                 lhs_ty
138             }
139
140             BinOpCategory::Math |
141             BinOpCategory::Bitwise => {
142                 // both LHS and RHS and result will have the same type
143                 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
144                 lhs_ty
145             }
146
147             BinOpCategory::Comparison => {
148                 // both LHS and RHS and result will have the same type
149                 self.demand_suptype(rhs_expr.span, lhs_ty, rhs_ty);
150                 tcx.mk_bool()
151             }
152         }
153     }
154
155     fn check_overloaded_binop(&self,
156                               expr: &'gcx hir::Expr,
157                               lhs_expr: &'gcx hir::Expr,
158                               rhs_expr: &'gcx hir::Expr,
159                               op: hir::BinOp,
160                               is_assign: IsAssign)
161                               -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>)
162     {
163         debug!("check_overloaded_binop(expr.id={}, op={:?}, is_assign={:?})",
164                expr.id,
165                op,
166                is_assign);
167
168         let lhs_needs = match is_assign {
169             IsAssign::Yes => Needs::MutPlace,
170             IsAssign::No => Needs::None
171         };
172         // Find a suitable supertype of the LHS expression's type, by coercing to
173         // a type variable, to pass as the `Self` to the trait, avoiding invariant
174         // trait matching creating lifetime constraints that are too strict.
175         // E.g. adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result
176         // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`.
177         let lhs_ty = self.check_expr_coercable_to_type_with_needs(lhs_expr,
178             self.next_ty_var(TypeVariableOrigin::MiscVariable(lhs_expr.span)),
179             lhs_needs);
180         let lhs_ty = self.resolve_type_vars_with_obligations(lhs_ty);
181
182         // NB: As we have not yet type-checked the RHS, we don't have the
183         // type at hand. Make a variable to represent it. The whole reason
184         // for this indirection is so that, below, we can check the expr
185         // using this variable as the expected type, which sometimes lets
186         // us do better coercions than we would be able to do otherwise,
187         // particularly for things like `String + &String`.
188         let rhs_ty_var = self.next_ty_var(TypeVariableOrigin::MiscVariable(rhs_expr.span));
189
190         let result = self.lookup_op_method(lhs_ty, &[rhs_ty_var], Op::Binary(op, is_assign));
191
192         // see `NB` above
193         let rhs_ty = self.check_expr_coercable_to_type(rhs_expr, rhs_ty_var);
194         let rhs_ty = self.resolve_type_vars_with_obligations(rhs_ty);
195
196         let return_ty = match result {
197             Ok(method) => {
198                 let by_ref_binop = !op.node.is_by_value();
199                 if is_assign == IsAssign::Yes || by_ref_binop {
200                     if let ty::TyRef(region, mt) = method.sig.inputs()[0].sty {
201                         let mutbl = match mt.mutbl {
202                             hir::MutImmutable => AutoBorrowMutability::Immutable,
203                             hir::MutMutable => AutoBorrowMutability::Mutable {
204                                 // Allow two-phase borrows for binops in initial deployment
205                                 // since they desugar to methods
206                                 allow_two_phase_borrow: true,
207                             }
208                         };
209                         let autoref = Adjustment {
210                             kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
211                             target: method.sig.inputs()[0]
212                         };
213                         self.apply_adjustments(lhs_expr, vec![autoref]);
214                     }
215                 }
216                 if by_ref_binop {
217                     if let ty::TyRef(region, mt) = method.sig.inputs()[1].sty {
218                         let mutbl = match mt.mutbl {
219                             hir::MutImmutable => AutoBorrowMutability::Immutable,
220                             hir::MutMutable => AutoBorrowMutability::Mutable {
221                                 // Allow two-phase borrows for binops in initial deployment
222                                 // since they desugar to methods
223                                 allow_two_phase_borrow: true,
224                             }
225                         };
226                         let autoref = Adjustment {
227                             kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)),
228                             target: method.sig.inputs()[1]
229                         };
230                         // HACK(eddyb) Bypass checks due to reborrows being in
231                         // some cases applied on the RHS, on top of which we need
232                         // to autoref, which is not allowed by apply_adjustments.
233                         // self.apply_adjustments(rhs_expr, vec![autoref]);
234                         self.tables
235                             .borrow_mut()
236                             .adjustments_mut()
237                             .entry(rhs_expr.hir_id)
238                             .or_insert(vec![])
239                             .push(autoref);
240                     }
241                 }
242                 self.write_method_call(expr.hir_id, method);
243
244                 method.sig.output()
245             }
246             Err(()) => {
247                 // error types are considered "builtin"
248                 if !lhs_ty.references_error() {
249                     if let IsAssign::Yes = is_assign {
250                         struct_span_err!(self.tcx.sess, expr.span, E0368,
251                                          "binary assignment operation `{}=` \
252                                           cannot be applied to type `{}`",
253                                          op.node.as_str(),
254                                          lhs_ty)
255                             .span_label(lhs_expr.span,
256                                         format!("cannot use `{}=` on type `{}`",
257                                         op.node.as_str(), lhs_ty))
258                             .emit();
259                     } else {
260                         let mut err = struct_span_err!(self.tcx.sess, expr.span, E0369,
261                             "binary operation `{}` cannot be applied to type `{}`",
262                             op.node.as_str(),
263                             lhs_ty);
264
265                         if let TypeVariants::TyRef(_, ref ty_mut) = lhs_ty.sty {
266                             if {
267                                 !self.infcx.type_moves_by_default(self.param_env,
268                                                                   ty_mut.ty,
269                                                                   lhs_expr.span) &&
270                                     self.lookup_op_method(ty_mut.ty,
271                                                           &[rhs_ty],
272                                                           Op::Binary(op, is_assign))
273                                         .is_ok()
274                             } {
275                                 err.note(
276                                     &format!(
277                                         "this is a reference to a type that `{}` can be applied \
278                                         to; you need to dereference this variable once for this \
279                                         operation to work",
280                                     op.node.as_str()));
281                             }
282                         }
283
284                         let missing_trait = match op.node {
285                             hir::BiAdd    => Some("std::ops::Add"),
286                             hir::BiSub    => Some("std::ops::Sub"),
287                             hir::BiMul    => Some("std::ops::Mul"),
288                             hir::BiDiv    => Some("std::ops::Div"),
289                             hir::BiRem    => Some("std::ops::Rem"),
290                             hir::BiBitAnd => Some("std::ops::BitAnd"),
291                             hir::BiBitOr  => Some("std::ops::BitOr"),
292                             hir::BiShl    => Some("std::ops::Shl"),
293                             hir::BiShr    => Some("std::ops::Shr"),
294                             hir::BiEq | hir::BiNe => Some("std::cmp::PartialEq"),
295                             hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe =>
296                                 Some("std::cmp::PartialOrd"),
297                             _             => None
298                         };
299
300                         if let Some(missing_trait) = missing_trait {
301                             if missing_trait == "std::ops::Add" &&
302                                 self.check_str_addition(expr, lhs_expr, rhs_expr, lhs_ty,
303                                                         rhs_ty, &mut err) {
304                                 // This has nothing here because it means we did string
305                                 // concatenation (e.g. "Hello " + "World!"). This means
306                                 // we don't want the note in the else clause to be emitted
307                             } else if let ty::TyParam(_) = lhs_ty.sty {
308                                 // FIXME: point to span of param
309                                 err.note(
310                                     &format!("`{}` might need a bound for `{}`",
311                                              lhs_ty, missing_trait));
312                             } else {
313                                 err.note(
314                                     &format!("an implementation of `{}` might be missing for `{}`",
315                                              missing_trait, lhs_ty));
316                             }
317                         }
318                         err.emit();
319                     }
320                 }
321                 self.tcx.types.err
322             }
323         };
324
325         (lhs_ty, rhs_ty, return_ty)
326     }
327
328     fn check_str_addition(&self,
329                           expr: &'gcx hir::Expr,
330                           lhs_expr: &'gcx hir::Expr,
331                           rhs_expr: &'gcx hir::Expr,
332                           lhs_ty: Ty<'tcx>,
333                           rhs_ty: Ty<'tcx>,
334                           err: &mut errors::DiagnosticBuilder) -> bool {
335         let codemap = self.tcx.sess.codemap();
336         let msg = "`to_owned()` can be used to create an owned `String` \
337                    from a string reference. String concatenation \
338                    appends the string on the right to the string \
339                    on the left and may require reallocation. This \
340                    requires ownership of the string on the left";
341         // If this function returns true it means a note was printed, so we don't need
342         // to print the normal "implementation of `std::ops::Add` might be missing" note
343         match (&lhs_ty.sty, &rhs_ty.sty) {
344             (&TyRef(_, ref l_ty), &TyRef(_, ref r_ty))
345             if l_ty.ty.sty == TyStr && r_ty.ty.sty == TyStr => {
346                 err.span_label(expr.span,
347                     "`+` can't be used to concatenate two `&str` strings");
348                 match codemap.span_to_snippet(lhs_expr.span) {
349                     Ok(lstring) => err.span_suggestion(lhs_expr.span,
350                                                        msg,
351                                                        format!("{}.to_owned()", lstring)),
352                     _ => err.help(msg),
353                 };
354                 true
355             }
356             (&TyRef(_, ref l_ty), &TyAdt(..))
357             if l_ty.ty.sty == TyStr && &format!("{:?}", rhs_ty) == "std::string::String" => {
358                 err.span_label(expr.span,
359                     "`+` can't be used to concatenate a `&str` with a `String`");
360                 match codemap.span_to_snippet(lhs_expr.span) {
361                     Ok(lstring) => err.span_suggestion(lhs_expr.span,
362                                                        msg,
363                                                        format!("{}.to_owned()", lstring)),
364                     _ => err.help(msg),
365                 };
366                 match codemap.span_to_snippet(rhs_expr.span) {
367                     Ok(rstring) => {
368                         err.span_suggestion(rhs_expr.span,
369                                             "you also need to borrow the `String` on the right to \
370                                              get a `&str`",
371                                             format!("&{}", rstring));
372                     }
373                     _ => {}
374                 };
375                 true
376             }
377             _ => false,
378         }
379     }
380
381     pub fn check_user_unop(&self,
382                            ex: &'gcx hir::Expr,
383                            operand_ty: Ty<'tcx>,
384                            op: hir::UnOp)
385                            -> Ty<'tcx>
386     {
387         assert!(op.is_by_value());
388         match self.lookup_op_method(operand_ty, &[], Op::Unary(op, ex.span)) {
389             Ok(method) => {
390                 self.write_method_call(ex.hir_id, method);
391                 method.sig.output()
392             }
393             Err(()) => {
394                 let actual = self.resolve_type_vars_if_possible(&operand_ty);
395                 if !actual.references_error() {
396                     struct_span_err!(self.tcx.sess, ex.span, E0600,
397                                      "cannot apply unary operator `{}` to type `{}`",
398                                      op.as_str(), actual).emit();
399                 }
400                 self.tcx.types.err
401             }
402         }
403     }
404
405     fn lookup_op_method(&self, lhs_ty: Ty<'tcx>, other_tys: &[Ty<'tcx>], op: Op)
406                         -> Result<MethodCallee<'tcx>, ()>
407     {
408         let lang = self.tcx.lang_items();
409
410         let span = match op {
411             Op::Binary(op, _) => op.span,
412             Op::Unary(_, span) => span
413         };
414         let (opname, trait_did) = if let Op::Binary(op, IsAssign::Yes) = op {
415             match op.node {
416                 hir::BiAdd => ("add_assign", lang.add_assign_trait()),
417                 hir::BiSub => ("sub_assign", lang.sub_assign_trait()),
418                 hir::BiMul => ("mul_assign", lang.mul_assign_trait()),
419                 hir::BiDiv => ("div_assign", lang.div_assign_trait()),
420                 hir::BiRem => ("rem_assign", lang.rem_assign_trait()),
421                 hir::BiBitXor => ("bitxor_assign", lang.bitxor_assign_trait()),
422                 hir::BiBitAnd => ("bitand_assign", lang.bitand_assign_trait()),
423                 hir::BiBitOr => ("bitor_assign", lang.bitor_assign_trait()),
424                 hir::BiShl => ("shl_assign", lang.shl_assign_trait()),
425                 hir::BiShr => ("shr_assign", lang.shr_assign_trait()),
426                 hir::BiLt | hir::BiLe |
427                 hir::BiGe | hir::BiGt |
428                 hir::BiEq | hir::BiNe |
429                 hir::BiAnd | hir::BiOr => {
430                     span_bug!(span,
431                               "impossible assignment operation: {}=",
432                               op.node.as_str())
433                 }
434             }
435         } else if let Op::Binary(op, IsAssign::No) = op {
436             match op.node {
437                 hir::BiAdd => ("add", lang.add_trait()),
438                 hir::BiSub => ("sub", lang.sub_trait()),
439                 hir::BiMul => ("mul", lang.mul_trait()),
440                 hir::BiDiv => ("div", lang.div_trait()),
441                 hir::BiRem => ("rem", lang.rem_trait()),
442                 hir::BiBitXor => ("bitxor", lang.bitxor_trait()),
443                 hir::BiBitAnd => ("bitand", lang.bitand_trait()),
444                 hir::BiBitOr => ("bitor", lang.bitor_trait()),
445                 hir::BiShl => ("shl", lang.shl_trait()),
446                 hir::BiShr => ("shr", lang.shr_trait()),
447                 hir::BiLt => ("lt", lang.partial_ord_trait()),
448                 hir::BiLe => ("le", lang.partial_ord_trait()),
449                 hir::BiGe => ("ge", lang.partial_ord_trait()),
450                 hir::BiGt => ("gt", lang.partial_ord_trait()),
451                 hir::BiEq => ("eq", lang.eq_trait()),
452                 hir::BiNe => ("ne", lang.eq_trait()),
453                 hir::BiAnd | hir::BiOr => {
454                     span_bug!(span, "&& and || are not overloadable")
455                 }
456             }
457         } else if let Op::Unary(hir::UnNot, _) = op {
458             ("not", lang.not_trait())
459         } else if let Op::Unary(hir::UnNeg, _) = op {
460             ("neg", lang.neg_trait())
461         } else {
462             bug!("lookup_op_method: op not supported: {:?}", op)
463         };
464
465         debug!("lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})",
466                lhs_ty,
467                op,
468                opname,
469                trait_did);
470
471         let method = trait_did.and_then(|trait_did| {
472             let opname = Symbol::intern(opname);
473             self.lookup_method_in_trait(span, opname, trait_did, lhs_ty, Some(other_tys))
474         });
475
476         match method {
477             Some(ok) => {
478                 let method = self.register_infer_ok_obligations(ok);
479                 self.select_obligations_where_possible(false);
480
481                 Ok(method)
482             }
483             None => {
484                 Err(())
485             }
486         }
487     }
488 }
489
490 // Binary operator categories. These categories summarize the behavior
491 // with respect to the builtin operationrs supported.
492 enum BinOpCategory {
493     /// &&, || -- cannot be overridden
494     Shortcircuit,
495
496     /// <<, >> -- when shifting a single integer, rhs can be any
497     /// integer type. For simd, types must match.
498     Shift,
499
500     /// +, -, etc -- takes equal types, produces same type as input,
501     /// applicable to ints/floats/simd
502     Math,
503
504     /// &, |, ^ -- takes equal types, produces same type as input,
505     /// applicable to ints/floats/simd/bool
506     Bitwise,
507
508     /// ==, !=, etc -- takes equal types, produces bools, except for simd,
509     /// which produce the input type
510     Comparison,
511 }
512
513 impl BinOpCategory {
514     fn from(op: hir::BinOp) -> BinOpCategory {
515         match op.node {
516             hir::BiShl | hir::BiShr =>
517                 BinOpCategory::Shift,
518
519             hir::BiAdd |
520             hir::BiSub |
521             hir::BiMul |
522             hir::BiDiv |
523             hir::BiRem =>
524                 BinOpCategory::Math,
525
526             hir::BiBitXor |
527             hir::BiBitAnd |
528             hir::BiBitOr =>
529                 BinOpCategory::Bitwise,
530
531             hir::BiEq |
532             hir::BiNe |
533             hir::BiLt |
534             hir::BiLe |
535             hir::BiGe |
536             hir::BiGt =>
537                 BinOpCategory::Comparison,
538
539             hir::BiAnd |
540             hir::BiOr =>
541                 BinOpCategory::Shortcircuit,
542         }
543     }
544 }
545
546 /// Whether the binary operation is an assignment (`a += b`), or not (`a + b`)
547 #[derive(Clone, Copy, Debug, PartialEq)]
548 enum IsAssign {
549     No,
550     Yes,
551 }
552
553 #[derive(Clone, Copy, Debug)]
554 enum Op {
555     Binary(hir::BinOp, IsAssign),
556     Unary(hir::UnOp, Span),
557 }
558
559 /// Returns true if this is a built-in arithmetic operation (e.g. u32
560 /// + u32, i16x4 == i16x4) and false if these types would have to be
561 /// overloaded to be legal. There are two reasons that we distinguish
562 /// builtin operations from overloaded ones (vs trying to drive
563 /// everything uniformly through the trait system and intrinsics or
564 /// something like that):
565 ///
566 /// 1. Builtin operations can trivially be evaluated in constants.
567 /// 2. For comparison operators applied to SIMD types the result is
568 ///    not of type `bool`. For example, `i16x4==i16x4` yields a
569 ///    type like `i16x4`. This means that the overloaded trait
570 ///    `PartialEq` is not applicable.
571 ///
572 /// Reason #2 is the killer. I tried for a while to always use
573 /// overloaded logic and just check the types in constants/trans after
574 /// the fact, and it worked fine, except for SIMD types. -nmatsakis
575 fn is_builtin_binop(lhs: Ty, rhs: Ty, op: hir::BinOp) -> bool {
576     match BinOpCategory::from(op) {
577         BinOpCategory::Shortcircuit => {
578             true
579         }
580
581         BinOpCategory::Shift => {
582             lhs.references_error() || rhs.references_error() ||
583                 lhs.is_integral() && rhs.is_integral()
584         }
585
586         BinOpCategory::Math => {
587             lhs.references_error() || rhs.references_error() ||
588                 lhs.is_integral() && rhs.is_integral() ||
589                 lhs.is_floating_point() && rhs.is_floating_point()
590         }
591
592         BinOpCategory::Bitwise => {
593             lhs.references_error() || rhs.references_error() ||
594                 lhs.is_integral() && rhs.is_integral() ||
595                 lhs.is_floating_point() && rhs.is_floating_point() ||
596                 lhs.is_bool() && rhs.is_bool()
597         }
598
599         BinOpCategory::Comparison => {
600             lhs.references_error() || rhs.references_error() ||
601                 lhs.is_scalar() && rhs.is_scalar()
602         }
603     }
604 }