-
Notifications
You must be signed in to change notification settings - Fork 391
/
DefaultDescriptorToDocumentableTranslator.kt
1183 lines (1056 loc) · 57.1 KB
/
DefaultDescriptorToDocumentableTranslator.kt
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
package org.jetbrains.dokka.base.translators.descriptors
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.util.PsiLiteralUtil.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import org.jetbrains.dokka.DokkaConfiguration.DokkaSourceSet
import org.jetbrains.dokka.analysis.DescriptorDocumentableSource
import org.jetbrains.dokka.analysis.DokkaResolutionFacade
import org.jetbrains.dokka.analysis.KotlinAnalysis
import org.jetbrains.dokka.analysis.from
import org.jetbrains.dokka.base.DokkaBase
import org.jetbrains.dokka.base.parsers.MarkdownParser
import org.jetbrains.dokka.base.translators.psi.parsers.JavadocParser
import org.jetbrains.dokka.base.translators.typeConstructorsBeingExceptions
import org.jetbrains.dokka.base.translators.unquotedValue
import org.jetbrains.dokka.links.*
import org.jetbrains.dokka.links.Callable
import org.jetbrains.dokka.model.*
import org.jetbrains.dokka.model.AnnotationTarget
import org.jetbrains.dokka.model.Nullable
import org.jetbrains.dokka.model.doc.*
import org.jetbrains.dokka.model.properties.PropertyContainer
import org.jetbrains.dokka.plugability.DokkaContext
import org.jetbrains.dokka.plugability.plugin
import org.jetbrains.dokka.plugability.querySingle
import org.jetbrains.dokka.transformers.sources.AsyncSourceToDocumentableTranslator
import org.jetbrains.dokka.utilities.DokkaLogger
import org.jetbrains.dokka.utilities.parallelMap
import org.jetbrains.dokka.utilities.parallelMapNotNull
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor
import org.jetbrains.kotlin.builtins.isBuiltinExtensionFunctionalType
import org.jetbrains.kotlin.builtins.isExtensionFunctionType
import org.jetbrains.kotlin.builtins.isSuspendFunctionTypeOrSubtype
import org.jetbrains.kotlin.codegen.isJvmStaticInObjectOrClassOrInterface
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor
import org.jetbrains.kotlin.idea.kdoc.findKDoc
import org.jetbrains.kotlin.idea.kdoc.resolveKDocLink
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.load.kotlin.toSourceElement
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.components.isVararg
import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentsInParentheses
import org.jetbrains.kotlin.resolve.constants.ConstantValue
import org.jetbrains.kotlin.resolve.constants.KClassValue.Value.LocalClass
import org.jetbrains.kotlin.resolve.constants.KClassValue.Value.NormalClass
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.parents
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.resolve.source.KotlinSourceElement
import org.jetbrains.kotlin.resolve.source.PsiSourceElement
import org.jetbrains.kotlin.resolve.source.PsiSourceFile
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.immediateSupertypes
import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.nio.file.Paths
import org.jetbrains.kotlin.resolve.constants.AnnotationValue as ConstantsAnnotationValue
import org.jetbrains.kotlin.resolve.constants.ArrayValue as ConstantsArrayValue
import org.jetbrains.kotlin.resolve.constants.BooleanValue as ConstantsBooleanValue
import org.jetbrains.kotlin.resolve.constants.DoubleValue as ConstantsDoubleValue
import org.jetbrains.kotlin.resolve.constants.EnumValue as ConstantsEnumValue
import org.jetbrains.kotlin.resolve.constants.FloatValue as ConstantsFloatValue
import org.jetbrains.kotlin.resolve.constants.IntValue as ConstantsIntValue
import org.jetbrains.kotlin.resolve.constants.KClassValue as ConstantsKtClassValue
import org.jetbrains.kotlin.resolve.constants.LongValue as ConstantsLongValue
import org.jetbrains.kotlin.resolve.constants.NullValue as ConstantsNullValue
import org.jetbrains.kotlin.resolve.constants.UIntValue as ConstantsUIntValue
import org.jetbrains.kotlin.resolve.constants.ULongValue as ConstantsULongValue
class DefaultDescriptorToDocumentableTranslator(
private val context: DokkaContext
) : AsyncSourceToDocumentableTranslator, ExternalClasslikesTranslator {
private val kotlinAnalysis: KotlinAnalysis = context.plugin<DokkaBase>().querySingle { kotlinAnalysis }
override suspend fun invokeSuspending(sourceSet: DokkaSourceSet, context: DokkaContext): DModule {
val (environment, facade) = kotlinAnalysis[sourceSet]
val packageFragments = environment.getSourceFiles().asSequence()
.map { it.packageFqName }
.distinct()
.mapNotNull { facade.resolveSession.getPackageFragment(it) }
.toList()
return DokkaDescriptorVisitor(sourceSet, kotlinAnalysis[sourceSet].facade, context.logger).run {
packageFragments.mapNotNull { it.safeAs<PackageFragmentDescriptor>() }.parallelMap {
visitPackageFragmentDescriptor(
it
)
}
}.let {
DModule(
name = context.configuration.moduleName,
packages = it,
documentation = emptyMap(),
expectPresentInSet = null,
sourceSets = setOf(sourceSet)
)
}
}
override fun translateClassDescriptor(descriptor: ClassDescriptor, sourceSet: DokkaSourceSet): DClasslike {
val driInfo = DRI.from(descriptor.parents.first()).withEmptyInfo()
return runBlocking(Dispatchers.Default) {
DokkaDescriptorVisitor(sourceSet, kotlinAnalysis[sourceSet].facade, context.logger)
.visitClassDescriptor(descriptor, driInfo)
}
}
}
data class DRIWithPlatformInfo(
val dri: DRI,
val actual: SourceSetDependent<DocumentableSource>
)
fun DRI.withEmptyInfo() = DRIWithPlatformInfo(this, emptyMap())
private class DokkaDescriptorVisitor(
private val sourceSet: DokkaSourceSet,
private val resolutionFacade: DokkaResolutionFacade,
private val logger: DokkaLogger
) {
private val javadocParser = JavadocParser(logger, resolutionFacade)
private fun Collection<DeclarationDescriptor>.filterDescriptorsInSourceSet() = filter {
it.toSourceElement.containingFile.toString().let { path ->
path.isNotBlank() && sourceSet.sourceRoots.any { root ->
Paths.get(path).startsWith(root.toPath())
}
}
}
private fun <T> T.toSourceSetDependent() = if (this != null) mapOf(sourceSet to this) else emptyMap()
suspend fun visitPackageFragmentDescriptor(descriptor: PackageFragmentDescriptor): DPackage {
val name = descriptor.fqName.asString().takeUnless { it.isBlank() } ?: ""
val driWithPlatform = DRI(packageName = name).withEmptyInfo()
val scope = descriptor.getMemberScope()
return coroutineScope {
val descriptorsWithKind = scope.getDescriptorsWithKind(true)
val functions = async { descriptorsWithKind.functions.visitFunctions(driWithPlatform) }
val properties = async { descriptorsWithKind.properties.visitProperties(driWithPlatform) }
val classlikes = async { descriptorsWithKind.classlikes.visitClasslikes(driWithPlatform) }
val typealiases = async { descriptorsWithKind.typealiases.visitTypealiases() }
DPackage(
dri = driWithPlatform.dri,
functions = functions.await(),
properties = properties.await(),
classlikes = classlikes.await(),
typealiases = typealiases.await(),
documentation = descriptor.resolveDescriptorData(),
sourceSets = setOf(sourceSet)
)
}
}
suspend fun visitClassDescriptor(descriptor: ClassDescriptor, parent: DRIWithPlatformInfo): DClasslike =
when (descriptor.kind) {
ClassKind.ENUM_CLASS -> enumDescriptor(descriptor, parent)
ClassKind.OBJECT -> objectDescriptor(descriptor, parent)
ClassKind.INTERFACE -> interfaceDescriptor(descriptor, parent)
ClassKind.ANNOTATION_CLASS -> annotationDescriptor(descriptor, parent)
else -> classDescriptor(descriptor, parent)
}
private suspend fun interfaceDescriptor(descriptor: ClassDescriptor, parent: DRIWithPlatformInfo): DInterface {
val driWithPlatform = parent.dri.withClass(descriptor.name.asString()).withEmptyInfo()
val scope = descriptor.unsubstitutedMemberScope
val isExpect = descriptor.isExpect
val isActual = descriptor.isActual
val info = descriptor.resolveClassDescriptionData()
return coroutineScope {
val descriptorsWithKind = scope.getDescriptorsWithKind()
val functions = async { descriptorsWithKind.functions.visitFunctions(driWithPlatform) }
val properties = async { descriptorsWithKind.properties.visitProperties(driWithPlatform) }
val classlikes = async { descriptorsWithKind.classlikes.visitClasslikes(driWithPlatform) }
val generics = async { descriptor.declaredTypeParameters.parallelMap { it.toVariantTypeParameter() } }
DInterface(
dri = driWithPlatform.dri,
name = descriptor.name.asString(),
functions = functions.await(),
properties = properties.await(),
classlikes = classlikes.await(),
sources = descriptor.createSources(),
expectPresentInSet = sourceSet.takeIf { isExpect },
visibility = descriptor.visibility.toDokkaVisibility().toSourceSetDependent(),
supertypes = info.supertypes.toSourceSetDependent(),
documentation = info.docs,
generics = generics.await(),
companion = descriptor.companion(driWithPlatform),
sourceSets = setOf(sourceSet),
isExpectActual = (isExpect || isActual),
extra = PropertyContainer.withAll(
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
descriptor.getAnnotations().toSourceSetDependent().toAnnotations(),
ImplementedInterfaces(info.ancestry.allImplementedInterfaces().toSourceSetDependent()),
info.ancestry.exceptionInSupertypesOrNull()
)
)
}
}
private suspend fun objectDescriptor(descriptor: ClassDescriptor, parent: DRIWithPlatformInfo): DObject {
val driWithPlatform = parent.dri.withClass(descriptor.name.asString()).withEmptyInfo()
val scope = descriptor.unsubstitutedMemberScope
val isExpect = descriptor.isExpect
val isActual = descriptor.isActual
val info = descriptor.resolveClassDescriptionData()
return coroutineScope {
val descriptorsWithKind = scope.getDescriptorsWithKind()
val functions = async { descriptorsWithKind.functions.visitFunctions(driWithPlatform) }
val properties = async { descriptorsWithKind.properties.visitProperties(driWithPlatform) }
val classlikes = async { descriptorsWithKind.classlikes.visitClasslikes(driWithPlatform) }
DObject(
dri = driWithPlatform.dri,
name = descriptor.name.asString(),
functions = functions.await(),
properties = properties.await(),
classlikes = classlikes.await(),
sources = descriptor.createSources(),
expectPresentInSet = sourceSet.takeIf { isExpect },
visibility = descriptor.visibility.toDokkaVisibility().toSourceSetDependent(),
supertypes = info.supertypes.toSourceSetDependent(),
documentation = info.docs,
sourceSets = setOf(sourceSet),
isExpectActual = (isExpect || isActual),
extra = PropertyContainer.withAll(
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
descriptor.getAnnotations().toSourceSetDependent().toAnnotations(),
ImplementedInterfaces(info.ancestry.allImplementedInterfaces().toSourceSetDependent()),
info.ancestry.exceptionInSupertypesOrNull()
)
)
}
}
private suspend fun enumDescriptor(descriptor: ClassDescriptor, parent: DRIWithPlatformInfo): DEnum {
val driWithPlatform = parent.dri.withClass(descriptor.name.asString()).withEmptyInfo()
val scope = descriptor.unsubstitutedMemberScope
val isExpect = descriptor.isExpect
val isActual = descriptor.isActual
val info = descriptor.resolveClassDescriptionData()
return coroutineScope {
val descriptorsWithKind = scope.getDescriptorsWithKind()
val functions = async { descriptorsWithKind.functions.visitFunctions(driWithPlatform) }
val properties = async { descriptorsWithKind.properties.visitProperties(driWithPlatform) }
val classlikes = async { descriptorsWithKind.classlikes.visitClasslikes(driWithPlatform) }
val constructors =
async { descriptor.constructors.parallelMap { visitConstructorDescriptor(it, driWithPlatform) } }
val entries = async { descriptorsWithKind.enumEntries.visitEnumEntries(driWithPlatform) }
DEnum(
dri = driWithPlatform.dri,
name = descriptor.name.asString(),
entries = entries.await(),
constructors = constructors.await(),
functions = functions.await(),
properties = properties.await(),
classlikes = classlikes.await(),
sources = descriptor.createSources(),
expectPresentInSet = sourceSet.takeIf { isExpect },
visibility = descriptor.visibility.toDokkaVisibility().toSourceSetDependent(),
supertypes = info.supertypes.toSourceSetDependent(),
documentation = info.docs,
companion = descriptor.companion(driWithPlatform),
sourceSets = setOf(sourceSet),
isExpectActual = (isExpect || isActual),
extra = PropertyContainer.withAll(
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
descriptor.getAnnotations().toSourceSetDependent().toAnnotations(),
ImplementedInterfaces(info.ancestry.allImplementedInterfaces().toSourceSetDependent())
)
)
}
}
private suspend fun visitEnumEntryDescriptor(descriptor: ClassDescriptor, parent: DRIWithPlatformInfo): DEnumEntry {
val driWithPlatform = parent.dri.withClass(descriptor.name.asString()).withEmptyInfo()
val scope = descriptor.unsubstitutedMemberScope
val isExpect = descriptor.isExpect
return coroutineScope {
val descriptorsWithKind = scope.getDescriptorsWithKind()
val functions = async { descriptorsWithKind.functions.visitFunctions(driWithPlatform) }
val properties = async { descriptorsWithKind.properties.visitProperties(driWithPlatform) }
val classlikes = async { descriptorsWithKind.classlikes.visitClasslikes(driWithPlatform) }
DEnumEntry(
dri = driWithPlatform.dri.withEnumEntryExtra(),
name = descriptor.name.asString(),
documentation = descriptor.resolveDescriptorData(),
functions = functions.await(),
properties = properties.await(),
classlikes = classlikes.await(),
sourceSets = setOf(sourceSet),
expectPresentInSet = sourceSet.takeIf { isExpect },
extra = PropertyContainer.withAll(
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
descriptor.getAnnotations().toSourceSetDependent().toAnnotations(),
ConstructorValues(descriptor.getAppliedConstructorParameters().toSourceSetDependent())
)
)
}
}
private suspend fun annotationDescriptor(descriptor: ClassDescriptor, parent: DRIWithPlatformInfo): DAnnotation {
val driWithPlatform = parent.dri.withClass(descriptor.name.asString()).withEmptyInfo()
val scope = descriptor.unsubstitutedMemberScope
val isExpect = descriptor.isExpect
val isActual = descriptor.isActual
return coroutineScope {
val descriptorsWithKind = scope.getDescriptorsWithKind()
val functions = async { descriptorsWithKind.functions.visitFunctions(driWithPlatform) }
val properties = async { descriptorsWithKind.properties.visitProperties(driWithPlatform) }
val classlikes = async { descriptorsWithKind.classlikes.visitClasslikes(driWithPlatform) }
val generics = async { descriptor.declaredTypeParameters.parallelMap { it.toVariantTypeParameter() } }
val constructors =
async { descriptor.constructors.parallelMap { visitConstructorDescriptor(it, driWithPlatform) } }
DAnnotation(
dri = driWithPlatform.dri,
name = descriptor.name.asString(),
documentation = descriptor.resolveDescriptorData(),
functions = functions.await(),
properties = properties.await(),
classlikes = classlikes.await(),
expectPresentInSet = sourceSet.takeIf { isExpect },
sourceSets = setOf(sourceSet),
isExpectActual = (isExpect || isActual),
extra = PropertyContainer.withAll(
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
descriptor.getAnnotations().toSourceSetDependent().toAnnotations()
),
companion = descriptor.companionObjectDescriptor?.let { objectDescriptor(it, driWithPlatform) },
visibility = descriptor.visibility.toDokkaVisibility().toSourceSetDependent(),
generics = generics.await(),
constructors = constructors.await(),
sources = descriptor.createSources()
)
}
}
private suspend fun classDescriptor(descriptor: ClassDescriptor, parent: DRIWithPlatformInfo): DClass {
val driWithPlatform = parent.dri.withClass(descriptor.name.asString()).withEmptyInfo()
val scope = descriptor.unsubstitutedMemberScope
val isExpect = descriptor.isExpect
val isActual = descriptor.isActual
val info = descriptor.resolveClassDescriptionData()
val actual = descriptor.createSources()
return coroutineScope {
val descriptorsWithKind = scope.getDescriptorsWithKind()
val (regularFunctions, accessors) = splitFunctionsAndAccessors(
properties = descriptorsWithKind.properties,
functions = descriptorsWithKind.functions
)
val functions = async { regularFunctions.visitFunctions(driWithPlatform) }
val properties = async { descriptorsWithKind.properties.visitProperties(driWithPlatform, accessors) }
val classlikes = async { descriptorsWithKind.classlikes.visitClasslikes(driWithPlatform) }
val generics = async { descriptor.declaredTypeParameters.parallelMap { it.toVariantTypeParameter() } }
val constructors = async {
descriptor.constructors.parallelMap {
visitConstructorDescriptor(
it,
if (it.isPrimary) DRIWithPlatformInfo(driWithPlatform.dri, actual)
else DRIWithPlatformInfo(driWithPlatform.dri, emptyMap())
)
}
}
DClass(
dri = driWithPlatform.dri,
name = descriptor.name.asString(),
constructors = constructors.await(),
functions = functions.await(),
properties = properties.await(),
classlikes = classlikes.await(),
sources = actual,
expectPresentInSet = sourceSet.takeIf { isExpect },
visibility = descriptor.visibility.toDokkaVisibility().toSourceSetDependent(),
supertypes = info.supertypes.toSourceSetDependent(),
generics = generics.await(),
documentation = info.docs,
modifier = descriptor.modifier().toSourceSetDependent(),
companion = descriptor.companion(driWithPlatform),
sourceSets = setOf(sourceSet),
isExpectActual = (isExpect || isActual),
extra = PropertyContainer.withAll(
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
descriptor.getAnnotations().toSourceSetDependent().toAnnotations(),
ImplementedInterfaces(info.ancestry.allImplementedInterfaces().toSourceSetDependent()),
info.ancestry.exceptionInSupertypesOrNull()
)
)
}
}
/**
* @param implicitAccessors getters/setters that are not part of the property descriptor, for instance
* average methods inherited from java sources
*/
private suspend fun visitPropertyDescriptor(
originalDescriptor: PropertyDescriptor,
implicitAccessors: List<FunctionDescriptor>,
parent: DRIWithPlatformInfo
): DProperty {
val (dri, _) = originalDescriptor.createDRI()
val inheritedFrom = dri.getInheritedFromDRI(parent)
val descriptor = originalDescriptor.getConcreteDescriptor()
val isExpect = descriptor.isExpect
val isActual = descriptor.isActual
val actual = originalDescriptor.createSources()
// example - generated getter that comes with data classes
suspend fun getDescriptorGetter() =
descriptor.accessors
.filterIsInstance<PropertyGetterDescriptor>()
.singleOrNull()
?.let {
visitPropertyAccessorDescriptor(it, descriptor, dri, inheritedFrom)
}
suspend fun getImplicitAccessorGetter() =
implicitAccessors
.firstOrNull { it.isGetterFor(originalDescriptor) }
?.let { visitFunctionDescriptor(it, parent) }
// example - generated setter that comes with data classes
suspend fun getDescriptorSetter() =
descriptor.accessors
.filterIsInstance<PropertySetterDescriptor>()
.singleOrNull()
?.let {
visitPropertyAccessorDescriptor(it, descriptor, dri, inheritedFrom)
}
suspend fun getImplicitAccessorSetter() =
implicitAccessors
.firstOrNull { it.isSetterFor(originalDescriptor) }
?.let { visitFunctionDescriptor(it, parent) }
return coroutineScope {
val generics = async { descriptor.typeParameters.parallelMap { it.toVariantTypeParameter() } }
DProperty(
dri = dri,
name = descriptor.name.asString(),
receiver = descriptor.extensionReceiverParameter?.let {
visitReceiverParameterDescriptor(it, DRIWithPlatformInfo(dri, actual))
},
sources = actual,
getter = getDescriptorGetter() ?: getImplicitAccessorGetter(),
setter = getDescriptorSetter() ?: getImplicitAccessorSetter(),
visibility = descriptor.visibility.toDokkaVisibility().toSourceSetDependent(),
documentation = descriptor.resolveDescriptorData(),
modifier = descriptor.modifier().toSourceSetDependent(),
type = descriptor.returnType!!.toBound(),
expectPresentInSet = sourceSet.takeIf { isExpect },
sourceSets = setOf(sourceSet),
generics = generics.await(),
isExpectActual = (isExpect || isActual),
extra = PropertyContainer.withAll(
listOfNotNull(
(descriptor.additionalExtras() + descriptor.getAnnotationsWithBackingField()
.toAdditionalExtras()).toSet().toSourceSetDependent().toAdditionalModifiers(),
(descriptor.getAnnotationsWithBackingField() + descriptor.fileLevelAnnotations()).toSourceSetDependent()
.toAnnotations(),
descriptor.getDefaultValue()?.let { DefaultValue(it.toSourceSetDependent()) },
inheritedFrom?.let { InheritedMember(it.toSourceSetDependent()) },
)
)
)
}
}
private fun CallableMemberDescriptor.createDRI(wasOverridenBy: DRI? = null): Pair<DRI, DRI?> =
if (kind == CallableMemberDescriptor.Kind.DECLARATION || overriddenDescriptors.isEmpty())
Pair(DRI.from(this), wasOverridenBy)
else
overriddenDescriptors.first().createDRI(DRI.from(this))
private suspend fun visitFunctionDescriptor(
originalDescriptor: FunctionDescriptor,
parent: DRIWithPlatformInfo
): DFunction {
val (dri, _) = originalDescriptor.createDRI()
val inheritedFrom = dri.getInheritedFromDRI(parent)
val descriptor = originalDescriptor.getConcreteDescriptor()
val isExpect = descriptor.isExpect
val isActual = descriptor.isActual
val actual = originalDescriptor.createSources()
return coroutineScope {
val generics = async { descriptor.typeParameters.parallelMap { it.toVariantTypeParameter() } }
DFunction(
dri = dri,
name = descriptor.name.asString(),
isConstructor = false,
receiver = descriptor.extensionReceiverParameter?.let {
visitReceiverParameterDescriptor(it, DRIWithPlatformInfo(dri, actual))
},
parameters = descriptor.valueParameters.mapIndexed { index, desc ->
parameter(index, desc, DRIWithPlatformInfo(dri, actual))
},
expectPresentInSet = sourceSet.takeIf { isExpect },
sources = actual,
visibility = descriptor.visibility.toDokkaVisibility().toSourceSetDependent(),
generics = generics.await(),
documentation = descriptor.takeIf { it.kind != CallableMemberDescriptor.Kind.SYNTHESIZED }
?.resolveDescriptorData() ?: emptyMap(),
modifier = descriptor.modifier().toSourceSetDependent(),
type = descriptor.returnType!!.toBound(),
sourceSets = setOf(sourceSet),
isExpectActual = (isExpect || isActual),
extra = PropertyContainer.withAll(
inheritedFrom?.let { InheritedMember(it.toSourceSetDependent()) },
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
(descriptor.getAnnotations() + descriptor.fileLevelAnnotations()).toSourceSetDependent()
.toAnnotations(),
ObviousMember.takeIf { descriptor.isObvious },
)
)
}
}
/**
* `createDRI` returns the DRI of the exact element and potential DRI of an element that is overriding it
* (It can be also FAKE_OVERRIDE which is in fact just inheritance of the symbol)
*
* Looking at what PSIs do, they give the DRI of the element within the classnames where it is actually
* declared and inheritedFrom as the same DRI but truncated callable part.
* Therefore, we set callable to null and take the DRI only if it is indeed coming from different class.
*/
private fun DRI.getInheritedFromDRI(parent: DRIWithPlatformInfo): DRI? {
return this.copy(callable = null)
.takeIf { parent.dri.classNames != this.classNames || parent.dri.packageName != this.packageName }
}
suspend fun visitConstructorDescriptor(descriptor: ConstructorDescriptor, parent: DRIWithPlatformInfo): DFunction {
val name = descriptor.constructedClass.name.toString()
val dri = parent.dri.copy(callable = Callable.from(descriptor, name))
val actual = descriptor.createSources()
val isExpect = descriptor.isExpect
val isActual = descriptor.isActual
return coroutineScope {
val generics = async { descriptor.typeParameters.parallelMap { it.toVariantTypeParameter() } }
DFunction(
dri = dri,
name = name,
isConstructor = true,
receiver = descriptor.extensionReceiverParameter?.let {
visitReceiverParameterDescriptor(it, DRIWithPlatformInfo(dri, actual))
},
parameters = descriptor.valueParameters.mapIndexed { index, desc ->
parameter(index, desc, DRIWithPlatformInfo(dri, actual))
},
sources = actual,
expectPresentInSet = sourceSet.takeIf { isExpect },
visibility = descriptor.visibility.toDokkaVisibility().toSourceSetDependent(),
documentation = descriptor.resolveDescriptorData().let { sourceSetDependent ->
if (descriptor.isPrimary) {
sourceSetDependent.map { entry ->
Pair(
entry.key,
entry.value.copy(children = (entry.value.children.find { it is Constructor }?.root?.let { constructor ->
listOf(Description(constructor))
} ?: emptyList<TagWrapper>()) + entry.value.children.filterIsInstance<Param>()))
}.toMap()
} else {
sourceSetDependent
}
},
type = descriptor.returnType.toBound(),
modifier = descriptor.modifier().toSourceSetDependent(),
generics = generics.await(),
sourceSets = setOf(sourceSet),
isExpectActual = (isExpect || isActual),
extra = PropertyContainer.withAll<DFunction>(
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
descriptor.getAnnotations().toSourceSetDependent().toAnnotations()
).let {
if (descriptor.isPrimary) {
it + PrimaryConstructorExtra
} else it
}
)
}
}
private suspend fun visitReceiverParameterDescriptor(
descriptor: ReceiverParameterDescriptor,
parent: DRIWithPlatformInfo
) = DParameter(
dri = parent.dri.copy(target = PointingToDeclaration),
name = null,
type = descriptor.type.toBound(),
expectPresentInSet = null,
documentation = descriptor.resolveDescriptorData(),
sourceSets = setOf(sourceSet),
extra = PropertyContainer.withAll(descriptor.getAnnotations().toSourceSetDependent().toAnnotations())
)
private suspend fun visitPropertyAccessorDescriptor(
descriptor: PropertyAccessorDescriptor,
propertyDescriptor: PropertyDescriptor,
parent: DRI,
inheritedFrom: DRI? = null
): DFunction {
val dri = parent.copy(callable = Callable.from(descriptor))
val isGetter = descriptor is PropertyGetterDescriptor
val isExpect = descriptor.isExpect
val isActual = descriptor.isActual
suspend fun PropertyDescriptor.asParameter(parent: DRI) =
DParameter(
parent.copy(target = PointingToCallableParameters(parameterIndex = 1)),
this.name.asString(),
type = this.type.toBound(),
expectPresentInSet = sourceSet.takeIf { isExpect },
documentation = descriptor.resolveDescriptorData(),
sourceSets = setOf(sourceSet),
extra = PropertyContainer.withAll(
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
getAnnotationsWithBackingField().toSourceSetDependent().toAnnotations()
)
)
val name = run {
val rawName = propertyDescriptor.name.asString()
/*
* Kotlin has special rules for conversion around properties that
* start with "is" For more info see:
* https://kotlinlang.org/docs/java-interop.html#getters-and-setters
* https://kotlinlang.org/docs/java-to-kotlin-interop.html#properties
*
* Based on our testing, this rule only applies when the letter after
* the "is" is *not* lowercase. This means that words like "issue" won't
* have the rule applied but "is_foobar" and "is1of" will have the rule applied.
*/
val specialCaseIs = rawName.startsWith("is")
&& rawName.getOrNull(2)?.isLowerCase() == false
if (specialCaseIs) {
if (isGetter) rawName else rawName.replaceFirst("is", "set")
} else {
if (isGetter) "get${rawName.capitalize()}" else "set${rawName.capitalize()}"
}
}
val parameters =
if (isGetter) {
emptyList()
} else {
listOf(propertyDescriptor.asParameter(dri))
}
return coroutineScope {
val generics = async { descriptor.typeParameters.parallelMap { it.toVariantTypeParameter() } }
DFunction(
dri,
name,
isConstructor = false,
parameters = parameters,
visibility = descriptor.visibility.toDokkaVisibility().toSourceSetDependent(),
documentation = descriptor.resolveDescriptorData().mapInheritedTagWrappers(),
type = descriptor.returnType!!.toBound(),
generics = generics.await(),
modifier = descriptor.modifier().toSourceSetDependent(),
expectPresentInSet = sourceSet.takeIf { isExpect },
receiver = descriptor.extensionReceiverParameter?.let {
visitReceiverParameterDescriptor(
it,
DRIWithPlatformInfo(dri, descriptor.createSources())
)
},
sources = descriptor.createSources(),
sourceSets = setOf(sourceSet),
isExpectActual = (isExpect || isActual),
extra = PropertyContainer.withAll(
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
descriptor.getAnnotations().toSourceSetDependent().toAnnotations(),
inheritedFrom?.let { InheritedMember(it.toSourceSetDependent()) }
)
)
}
}
/**
* Workaround for a problem with inheriting parent TagWrappers of the wrong type.
*
* For instance, if you annotate a class with `@property`, kotlin compiler will propagate
* this tag to the property and it's getters and setters. In case of getters and setters,
* it's more correct to display propagated docs as description instead of property
*/
private fun SourceSetDependent<DocumentationNode>.mapInheritedTagWrappers(): SourceSetDependent<DocumentationNode> {
return this.mapValues { (_, value) ->
val mappedChildren = value.children.map {
when (it) {
is Property -> Description(it.root)
else -> it
}
}
value.copy(children = mappedChildren)
}
}
private suspend fun visitTypeAliasDescriptor(descriptor: TypeAliasDescriptor) =
with(descriptor) {
coroutineScope {
val generics = async { descriptor.declaredTypeParameters.parallelMap { it.toVariantTypeParameter() } }
val info = buildAncestryInformation(defaultType).copy(
superclass = buildAncestryInformation(underlyingType),
interfaces = emptyList()
)
DTypeAlias(
dri = DRI.from(this@with),
name = name.asString(),
type = defaultType.toBound(),
expectPresentInSet = null,
underlyingType = underlyingType.toBound().toSourceSetDependent(),
visibility = visibility.toDokkaVisibility().toSourceSetDependent(),
documentation = resolveDescriptorData(),
sourceSets = setOf(sourceSet),
generics = generics.await(),
extra = PropertyContainer.withAll(
descriptor.getAnnotations().toSourceSetDependent().toAnnotations(),
info.exceptionInSupertypesOrNull(),
)
)
}
}
private suspend fun parameter(index: Int, descriptor: ValueParameterDescriptor, parent: DRIWithPlatformInfo) =
DParameter(
dri = parent.dri.copy(target = PointingToCallableParameters(index)),
name = descriptor.name.asString(),
type = descriptor.varargElementType?.toBound() ?: descriptor.type.toBound(),
expectPresentInSet = null,
documentation = descriptor.resolveDescriptorData(),
sourceSets = setOf(sourceSet),
extra = PropertyContainer.withAll(listOfNotNull(
descriptor.additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
descriptor.getAnnotations().toSourceSetDependent().toAnnotations(),
descriptor.getDefaultValue()?.let { DefaultValue(it.toSourceSetDependent()) }
))
)
private data class DescriptorsWithKind(
val functions: List<FunctionDescriptor>,
val properties: List<PropertyDescriptor>,
val classlikes: List<ClassDescriptor>,
val typealiases: List<TypeAliasDescriptor>,
val enumEntries: List<ClassDescriptor>
)
private fun MemberScope.getDescriptorsWithKind(shouldFilter: Boolean = false): DescriptorsWithKind {
val descriptors = getContributedDescriptors { true }.let {
if (shouldFilter) it.filterDescriptorsInSourceSet() else it
}
class EnumEntryDescriptor
val groupedDescriptors = descriptors.groupBy {
when {
it is FunctionDescriptor -> FunctionDescriptor::class
it is PropertyDescriptor -> PropertyDescriptor::class
it is ClassDescriptor && it.kind != ClassKind.ENUM_ENTRY -> ClassDescriptor::class
it is TypeAliasDescriptor -> TypeAliasDescriptor::class
it is ClassDescriptor && it.kind == ClassKind.ENUM_ENTRY -> EnumEntryDescriptor::class
else -> IllegalStateException::class
}
}
@Suppress("UNCHECKED_CAST")
return DescriptorsWithKind(
(groupedDescriptors[FunctionDescriptor::class] ?: emptyList()) as List<FunctionDescriptor>,
(groupedDescriptors[PropertyDescriptor::class] ?: emptyList()) as List<PropertyDescriptor>,
(groupedDescriptors[ClassDescriptor::class] ?: emptyList()) as List<ClassDescriptor>,
(groupedDescriptors[TypeAliasDescriptor::class] ?: emptyList()) as List<TypeAliasDescriptor>,
(groupedDescriptors[EnumEntryDescriptor::class] ?: emptyList()) as List<ClassDescriptor>
)
}
private suspend fun List<FunctionDescriptor>.visitFunctions(parent: DRIWithPlatformInfo): List<DFunction> =
coroutineScope { parallelMap { visitFunctionDescriptor(it, parent) } }
private suspend fun List<PropertyDescriptor>.visitProperties(
parent: DRIWithPlatformInfo,
implicitAccessors: Map<PropertyDescriptor, List<FunctionDescriptor>> = emptyMap(),
): List<DProperty> {
return coroutineScope {
parallelMap {
val propertyAccessors = implicitAccessors[it] ?: emptyList()
visitPropertyDescriptor(it, propertyAccessors, parent)
}
}
}
private suspend fun List<ClassDescriptor>.visitClasslikes(parent: DRIWithPlatformInfo): List<DClasslike> =
coroutineScope { parallelMap { visitClassDescriptor(it, parent) } }
private suspend fun List<TypeAliasDescriptor>.visitTypealiases(): List<DTypeAlias> =
coroutineScope { parallelMap { visitTypeAliasDescriptor(it) } }
private suspend fun List<ClassDescriptor>.visitEnumEntries(parent: DRIWithPlatformInfo): List<DEnumEntry> =
coroutineScope { parallelMap { visitEnumEntryDescriptor(it, parent) } }
private fun DeclarationDescriptor.resolveDescriptorData(): SourceSetDependent<DocumentationNode> =
getDocumentation()?.toSourceSetDependent() ?: emptyMap()
private suspend fun toTypeConstructor(kt: KotlinType) =
GenericTypeConstructor(
DRI.from(kt.constructor.declarationDescriptor as DeclarationDescriptor),
kt.arguments.map { it.toProjection() },
extra = PropertyContainer.withAll(kt.getAnnotations().toSourceSetDependent().toAnnotations())
)
private suspend fun buildAncestryInformation(
kotlinType: KotlinType
): AncestryNode {
val (interfaces, superclass) = kotlinType.immediateSupertypes().filterNot { it.isAnyOrNullableAny() }
.partition {
val declaration = it.constructor.declarationDescriptor
val descriptor = declaration as? ClassDescriptor
?: (declaration as? TypeAliasDescriptor)?.underlyingType?.constructor?.declarationDescriptor as? ClassDescriptor
descriptor?.kind == ClassKind.INTERFACE
}
return coroutineScope {
AncestryNode(
typeConstructor = toTypeConstructor(kotlinType),
superclass = superclass.parallelMap(::buildAncestryInformation).singleOrNull(),
interfaces = interfaces.parallelMap(::buildAncestryInformation)
)
}
}
private suspend fun ClassDescriptor.resolveClassDescriptionData(): ClassInfo {
return coroutineScope {
ClassInfo(
buildAncestryInformation(this@resolveClassDescriptionData.defaultType),
resolveDescriptorData()
)
}
}
private suspend fun TypeParameterDescriptor.toVariantTypeParameter() =
DTypeParameter(
variantTypeParameter(
TypeParameter(DRI.from(this), name.identifier, annotations.getPresentableName())
),
resolveDescriptorData(),
null,
upperBounds.map { it.toBound() },
setOf(sourceSet),
extra = PropertyContainer.withAll(
additionalExtras().toSourceSetDependent().toAdditionalModifiers(),
getAnnotations().toSourceSetDependent().toAnnotations()
)
)
private fun org.jetbrains.kotlin.descriptors.annotations.Annotations.getPresentableName(): String? =
mapNotNull { it.toAnnotation() }.singleOrNull { it.dri.classNames == "ParameterName" }?.params?.get("name")
.safeAs<StringValue>()?.value?.let { unquotedValue(it) }
private suspend fun KotlinType.toBound(): Bound {
suspend fun <T : AnnotationTarget> annotations(): PropertyContainer<T> =
getAnnotations().takeIf { it.isNotEmpty() }?.let { annotations ->
PropertyContainer.withAll(annotations.toSourceSetDependent().toAnnotations())
} ?: PropertyContainer.empty()
return when (this) {
is DynamicType -> Dynamic
is AbbreviatedType -> TypeAliased(
abbreviation.toBound(),
expandedType.toBound(),
annotations()
)
else -> when (val ctor = constructor.declarationDescriptor) {
is TypeParameterDescriptor -> TypeParameter(
dri = DRI.from(ctor),
name = ctor.name.asString(),
presentableName = annotations.getPresentableName(),
extra = annotations()
)
is FunctionClassDescriptor -> FunctionalTypeConstructor(
DRI.from(ctor),
arguments.map { it.toProjection() },
isExtensionFunction = isExtensionFunctionType || isBuiltinExtensionFunctionalType,
isSuspendable = isSuspendFunctionTypeOrSubtype,
presentableName = annotations.getPresentableName(),
extra = annotations()
)
else -> GenericTypeConstructor(
DRI.from(ctor!!), // TODO: remove '!!'
arguments.map { it.toProjection() },
annotations.getPresentableName(),
extra = annotations()
)
}.let {
if (isMarkedNullable) Nullable(it) else it
}
}
}
private suspend fun TypeProjection.toProjection(): Projection =
if (isStarProjection) Star else formPossiblyVariant()
private suspend fun TypeProjection.formPossiblyVariant(): Projection =
type.toBound().wrapWithVariance(projectionKind)
private fun TypeParameterDescriptor.variantTypeParameter(type: TypeParameter) =
type.wrapWithVariance(variance)
private fun <T : Bound> T.wrapWithVariance(variance: org.jetbrains.kotlin.types.Variance) =
when (variance) {
org.jetbrains.kotlin.types.Variance.INVARIANT -> Invariance(this)
org.jetbrains.kotlin.types.Variance.IN_VARIANCE -> Contravariance(this)
org.jetbrains.kotlin.types.Variance.OUT_VARIANCE -> Covariance(this)
}
private fun DeclarationDescriptor.getDocumentation() = (findKDoc()?.let {
MarkdownParser.parseFromKDocTag(
kDocTag = it,
externalDri = { link: String ->
try {
resolveKDocLink(
context = resolutionFacade.resolveSession.bindingContext,
resolutionFacade = resolutionFacade,
fromDescriptor = this,
fromSubjectOfTag = null,
qualifiedName = link.split('.')
).firstOrNull()?.let { DRI.from(it) }
} catch (e1: IllegalArgumentException) {
logger.warn("Couldn't resolve link for $link")
null
}
},
kdocLocation = toSourceElement.containingFile.name?.let {
val fqName = fqNameOrNull()?.asString()
if (fqName != null) "$it/$fqName"
else it
}
)
} ?: getJavaDocs())?.takeIf { it.children.isNotEmpty() }
private fun DeclarationDescriptor.getJavaDocs(): DocumentationNode? {
val overriddenDescriptors = (this as? CallableDescriptor)?.overriddenDescriptors ?: emptyList()
val allDescriptors = overriddenDescriptors + listOf(this)
return allDescriptors
.mapNotNull { it.findPsi() as? PsiNamedElement }
.firstOrNull()
?.let { javadocParser.parseDocumentation(it) }
}
private suspend fun ClassDescriptor.companion(dri: DRIWithPlatformInfo): DObject? = companionObjectDescriptor?.let {
objectDescriptor(it, dri)
}
private fun MemberDescriptor.modifier() = when (modality) {
Modality.FINAL -> KotlinModifier.Final
Modality.SEALED -> KotlinModifier.Sealed
Modality.OPEN -> KotlinModifier.Open