@@ -1041,6 +1041,76 @@ static void addCommentsToUnit(Collection<Comment> comments, CompilationUnit res)
10411041 .forEach (before ::add );
10421042 before .sort (Comparator .comparingInt (Comment ::getStartPosition ));
10431043 res .setCommentTable (before .toArray (Comment []::new ));
1044+
1045+
1046+ List <Javadoc > orphanedJavadoc = new ArrayList <>();
1047+ for ( Comment c : comments ) {
1048+ if ( c instanceof Javadoc j && j .getParent () == null ) {
1049+ orphanedJavadoc .add (j );
1050+ }
1051+ }
1052+
1053+ // Fix known missing javadoc errors due to JDT being out of spec
1054+ ArrayList <Initializer > initializers = new ArrayList <>();
1055+ HashMap <Comment , ASTNode > possibleOwners = new HashMap <>();
1056+ res .accept (new ASTVisitor () {
1057+ @ Override
1058+ public boolean preVisit2 (ASTNode node ) {
1059+ boolean ret = false ;
1060+ for ( Javadoc c : orphanedJavadoc ) {
1061+ ret |= preVisitPerComment (node , c );
1062+ }
1063+ return ret ;
1064+ }
1065+ public boolean preVisitPerComment (ASTNode node , Javadoc c ) {
1066+ int commentStart = c .getStartPosition ();
1067+ int commentEnd = commentStart + c .getLength ();
1068+ int start = node .getStartPosition ();
1069+ int end = start + node .getLength ();
1070+ if ( end < commentStart ) {
1071+ return false ;
1072+ }
1073+ if ( start > commentEnd ) {
1074+ ASTNode closest = possibleOwners .get (c );
1075+ if ( closest == null ) {
1076+ possibleOwners .put (c , node );
1077+ } else {
1078+ int closestStart = closest .getStartPosition ();
1079+ //int closestEnd = start + closest.getLength();
1080+ int closestDiff = commentEnd - closestStart ;
1081+ int thisDiff = commentEnd - start ;
1082+ if ( thisDiff < closestDiff ) {
1083+ possibleOwners .put (c , node );
1084+ }
1085+ }
1086+ return false ;
1087+ }
1088+ return true ;
1089+ }
1090+ @ Override
1091+ public boolean visit (Initializer node ) {
1092+ initializers .add (node );
1093+ return true ;
1094+ }
1095+ // TODO add other locations where jdt violates spec, other than Initializer
1096+ });
1097+ for ( Javadoc k : orphanedJavadoc ) {
1098+ ASTNode closest = possibleOwners .get (k );
1099+ if ( closest instanceof Initializer i ) {
1100+ try {
1101+ i .setJavadoc (k );
1102+ int iStart = i .getStartPosition ();
1103+ int kStart = k .getStartPosition ();
1104+ int iEnd = iStart + i .getLength ();
1105+ int kEnd = kStart + k .getLength ();
1106+ int min = Math .min (iStart , kStart );
1107+ int end = Math .max (iEnd , kEnd );
1108+ i .setSourceRange (min , end - min );
1109+ } catch (RuntimeException re ) {
1110+ // Ignore
1111+ }
1112+ }
1113+ }
10441114 }
10451115
10461116 private static boolean noCommentAt (CompilationUnit unit , int pos ) {
0 commit comments