summaryrefslogtreecommitdiff
path: root/compilerplugins/clang/implicitboolconversion.cxx
blob: 0d933bfa4480f2b056300f7949e73dad63f47dd6 (plain)
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
954
955
956
957
958
959
960
961
962
963
964
965
966
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <stack>
#include <string>
#include <vector>

#include "compat.hxx"
#include "plugin.hxx"

template<> struct std::iterator_traits<ExprIterator> {
    typedef std::ptrdiff_t difference_type;
    typedef Expr * value_type;
    typedef Expr const ** pointer;
    typedef Expr const & reference;
    typedef std::random_access_iterator_tag iterator_category;
};

template<> struct std::iterator_traits<ConstExprIterator> {
    typedef std::ptrdiff_t difference_type;
    typedef Expr const * value_type;
    typedef Expr const ** pointer;
    typedef Expr const & reference;
    typedef std::random_access_iterator_tag iterator_category;
};

namespace {

Expr const * ignoreParenAndTemporaryMaterialization(Expr const * expr) {
    for (;;) {
        expr = expr->IgnoreParens();
        auto e = dyn_cast<MaterializeTemporaryExpr>(expr);
        if (e == nullptr) {
            return expr;
        }
        expr = e->GetTemporaryExpr();
    }
}

Expr const * ignoreParenImpCastAndComma(Expr const * expr) {
    for (;;) {
        expr = expr->IgnoreParenImpCasts();
        BinaryOperator const * op = dyn_cast<BinaryOperator>(expr);
        if (op == nullptr || op->getOpcode() != BO_Comma) {
            return expr;
        }
        expr = op->getRHS();
    }
}

SubstTemplateTypeParmType const * getAsSubstTemplateTypeParmType(QualType type)
{
    //TODO: unwrap all kinds of (non-SubstTemplateTypeParmType) sugar, not only
    // TypedefType sugar:
    for (;;) {
        TypedefType const * t = type->getAs<TypedefType>();
        if (t == nullptr) {
            return dyn_cast<SubstTemplateTypeParmType>(type);
        }
        type = t->desugar();
    }
}

bool areSameTypedef(QualType type1, QualType type2) {
    // type1.getTypePtr() == typ2.getTypePtr() fails for e.g. ::sal_Bool vs.
    // sal_Bool:
    auto t1 = type1->getAs<TypedefType>();
    auto t2 = type2->getAs<TypedefType>();
    return t1 != nullptr && t2 != nullptr && t1->getDecl() == t2->getDecl();
}

bool isBool(QualType type, bool allowTypedefs = true) {
    if (type->isBooleanType()) {
        return true;
    }
    if (!allowTypedefs) {
        return false;
    }
    TypedefType const * t2 = type->getAs<TypedefType>();
    if (t2 == nullptr) {
        return false;
    }
    std::string name(t2->getDecl()->getNameAsString());
    return name == "sal_Bool" || name == "BOOL" || name == "Boolean"
        || name == "FT_Bool" || name == "FcBool" || name == "GLboolean"
        || name == "NPBool" || name == "UBool" || name == "dbus_bool_t"
        || name == "gboolean" || name == "hb_bool_t" || name == "jboolean";
}

bool isBool(Expr const * expr, bool allowTypedefs = true) {
    return isBool(expr->getType(), allowTypedefs);
}

bool isMatchingBool(Expr const * expr, Expr const * comparisonExpr) {
    return isBool(expr, false)
        || areSameTypedef(expr->getType(), comparisonExpr->getType());
}

bool isBoolExpr(Expr const * expr) {
    if (isBool(expr)) {
        return true;
    }
    expr = ignoreParenImpCastAndComma(expr);
    ConditionalOperator const * co = dyn_cast<ConditionalOperator>(expr);
    if (co != nullptr) {
        ImplicitCastExpr const * ic1 = dyn_cast<ImplicitCastExpr>(
            co->getTrueExpr()->IgnoreParens());
        ImplicitCastExpr const * ic2 = dyn_cast<ImplicitCastExpr>(
            co->getFalseExpr()->IgnoreParens());
        if (ic1 != nullptr && ic2 != nullptr
            && ic1->getType()->isSpecificBuiltinType(BuiltinType::Int)
            && isBoolExpr(ic1->getSubExpr()->IgnoreParens())
            && ic2->getType()->isSpecificBuiltinType(BuiltinType::Int)
            && isBoolExpr(ic2->getSubExpr()->IgnoreParens()))
        {
            return true;
        }
    }
    std::stack<Expr const *> stack;
    Expr const * e = expr;
    for (;;) {
        e = ignoreParenImpCastAndComma(e);
        MemberExpr const * me = dyn_cast<MemberExpr>(e);
        if (me == nullptr) {
            break;
        }
        stack.push(e);
        e = me->getBase();
    }
    for (;;) {
        e = ignoreParenImpCastAndComma(e);
        CXXOperatorCallExpr const * op = dyn_cast<CXXOperatorCallExpr>(e);
        if (op == nullptr || op->getOperator() != OO_Subscript) {
            break;
        }
        stack.push(e);
        e = op->getArg(0);
    }
    if (!stack.empty()) {
        TemplateSpecializationType const * t
            = e->getType()->getAs<TemplateSpecializationType>();
        for (;;) {
            if (t == nullptr) {
                break;
            }
            QualType ty;
            MemberExpr const * me = dyn_cast<MemberExpr>(stack.top());
            if (me != nullptr) {
                TemplateDecl const * td
                    = t->getTemplateName().getAsTemplateDecl();
                if (td == nullptr) {
                    break;
                }
                TemplateParameterList const * ps = td->getTemplateParameters();
                SubstTemplateTypeParmType const * t2
                    = getAsSubstTemplateTypeParmType(
                        me->getMemberDecl()->getType());
                if (t2 == nullptr) {
                    break;
                }
                auto i = std::find(
                    ps->begin(), ps->end(),
                    t2->getReplacedParameter()->getDecl());
                if (i == ps->end()) {
                    break;
                }
                if (ps->size() != t->getNumArgs()) { //TODO
                    break;
                }
                TemplateArgument const & arg = t->getArg(i - ps->begin());
                if (arg.getKind() != TemplateArgument::Type) {
                    break;
                }
                ty = arg.getAsType();
            } else {
                CXXOperatorCallExpr const * op
                    = dyn_cast<CXXOperatorCallExpr>(stack.top());
                assert(op != nullptr);
                TemplateDecl const * d
                    = t->getTemplateName().getAsTemplateDecl();
                if (d == nullptr
                    || (d->getQualifiedNameAsString()
                        != "com::sun::star::uno::Sequence")
                    || t->getNumArgs() != 1
                    || t->getArg(0).getKind() != TemplateArgument::Type)
                {
                    break;
                }
                ty = t->getArg(0).getAsType();
            }
            stack.pop();
            if (stack.empty()) {
                if (isBool(ty)) {
                    return true;
                }
                break;
            }
            t = ty->getAs<TemplateSpecializationType>();
        }
    }
    return false;
}

// It appears that, given a function declaration, there is no way to determine
// the language linkage of the function's type, only of the function's name
// (via FunctionDecl::isExternC); however, in a case like
//
//   extern "C" { static void f(); }
//
// the function's name does not have C language linkage while the function's
// type does (as clarified in C++11 [decl.link]); cf. <http://clang-developers.
// 42468.n3.nabble.com/Language-linkage-of-function-type-tt4037248.html>
// "Language linkage of function type":
bool hasCLanguageLinkageType(FunctionDecl const * decl) {
    assert(decl != nullptr);
    if (decl->isExternC()) {
        return true;
    }
#if (__clang_major__ == 3 && __clang_minor__ >= 3) || __clang_major__ > 3
    if (decl->isInExternCContext()) {
        return true;
    }
#else
    if (decl->getCanonicalDecl()->getDeclContext()->isExternCContext()) {
        return true;
    }
#endif
    return false;
}

class ImplicitBoolConversion:
    public RecursiveASTVisitor<ImplicitBoolConversion>, public loplugin::Plugin
{
public:
    explicit ImplicitBoolConversion(InstantiationData const & data):
        Plugin(data) {}

    virtual void run() override
    { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }

    bool TraverseCallExpr(CallExpr * expr);

    bool TraverseCXXMemberCallExpr(CXXMemberCallExpr * expr);

    bool TraverseCXXConstructExpr(CXXConstructExpr * expr);

    bool TraverseCXXTemporaryObjectExpr(CXXTemporaryObjectExpr * expr);

    bool TraverseCStyleCastExpr(CStyleCastExpr * expr);

    bool TraverseCXXStaticCastExpr(CXXStaticCastExpr * expr);

    bool TraverseCXXFunctionalCastExpr(CXXFunctionalCastExpr * expr);

    bool TraverseConditionalOperator(ConditionalOperator * expr);

    bool TraverseBinLT(BinaryOperator * expr);

    bool TraverseBinLE(BinaryOperator * expr);

    bool TraverseBinGT(BinaryOperator * expr);

    bool TraverseBinGE(BinaryOperator * expr);

    bool TraverseBinEQ(BinaryOperator * expr);

    bool TraverseBinNE(BinaryOperator * expr);

    bool TraverseBinAssign(BinaryOperator * expr);

    bool TraverseBinAndAssign(CompoundAssignOperator * expr);

    bool TraverseBinOrAssign(CompoundAssignOperator * expr);

    bool TraverseBinXorAssign(CompoundAssignOperator * expr);

    bool TraverseReturnStmt(ReturnStmt * stmt);

    bool TraverseFunctionDecl(FunctionDecl * decl);

    bool VisitImplicitCastExpr(ImplicitCastExpr const * expr);

private:
    bool isExternCFunctionCall(
        CallExpr const * expr, FunctionProtoType const ** functionType);

    bool isExternCFunctionCallReturningInt(Expr const * expr);

    void checkCXXConstructExpr(CXXConstructExpr const * expr);

    void reportWarning(ImplicitCastExpr const * expr);

    std::stack<std::vector<ImplicitCastExpr const *>> nested;
    std::stack<CallExpr const *> calls;
    bool externCIntFunctionDefinition = false;
};

bool ImplicitBoolConversion::TraverseCallExpr(CallExpr * expr) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    calls.push(expr);
    bool ret = RecursiveASTVisitor::TraverseCallExpr(expr);
    FunctionProtoType const * t;
    bool ext = isExternCFunctionCall(expr, &t);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        auto j = std::find_if(
            expr->arg_begin(), expr->arg_end(),
            [&i](Expr * e) {
                return i == ignoreParenAndTemporaryMaterialization(e);
            });
        if (j == expr->arg_end()) {
            reportWarning(i);
        } else {
            std::ptrdiff_t n = j - expr->arg_begin();
            assert(n >= 0);
            if (t != nullptr
                && static_cast<std::size_t>(n) >= compat::getNumParams(*t))
            {
                assert(t->isVariadic());
                // ignore bool to int promotions of variadic arguments
            } else if (ext) {
                if (t != nullptr) {
                    assert(
                        static_cast<std::size_t>(n) < compat::getNumParams(*t));
                    if (!(compat::getParamType(*t, n)->isSpecificBuiltinType(
                              BuiltinType::Int)
                          || compat::getParamType(*t, n)->isSpecificBuiltinType(
                              BuiltinType::UInt)
                          || compat::getParamType(*t, n)->isSpecificBuiltinType(
                              BuiltinType::Long)))
                    {
                        reportWarning(i);
                    }
                } else {
                    reportWarning(i);
                }
            } else {
                // Filter out
                //
                //   template<typename T> void f(T);
                //   f<sal_Bool>(true);
                //
                DeclRefExpr const * dr = dyn_cast<DeclRefExpr>(
                    expr->getCallee()->IgnoreParenImpCasts());
                if (dr != nullptr && dr->hasExplicitTemplateArgs()) {
                    FunctionDecl const * fd
                        = dyn_cast<FunctionDecl>(dr->getDecl());
                    if (fd != nullptr
                        && static_cast<std::size_t>(n) < fd->getNumParams())
                    {
                        SubstTemplateTypeParmType const * t2
                            = getAsSubstTemplateTypeParmType(
                                fd->getParamDecl(n)->getType()
                                .getNonReferenceType());
                        if (t2 != nullptr) {
                            //TODO: fix this superficial nonsense check:
                            ASTTemplateArgumentListInfo const & ai
                                = dr->getExplicitTemplateArgs();
                            if (ai.NumTemplateArgs == 1
                                && (ai[0].getArgument().getKind()
                                    == TemplateArgument::Type)
                                && isBool(ai[0].getTypeSourceInfo()->getType()))
                            {
                                continue;
                            }
                        }
                    }
                }
                reportWarning(i);
            }
        }
    }
    calls.pop();
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseCXXMemberCallExpr(CXXMemberCallExpr * expr)
{
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseCXXMemberCallExpr(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        auto j = std::find_if(
            expr->arg_begin(), expr->arg_end(),
            [&i](Expr * e) {
                return i == ignoreParenAndTemporaryMaterialization(e);
            });
        if (j != expr->arg_end()) {
            // Filter out
            //
            //  template<typename T> struct S { void f(T); };
            //  S<sal_Bool> s;
            //  s.f(true);
            //
            std::ptrdiff_t n = j - expr->arg_begin();
            assert(n >= 0);
            CXXMethodDecl const * d = expr->getMethodDecl();
            if (static_cast<std::size_t>(n) >= d->getNumParams()) {
                // Ignore bool to int promotions of variadic arguments:
                assert(d->isVariadic());
                continue;
            }
            QualType ty
                = ignoreParenImpCastAndComma(expr->getImplicitObjectArgument())
                ->getType();
            if (dyn_cast<MemberExpr>(expr->getCallee())->isArrow()) {
                ty = ty->getAs<PointerType>()->getPointeeType();
            }
            TemplateSpecializationType const * ct
                = ty->getAs<TemplateSpecializationType>();
            if (ct != nullptr) {
                SubstTemplateTypeParmType const * pt
                    = getAsSubstTemplateTypeParmType(
                        d->getParamDecl(n)->getType().getNonReferenceType());
                if (pt != nullptr) {
                    TemplateDecl const * td
                        = ct->getTemplateName().getAsTemplateDecl();
                    if (td != nullptr) {
                        //TODO: fix this superficial nonsense check:
                        if (ct->getNumArgs() >= 1
                            && ct->getArg(0).getKind() == TemplateArgument::Type
                            && isBool(ct->getArg(0).getAsType()))
                        {
                            continue;
                        }
                    }
                }
            }
        }
        reportWarning(i);
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseCXXConstructExpr(CXXConstructExpr * expr) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseCXXConstructExpr(expr);
    checkCXXConstructExpr(expr);
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseCXXTemporaryObjectExpr(
    CXXTemporaryObjectExpr * expr)
{
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseCXXTemporaryObjectExpr(expr);
    checkCXXConstructExpr(expr);
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseCStyleCastExpr(CStyleCastExpr * expr) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseCStyleCastExpr(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (i != expr->getSubExpr()->IgnoreParens()) {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseCXXStaticCastExpr(CXXStaticCastExpr * expr)
{
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseCXXStaticCastExpr(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (i != expr->getSubExpr()->IgnoreParens()) {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseCXXFunctionalCastExpr(
    CXXFunctionalCastExpr * expr)
{
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseCXXFunctionalCastExpr(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (i != expr->getSubExpr()->IgnoreParens()) {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseConditionalOperator(
    ConditionalOperator * expr)
{
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseConditionalOperator(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (!((i == expr->getTrueExpr()->IgnoreParens()
               && (isBoolExpr(expr->getFalseExpr()->IgnoreParenImpCasts())
                   || isExternCFunctionCallReturningInt(expr->getFalseExpr())))
              || (i == expr->getFalseExpr()->IgnoreParens()
                  && (isBoolExpr(expr->getTrueExpr()->IgnoreParenImpCasts())
                      || isExternCFunctionCallReturningInt(
                          expr->getTrueExpr())))
              || (!compiler.getLangOpts().CPlusPlus
                  && i == expr->getCond()->IgnoreParens())))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseBinLT(BinaryOperator * expr) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseBinLT(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (!((i == expr->getLHS()->IgnoreParens()
               && isMatchingBool(
                   expr->getRHS()->IgnoreImpCasts(), i->getSubExprAsWritten()))
              || (i == expr->getRHS()->IgnoreParens()
                  && isMatchingBool(
                      expr->getLHS()->IgnoreImpCasts(),
                      i->getSubExprAsWritten()))))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseBinLE(BinaryOperator * expr) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseBinLE(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (!((i == expr->getLHS()->IgnoreParens()
               && isMatchingBool(
                   expr->getRHS()->IgnoreImpCasts(), i->getSubExprAsWritten()))
              || (i == expr->getRHS()->IgnoreParens()
                  && isMatchingBool(
                      expr->getLHS()->IgnoreImpCasts(),
                      i->getSubExprAsWritten()))))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseBinGT(BinaryOperator * expr) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseBinGT(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (!((i == expr->getLHS()->IgnoreParens()
               && isMatchingBool(
                   expr->getRHS()->IgnoreImpCasts(), i->getSubExprAsWritten()))
              || (i == expr->getRHS()->IgnoreParens()
                  && isMatchingBool(
                      expr->getLHS()->IgnoreImpCasts(),
                      i->getSubExprAsWritten()))))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseBinGE(BinaryOperator * expr) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseBinGE(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (!((i == expr->getLHS()->IgnoreParens()
               && isMatchingBool(
                   expr->getRHS()->IgnoreImpCasts(), i->getSubExprAsWritten()))
              || (i == expr->getRHS()->IgnoreParens()
                  && isMatchingBool(
                      expr->getLHS()->IgnoreImpCasts(),
                      i->getSubExprAsWritten()))))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseBinEQ(BinaryOperator * expr) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseBinEQ(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (!((i == expr->getLHS()->IgnoreParens()
               && isMatchingBool(
                   expr->getRHS()->IgnoreImpCasts(), i->getSubExprAsWritten()))
              || (i == expr->getRHS()->IgnoreParens()
                  && isMatchingBool(
                      expr->getLHS()->IgnoreImpCasts(),
                      i->getSubExprAsWritten()))))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseBinNE(BinaryOperator * expr) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseBinNE(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (!((i == expr->getLHS()->IgnoreParens()
               && isMatchingBool(
                   expr->getRHS()->IgnoreImpCasts(), i->getSubExprAsWritten()))
              || (i == expr->getRHS()->IgnoreParens()
                  && isMatchingBool(
                      expr->getLHS()->IgnoreImpCasts(),
                      i->getSubExprAsWritten()))))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseBinAssign(BinaryOperator * expr) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseBinAssign(expr);
    // /usr/include/gtk-2.0/gtk/gtktogglebutton.h: struct _GtkToggleButton:
    //  guint GSEAL (active) : 1;
    // even though <http://www.gtk.org/api/2.6/gtk/GtkToggleButton.html>:
    //  "active"               gboolean              : Read / Write
    bool ext = false;
    MemberExpr const * me = dyn_cast<MemberExpr>(expr->getLHS());
    if (me != nullptr) {
        FieldDecl const * fd = dyn_cast<FieldDecl>(me->getMemberDecl());
        if (fd != nullptr && fd->isBitField()
            && fd->getBitWidthValue(compiler.getASTContext()) == 1)
        {
            TypedefType const * t = fd->getType()->getAs<TypedefType>();
            ext = t != nullptr && t->getDecl()->getNameAsString() == "guint";
        }
    }
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (i != expr->getRHS()->IgnoreParens()
            || !(ext || isBoolExpr(expr->getLHS())))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseBinAndAssign(CompoundAssignOperator * expr)
{
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseBinAndAssign(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (i != expr->getRHS()->IgnoreParens()
            || !isBool(expr->getLHS()->IgnoreParens(), false))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    if (!ignoreLocation(expr) && isBool(expr->getLHS(), false)
        && !isBool(expr->getRHS()->IgnoreParenImpCasts(), false))
    {
        report(
            DiagnosticsEngine::Warning, "mix of %0 and %1 in operator &=",
            expr->getRHS()->getLocStart())
            << expr->getLHS()->getType()
            << expr->getRHS()->IgnoreParenImpCasts()->getType()
            << expr->getSourceRange();
    }
    return ret;
}

bool ImplicitBoolConversion::TraverseBinOrAssign(CompoundAssignOperator * expr)
{
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseBinOrAssign(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (i != expr->getRHS()->IgnoreParens()
            || !isBool(expr->getLHS()->IgnoreParens(), false))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    if (!ignoreLocation(expr) && isBool(expr->getLHS(), false)
        && !isBool(expr->getRHS()->IgnoreParenImpCasts(), false))
    {
        report(
            DiagnosticsEngine::Warning, "mix of %0 and %1 in operator |=",
            expr->getRHS()->getLocStart())
            << expr->getLHS()->getType()
            << expr->getRHS()->IgnoreParenImpCasts()->getType()
            << expr->getSourceRange();
    }
    return ret;
}

bool ImplicitBoolConversion::TraverseBinXorAssign(CompoundAssignOperator * expr)
{
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseBinXorAssign(expr);
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (i != expr->getRHS()->IgnoreParens()
            || !isBool(expr->getLHS()->IgnoreParens(), false))
        {
            reportWarning(i);
        }
    }
    nested.pop();
    if (!ignoreLocation(expr) && isBool(expr->getLHS(), false)
        && !isBool(expr->getRHS()->IgnoreParenImpCasts(), false))
    {
        report(
            DiagnosticsEngine::Warning, "mix of %0 and %1 in operator ^=",
            expr->getRHS()->getLocStart())
            << expr->getLHS()->getType()
            << expr->getRHS()->IgnoreParenImpCasts()->getType()
            << expr->getSourceRange();
    }
    return ret;
}

bool ImplicitBoolConversion::TraverseReturnStmt(ReturnStmt * stmt) {
    nested.push(std::vector<ImplicitCastExpr const *>());
    bool ret = RecursiveASTVisitor::TraverseReturnStmt(stmt);
    Expr const * expr = stmt->getRetValue();
    if (expr != nullptr) {
        ExprWithCleanups const * ec = dyn_cast<ExprWithCleanups>(expr);
        if (ec != nullptr) {
            expr = ec->getSubExpr();
        }
        expr = expr->IgnoreParens();
    }
    assert(!nested.empty());
    for (auto i: nested.top()) {
        if (i != expr || !externCIntFunctionDefinition) {
            reportWarning(i);
        }
    }
    nested.pop();
    return ret;
}

bool ImplicitBoolConversion::TraverseFunctionDecl(FunctionDecl * decl) {
    bool ext = false;
    if (hasCLanguageLinkageType(decl) && decl->isThisDeclarationADefinition()) {
        QualType t { compat::getReturnType(*decl) };
        if (t->isSpecificBuiltinType(BuiltinType::Int)
            || t->isSpecificBuiltinType(BuiltinType::UInt))
        {
            ext = true;
        } else {
            TypedefType const * t2 = t->getAs<TypedefType>();
            // cf. rtl_locale_equals (and sal_Int32 can be long):
            if (t2 != nullptr
                && t2->getDecl()->getNameAsString() == "sal_Int32")
            {
                ext = true;
            }
        }
    }
    if (ext) {
        assert(!externCIntFunctionDefinition);
        externCIntFunctionDefinition = true;
    }
    bool ret = RecursiveASTVisitor::TraverseFunctionDecl(decl);
    if (ext) {
        externCIntFunctionDefinition = false;
    }
    return ret;
}

bool ImplicitBoolConversion::VisitImplicitCastExpr(
    ImplicitCastExpr const * expr)
{
    if (ignoreLocation(expr)) {
        return true;
    }
    if (isBool(expr->getSubExprAsWritten()) && !isBool(expr)) {
        // Ignore NoOp from 'sal_Bool' (aka 'unsigned char') to 'const unsigned
        // char' in makeAny(b) with b of type sal_Bool:
        if (expr->getCastKind() != CK_NoOp) {
            if (nested.empty()) {
                reportWarning(expr);
            } else {
                nested.top().push_back(expr);
            }
        }
        return true;
    }
    ExplicitCastExpr const * sub = dyn_cast<ExplicitCastExpr>(
        expr->getSubExpr()->IgnoreParenImpCasts());
    if (sub != nullptr
        && (sub->getSubExpr()->IgnoreParenImpCasts()->getType().IgnoreParens()
            == expr->getType().IgnoreParens())
        && isBool(sub->getSubExpr()->IgnoreParenImpCasts()))
    {
        report(
            DiagnosticsEngine::Warning,
            "explicit conversion (%0) from %1 to %2 implicitly cast back to %3",
            expr->getLocStart())
            << sub->getCastKindName()
            << sub->getSubExpr()->IgnoreParenImpCasts()->getType()
            << sub->getType() << expr->getType() << expr->getSourceRange();
        return true;
    }
    if (expr->getType()->isBooleanType() && !isBoolExpr(expr->getSubExpr())
        && !calls.empty())
    {
        CallExpr const * call = calls.top();
        if (std::find_if(
                call->arg_begin(), call->arg_end(),
                [expr](Expr const * e) { return expr == e->IgnoreParens(); })
            != call->arg_end())
        {
            report(
                DiagnosticsEngine::Warning,
                "implicit conversion (%0) of call argument from %1 to %2",
                expr->getLocStart())
                << expr->getCastKindName() << expr->getSubExpr()->getType()
                << expr->getType() << expr->getSourceRange();
            return true;
        }
    }
    return true;
}

bool ImplicitBoolConversion::isExternCFunctionCall(
    CallExpr const * expr, FunctionProtoType const ** functionType)
{
    assert(functionType != nullptr);
    *functionType = nullptr;
    Decl const * d = expr->getCalleeDecl();
    if (d != nullptr) {
        FunctionDecl const * fd = dyn_cast<FunctionDecl>(d);
        if (fd != nullptr) {
            PointerType const * pt = fd->getType()->getAs<PointerType>();
            QualType t2(pt == nullptr ? fd->getType() : pt->getPointeeType());
            *functionType = t2->getAs<FunctionProtoType>();
            assert(
                *functionType != nullptr || !compiler.getLangOpts().CPlusPlus
                || (fd->getBuiltinID() != Builtin::NotBuiltin
                    && isa<FunctionNoProtoType>(t2)));
                // __builtin_*s have no proto type?
            return fd->isExternC()
                || compiler.getSourceManager().isInExternCSystemHeader(
                    fd->getLocation());
        }
        VarDecl const * vd = dyn_cast<VarDecl>(d);
        if (vd != nullptr) {
            PointerType const * pt = vd->getType()->getAs<PointerType>();
            *functionType
                = ((pt == nullptr ? vd->getType() : pt->getPointeeType())
                   ->getAs<FunctionProtoType>());
            return vd->isExternC();
        }
    }
    return false;
}

bool ImplicitBoolConversion::isExternCFunctionCallReturningInt(
    Expr const * expr)
{
    CallExpr const * e = dyn_cast<CallExpr>(expr->IgnoreParenImpCasts());
    FunctionProtoType const * t;
    return e != nullptr && e->getType()->isSpecificBuiltinType(BuiltinType::Int)
        && isExternCFunctionCall(e, &t);
}

void ImplicitBoolConversion::checkCXXConstructExpr(
    CXXConstructExpr const * expr)
{
    assert(!nested.empty());
    for (auto i: nested.top()) {
        auto j = std::find_if(
            expr->arg_begin(), expr->arg_end(),
            [&i](Expr const * e) {
                return i == ignoreParenAndTemporaryMaterialization(e);
            });
        if (j != expr->arg_end()) {
            TemplateSpecializationType const * t1 = expr->getType()->
                getAs<TemplateSpecializationType>();
            SubstTemplateTypeParmType const * t2 = nullptr;
            CXXConstructorDecl const * d = expr->getConstructor();
            if (d->getNumParams() == expr->getNumArgs()) { //TODO: better check
                t2 = getAsSubstTemplateTypeParmType(
                    d->getParamDecl(j - expr->arg_begin())->getType()
                    .getNonReferenceType());
            }
            if (t1 != nullptr && t2 != nullptr) {
                TemplateDecl const * td
                    = t1->getTemplateName().getAsTemplateDecl();
                if (td != nullptr) {
                    TemplateParameterList const * ps
                        = td->getTemplateParameters();
                    auto i = std::find(
                        ps->begin(), ps->end(),
                        t2->getReplacedParameter()->getDecl());
                    if (i != ps->end()) {
                        if (ps->size() == t1->getNumArgs()) { //TODO
                            TemplateArgument const & arg = t1->getArg(
                                i - ps->begin());
                            if (arg.getKind() == TemplateArgument::Type
                                && isBool(arg.getAsType()))
                            {
                                continue;
                            }
                        }
                    }
                }
            }
        }
        reportWarning(i);
    }
}

void ImplicitBoolConversion::reportWarning(ImplicitCastExpr const * expr) {
    report(
        DiagnosticsEngine::Warning,
        "implicit conversion (%0) from %1 to %2", expr->getLocStart())
        << expr->getCastKindName() << expr->getSubExprAsWritten()->getType()
        << expr->getType() << expr->getSourceRange();
}

loplugin::Plugin::Registration<ImplicitBoolConversion> X(
    "implicitboolconversion");

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */