summaryrefslogtreecommitdiff
path: root/plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structuralsearch/visitor/KotlinMatchingVisitor.kt
blob: 913c1a29542f12ebe96b114736f79bff0604e11f (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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package org.jetbrains.kotlin.idea.structuralsearch.visitor

import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.elementType
import com.intellij.structuralsearch.StructuralSearchUtil
import com.intellij.structuralsearch.impl.matcher.CompiledPattern
import com.intellij.structuralsearch.impl.matcher.GlobalMatchingVisitor
import com.intellij.structuralsearch.impl.matcher.handlers.LiteralWithSubstitutionHandler
import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler
import com.intellij.util.containers.reverse
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.PropertyDescriptorImpl
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.calleeName
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.structuralsearch.*
import org.jetbrains.kotlin.kdoc.lexer.KDocTokens
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.kdoc.psi.impl.KDocImpl
import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink
import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection
import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.util.OperatorNameConventions

class KotlinMatchingVisitor(private val myMatchingVisitor: GlobalMatchingVisitor) : SSRKtVisitor() {
    /** Gets the next element in the query tree and removes unnecessary parentheses. */
    private inline fun <reified T> getTreeElementDepar(): T? = when (val element = myMatchingVisitor.element) {
        is KtParenthesizedExpression -> {
            val deparenthesized = element.deparenthesize()
            if (deparenthesized is T) deparenthesized else {
                myMatchingVisitor.result = false
                null
            }
        }
        else -> getTreeElement<T>()
    }

    /** Gets the next element in the tree */
    private inline fun <reified T> getTreeElement(): T? = when (val element = myMatchingVisitor.element) {
        is T -> element
        else -> {
            myMatchingVisitor.result = false
            null
        }
    }
    
    private inline fun <reified T:KtElement> factory(context: PsiElement, f: KtPsiFactory.() -> T): T {
        val psiFactory = KtPsiFactory(context, true)
        val result = psiFactory.f()
        (result.containingFile as KtFile).analysisContext = context
        return result
    }

    private fun GlobalMatchingVisitor.matchSequentially(elements: List<PsiElement?>, elements2: List<PsiElement?>) =
        matchSequentially(elements.toTypedArray(), elements2.toTypedArray())

    private fun GlobalMatchingVisitor.matchInAnyOrder(elements: List<PsiElement?>, elements2: List<PsiElement?>) =
        matchInAnyOrder(elements.toTypedArray(), elements2.toTypedArray())

    private fun GlobalMatchingVisitor.matchNormalized(
        element: KtExpression?,
        element2: KtExpression?,
        returnExpr: Boolean = false
    ): Boolean {
        val (e1, e2) =
            if (element is KtBlockExpression && element2 is KtBlockExpression) element to element2
            else normalizeExpressions(element, element2, returnExpr)

        val impossible = e1?.let {
            val handler = getHandler(it)
            e2 !is KtBlockExpression && handler is SubstitutionHandler && handler.minOccurs > 1
        } ?: false

        return !impossible && match(e1, e2)
    }

    private fun getHandler(element: PsiElement) = myMatchingVisitor.matchContext.pattern.getHandler(element)

    private fun matchTextOrVariable(el1: PsiElement?, el2: PsiElement?): Boolean {
        if (el1 == null) return true
        if (el2 == null) return el1 == el2
        return when (val handler = getHandler(el1)) {
            is SubstitutionHandler -> handler.validate(el2, myMatchingVisitor.matchContext)
            else -> myMatchingVisitor.matchText(el1, el2)
        }
    }

    override fun visitLeafPsiElement(leafPsiElement: LeafPsiElement) {
        val other = getTreeElementDepar<LeafPsiElement>() ?: return

        // Match element type
        if (!myMatchingVisitor.setResult(leafPsiElement.elementType == other.elementType)) return

        when (leafPsiElement.elementType) {
            KDocTokens.TEXT -> {
                myMatchingVisitor.result = when (val handler = leafPsiElement.getUserData(CompiledPattern.HANDLER_KEY)) {
                    is LiteralWithSubstitutionHandler -> handler.match(leafPsiElement, other, myMatchingVisitor.matchContext)
                    else -> matchTextOrVariable(leafPsiElement, other)
                }
            }
            KDocTokens.TAG_NAME, KtTokens.IDENTIFIER -> myMatchingVisitor.result = matchTextOrVariable(leafPsiElement, other)
        }
    }

    override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) {
        val other = getTreeElementDepar<KtExpression>() ?: return
        myMatchingVisitor.result = when (other) {
            is KtArrayAccessExpression -> myMatchingVisitor.match(expression.arrayExpression, other.arrayExpression)
                    && myMatchingVisitor.matchSons(expression.indicesNode, other.indicesNode)
            is KtDotQualifiedExpression -> myMatchingVisitor.match(expression.arrayExpression, other.receiverExpression)
                    && other.calleeName == "${OperatorNameConventions.GET}"
                    && myMatchingVisitor.matchSequentially(
                expression.indexExpressions, other.callExpression?.valueArguments?.map(KtValueArgument::getArgumentExpression)!!
            )
            else -> false
        }

    }

    /** Matches binary expressions including translated operators. */
    override fun visitBinaryExpression(expression: KtBinaryExpression) {
        fun KtBinaryExpression.match(other: KtBinaryExpression) = operationToken == other.operationToken
                && myMatchingVisitor.match(left, other.left)
                && myMatchingVisitor.match(right, other.right)

        fun KtQualifiedExpression.match(name: Name?, receiver: KtExpression?, callEntry: KtExpression?): Boolean {
            val callExpr = callExpression
            return callExpr is KtCallExpression && calleeName == "$name"
                    && myMatchingVisitor.match(receiver, receiverExpression)
                    && myMatchingVisitor.match(callEntry, callExpr.valueArguments.first().getArgumentExpression())
        }

        fun KtBinaryExpression.matchEq(other: KtBinaryExpression): Boolean {
            val otherLeft = other.left?.deparenthesize()
            val otherRight = other.right?.deparenthesize()
            return otherLeft is KtSafeQualifiedExpression
                    && otherLeft.match(OperatorNameConventions.EQUALS, left, right)
                    && other.operationToken == KtTokens.ELVIS
                    && otherRight is KtBinaryExpression
                    && myMatchingVisitor.match(right, otherRight.left)
                    && otherRight.operationToken == KtTokens.EQEQEQ
                    && myMatchingVisitor.match(factory(other) {createExpression("null")}, otherRight.right)
        }

        val other = getTreeElementDepar<KtExpression>() ?: return
        when (other) {
            is KtBinaryExpression -> {
                if (expression.operationToken == KtTokens.IDENTIFIER ) {
                    myMatchingVisitor.result = myMatchingVisitor.match(expression.left, other.right)
                            && myMatchingVisitor.match(expression.right, other.right)
                            && myMatchingVisitor.match(expression.operationReference, other.operationReference)
                    return
                }
                if (myMatchingVisitor.setResult(expression.match(other))) return
                when (expression.operationToken) { // semantical matching
                    KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ -> { // a.compareTo(b) OP 0
                        val left = other.left?.deparenthesize()
                        myMatchingVisitor.result = left is KtDotQualifiedExpression
                                && left.match(OperatorNameConventions.COMPARE_TO, expression.left, expression.right)
                                && expression.operationToken == other.operationToken
                                && myMatchingVisitor.match(other.right, factory(other) {createExpression("0")})

                    }
                    in augmentedAssignmentsMap.keys -> { // x OP= y with x = x OP y
                        if (other.operationToken == KtTokens.EQ) {
                            val right = other.right?.deparenthesize()
                            val left = other.left?.deparenthesize()
                            myMatchingVisitor.result = right is KtBinaryExpression
                                    && augmentedAssignmentsMap[expression.operationToken] == right.operationToken
                                    && myMatchingVisitor.match(expression.left, left)
                                    && myMatchingVisitor.match(expression.left, right.left)
                                    && myMatchingVisitor.match(expression.right, right.right)
                        }
                    }
                    KtTokens.EQ -> { //  x = x OP y with x OP= y
                        val right = expression.right?.deparenthesize()
                        if (right is KtBinaryExpression && right.operationToken == augmentedAssignmentsMap[other.operationToken]) {
                            myMatchingVisitor.result = myMatchingVisitor.match(expression.left, other.left)
                                    && myMatchingVisitor.match(right.left, other.left)
                                    && myMatchingVisitor.match(right.right, other.right)
                        }
                    }
                    KtTokens.EQEQ -> { // a?.equals(b) ?: (b === null)
                        myMatchingVisitor.result = expression.matchEq(other)
                    }
                }
            }
            is KtDotQualifiedExpression -> { // translated matching
                val token = expression.operationToken
                val left = expression.left
                val right = expression.right
                when {
                    token == KtTokens.IN_KEYWORD -> { // b.contains(a)
                        val parent = other.parent
                        val isNotNegated = if (parent is KtPrefixExpression) parent.operationToken != KtTokens.EXCL else true
                        myMatchingVisitor.result = isNotNegated && other.match(OperatorNameConventions.CONTAINS, right, left)
                    }
                    token == KtTokens.NOT_IN -> myMatchingVisitor.result = false // already matches with prefix expression
                    token == KtTokens.EQ && left is KtArrayAccessExpression -> { // a[x] = expression
                        val matchedArgs = left.indexExpressions.apply { add(right) }
                        myMatchingVisitor.result = myMatchingVisitor.match(left.arrayExpression, other.receiverExpression)
                                && other.calleeName == "${OperatorNameConventions.SET}"
                                && myMatchingVisitor.matchSequentially(
                            matchedArgs, other.callExpression?.valueArguments?.map(KtValueArgument::getArgumentExpression)!!
                        )
                    }
                    else -> { // a.plus(b) all arithmetic operators
                        val selector = other.selectorExpression
                        if (expression.operationToken == KtTokens.EQ && right is KtBinaryExpression) {
                            // Matching x = x + y with x.plusAssign(y)
                            val opName = augmentedAssignmentsMap.reverse()[right.operationToken]?.binaryExprOpName()
                            myMatchingVisitor.result = selector is KtCallExpression
                                    && myMatchingVisitor.match(left, other.receiverExpression)
                                    && other.match(opName, right.left, right.right)
                        } else {
                            myMatchingVisitor.result = selector is KtCallExpression && other.match(
                                expression.operationToken.binaryExprOpName(), left, right
                            )
                        }
                    }
                }
            }
            is KtPrefixExpression -> { // translated matching
                val baseExpr = other.baseExpression?.deparenthesize()
                when (expression.operationToken) {
                    KtTokens.NOT_IN -> { // !b.contains(a)
                        myMatchingVisitor.result = other.operationToken == KtTokens.EXCL
                                && baseExpr is KtDotQualifiedExpression
                                && baseExpr.match(OperatorNameConventions.CONTAINS, expression.right, expression.left)
                    }
                    KtTokens.EXCLEQ -> { // !(a?.equals(b) ?: (b === null))
                        myMatchingVisitor.result = other.operationToken == KtTokens.EXCL
                                && baseExpr is KtBinaryExpression
                                && expression.matchEq(baseExpr)
                    }
                }
            }
            else -> myMatchingVisitor.result = false
        }
    }

    override fun visitBlockExpression(expression: KtBlockExpression) {
        val other = getTreeElementDepar<KtBlockExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.matchSequentially(expression.statements, other.statements)
    }

    override fun visitUnaryExpression(expression: KtUnaryExpression) {
        val other = getTreeElementDepar<KtExpression>() ?: return
        myMatchingVisitor.result = when (other) {
            is KtDotQualifiedExpression -> {
                myMatchingVisitor.match(expression.baseExpression, other.receiverExpression)
                        && OperatorConventions.UNARY_OPERATION_NAMES[expression.operationToken].toString() == other.calleeName
            }
            is KtUnaryExpression -> myMatchingVisitor.match(expression.baseExpression, other.baseExpression)
                    && myMatchingVisitor.match(expression.operationReference, other.operationReference)
            else -> false
        }

    }

    override fun visitParenthesizedExpression(expression: KtParenthesizedExpression) {
        fun KtExpression.countParenthesize(initial: Int = 0): Int {
            val parentheses = children.firstOrNull { it is KtParenthesizedExpression } as KtExpression?
            return parentheses?.countParenthesize(initial + 1) ?: initial
        }

        val other = getTreeElement<KtParenthesizedExpression>() ?: return
        if (!myMatchingVisitor.setResult(expression.countParenthesize() == other.countParenthesize())) return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.deparenthesize(), other.deparenthesize())
    }

    override fun visitConstantExpression(expression: KtConstantExpression) {
        val other = getTreeElementDepar<KtExpression>() ?: return
        myMatchingVisitor.result = matchTextOrVariable(expression, other)
    }

    override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
        val other = getTreeElementDepar<PsiElement>() ?: return

        val exprHandler = getHandler(expression)
        if (other is KtReferenceExpression && exprHandler is SubstitutionHandler) {
            val ref = other.mainReference
            val bindingContext = ref.element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
            val referenced = ref.resolveToDescriptors(bindingContext).firstOrNull()?.let {
                if (it is ConstructorDescriptor) it.constructedClass else it
            }
            if (referenced is ClassifierDescriptor) {
                val fqName = referenced.fqNameOrNull()
                val predicate = exprHandler.findRegExpPredicate()
                if (predicate != null && fqName != null &&
                    predicate.doMatch(fqName.asString(), myMatchingVisitor.matchContext, other)
                ) {
                    myMatchingVisitor.result = true
                    exprHandler.addResult(other, myMatchingVisitor.matchContext)
                    return
                }
            }
        }

        // Match Int::class with X.Int::class
        val skipReceiver = other.parent is KtDoubleColonExpression
                && other is KtDotQualifiedExpression
                && myMatchingVisitor.match(expression, other.selectorExpression)

        myMatchingVisitor.result = skipReceiver || matchTextOrVariable(
            expression.getReferencedNameElement(),
            if (other is KtSimpleNameExpression) other.getReferencedNameElement() else other
        )

        val handler = getHandler(expression.getReferencedNameElement())
        if (myMatchingVisitor.result && handler is SubstitutionHandler) {
            handler.handle(
                if (other is KtSimpleNameExpression) other.getReferencedNameElement() else other,
                myMatchingVisitor.matchContext
            )
        }
    }

    override fun visitContinueExpression(expression: KtContinueExpression) {
        val other = getTreeElementDepar<KtContinueExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
    }

    override fun visitBreakExpression(expression: KtBreakExpression) {
        val other = getTreeElementDepar<KtBreakExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
    }

    override fun visitThisExpression(expression: KtThisExpression) {
        val other = getTreeElementDepar<KtThisExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
    }

    override fun visitSuperExpression(expression: KtSuperExpression) {
        val other = getTreeElementDepar<KtSuperExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
                && myMatchingVisitor.match(expression.superTypeQualifier, other.superTypeQualifier)
    }

    override fun visitReturnExpression(expression: KtReturnExpression) {
        val other = getTreeElementDepar<KtReturnExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
                && myMatchingVisitor.match(expression.returnedExpression, other.returnedExpression)
    }

    override fun visitFunctionType(type: KtFunctionType) {
        val other = getTreeElementDepar<KtFunctionType>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(type.receiverTypeReference, other.receiverTypeReference)
                && myMatchingVisitor.match(type.parameterList, other.parameterList)
                && myMatchingVisitor.match(type.returnTypeReference, other.returnTypeReference)
    }

    override fun visitUserType(type: KtUserType) {
        val other = myMatchingVisitor.element

        myMatchingVisitor.result = when (other) {
            is KtUserType -> {
                type.qualifier?.let { typeQualifier -> // if query has fq type
                    myMatchingVisitor.match(typeQualifier, other.qualifier) // recursively match qualifiers
                            && myMatchingVisitor.match(type.referenceExpression, other.referenceExpression)
                            && myMatchingVisitor.match(type.typeArgumentList, other.typeArgumentList)
                } ?: let { // no fq type
                    myMatchingVisitor.match(type.referenceExpression, other.referenceExpression)
                            && myMatchingVisitor.match(type.typeArgumentList, other.typeArgumentList)
                }
            }
            is KtTypeElement -> matchTextOrVariable(type.referenceExpression, other)
            else -> false
        }
    }

    override fun visitNullableType(nullableType: KtNullableType) {
        val other = getTreeElementDepar<KtNullableType>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(nullableType.innerType, other.innerType)
    }

    override fun visitDynamicType(type: KtDynamicType) {
        myMatchingVisitor.result = myMatchingVisitor.element is KtDynamicType
    }

    private fun matchTypeReferenceWithDeclaration(typeReference: KtTypeReference?, other: KtDeclaration): Boolean {
        val type = other.resolveKotlinType()
        if (type != null) {
            val fqType = DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type)
            val analzyableFile = factory(other) {createAnalyzableFile("${other.hashCode()}.kt", "val x: $fqType = TODO()", other)}
            return myMatchingVisitor.match(typeReference, (analzyableFile.lastChild as KtProperty).typeReference)
        }
        return false
    }

    override fun visitTypeReference(typeReference: KtTypeReference) {
        val other = getTreeElementDepar<KtTypeReference>() ?: return
        val parent = other.parent

        val isReceiverTypeReference = when (parent) {
            is KtProperty -> parent.receiverTypeReference == other
            is KtNamedFunction -> parent.receiverTypeReference == other
            else -> false
        }

        val type = when {
            !isReceiverTypeReference && parent is KtProperty -> parent.resolveKotlinType()
            isReceiverTypeReference && parent is KtDeclaration && parent.descriptor is FunctionDescriptor ->
                (parent.descriptor as FunctionDescriptor).extensionReceiverParameter?.value?.type
            isReceiverTypeReference && parent is KtDeclaration && parent.descriptor is PropertyDescriptorImpl ->
                (parent.descriptor as PropertyDescriptorImpl).extensionReceiverParameter?.value?.type
            else -> null
        }

        val fqMatch = when {
            type != null -> {
                val handler = getHandler(typeReference)
                type.renderNames().any {
                    if (handler is SubstitutionHandler)
                        if (handler.findRegExpPredicate()?.doMatch(it, myMatchingVisitor.matchContext, other) == true) {
                            handler.addResult(other, myMatchingVisitor.matchContext)
                            true
                        } else false
                    else myMatchingVisitor.matchText(typeReference.text, it)
                }

            }
            else -> false
        }

        myMatchingVisitor.result = fqMatch || myMatchingVisitor.matchSons(typeReference, other)
    }

    override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
        val other = getTreeElementDepar<KtQualifiedExpression>() ?: return
        myMatchingVisitor.result = expression.operationSign == other.operationSign
                && myMatchingVisitor.match(expression.receiverExpression, other.receiverExpression)
                && myMatchingVisitor.match(expression.selectorExpression, other.selectorExpression)
    }

    override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
        val other = getTreeElementDepar<KtExpression>() ?: return
        val handler = getHandler(expression.receiverExpression)
        if (other is KtDotQualifiedExpression) {
            // Regular matching
            myMatchingVisitor.result = myMatchingVisitor.matchOptionally(expression.receiverExpression, other.receiverExpression)
                    && other.selectorExpression is KtCallExpression == expression.selectorExpression is KtCallExpression
                    && myMatchingVisitor.match(expression.selectorExpression, other.selectorExpression)
        } else {
            val selector = expression.selectorExpression

            // Match '_?.'_()
            myMatchingVisitor.result = selector is KtCallExpression == other is KtCallExpression
                    && (handler is SubstitutionHandler && handler.minOccurs == 0 || other.parent is KtDoubleColonExpression)
                    && other.parent !is KtDotQualifiedExpression
                    && other.parent !is KtReferenceExpression
                    && myMatchingVisitor.match(selector, other)

            // Match fq.call() with call()
            if (!myMatchingVisitor.result && other is KtCallExpression && other.parent !is KtDotQualifiedExpression && selector is KtCallExpression) {
                val expressionCall = expression.text.substringBefore('(')
                val otherCall = other.getCallableDescriptor()?.fqNameSafe
                myMatchingVisitor.result = otherCall != null
                                           && myMatchingVisitor.matchText(expressionCall, otherCall.toString().substringBefore(".<"))
                                           && myMatchingVisitor.match(selector.typeArgumentList, other.typeArgumentList)
                                           && matchValueArguments(resolveParameters(other),
                                                                  selector.valueArgumentList, other.valueArgumentList,
                                                                  selector.lambdaArguments, other.lambdaArguments)
            }
        }
    }

    override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
        val other = getTreeElementDepar<KtLambdaExpression>() ?: return
        val lambdaVP = lambdaExpression.valueParameters
        val otherVP = other.valueParameters

        myMatchingVisitor.result =
            (!lambdaExpression.functionLiteral.hasParameterSpecification()
                    || myMatchingVisitor.matchSequentially(lambdaVP, otherVP)
                    || lambdaVP.map { p -> getHandler(p).let { if (it is SubstitutionHandler) it.minOccurs else 1 } }.sum() == 1
                            && !other.functionLiteral.hasParameterSpecification()
                            && (other.functionLiteral.descriptor as AnonymousFunctionDescriptor).valueParameters.size == 1)
                && myMatchingVisitor.match(lambdaExpression.bodyExpression, other.bodyExpression)
    }

    override fun visitTypeProjection(typeProjection: KtTypeProjection) {
        val other = getTreeElementDepar<KtTypeProjection>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(typeProjection.typeReference, other.typeReference)
                && myMatchingVisitor.match(typeProjection.modifierList, other.modifierList)
                && typeProjection.projectionKind == other.projectionKind
    }

    override fun visitTypeArgumentList(typeArgumentList: KtTypeArgumentList) {
        val other = getTreeElementDepar<KtTypeArgumentList>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.matchSequentially(typeArgumentList.arguments, other.arguments)
    }

    override fun visitArgument(argument: KtValueArgument) {
        val other = getTreeElementDepar<KtValueArgument>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(argument.getArgumentExpression(), other.getArgumentExpression())
                && (!argument.isNamed() || !other.isNamed() || matchTextOrVariable(
            argument.getArgumentName(), other.getArgumentName()
        ))
    }

    private fun MutableList<KtValueArgument>.addDefaultArguments(parameters: List<KtParameter?>) {
        if (parameters.isEmpty()) return
        val params = parameters.toTypedArray()
        var i = 0
        while (i < size) {
            val arg = get(i)
            if (arg.isNamed()) {
                params[parameters.indexOfFirst { it?.nameAsName == arg.getArgumentName()?.asName }] = null
                i++
            } else {
                val curParam = params[i] ?: throw IllegalStateException(
                    KotlinBundle.message("error.param.can.t.be.null.at.index.0.in.1", i, params.map { it?.text })
                )
                params[i] = null
                if (curParam.isVarArg) {
                    val varArgType = arg.getArgumentExpression()?.resolveType()
                    var curArg: KtValueArgument? = arg
                    while (varArgType != null && varArgType == curArg?.getArgumentExpression()?.resolveType() || curArg?.isSpread == true) {
                        i++
                        curArg = getOrNull(i)

                    }
                } else i++
            }
        }
        params.filterNotNull().forEach { add(factory(myMatchingVisitor.element) {createArgument(it.defaultValue, it.nameAsName, reformat = false) }) }
    }

    private fun matchValueArguments(
        parameters: List<KtParameter>,
        valueArgList: KtValueArgumentList?,
        otherValueArgList: KtValueArgumentList?,
        lambdaArgList: List<KtLambdaArgument>,
        otherLambdaArgList: List<KtLambdaArgument>
    ): Boolean {
        if (valueArgList != null) {
            val handler = getHandler(valueArgList)
            val normalizedOtherArgs = otherValueArgList?.arguments?.toMutableList() ?: mutableListOf()
            normalizedOtherArgs.addAll(otherLambdaArgList)
            normalizedOtherArgs.addDefaultArguments(parameters)
            if (normalizedOtherArgs.isEmpty() && handler is SubstitutionHandler && handler.minOccurs == 0) {
                return myMatchingVisitor.matchSequentially(lambdaArgList, otherLambdaArgList)
            }
            val normalizedArgs = valueArgList.arguments.toMutableList()
            normalizedArgs.addAll(lambdaArgList)
            return matchValueArguments(normalizedArgs, normalizedOtherArgs)
        }
        return matchValueArguments(lambdaArgList, otherLambdaArgList)
    }

    private fun matchValueArguments(queryArgs: List<KtValueArgument>, codeArgs: List<KtValueArgument>): Boolean {
        var queryIndex = 0
        var codeIndex = 0
        while (queryIndex < queryArgs.size) {
            val queryArg = queryArgs[queryIndex]
            val codeArg = codeArgs.getOrElse(codeIndex) { return@matchValueArguments false }
            if (getHandler(queryArg) is SubstitutionHandler) {
                return myMatchingVisitor.matchSequentially(
                    queryArgs.subList(queryIndex, queryArgs.lastIndex + 1),
                    codeArgs.subList(codeIndex, codeArgs.lastIndex + 1)
                )
            }

            // varargs declared in call matching with one-to-one argument passing
            if (queryArg.isSpread && !codeArg.isSpread) {
                val spreadArgExpr = queryArg.getArgumentExpression()
                if (spreadArgExpr is KtCallExpression) {
                    spreadArgExpr.valueArguments.forEach { spreadedArg ->
                        if (!myMatchingVisitor.match(spreadedArg, codeArgs[codeIndex++])) return@matchValueArguments false
                    }
                    queryIndex++
                    continue
                }   // can't match array that is not created in the call itself
                myMatchingVisitor.result = false
                return myMatchingVisitor.result
            }
            if (!queryArg.isSpread && codeArg.isSpread) {
                val spreadArgExpr = codeArg.getArgumentExpression()
                if (spreadArgExpr is KtCallExpression) {
                    spreadArgExpr.valueArguments.forEach { spreadedArg ->
                        if (!myMatchingVisitor.match(queryArgs[queryIndex++], spreadedArg)) return@matchValueArguments false
                    }
                    codeIndex++
                    continue
                }
                return false// can't match array that is not created in the call itself
            }
            // normal argument matching
            if (!myMatchingVisitor.match(queryArg, codeArg)) {
                return if (queryArg.isNamed() || codeArg.isNamed()) { // start comparing for out of order arguments
                    myMatchingVisitor.matchInAnyOrder(
                        queryArgs.subList(queryIndex, queryArgs.lastIndex + 1),
                        codeArgs.subList(codeIndex, codeArgs.lastIndex + 1)
                    )
                } else false
            }
            queryIndex++
            codeIndex++
        }
        if (codeIndex != codeArgs.size) return false
        return true
    }

    private fun resolveParameters(other: KtElement): List<KtParameter> {
        return other.resolveToCall()?.candidateDescriptor?.original?.valueParameters?.mapNotNull {
            it.source.getPsi() as? KtParameter
        } ?: emptyList()
    }

    override fun visitCallExpression(expression: KtCallExpression) {
        val other = getTreeElementDepar<KtExpression>() ?: return
        val parameters = resolveParameters(other)
        myMatchingVisitor.result = when (other) {
            is KtCallExpression -> {
                myMatchingVisitor.match(expression.calleeExpression, other.calleeExpression)
                        && myMatchingVisitor.match(expression.typeArgumentList, other.typeArgumentList)
                        && matchValueArguments(
                    parameters, expression.valueArgumentList, other.valueArgumentList,
                    expression.lambdaArguments, other.lambdaArguments
                )
            }
            is KtDotQualifiedExpression -> other.callExpression is KtCallExpression
                    && myMatchingVisitor.match(expression.calleeExpression, other.receiverExpression)
                    && other.calleeName == "${OperatorNameConventions.INVOKE}"
                    && matchValueArguments(
                parameters,
                expression.valueArgumentList, other.callExpression?.valueArgumentList,
                expression.lambdaArguments, other.callExpression?.lambdaArguments ?: emptyList()
            )
            else -> false
        }
    }

    override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) {
        val other = getTreeElementDepar<KtCallableReferenceExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.callableReference, other.callableReference)
                && myMatchingVisitor.matchOptionally(expression.receiverExpression, other.receiverExpression)
    }

    override fun visitTypeParameter(parameter: KtTypeParameter) {
        val other = getTreeElementDepar<KtTypeParameter>() ?: return
        myMatchingVisitor.result = matchTextOrVariable(parameter.firstChild, other.firstChild) // match generic identifier
                && myMatchingVisitor.match(parameter.extendsBound, other.extendsBound)
                && parameter.variance == other.variance
        parameter.nameIdentifier?.let { nameIdentifier ->
            val handler = getHandler(nameIdentifier)
            if (myMatchingVisitor.result && handler is SubstitutionHandler) {
                handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
            }
        }
    }

    override fun visitParameter(parameter: KtParameter) {
        val other = getTreeElementDepar<KtParameter>() ?: return
        val decl = other.parent.parent
        val typeMatched = when {
            decl is KtFunctionType || decl is KtCatchClause || (parameter.isVarArg && other.isVarArg) -> {
                myMatchingVisitor.match(parameter.typeReference, other.typeReference)
            }
            else -> matchTypeReferenceWithDeclaration(parameter.typeReference, other)
        }
        val otherNameIdentifier = if (getHandler(parameter) is SubstitutionHandler
            && parameter.nameIdentifier != null
            && other.nameIdentifier == null
        ) other else other.nameIdentifier
        myMatchingVisitor.result = typeMatched
                && myMatchingVisitor.match(parameter.defaultValue, other.defaultValue)
                && (parameter.isVarArg == other.isVarArg || getHandler(parameter) is SubstitutionHandler)
                && myMatchingVisitor.match(parameter.valOrVarKeyword, other.valOrVarKeyword)
                && (parameter.nameIdentifier == null || matchTextOrVariable(parameter.nameIdentifier, otherNameIdentifier))
                && myMatchingVisitor.match(parameter.modifierList, other.modifierList)
                && myMatchingVisitor.match(parameter.destructuringDeclaration, other.destructuringDeclaration)
        parameter.nameIdentifier?.let { nameIdentifier ->
            val handler = getHandler(nameIdentifier)
            if (myMatchingVisitor.result && handler is SubstitutionHandler) {
                handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
            }
        }
    }

    override fun visitTypeParameterList(list: KtTypeParameterList) {
        val other = getTreeElementDepar<KtTypeParameterList>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.matchSequentially(list.parameters, other.parameters)
    }

    override fun visitParameterList(list: KtParameterList) {
        val other = getTreeElementDepar<KtParameterList>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.matchSequentially(list.parameters, other.parameters)
    }

    override fun visitConstructorDelegationCall(call: KtConstructorDelegationCall) {
        val other = getTreeElementDepar<KtConstructorDelegationCall>() ?: return
        val parameters = resolveParameters(other)
        myMatchingVisitor.result = myMatchingVisitor.match(call.calleeExpression, other.calleeExpression)
                && myMatchingVisitor.match(call.typeArgumentList, other.typeArgumentList)
                && matchValueArguments(
            parameters,
            call.valueArgumentList, other.valueArgumentList, call.lambdaArguments, other.lambdaArguments
        )
    }

    override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) {
        val other = getTreeElementDepar<KtSecondaryConstructor>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(constructor.modifierList, other.modifierList)
                && myMatchingVisitor.match(constructor.typeParameterList, other.typeParameterList)
                && myMatchingVisitor.match(constructor.valueParameterList, other.valueParameterList)
                && myMatchingVisitor.match(constructor.getDelegationCallOrNull(), other.getDelegationCallOrNull())
                && myMatchingVisitor.match(constructor.bodyExpression, other.bodyExpression)
    }

    override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) {
        val other = getTreeElementDepar<KtPrimaryConstructor>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(constructor.modifierList, other.modifierList)
                && myMatchingVisitor.match(constructor.typeParameterList, other.typeParameterList)
                && myMatchingVisitor.match(constructor.valueParameterList, other.valueParameterList)
    }

    override fun visitAnonymousInitializer(initializer: KtAnonymousInitializer) {
        val other = getTreeElementDepar<KtAnonymousInitializer>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(initializer.body, other.body)
    }

    override fun visitClassBody(classBody: KtClassBody) {
        val other = getTreeElementDepar<KtClassBody>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.matchSonsInAnyOrder(classBody, other)
    }

    override fun visitSuperTypeCallEntry(call: KtSuperTypeCallEntry) {
        val other = getTreeElementDepar<KtSuperTypeCallEntry>() ?: return
        val parameters = resolveParameters(other)
        myMatchingVisitor.result = myMatchingVisitor.match(call.calleeExpression, other.calleeExpression)
                && myMatchingVisitor.match(call.typeArgumentList, other.typeArgumentList)
                && matchValueArguments(
            parameters,
            call.valueArgumentList, other.valueArgumentList, call.lambdaArguments, other.lambdaArguments
        )
    }

    override fun visitSuperTypeEntry(specifier: KtSuperTypeEntry) {
        val other = getTreeElementDepar<KtSuperTypeEntry>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(specifier.typeReference, other.typeReference)
    }

    private fun matchTypeAgainstElement(
        type: String,
        element: PsiElement,
        other: PsiElement
    ): Boolean {
        return when (val predicate = (getHandler(element) as? SubstitutionHandler)?.findRegExpPredicate()) {
            null -> element.text == type
                    // Ignore type parameters if absent from the pattern
                    || !element.text.contains('<') && element.text == type.removeTypeParameters()
            else -> predicate.doMatch(type, myMatchingVisitor.matchContext, other)
        }
    }

    override fun visitSuperTypeList(list: KtSuperTypeList) {
        val other = getTreeElementDepar<KtSuperTypeList>() ?: return

        val withinHierarchyEntries = list.entries.filter {
            val type = it.typeReference; type is KtTypeReference && getHandler(type).withinHierarchyTextFilterSet
        }
        (other.parent as? KtClassOrObject)?.let { klass ->
            val supertypes = (klass.descriptor as ClassDescriptor).toSimpleType().supertypes()
            withinHierarchyEntries.forEach { entry ->
                val typeReference = entry.typeReference
                if (!matchTextOrVariable(typeReference, klass.nameIdentifier) && typeReference != null && supertypes.none {
                        it.renderNames().any { type -> matchTypeAgainstElement(type, typeReference, other) }
                    }) {
                    myMatchingVisitor.result = false
                    return@visitSuperTypeList
                }
            }
        }

        myMatchingVisitor.result =
            myMatchingVisitor.matchInAnyOrder(list.entries.filter { it !in withinHierarchyEntries }, other.entries)
    }

    override fun visitClass(klass: KtClass) {
        val other = getTreeElementDepar<KtClass>() ?: return
        val otherDescriptor = other.descriptor ?: return

        val identifier = klass.nameIdentifier
        val otherIdentifier = other.nameIdentifier
        var matchNameIdentifiers = matchTextOrVariable(identifier, otherIdentifier)
                || identifier != null && otherIdentifier != null && matchTypeAgainstElement(
            (otherDescriptor as LazyClassDescriptor).defaultType.fqName.toString(), identifier, otherIdentifier
                )

        // Possible match if "within hierarchy" is set
        if (!matchNameIdentifiers && identifier != null && otherIdentifier != null) {
            val identifierHandler = getHandler(identifier)
            val checkHierarchyDown = identifierHandler.withinHierarchyTextFilterSet

            if (checkHierarchyDown) {
                // Check hierarchy down (down of pattern element = supertypes of code element)
                matchNameIdentifiers = (otherDescriptor as ClassDescriptor).toSimpleType().supertypes().any { type ->
                    type.renderNames().any { renderedType ->
                        matchTypeAgainstElement(renderedType, identifier, otherIdentifier)
                    }
                }
            } else if (identifier.getUserData(KotlinCompilingVisitor.WITHIN_HIERARCHY) == true) {
                // Check hierarchy up (up of pattern element = inheritors of code element)
                matchNameIdentifiers = HierarchySearchRequest(
                    other,
                    GlobalSearchScope.allScope(other.project),
                    true
                ).searchInheritors().any { psiClass ->
                    arrayOf(psiClass.name, psiClass.qualifiedName).filterNotNull().any { renderedType ->
                        matchTypeAgainstElement(renderedType, identifier, otherIdentifier)
                    }
                }
            }
        }

        myMatchingVisitor.result = myMatchingVisitor.match(klass.getClassOrInterfaceKeyword(), other.getClassOrInterfaceKeyword())
                && myMatchingVisitor.match(klass.modifierList, other.modifierList)
                && matchNameIdentifiers
                && myMatchingVisitor.match(klass.typeParameterList, other.typeParameterList)
                && myMatchingVisitor.match(klass.primaryConstructor, other.primaryConstructor)
                && myMatchingVisitor.matchInAnyOrder(klass.secondaryConstructors, other.secondaryConstructors)
                && myMatchingVisitor.match(klass.getSuperTypeList(), other.getSuperTypeList())
                && myMatchingVisitor.match(klass.body, other.body)
                && myMatchingVisitor.match(klass.docComment, other.docComment)
        val handler = getHandler(klass.nameIdentifier!!)
        if (myMatchingVisitor.result && handler is SubstitutionHandler) {
            handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
        }
    }

    override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) {
        val other = getTreeElementDepar<KtObjectLiteralExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.objectDeclaration, other.objectDeclaration)
    }

    override fun visitObjectDeclaration(declaration: KtObjectDeclaration) {
        val other = getTreeElementDepar<KtObjectDeclaration>() ?: return
        val otherIdentifier =
            other.nameIdentifier ?: if (other.isCompanion()) (other.parent.parent as KtClass).nameIdentifier else null
        myMatchingVisitor.result = myMatchingVisitor.match(declaration.modifierList, other.modifierList)
                && matchTextOrVariable(declaration.nameIdentifier, otherIdentifier)
                && myMatchingVisitor.match(declaration.getSuperTypeList(), other.getSuperTypeList())
                && myMatchingVisitor.match(declaration.body, other.body)
        declaration.nameIdentifier?.let { declNameIdentifier ->
            val handler = getHandler(declNameIdentifier)
            if (myMatchingVisitor.result && handler is SubstitutionHandler) {
                handler.handle(otherIdentifier, myMatchingVisitor.matchContext)
            }
        }
    }

    private fun normalizeExpressionRet(expression: KtExpression?): KtExpression? = when {
        expression is KtBlockExpression && expression.statements.size == 1 -> expression.firstStatement?.let {
            if (it is KtReturnExpression) it.returnedExpression else it
        }
        else -> expression
    }

    private fun normalizeExpression(expression: KtExpression?): KtExpression? = when {
        expression is KtBlockExpression && expression.statements.size == 1 -> expression.firstStatement
        else -> expression
    }

    private fun normalizeExpressions(
        patternExpr: KtExpression?,
        codeExpr: KtExpression?,
        returnExpr: Boolean
    ): Pair<KtExpression?, KtExpression?> {
        val normalizedExpr = if (returnExpr) normalizeExpressionRet(patternExpr) else normalizeExpression(patternExpr)
        val normalizedCodeExpr = if (returnExpr) normalizeExpressionRet(codeExpr) else normalizeExpression(codeExpr)

        return when {
            normalizedExpr is KtBlockExpression || normalizedCodeExpr is KtBlockExpression -> patternExpr to codeExpr
            else -> normalizedExpr to normalizedCodeExpr
        }
    }

    override fun visitNamedFunction(function: KtNamedFunction) {
        val other = getTreeElementDepar<KtNamedFunction>() ?: return
        val (patternBody, codeBody) = normalizeExpressions(function.bodyBlockExpression, other.bodyBlockExpression, true)

        val bodyHandler = patternBody?.let(::getHandler)
        val bodyMatch = when {
            patternBody is KtNameReferenceExpression && codeBody == null -> bodyHandler is SubstitutionHandler
                    && bodyHandler.minOccurs <= 1 && bodyHandler.maxOccurs >= 1
                    && myMatchingVisitor.match(patternBody, other.bodyExpression)
            patternBody is KtNameReferenceExpression -> myMatchingVisitor.match(
                function.bodyBlockExpression,
                other.bodyBlockExpression
            )
            patternBody == null && codeBody == null -> myMatchingVisitor.match(function.bodyExpression, other.bodyExpression)
            patternBody == null -> function.bodyExpression == null || codeBody !is KtBlockExpression && myMatchingVisitor.match(function.bodyExpression, codeBody)
            codeBody == null -> patternBody !is KtBlockExpression && myMatchingVisitor.match(patternBody, other.bodyExpression)
            else -> myMatchingVisitor.match(function.bodyBlockExpression, other.bodyBlockExpression)
        }
        myMatchingVisitor.result = myMatchingVisitor.match(function.modifierList, other.modifierList)
                && matchTextOrVariable(function.nameIdentifier, other.nameIdentifier)
                && myMatchingVisitor.match(function.typeParameterList, other.typeParameterList)
                && matchTypeReferenceWithDeclaration(function.typeReference, other)
                && myMatchingVisitor.match(function.valueParameterList, other.valueParameterList)
                && myMatchingVisitor.match(function.receiverTypeReference, other.receiverTypeReference)
                && bodyMatch

        function.nameIdentifier?.let { nameIdentifier ->
            val handler = getHandler(nameIdentifier)
            if (myMatchingVisitor.result && handler is SubstitutionHandler) {
                handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
            }
        }
    }

    override fun visitModifierList(list: KtModifierList) {
        val other = getTreeElementDepar<KtModifierList>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.matchSonsInAnyOrder(list, other)
    }

    override fun visitIfExpression(expression: KtIfExpression) {
        val other = getTreeElementDepar<KtIfExpression>() ?: return
        val elseBranch = normalizeExpression(expression.`else`)
        myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition)
                && myMatchingVisitor.matchNormalized(expression.then, other.then)
                && (elseBranch == null || myMatchingVisitor.matchNormalized(expression.`else`, other.`else`))
    }

    override fun visitForExpression(expression: KtForExpression) {
        val other = getTreeElementDepar<KtForExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.loopParameter, other.loopParameter)
                && myMatchingVisitor.match(expression.loopRange, other.loopRange)
                && myMatchingVisitor.matchNormalized(expression.body, other.body)
    }

    override fun visitWhileExpression(expression: KtWhileExpression) {
        val other = getTreeElementDepar<KtWhileExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition)
                && myMatchingVisitor.matchNormalized(expression.body, other.body)
    }

    override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
        val other = getTreeElementDepar<KtDoWhileExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition)
                && myMatchingVisitor.matchNormalized(expression.body, other.body)
    }

    override fun visitWhenConditionInRange(condition: KtWhenConditionInRange) {
        val other = getTreeElementDepar<KtWhenConditionInRange>() ?: return
        myMatchingVisitor.result = condition.isNegated == other.isNegated
                && myMatchingVisitor.match(condition.rangeExpression, other.rangeExpression)
    }

    override fun visitWhenConditionIsPattern(condition: KtWhenConditionIsPattern) {
        val other = getTreeElementDepar<KtWhenConditionIsPattern>() ?: return
        myMatchingVisitor.result = condition.isNegated == other.isNegated
                && myMatchingVisitor.match(condition.typeReference, other.typeReference)
    }

    override fun visitWhenConditionWithExpression(condition: KtWhenConditionWithExpression) {
        val other = getTreeElementDepar<PsiElement>() ?: return
        val handler = getHandler(condition)
        if (handler is SubstitutionHandler) {
            myMatchingVisitor.result = handler.handle(other, myMatchingVisitor.matchContext)
        } else {
            myMatchingVisitor.result = other is KtWhenConditionWithExpression
                                       && myMatchingVisitor.match(condition.expression, other.expression)
        }
    }

    override fun visitWhenEntry(ktWhenEntry: KtWhenEntry) {
        val other = getTreeElementDepar<KtWhenEntry>() ?: return

        // $x$ -> $y$ should match else branches
        val bypassElseTest = ktWhenEntry.firstChild is KtWhenConditionWithExpression
                && ktWhenEntry.firstChild.children.size == 1
                && ktWhenEntry.firstChild.firstChild is KtNameReferenceExpression

        myMatchingVisitor.result =
            (bypassElseTest && other.isElse || myMatchingVisitor.matchInAnyOrder(ktWhenEntry.conditions, other.conditions))
                    && myMatchingVisitor.match(ktWhenEntry.expression, other.expression)
                    && (bypassElseTest || ktWhenEntry.isElse == other.isElse)
    }

    override fun visitWhenExpression(expression: KtWhenExpression) {
        val other = getTreeElementDepar<KtWhenExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.subjectExpression, other.subjectExpression)
                && myMatchingVisitor.matchInAnyOrder(expression.entries, other.entries)
    }

    override fun visitFinallySection(finallySection: KtFinallySection) {
        val other = getTreeElementDepar<KtFinallySection>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(finallySection.finalExpression, other.finalExpression)
    }

    override fun visitCatchSection(catchClause: KtCatchClause) {
        val other = getTreeElementDepar<KtCatchClause>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(catchClause.parameterList, other.parameterList)
                && myMatchingVisitor.match(catchClause.catchBody, other.catchBody)
    }

    override fun visitTryExpression(expression: KtTryExpression) {
        val other = getTreeElementDepar<KtTryExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.tryBlock, other.tryBlock)
                && myMatchingVisitor.matchInAnyOrder(expression.catchClauses, other.catchClauses)
                && myMatchingVisitor.match(expression.finallyBlock, other.finallyBlock)
    }

    override fun visitTypeAlias(typeAlias: KtTypeAlias) {
        val other = getTreeElementDepar<KtTypeAlias>() ?: return
        myMatchingVisitor.result = matchTextOrVariable(typeAlias.nameIdentifier, other.nameIdentifier)
                && myMatchingVisitor.match(typeAlias.getTypeReference(), other.getTypeReference())
                && myMatchingVisitor.matchInAnyOrder(typeAlias.annotationEntries, other.annotationEntries)
        val handler = getHandler(typeAlias.nameIdentifier!!)
        if (myMatchingVisitor.result && handler is SubstitutionHandler) {
            handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
        }
    }

    override fun visitConstructorCalleeExpression(constructorCalleeExpression: KtConstructorCalleeExpression) {
        val other = getTreeElementDepar<KtConstructorCalleeExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(
            constructorCalleeExpression.constructorReferenceExpression, other.constructorReferenceExpression
        )
    }

    override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) {
        val other = getTreeElementDepar<KtAnnotationEntry>() ?: return
        val parameters = resolveParameters(other)
        myMatchingVisitor.result = myMatchingVisitor.match(annotationEntry.calleeExpression, other.calleeExpression)
                && myMatchingVisitor.match(annotationEntry.typeArgumentList, other.typeArgumentList)
                && matchValueArguments(
            parameters,
            annotationEntry.valueArgumentList, other.valueArgumentList, annotationEntry.lambdaArguments, other.lambdaArguments
        )
                && matchTextOrVariable(annotationEntry.useSiteTarget, other.useSiteTarget)
    }

    override fun visitAnnotatedExpression(expression: KtAnnotatedExpression) {
        myMatchingVisitor.result = when (val other = myMatchingVisitor.element) {
            is KtAnnotatedExpression -> myMatchingVisitor.match(expression.baseExpression, other.baseExpression)
                    && myMatchingVisitor.matchInAnyOrder(expression.annotationEntries, other.annotationEntries)
            else -> myMatchingVisitor.match(expression.baseExpression, other) && expression.annotationEntries.all {
                val handler = getHandler(it); handler is SubstitutionHandler && handler.minOccurs == 0
            }
        }
    }

    override fun visitProperty(property: KtProperty) {
        val other = getTreeElementDepar<KtProperty>() ?: return

        myMatchingVisitor.result = matchTypeReferenceWithDeclaration(property.typeReference, other)
                && myMatchingVisitor.match(property.modifierList, other.modifierList)
                && matchTextOrVariable(property.nameIdentifier, other.nameIdentifier)
                && myMatchingVisitor.match(property.docComment, other.docComment)
                && myMatchingVisitor.matchOptionally(
            property.delegateExpressionOrInitializer,
            other.delegateExpressionOrInitializer
        )
                && myMatchingVisitor.match(property.getter, other.getter)
                && myMatchingVisitor.match(property.setter, other.setter)
                && myMatchingVisitor.match(property.receiverTypeReference, other.receiverTypeReference)
        val handler = getHandler(property.nameIdentifier!!)

        if (myMatchingVisitor.result && handler is SubstitutionHandler) {
            handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
        }
    }

    override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
        val other = getTreeElementDepar<KtPropertyAccessor>() ?: return
        val accessorBody = if (accessor.hasBlockBody()) accessor.bodyBlockExpression else accessor.bodyExpression
        val otherBody = if (other.hasBlockBody()) other.bodyBlockExpression else other.bodyExpression
        myMatchingVisitor.result = myMatchingVisitor.match(accessor.modifierList, other.modifierList)
                && myMatchingVisitor.matchNormalized(accessorBody, otherBody, true)
    }

    override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) {
        val other = getTreeElementDepar<KtStringTemplateExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.matchSequentially(expression.entries, other.entries)
    }

    override fun visitSimpleNameStringTemplateEntry(entry: KtSimpleNameStringTemplateEntry) {
        val other = getTreeElement<KtStringTemplateEntry>() ?: return
        val handler = getHandler(entry)
        if (handler is SubstitutionHandler) {
            myMatchingVisitor.result = handler.handle(other, myMatchingVisitor.matchContext)
            return
        }
        myMatchingVisitor.result = when (other) {
            is KtSimpleNameStringTemplateEntry, is KtBlockStringTemplateEntry ->
                myMatchingVisitor.match(entry.expression, other.expression)
            else -> false
        }
    }

    override fun visitLiteralStringTemplateEntry(entry: KtLiteralStringTemplateEntry) {
        val other = myMatchingVisitor.element
        myMatchingVisitor.result = when (val handler = entry.getUserData(CompiledPattern.HANDLER_KEY)) {
            is LiteralWithSubstitutionHandler -> handler.match(entry, other, myMatchingVisitor.matchContext)
            else -> matchTextOrVariable(entry, other)
        }
    }

    override fun visitBlockStringTemplateEntry(entry: KtBlockStringTemplateEntry) {
        val other = getTreeElementDepar<KtBlockStringTemplateEntry>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(entry.expression, other.expression)
    }

    override fun visitEscapeStringTemplateEntry(entry: KtEscapeStringTemplateEntry) {
        val other = getTreeElementDepar<KtEscapeStringTemplateEntry>() ?: return
        myMatchingVisitor.result = matchTextOrVariable(entry, other)
    }

    override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) {
        val other = getTreeElementDepar<KtBinaryExpressionWithTypeRHS>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.operationReference, other.operationReference)
                && myMatchingVisitor.match(expression.left, other.left)
                && myMatchingVisitor.match(expression.right, other.right)
    }

    override fun visitIsExpression(expression: KtIsExpression) {
        val other = getTreeElementDepar<KtIsExpression>() ?: return
        myMatchingVisitor.result = expression.isNegated == other.isNegated
                && myMatchingVisitor.match(expression.leftHandSide, other.leftHandSide)
                && myMatchingVisitor.match(expression.typeReference, other.typeReference)
    }

    override fun visitDestructuringDeclaration(destructuringDeclaration: KtDestructuringDeclaration) {
        val other = getTreeElementDepar<KtDestructuringDeclaration>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.matchSequentially(destructuringDeclaration.entries, other.entries)
                && myMatchingVisitor.match(destructuringDeclaration.initializer, other.initializer)
                && myMatchingVisitor.match(destructuringDeclaration.docComment, other.docComment)
    }

    override fun visitDestructuringDeclarationEntry(multiDeclarationEntry: KtDestructuringDeclarationEntry) {
        val other = getTreeElementDepar<KtDestructuringDeclarationEntry>() ?: return
        myMatchingVisitor.result = matchTypeReferenceWithDeclaration(multiDeclarationEntry.typeReference, other)
                && myMatchingVisitor.match(multiDeclarationEntry.modifierList, other.modifierList)
                && multiDeclarationEntry.isVar == other.isVar
                && matchTextOrVariable(multiDeclarationEntry.nameIdentifier, other.nameIdentifier)
    }

    override fun visitThrowExpression(expression: KtThrowExpression) {
        val other = getTreeElementDepar<KtThrowExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.referenceExpression(), other.referenceExpression())
    }

    override fun visitClassLiteralExpression(expression: KtClassLiteralExpression) {
        val other = getTreeElementDepar<KtClassLiteralExpression>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.match(expression.firstChild, other.firstChild)
                || other.resolveType()?.let { resolved ->
            myMatchingVisitor.matchText(expression.text, resolved.arguments.first().type.fqName.toString())
        } ?: false
    }

    override fun visitComment(comment: PsiComment) {
        val other = getTreeElementDepar<PsiComment>() ?: return
        when (val handler = comment.getUserData(CompiledPattern.HANDLER_KEY)) {
            is LiteralWithSubstitutionHandler -> {
                if (other is KDocImpl) {
                    myMatchingVisitor.result = handler.match(comment, other, myMatchingVisitor.matchContext)
                } else {
                    val offset = 2 + other.text.substring(2).indexOfFirst { it > ' ' }
                    myMatchingVisitor.result = handler.match(other, getCommentText(other), offset, myMatchingVisitor.matchContext)
                }
            }
            is SubstitutionHandler -> {
                handler.findRegExpPredicate()?.let {
                    it.setNodeTextGenerator { comment -> getCommentText(comment as PsiComment) }
                }
                myMatchingVisitor.result = handler.handle(
                    other,
                    2,
                    other.textLength - if (other.tokenType == KtTokens.EOL_COMMENT) 0 else 2,
                    myMatchingVisitor.matchContext
                )
            }
            else -> myMatchingVisitor.result = myMatchingVisitor.matchText(
                StructuralSearchUtil.normalize(getCommentText(comment)),
                StructuralSearchUtil.normalize(getCommentText(other))
            )
        }
    }

    override fun visitKDoc(kDoc: KDoc) {
        val other = getTreeElementDepar<KDoc>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(
            kDoc.getChildrenOfType<KDocSection>(),
            other.getChildrenOfType<KDocSection>()
        )
    }

    override fun visitKDocSection(section: KDocSection) {
        val other = getTreeElementDepar<KDocSection>() ?: return

        val important: (PsiElement) -> Boolean = {
            it.elementType != KDocTokens.LEADING_ASTERISK
                    && !(it.elementType == KDocTokens.TEXT && it.text.trim().isEmpty())
        }

        myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(
            section.allChildren.filter(important).toList(),
            other.allChildren.filter(important).toList()
        )
    }

    override fun visitKDocTag(tag: KDocTag) {
        val other = getTreeElementDepar<KDocTag>() ?: return
        myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(tag.getChildrenOfType(), other.getChildrenOfType())
    }

    override fun visitKDocLink(link: KDocLink) {
        val other = getTreeElementDepar<KDocLink>() ?: return
        myMatchingVisitor.result = matchTextOrVariable(link, other)
    }

    companion object {
        private val augmentedAssignmentsMap = mapOf(
            KtTokens.PLUSEQ to KtTokens.PLUS,
            KtTokens.MINUSEQ to KtTokens.MINUS,
            KtTokens.MULTEQ to KtTokens.MUL,
            KtTokens.DIVEQ to KtTokens.DIV,
            KtTokens.PERCEQ to KtTokens.PERC
        )
    }
}