| 38 | |
| 39 | public class SrcDecorator { |
| 40 | public static String decorate(String src, ClassInstance cls, NameType nameType) { |
| 41 | String name = cls.getName(nameType); |
| 42 | |
| 43 | if (cls.getOuterClass() != null && name.contains("$")) { |
| 44 | // replace <outer>.<inner> with <outer>$<inner> since . is not a legal identifier within class names and thus gets rejected by JavaParser |
| 45 | |
| 46 | int nameStartPos = Math.max(0, name.lastIndexOf('/') + 1); |
| 47 | List<String> classNames = new ArrayList<>(); |
| 48 | boolean firstDollar = true; |
| 49 | |
| 50 | name = name.substring(nameStartPos, name.length()); |
| 51 | |
| 52 | for (int i = 0; i < name.length(); i++) { |
| 53 | char ch = name.charAt(i); |
| 54 | |
| 55 | if (ch == '$') { |
| 56 | if (firstDollar) { |
| 57 | firstDollar = false; |
| 58 | continue; |
| 59 | } |
| 60 | |
| 61 | classNames.add(name.substring(0, i)); |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | classNames.add(name.substring(0, name.length())); |
| 66 | |
| 67 | for (int i = classNames.size() - 1; i >= 0; i--) { |
| 68 | src = src.replace(classNames.get(i).replace('$', '.'), classNames.get(i)); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | JavaParser parser = new JavaParser(new ParserConfiguration() |
| 73 | .setLanguageLevel(LanguageLevel.RAW)); |
| 74 | |
| 75 | ParseResult<CompilationUnit> result = parser.parse(src); |
| 76 | CompilationUnit cu; |
| 77 | |
| 78 | if (result.isSuccessful()) { |
| 79 | cu = result.getResult().orElseThrow(); |
| 80 | } else { |
| 81 | String fixedSrc = tryFixCodeFormat(src, result.getProblems()); |
| 82 | |
| 83 | if (fixedSrc == null) { |
| 84 | throw new SrcParseException(result.getProblems(), src); |
| 85 | } |
| 86 | |
| 87 | ParseResult<CompilationUnit> fixedResult = parser.parse(fixedSrc); |
| 88 | |
| 89 | if (!fixedResult.isSuccessful()) { |
| 90 | throw new SrcParseException(fixedResult.getProblems(), fixedSrc); |
| 91 | } else { |
| 92 | cu = fixedResult.getResult().orElseThrow(); |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | TypeResolver resolver = new TypeResolver(); |
| 97 | resolver.setup(cls, nameType, cu); |