c2rust-transpile 0.22.1

C2Rust transpiler implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//! This module provides translations of unary and binary operator expressions.

use super::*;

fn neg_expr(arg: Box<Expr>) -> Box<Expr> {
    mk().unary_expr(UnOp::Neg(Default::default()), arg)
}

fn wrapping_neg_expr(arg: Box<Expr>) -> Box<Expr> {
    mk().method_call_expr(arg, "wrapping_neg", vec![])
}

impl From<c_ast::BinOp> for BinOp {
    fn from(op: c_ast::BinOp) -> Self {
        match op {
            c_ast::BinOp::Multiply => BinOp::Mul(Default::default()),
            c_ast::BinOp::Divide => BinOp::Div(Default::default()),
            c_ast::BinOp::Modulus => BinOp::Rem(Default::default()),
            c_ast::BinOp::Add => BinOp::Add(Default::default()),
            c_ast::BinOp::Subtract => BinOp::Sub(Default::default()),
            c_ast::BinOp::ShiftLeft => BinOp::Shl(Default::default()),
            c_ast::BinOp::ShiftRight => BinOp::Shr(Default::default()),
            c_ast::BinOp::Less => BinOp::Lt(Default::default()),
            c_ast::BinOp::Greater => BinOp::Gt(Default::default()),
            c_ast::BinOp::LessEqual => BinOp::Le(Default::default()),
            c_ast::BinOp::GreaterEqual => BinOp::Ge(Default::default()),
            c_ast::BinOp::EqualEqual => BinOp::Eq(Default::default()),
            c_ast::BinOp::NotEqual => BinOp::Ne(Default::default()),
            c_ast::BinOp::BitAnd => BinOp::BitAnd(Default::default()),
            c_ast::BinOp::BitXor => BinOp::BitXor(Default::default()),
            c_ast::BinOp::BitOr => BinOp::BitOr(Default::default()),
            c_ast::BinOp::And => BinOp::And(Default::default()),
            c_ast::BinOp::Or => BinOp::Or(Default::default()),

            _ => panic!("C BinOp {:?} is not a valid Rust BinOp", op),
        }
    }
}

impl<'c> Translation<'c> {
    pub fn convert_binary_expr(
        &self,
        mut ctx: ExprContext,
        expr_type_id: CQualTypeId,
        op: c_ast::BinOp,
        lhs: CExprId,
        rhs: CExprId,
        opt_lhs_type_id: Option<CQualTypeId>,
        opt_res_type_id: Option<CQualTypeId>,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        // If we're not making an assignment, a binop will require parens
        // applied to ternary conditionals
        if !op.is_assignment() {
            ctx.ternary_needs_parens = true;
        }

        let lhs_loc = &self.ast_context[lhs].loc;
        let rhs_loc = &self.ast_context[rhs].loc;
        use c_ast::BinOp::*;
        match op {
            Comma => {
                // The value of the LHS of a comma expression is always discarded
                self.convert_expr(ctx.unused(), lhs, None)?
                    .and_then(|_| self.convert_expr(ctx, rhs, Some(expr_type_id)))
            }

            And | Or => {
                let lhs = self.convert_condition(ctx, true, lhs)?;
                let rhs = self.convert_condition(ctx, true, rhs)?;
                lhs.map(|x| bool_to_int(mk().binary_expr(BinOp::from(op), x, rhs.to_expr())))
                    .and_then(|out| {
                        if ctx.is_unused() {
                            Ok(WithStmts::new(
                                vec![mk().semi_stmt(out)],
                                self.panic_or_err("Binary expression is not supposed to be used"),
                            ))
                        } else {
                            Ok(WithStmts::new_val(out))
                        }
                    })
            }

            // No sequence-point cases
            AssignAdd | AssignSubtract | AssignMultiply | AssignDivide | AssignModulus
            | AssignBitXor | AssignShiftLeft | AssignShiftRight | AssignBitOr | AssignBitAnd
            | Assign => self.convert_assignment_operator(
                ctx,
                op,
                expr_type_id,
                lhs,
                rhs,
                opt_lhs_type_id,
                opt_res_type_id,
            ),

            _ => {
                // Comparing references to pointers isn't consistently supported by rust
                // and so we need to decay references to pointers to do so. See
                // https://github.com/rust-lang/rust/issues/53772. This might be removable
                // once the above issue is resolved.
                if op == c_ast::BinOp::EqualEqual || op == c_ast::BinOp::NotEqual {
                    ctx = ctx.decay_ref();
                }

                let ty = self.convert_type(expr_type_id.ctype)?;

                let lhs_kind = &self.ast_context.index(lhs).kind;
                let mut lhs_type_id = lhs_kind.get_qual_type().ok_or_else(|| {
                    format_translation_err!(
                        self.ast_context.display_loc(lhs_loc),
                        "bad lhs type for assignment"
                    )
                })?;
                let rhs_kind = &self.ast_context.index(rhs).kind;
                let mut rhs_type_id = rhs_kind.get_qual_type().ok_or_else(|| {
                    format_translation_err!(
                        self.ast_context.display_loc(rhs_loc),
                        "bad rhs type for assignment"
                    )
                })?;

                // If this operation will (in Rust) take args of the same type, then propagate our
                // expected type down to the translation of our argument expressions.
                let lhs_resolved_ty = self.ast_context.resolve_type(lhs_type_id.ctype);
                let rhs_resolved_ty = self.ast_context.resolve_type(rhs_type_id.ctype);
                let expr_ty_kind = &self.ast_context.index(expr_type_id.ctype).kind;
                // Addition and subtraction can accept one pointer argument for .offset(), in which
                // case we don't want to homogenize arg types.
                if !lhs_resolved_ty.kind.is_pointer()
                    && !rhs_resolved_ty.kind.is_pointer()
                    && !expr_ty_kind.is_pointer()
                {
                    if op.all_types_same() {
                        // Ops like division and bitxor accept inputs of their expected result type.
                        lhs_type_id = expr_type_id;
                        rhs_type_id = expr_type_id;
                    } else if op.input_types_same() && lhs_resolved_ty.kind != rhs_resolved_ty.kind
                    {
                        // Ops like comparisons require argument types to match, but the result type
                        // doesn't inform us what type to choose. Select a synthetic definition of a
                        // portable rust type (e.g. u64 or usize) if either arg is one.
                        trace!(
                            "Binary op arg types differ: {:?} vs {:?}",
                            lhs_resolved_ty.kind,
                            rhs_resolved_ty.kind
                        );
                        let ty = if CTypeKind::PULLBACK_KINDS.contains(&lhs_resolved_ty.kind) {
                            lhs_type_id
                        } else {
                            rhs_type_id
                        };
                        lhs_type_id = ty;
                        rhs_type_id = ty;
                    } else if matches!(op, ShiftLeft | ShiftRight) {
                        lhs_type_id = expr_type_id;
                    }
                }

                if ctx.is_unused() {
                    Ok(self
                        .convert_expr(ctx, lhs, Some(lhs_type_id))?
                        .and_then(|_| self.convert_expr(ctx, rhs, Some(rhs_type_id)))?
                        .map(|_| self.panic_or_err("Binary expression is not supposed to be used")))
                } else {
                    let rhs_ctx = ctx;

                    // When we use methods on pointers (ie wrapping_offset_from or offset)
                    // we must ensure we have an explicit raw ptr for the self param, as
                    // self references do not decay
                    if op == c_ast::BinOp::Subtract || op == c_ast::BinOp::Add {
                        let ty_kind = &self.ast_context.resolve_type(lhs_type_id.ctype).kind;

                        if let CTypeKind::Pointer(_) = ty_kind {
                            ctx = ctx.decay_ref();
                        }
                    }

                    self.convert_expr(ctx, lhs, Some(lhs_type_id))?
                        .and_then(|lhs_val| {
                            self.convert_expr(rhs_ctx, rhs, Some(rhs_type_id))?
                                .and_then(|rhs_val| {
                                    let expr_ids = Some((lhs, rhs));
                                    self.convert_binary_operator(
                                        op,
                                        ty,
                                        expr_type_id.ctype,
                                        lhs_type_id,
                                        rhs_type_id,
                                        lhs_val,
                                        rhs_val,
                                        expr_ids,
                                    )
                                })
                        })
                }
            }
        }
    }

    fn convert_assignment_operator_aux(
        &self,
        bin_op_kind: BinOp,
        bin_op: c_ast::BinOp,
        read: Box<Expr>,
        write: Box<Expr>,
        rhs: Box<Expr>,
        compute_lhs_type_id: CQualTypeId,
        compute_res_type_id: CQualTypeId,
        lhs_type_id: CQualTypeId,
        rhs_type_id: CQualTypeId,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        if self.ast_context.resolve_type_id(compute_lhs_type_id.ctype)
            == self.ast_context.resolve_type_id(lhs_type_id.ctype)
        {
            Ok(WithStmts::new_val(mk().assign_op_expr(
                bin_op_kind,
                write,
                rhs,
            )))
        } else {
            let compute_lhs_resolved_ty = &self.ast_context.resolve_type(compute_lhs_type_id.ctype);
            let lhs_type = self.convert_type(compute_lhs_type_id.ctype)?;

            // We can't simply as-cast into a non primitive like f128
            let lhs = if compute_lhs_resolved_ty.kind == CTypeKind::LongDouble {
                self.use_crate(ExternCrate::F128);

                let fn_path = mk().abs_path_expr(vec!["f128", "f128", "from"]);
                let args = vec![read];

                mk().call_expr(fn_path, args)
            } else {
                mk().cast_expr(read, lhs_type.clone())
            };
            let ty = self.convert_type(compute_res_type_id.ctype)?;
            let mut val = self.convert_binary_operator(
                bin_op,
                ty,
                compute_res_type_id.ctype,
                compute_lhs_type_id,
                rhs_type_id,
                lhs,
                rhs,
                None,
            )?;

            let is_enum_result = self
                .ast_context
                .resolve_type(lhs_type_id.ctype)
                .kind
                .is_enum();
            let result_type = self.convert_type(lhs_type_id.ctype)?;
            let val = if is_enum_result {
                val.set_unsafe();
                val.map(|val| transmute_expr(lhs_type, result_type, val))
            } else {
                // We can't as-cast from a non primitive like f128 back to the result_type
                if compute_lhs_resolved_ty.kind == CTypeKind::LongDouble {
                    let resolved_lhs_kind = &self.ast_context.resolve_type(lhs_type_id.ctype).kind;

                    self.f128_cast_to(val, resolved_lhs_kind)?
                } else {
                    val.map(|val| mk().cast_expr(val, result_type))
                }
            };
            Ok(val.map(|val| mk().assign_expr(write.clone(), val)))
        }
    }

    /// Translate an assignment binary operator.
    ///
    /// `compute_lhs_ty` and `compute_res_ty` correspond to Clang's
    /// `CompoundAssignOperator::{CompLHSType,CompResultType}`; see the Clang docs:
    /// https://clang.llvm.org/doxygen/classclang_1_1CompoundAssignOperator.html#details
    fn convert_assignment_operator(
        &self,
        ctx: ExprContext,
        op: c_ast::BinOp,
        expr_type_id: CQualTypeId,
        lhs: CExprId,
        rhs: CExprId,
        compute_lhs_type_id: Option<CQualTypeId>,
        compute_res_type_id: Option<CQualTypeId>,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        if op == c_ast::BinOp::Assign {
            assert!(compute_lhs_type_id.is_none());
            assert!(compute_res_type_id.is_none());
        } else {
            assert!(compute_lhs_type_id.is_some());
            assert!(compute_res_type_id.is_some());
        }

        let rhs_type_id = self
            .ast_context
            .index(rhs)
            .kind
            .get_qual_type()
            .ok_or_else(|| format_err!("bad assignment rhs type"))?;
        let lhs_kind = &self.ast_context.index(lhs).kind;
        let lhs_type_id = lhs_kind
            .get_qual_type()
            .ok_or_else(|| format_err!("bad initial lhs type"))?;

        // First, translate the rhs. Then, if it must match the lhs but doesn't, add a cast.
        let mut rhs_translation = self.convert_expr(ctx.used(), rhs, Some(rhs_type_id))?;
        let lhs_rhs_types_must_match = {
            let lhs_resolved_ty = &self.ast_context.resolve_type(lhs_type_id.ctype);
            let rhs_resolved_ty = &self.ast_context.resolve_type(rhs_type_id.ctype);
            // Addition and subtraction can accept one pointer argument for .offset(), in which
            // case we don't want to homogenize arg types.
            let neither_ptr =
                !lhs_resolved_ty.kind.is_pointer() && !rhs_resolved_ty.kind.is_pointer();

            use c_ast::BinOp::*;
            match op.underlying_assignment() {
                Some(Add) => neither_ptr,
                Some(Subtract) => neither_ptr,
                Some(Multiply) => true,
                Some(Divide) => true,
                Some(Modulus) => true,
                Some(BitXor) => true,
                Some(ShiftLeft) => false,
                Some(ShiftRight) => false,
                Some(BitOr) => true,
                Some(BitAnd) => true,
                None => true,
                _ => unreachable!(),
            }
        };
        if lhs_rhs_types_must_match {
            // For compound assignment, use the compute type; for regular assignment, use lhs type
            let effective_lhs_ty = compute_lhs_type_id.unwrap_or(lhs_type_id);
            if effective_lhs_ty.ctype != rhs_type_id.ctype {
                let new_rhs_ty =
                    self.convert_type(compute_lhs_type_id.unwrap_or(lhs_type_id).ctype)?;
                rhs_translation = rhs_translation.map(|val| mk().cast_expr(val, new_rhs_ty));
            }
        }

        // Now that we've translated the rhs, finish translating the assignment operator.
        self.convert_assignment_operator_with_rhs(
            ctx,
            op,
            expr_type_id,
            lhs,
            rhs_type_id,
            rhs_translation,
            compute_lhs_type_id,
            compute_res_type_id,
        )
    }

    /// Translate an assignment binary operator, provided a pre-translated RHS expression
    fn convert_assignment_operator_with_rhs(
        &self,
        ctx: ExprContext,
        op: c_ast::BinOp,
        expr_type_id: CQualTypeId,
        lhs: CExprId,
        rhs_type_id: CQualTypeId,
        rhs_translation: WithStmts<Box<Expr>>,
        compute_lhs_type_id: Option<CQualTypeId>,
        compute_res_type_id: Option<CQualTypeId>,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        if op == c_ast::BinOp::Assign {
            assert!(compute_lhs_type_id.is_none());
            assert!(compute_res_type_id.is_none());
        } else {
            assert!(compute_lhs_type_id.is_some());
            assert!(compute_res_type_id.is_some());
        }

        let ty = self.convert_type(expr_type_id.ctype)?;

        let result_type_id = compute_res_type_id.unwrap_or(expr_type_id);
        let expr_or_comp_type_id = compute_lhs_type_id.unwrap_or(expr_type_id);
        let initial_lhs = &self.ast_context.index(lhs).kind;
        let initial_lhs_type_id = initial_lhs
            .get_qual_type()
            .ok_or_else(|| format_err!("bad initial lhs type"))?;

        let bitfield_id = match initial_lhs {
            CExprKind::Member(_, _, decl_id, _, _) => {
                let kind = &self.ast_context[*decl_id].kind;

                if let CDeclKind::Field {
                    bitfield_width: Some(_),
                    ..
                } = kind
                {
                    Some(decl_id)
                } else {
                    None
                }
            }
            _ => None,
        };

        if let Some(field_id) = bitfield_id {
            let rhs_expr = mk().cast_expr(rhs_translation.to_expr(), ty);
            return self.convert_bitfield_assignment_op_with_rhs(ctx, op, lhs, rhs_expr, *field_id);
        }

        let is_volatile = initial_lhs_type_id.qualifiers.is_volatile;
        let is_volatile_compound_assign = op.underlying_assignment().is_some() && is_volatile;

        let expr_resolved_ty = self.ast_context.resolve_type(expr_type_id.ctype);
        let compute_resolved_ty = &self.ast_context.resolve_type(expr_or_comp_type_id.ctype);

        let pointer_lhs = match &expr_resolved_ty.kind {
            &CTypeKind::Pointer(pointee) => Some(pointee),
            _ => None,
        };

        let is_unsigned_arith = match op {
            c_ast::BinOp::AssignAdd
            | c_ast::BinOp::AssignSubtract
            | c_ast::BinOp::AssignMultiply
            | c_ast::BinOp::AssignDivide
            | c_ast::BinOp::AssignModulus => compute_resolved_ty.kind.is_unsigned_integral_type(),
            _ => false,
        };

        let lhs_translation = if initial_lhs_type_id.ctype != expr_or_comp_type_id.ctype
            || ctx.is_used()
            || pointer_lhs.is_some()
            || is_volatile_compound_assign
            || is_unsigned_arith
        {
            self.name_reference_write_read(ctx, lhs)?
        } else {
            self.name_reference_write(ctx, lhs)?.map(|named_ref| {
                named_ref
                    .map_rvalue(|()| self.panic_or_err("Volatile value is not supposed to be read"))
            })
        };

        rhs_translation.and_then(|rhs| {
            lhs_translation.and_then(
                |NamedReference {
                     lvalue: write,
                     rvalue: read,
                 }| {
                    // Assignment expression itself
                    use c_ast::BinOp::*;
                    let assign_stmt = match op {
                        // Regular (possibly volatile) assignment
                        Assign if !is_volatile => WithStmts::new_val(mk().assign_expr(write, rhs)),
                        Assign => WithStmts::new_unsafe_val(self.volatile_write(
                            write,
                            initial_lhs_type_id,
                            rhs,
                        )?),

                        // Anything volatile needs to be desugared into explicit reads and writes
                        op if is_volatile || is_unsigned_arith => {
                            let op = op
                                .underlying_assignment()
                                .expect("Cannot convert non-assignment operator");

                            let val = if expr_or_comp_type_id.ctype == initial_lhs_type_id.ctype {
                                self.convert_binary_operator(
                                    op,
                                    ty,
                                    expr_type_id.ctype,
                                    initial_lhs_type_id,
                                    rhs_type_id,
                                    read.clone(),
                                    rhs,
                                    None,
                                )?
                            } else {
                                let lhs_type =
                                    self.convert_type(compute_lhs_type_id.unwrap().ctype)?;
                                let write_type = self.convert_type(expr_type_id.ctype)?;
                                let lhs = mk().cast_expr(read.clone(), lhs_type.clone());
                                let ty = self.convert_type(result_type_id.ctype)?;
                                let mut val = self.convert_binary_operator(
                                    op,
                                    ty,
                                    result_type_id.ctype,
                                    expr_or_comp_type_id,
                                    rhs_type_id,
                                    lhs,
                                    rhs,
                                    None,
                                )?;

                                let expr_resolved_ty =
                                    self.ast_context.resolve_type(expr_type_id.ctype);
                                let is_enum_result = expr_resolved_ty.kind.is_enum();
                                let expr_type = self.convert_type(expr_type_id.ctype)?;
                                let val = if is_enum_result {
                                    val.set_unsafe();
                                    val.map(|val| transmute_expr(lhs_type, expr_type, val))
                                } else {
                                    val.map(|val| mk().cast_expr(val, expr_type))
                                };
                                val.map(|val| mk().cast_expr(val, write_type))
                            };

                            #[allow(clippy::let_and_return /* , reason = "block is large, so variable name helps" */)]
                            let write = if is_volatile {
                                val.and_then(|val| {
                                    TranslationResult::Ok(WithStmts::new_unsafe_val(
                                        self.volatile_write(write, initial_lhs_type_id, val)?,
                                    ))
                                })?
                            } else {
                                val.map(|val| mk().assign_expr(write, val))
                            };
                            write
                        }

                        // Everything else
                        AssignAdd | AssignSubtract if pointer_lhs.is_some() => {
                            let ptr = self.convert_pointer_offset(
                                write.clone(),
                                rhs,
                                pointer_lhs.unwrap().ctype,
                                op == AssignSubtract,
                                false,
                            );
                            ptr.map(|ptr| mk().assign_expr(write, ptr))
                        }

                        _ => {
                            fn eq<Token: Default, F: Fn(Token) -> BinOp>(f: F) -> BinOp {
                                f(Default::default())
                            }

                            let (bin_op, bin_op_kind) = match op {
                                AssignAdd => (Add, eq(BinOp::AddAssign)),
                                AssignSubtract => (Subtract, eq(BinOp::SubAssign)),
                                AssignMultiply => (Multiply, eq(BinOp::MulAssign)),
                                AssignDivide => (Divide, eq(BinOp::DivAssign)),
                                AssignModulus => (Modulus, eq(BinOp::RemAssign)),
                                AssignBitXor => (BitXor, eq(BinOp::BitXorAssign)),
                                AssignShiftLeft => (ShiftLeft, eq(BinOp::ShlAssign)),
                                AssignShiftRight => (ShiftRight, eq(BinOp::ShrAssign)),
                                AssignBitOr => (BitOr, eq(BinOp::BitOrAssign)),
                                AssignBitAnd => (BitAnd, eq(BinOp::BitAndAssign)),
                                _ => panic!("Cannot convert non-assignment operator"),
                            };
                            self.convert_assignment_operator_aux(
                                bin_op_kind,
                                bin_op,
                                read.clone(),
                                write,
                                rhs,
                                compute_lhs_type_id.unwrap(),
                                compute_res_type_id.unwrap(),
                                expr_type_id,
                                rhs_type_id,
                            )?
                        }
                    };

                    assign_stmt.and_then(|assign_stmt| {
                        Ok(WithStmts::new(vec![mk().semi_stmt(assign_stmt)], read))
                    })
                },
            )
        })
    }

    /// Translate a non-assignment binary operator. It is expected that the `lhs` and `rhs`
    /// arguments be usable as rvalues.
    fn convert_binary_operator(
        &self,
        op: c_ast::BinOp,
        ty: Box<Type>,
        ctype: CTypeId,
        lhs_type: CQualTypeId,
        rhs_type: CQualTypeId,
        lhs: Box<Expr>,
        rhs: Box<Expr>,
        lhs_rhs_ids: Option<(CExprId, CExprId)>,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        let is_unsigned_integral_type = self
            .ast_context
            .resolve_type(ctype)
            .kind
            .is_unsigned_integral_type();

        Ok(WithStmts::new_val(match op {
            c_ast::BinOp::Add => return self.convert_addition(lhs_type, rhs_type, lhs, rhs),
            c_ast::BinOp::Subtract => {
                return self.convert_subtraction(ty, lhs_type, rhs_type, lhs, rhs)
            }

            c_ast::BinOp::Multiply if is_unsigned_integral_type => {
                mk().method_call_expr(lhs, "wrapping_mul", vec![rhs])
            }
            c_ast::BinOp::Multiply => mk().binary_expr(BinOp::Mul(Default::default()), lhs, rhs),

            c_ast::BinOp::Divide if is_unsigned_integral_type => {
                mk().method_call_expr(lhs, "wrapping_div", vec![rhs])
            }
            c_ast::BinOp::Divide => mk().binary_expr(BinOp::Div(Default::default()), lhs, rhs),

            c_ast::BinOp::Modulus if is_unsigned_integral_type => {
                mk().method_call_expr(lhs, "wrapping_rem", vec![rhs])
            }
            c_ast::BinOp::Modulus => mk().binary_expr(BinOp::Rem(Default::default()), lhs, rhs),

            c_ast::BinOp::BitXor => mk().binary_expr(BinOp::BitXor(Default::default()), lhs, rhs),

            c_ast::BinOp::ShiftRight => mk().binary_expr(BinOp::Shr(Default::default()), lhs, rhs),
            c_ast::BinOp::ShiftLeft => mk().binary_expr(BinOp::Shl(Default::default()), lhs, rhs),

            c_ast::BinOp::EqualEqual => {
                // Using is_none method for null comparison means we don't have to
                // rely on the PartialEq trait as much and is also more idiomatic
                let expr = if let Some((lhs_expr_id, rhs_expr_id)) = lhs_rhs_ids {
                    let fn_eq_null = self.ast_context.is_function_pointer(lhs_type.ctype)
                        && self.ast_context.is_null_expr(rhs_expr_id);
                    let null_eq_fn = self.ast_context.is_function_pointer(rhs_type.ctype)
                        && self.ast_context.is_null_expr(lhs_expr_id);

                    if fn_eq_null {
                        mk().method_call_expr(lhs, "is_none", vec![])
                    } else if null_eq_fn {
                        mk().method_call_expr(rhs, "is_none", vec![])
                    } else {
                        mk().binary_expr(BinOp::Eq(Default::default()), lhs, rhs)
                    }
                } else {
                    mk().binary_expr(BinOp::Eq(Default::default()), lhs, rhs)
                };

                bool_to_int(expr)
            }
            c_ast::BinOp::NotEqual => {
                // Using is_some method for null comparison means we don't have to
                // rely on the PartialEq trait as much and is also more idiomatic
                let expr = if let Some((lhs_expr_id, rhs_expr_id)) = lhs_rhs_ids {
                    let fn_eq_null = self.ast_context.is_function_pointer(lhs_type.ctype)
                        && self.ast_context.is_null_expr(rhs_expr_id);
                    let null_eq_fn = self.ast_context.is_function_pointer(rhs_type.ctype)
                        && self.ast_context.is_null_expr(lhs_expr_id);

                    if fn_eq_null {
                        mk().method_call_expr(lhs, "is_some", vec![])
                    } else if null_eq_fn {
                        mk().method_call_expr(rhs, "is_some", vec![])
                    } else {
                        mk().binary_expr(BinOp::Ne(Default::default()), lhs, rhs)
                    }
                } else {
                    mk().binary_expr(BinOp::Ne(Default::default()), lhs, rhs)
                };

                bool_to_int(expr)
            }
            c_ast::BinOp::Less => {
                bool_to_int(mk().binary_expr(BinOp::Lt(Default::default()), lhs, rhs))
            }
            c_ast::BinOp::Greater => {
                bool_to_int(mk().binary_expr(BinOp::Gt(Default::default()), lhs, rhs))
            }
            c_ast::BinOp::GreaterEqual => {
                bool_to_int(mk().binary_expr(BinOp::Ge(Default::default()), lhs, rhs))
            }
            c_ast::BinOp::LessEqual => {
                bool_to_int(mk().binary_expr(BinOp::Le(Default::default()), lhs, rhs))
            }

            c_ast::BinOp::BitAnd => mk().binary_expr(BinOp::BitAnd(Default::default()), lhs, rhs),
            c_ast::BinOp::BitOr => mk().binary_expr(BinOp::BitOr(Default::default()), lhs, rhs),

            op => unimplemented!("Translation of binary operator {:?}", op),
        }))
    }

    fn convert_addition(
        &self,
        lhs_type_id: CQualTypeId,
        rhs_type_id: CQualTypeId,
        lhs: Box<Expr>,
        rhs: Box<Expr>,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        let lhs_type = &self.ast_context.resolve_type(lhs_type_id.ctype).kind;
        let rhs_type = &self.ast_context.resolve_type(rhs_type_id.ctype).kind;

        if let &CTypeKind::Pointer(pointee) = lhs_type {
            Ok(self.convert_pointer_offset(lhs, rhs, pointee.ctype, false, false))
        } else if let &CTypeKind::Pointer(pointee) = rhs_type {
            Ok(self.convert_pointer_offset(rhs, lhs, pointee.ctype, false, false))
        } else if lhs_type.is_unsigned_integral_type() {
            Ok(WithStmts::new_val(mk().method_call_expr(
                lhs,
                "wrapping_add",
                vec![rhs],
            )))
        } else {
            Ok(WithStmts::new_val(mk().binary_expr(
                BinOp::Add(Default::default()),
                lhs,
                rhs,
            )))
        }
    }

    fn convert_subtraction(
        &self,
        ty: Box<Type>,
        lhs_type_id: CQualTypeId,
        rhs_type_id: CQualTypeId,
        lhs: Box<Expr>,
        rhs: Box<Expr>,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        let lhs_type = &self.ast_context.resolve_type(lhs_type_id.ctype).kind;
        let rhs_type = &self.ast_context.resolve_type(rhs_type_id.ctype).kind;

        if let &CTypeKind::Pointer(pointee) = rhs_type {
            let mut offset = mk().method_call_expr(lhs, "offset_from", vec![rhs]);

            if let Some(sz) = self.compute_size_of_expr(pointee.ctype) {
                let div = cast_int(sz, "isize", false);
                offset = mk().binary_expr(BinOp::Div(Default::default()), offset, div);
            }

            Ok(WithStmts::new_unsafe_val(mk().cast_expr(offset, ty)))
        } else if let &CTypeKind::Pointer(pointee) = lhs_type {
            Ok(self.convert_pointer_offset(lhs, rhs, pointee.ctype, true, false))
        } else if lhs_type.is_unsigned_integral_type() {
            Ok(WithStmts::new_val(mk().method_call_expr(
                lhs,
                "wrapping_sub",
                vec![rhs],
            )))
        } else {
            Ok(WithStmts::new_val(mk().binary_expr(
                BinOp::Sub(Default::default()),
                lhs,
                rhs,
            )))
        }
    }

    fn convert_pre_increment(
        &self,
        ctx: ExprContext,
        ty: CQualTypeId,
        up: bool,
        arg: CExprId,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        let op = if up {
            c_ast::BinOp::AssignAdd
        } else {
            c_ast::BinOp::AssignSubtract
        };
        let one = match self.ast_context.resolve_type(ty.ctype).kind {
            // TODO: If rust gets f16 support:
            // CTypeKind::Half |
            CTypeKind::Float | CTypeKind::Double => mk().lit_expr(mk().float_unsuffixed_lit("1.")),
            CTypeKind::LongDouble => {
                self.use_crate(ExternCrate::F128);

                let fn_path = mk().abs_path_expr(vec!["f128", "f128", "new"]);
                let args = vec![mk().lit_expr(mk().float_unsuffixed_lit("1."))];

                mk().call_expr(fn_path, args)
            }
            _ => mk().lit_expr(mk().int_unsuffixed_lit(1)),
        };
        let arg_type = self.ast_context[arg]
            .kind
            .get_qual_type()
            .ok_or_else(|| format_err!("bad arg type"))?;
        self.convert_assignment_operator_with_rhs(
            ctx.used(),
            op,
            arg_type,
            arg,
            ty,
            WithStmts::new_val(one),
            Some(arg_type),
            Some(arg_type),
        )
    }

    fn convert_post_increment(
        &self,
        ctx: ExprContext,
        ty: CQualTypeId,
        up: bool,
        arg: CExprId,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        // If we aren't going to be using the result, may as well do a simple pre-increment
        if ctx.is_unused() {
            return self.convert_pre_increment(ctx, ty, up, arg);
        }

        let ty = self
            .ast_context
            .index(arg)
            .kind
            .get_qual_type()
            .ok_or_else(|| format_err!("bad post inc type"))?;

        self.name_reference_write_read(ctx, arg)?.and_then(
            |NamedReference {
                 lvalue: write,
                 rvalue: read,
             }| {
                let val_name = self.renamer.borrow_mut().fresh();
                let save_old_val = mk().local_stmt(Box::new(mk().local(
                    mk().ident_pat(&val_name),
                    None,
                    Some(read.clone()),
                )));

                let mut one = match self.ast_context[ty.ctype].kind {
                    // TODO: If rust gets f16 support:
                    // CTypeKind::Half |
                    CTypeKind::Float | CTypeKind::Double => {
                        mk().lit_expr(mk().float_unsuffixed_lit("1."))
                    }
                    CTypeKind::LongDouble => {
                        self.use_crate(ExternCrate::F128);

                        let fn_path = mk().abs_path_expr(vec!["f128", "f128", "new"]);
                        let args = vec![mk().lit_expr(mk().float_unsuffixed_lit("1."))];

                        mk().call_expr(fn_path, args)
                    }
                    _ => mk().lit_expr(mk().int_unsuffixed_lit(1)),
                };

                let mut is_unsafe = false; // Track unsafety if we call `pointer::offset`.

                // *p + 1
                let val = if let &CTypeKind::Pointer(pointee) =
                    &self.ast_context.resolve_type(ty.ctype).kind
                {
                    if let Some(n) = self.compute_size_of_expr(pointee.ctype) {
                        one = n
                    }

                    let n = if up {
                        one
                    } else {
                        mk().unary_expr(UnOp::Neg(Default::default()), one)
                    };
                    is_unsafe = true;
                    mk().method_call_expr(read, "offset", vec![n])
                } else if self
                    .ast_context
                    .resolve_type(ty.ctype)
                    .kind
                    .is_unsigned_integral_type()
                {
                    let m = if up { "wrapping_add" } else { "wrapping_sub" };
                    mk().method_call_expr(read, m, vec![one])
                } else {
                    let k = if up {
                        BinOp::Add(Default::default())
                    } else {
                        BinOp::Sub(Default::default())
                    };
                    mk().binary_expr(k, read, one)
                };

                // *p = *p + rhs
                let assign_stmt = if ty.qualifiers.is_volatile {
                    is_unsafe = true;
                    self.volatile_write(write, ty, val)?
                } else {
                    mk().assign_expr(write, val)
                };

                let mut val = WithStmts::new(
                    vec![save_old_val, mk().expr_stmt(assign_stmt)],
                    mk().ident_expr(val_name),
                );
                if is_unsafe {
                    val.set_unsafe();
                }
                Ok(val)
            },
        )
    }

    pub fn convert_unary_operator(
        &self,
        ctx: ExprContext,
        name: c_ast::UnOp,
        cqual_type: CQualTypeId,
        arg: CExprId,
        lrvalue: LRValue,
    ) -> TranslationResult<WithStmts<Box<Expr>>> {
        let CQualTypeId { ctype, .. } = cqual_type;
        let resolved_ctype = self.ast_context.resolve_type(ctype);

        let mut unary = match name {
            c_ast::UnOp::AddressOf => self.convert_address_of(ctx, cqual_type, arg),
            c_ast::UnOp::PreIncrement => self.convert_pre_increment(ctx, cqual_type, true, arg),
            c_ast::UnOp::PreDecrement => self.convert_pre_increment(ctx, cqual_type, false, arg),
            c_ast::UnOp::PostIncrement => self.convert_post_increment(ctx, cqual_type, true, arg),
            c_ast::UnOp::PostDecrement => self.convert_post_increment(ctx, cqual_type, false, arg),
            c_ast::UnOp::Deref => self.convert_deref(ctx, cqual_type, arg, lrvalue),
            c_ast::UnOp::Plus => self.convert_expr(ctx.used(), arg, Some(cqual_type)), // promotion is explicit in the clang AST

            c_ast::UnOp::Negate => {
                let val = self.convert_expr(ctx.used(), arg, Some(cqual_type))?;

                if resolved_ctype.kind.is_unsigned_integral_type() {
                    Ok(val.map(wrapping_neg_expr))
                } else {
                    Ok(val.map(neg_expr))
                }
            }
            c_ast::UnOp::Complement => Ok(self
                .convert_expr(ctx.used(), arg, Some(cqual_type))?
                .map(|a| mk().unary_expr(UnOp::Not(Default::default()), a))),

            c_ast::UnOp::Not => {
                let val = self.convert_condition(ctx, false, arg)?;
                Ok(val.map(|x| mk().cast_expr(x, mk().abs_path_ty(vec!["core", "ffi", "c_int"]))))
            }
            c_ast::UnOp::Extension => {
                let arg = self.convert_expr(ctx, arg, Some(cqual_type))?;
                Ok(arg)
            }
            c_ast::UnOp::Real | c_ast::UnOp::Imag | c_ast::UnOp::Coawait => {
                panic!("Unsupported extension operator")
            }
        }?;

        // Some unused unary operators (`-foo()`) may have side effects, so we need
        // to add them to stmts when name is not increment/decrement operator.
        //
        // `UnOp::Extension` (`__extension__`) is another exception since
        // it's a no-op around the inner expression.
        if !matches!(
            name,
            c_ast::UnOp::PreDecrement
                | c_ast::UnOp::PreIncrement
                | c_ast::UnOp::PostDecrement
                | c_ast::UnOp::PostIncrement
                | c_ast::UnOp::Extension
        ) {
            unary = self.convert_side_effects_expr(
                ctx,
                unary,
                "Unary expression is not supposed to be used",
            )?;
        }
        Ok(unary)
    }
}