Fix of generating inner class with same name like parent
[mdsal.git] / binding2 / mdsal-binding2-generator-util / src / main / java / org / opendaylight / mdsal / binding / javav2 / generator / util / JavaIdentifierNormalizer.java
1 /*
2  * Copyright (c) 2017 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.javav2.generator.util;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.collect.ArrayListMultimap;
12 import com.google.common.collect.ImmutableSet;
13 import com.google.common.collect.ListMultimap;
14 import java.util.List;
15 import java.util.Set;
16 import org.apache.commons.lang3.StringUtils;
17 import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration;
18 import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration.Pair;
19 import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
20
21 /**
22  * This util class converts every non-java char in identifier to java char by
23  * its unicode name (<a href=
24  * "http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.8">JAVA SE
25  * SPECIFICATIONS - Identifiers</a>). There are special types of mapping
26  * non-java chars to original identifiers according to specific
27  * {@linkplain JavaIdentifier java type}:
28  * <ul>
29  * <li>class, enum, interface</li>
30  * <li>
31  * <ul>
32  * <li>without special separator</li>
33  * <li>the first character of identifier, any other first character of
34  * identifier part mapped by non-Java char name from unicode and char in
35  * identifier behind non-java char name are converting to upper case</li>
36  * <li>examples:</li>
37  * <li>
38  * <ul>
39  * <li>example* - ExampleAsterisk</li>
40  * <li>example*example - ExampleAserisksExample</li>
41  * <li>\example - ReverseSolidusExample</li>
42  * <li>1example - DigitOneExample</li>
43  * <li>example1 - Example1</li>
44  * <li>int - IntReservedKeyword</li>
45  * <li>con - ConReservedKeyword</li>
46  * </ul>
47  * </li>
48  * </ul>
49  * </li>
50  * <li>enum value, constant</li>
51  * <li>
52  * <ul>
53  * <li>used underscore as special separator</li>
54  * <li>converted identifier to upper case</li>
55  * <li>examples:</li>
56  * <li>
57  * <ul>
58  * <li>example* - EXAMPLE_ASTERISK</li>
59  * <li>example*example - EXAMPLE_ASTERISK_EXAMPLE</li>
60  * <li>\example - REVERSE_SOLIDUS_EXAMPLE</li>
61  * <li>1example - DIGIT_ONE_EXAMPLE</li>
62  * <li>example1 - EXAMPLE1</li>
63  * <li>int - INT_RESERVED_KEYWORD</li>
64  * <li>con - CON_RESERVED_KEYWORD</li>
65  * </ul>
66  * </li>
67  * </ul>
68  * </li>
69  * <li>method, variable</li>
70  * <li>
71  * <li>
72  * <ul>
73  * <li>without special separator</li>
74  * <li>the first character of identifier is converting to lower case</li>
75  * <li>any other first character of identifier part mapped by non-Java char name
76  * from unicode and char in identifier behind non-java char name are converting
77  * to upper case</li>
78  * <li>examples:</li>
79  * <li>
80  * <ul>
81  * <li>example* - exampleAsterisk</li>
82  * <li>example*example - exampleAserisksExample</li>
83  * <li>\example - reverseSolidusExample</li>
84  * <li>1example - digitOneExample</li>
85  * <li>example1 - example1</li>
86  * <li>int - intReservedKeyword</li>
87  * <li>con - conReservedKeyword</li>
88  * </ul>
89  * </li>
90  * </ul>
91  * </li>
92  * <li>package - full package name (<a href=
93  * "https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html">
94  * Naming a package</a>)</li>
95  * <li>
96  * <li>
97  * <ul>
98  * <li>parts of package name are separated by dots</li>
99  * <li>parts of package name are converting to lower case</li>
100  * <li>if parts of package name are reserved Java or Windows keywords, such as
101  * 'int' the suggested convention is to add an underscore to keyword</li>
102  * <li>dash is parsed as underscore according to <a href=
103  * "https://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html">
104  * Naming a package</a></li>
105  * <li>examples:</li>
106  * <li>
107  * <ul>
108  * <li>org.example* - org.exampleasterisk</li>
109  * <li>org.example*example - org.exampleasteriskexample</li>
110  * <li>org.\example - org.reversesolidusexample</li>
111  * <li>org.1example - org.digitoneexample</li>
112  * <li>org.example1 - org.example1</li>
113  * <li>org.int - org.int_</li>
114  * <li>org.con - org.con_</li>
115  * <li>org.foo-cont - org.foo_cont</li>
116  * </ul>
117  * </li>
118  * </ul>
119  * </li>
120  * </ul>
121  *
122  * There is special case in CLASS, INTERFACE, ENUM, ENUM VALUE, CONSTANT, METHOD
123  * and VARIABLE if identifier contains single dash - then the converter ignores
124  * the single dash in the way of the non-java chars. In other way, if dash is
125  * the first or the last char in the identifier or there is more dashes in a row
126  * in the identifier, then these dashes are converted as non-java chars.
127  * Example:
128  * <ul>
129  * <li>class, enum, interface</li>
130  * <li>
131  * <ul>
132  * <li>foo-cont - FooCont</li>
133  * <li>foo--cont - FooHyphenMinusHyphenMinusCont</li>
134  * <li>-foo - HyphenMinusFoo</li>
135  * <li>foo- - FooHyphenMinus</li>
136  * </ul>
137  * </li>
138  * <li>enum value, constant
139  * <li>
140  * <ul>
141  * <li>foo-cont - FOO_CONT</li>
142  * <li>foo--cont - FOO_HYPHEN_MINUS_HYPHEN_MINUS_CONT</li>
143  * <li>-foo - HYPHEN_MINUS_FOO</li>
144  * <li>foo- - FOO_HYPHEN_MINUS</li>
145  * </ul>
146  * </li>
147  * <li>method, variable</li>
148  * <li>
149  * <ul>
150  * <li>foo-cont - fooCont</li>
151  * <li>foo--cont - fooHyphenMinusHyphenMinusCont</li>
152  * <li>-foo - hyphenMinusFoo</li>
153  * <li>foo- - fooHyphenMinus</li>
154  * </ul>
155  * </li>
156  * </ul>
157  *
158  * Next special case talks about normalizing class name which already exists in
159  * package - but with different camel cases (foo, Foo, fOo, ...). To every next
160  * classes with same names will by added their actual rank (serial number),
161  * except the first one. This working for CLASS, ENUM and INTEFACE java
162  * identifiers. If there exist the same ENUM VALUES in ENUM (with different
163  * camel cases), then it's parsed with same logic like CLASSES, ENUMS and
164  * INTERFACES but according to list of pairs of their ENUM parent. Example:
165  *
166  * <ul>
167  * <li>class, enum, interface</li>
168  * <li>
169  * <ul>
170  * <li>package name org.example, class (or interface or enum) Foo - normalized
171  * to Foo
172  * <li>package name org.example, class (or interface or enum) fOo - normalized
173  * to Foo1
174  * </ul>
175  * </li>
176  * <li>enum value</li>
177  * <li>
178  * <ul>
179  * <li>
180  *
181  * <pre>
182  * type enumeration {
183  *     enum foo;
184  *     enum Foo;
185  * }
186  * </pre>
187  *
188  * </li>
189  * <li>YANG enum values will be mapped to 'FOO' and 'FOO_1' Java enum
190  * values.</li>
191  * </ul>
192  * </li>
193  * </ul>
194  */
195 @Beta
196 public final class JavaIdentifierNormalizer {
197
198     private static final int FIRST_CHAR = 0;
199     private static final int FIRST_INDEX = 1;
200     private static final char UNDERSCORE = '_';
201     private static final char DASH = '-';
202     private static final String EMPTY_STRING = "";
203     private static final String RESERVED_KEYWORD = "reserved_keyword";
204     private static final ListMultimap<String, String> PACKAGES_MAP = ArrayListMultimap.create();
205     public static final Set<String> SPECIAL_RESERVED_PATHS =
206             ImmutableSet.of("org.opendaylight.yangtools.yang.model","org.opendaylight.yangtools.concepts","org.opendaylight.yangtools.yang.common",
207                     "org.opendaylight.mdsal.binding.javav2.spec","java", "com");
208
209     private JavaIdentifierNormalizer() {
210         throw new UnsupportedOperationException("Util class");
211     }
212
213     /**
214      * <p>
215      * According to <a href="https://tools.ietf.org/html/rfc7950#section-9.6.4">YANG RFC 7950</a>,
216      * all assigned names in an enumeration MUST be unique. Created names are contained in the list
217      * of {@link Enumeration.Pair}. This method adds actual index with underscore behind name of new
218      * enum value only if this name already exists in one of the list of {@link Enumeration.Pair}.
219      * Then, the name will be converted to java chars according to {@link JavaIdentifier#ENUM_VALUE}
220      * and returned.
221      * </p>
222      * Example:
223      *
224      * <pre>
225      * type enumeration {
226      *     enum foo;
227      *     enum Foo;
228      * }
229      * </pre>
230      *
231      * YANG enum values will be mapped to 'FOO' and 'FOO_1' Java enum values.
232      *
233      * @param name
234      *            - name of new enum value
235      * @param values
236      *            - list of all actual enum values
237      * @return converted and fixed name of new enum value
238      */
239     public static String normalizeEnumValueIdentifier(final String name, final List<Pair> values) {
240         return convertIdentifierEnumValue(name, name, values, FIRST_INDEX);
241     }
242
243     /**
244      * Normalizing full package name by non java chars and reserved keywords.
245      *
246      * @param fullPackageName
247      *            - full package name
248      * @return normalized name
249      */
250     public static String normalizeFullPackageName(final String fullPackageName) {
251         final String[] packageNameParts = fullPackageName.split("\\.");
252         final StringBuilder sb = new StringBuilder();
253         for (int i = 0; i < packageNameParts.length; i++) {
254             String normalizedPartialPackageName = normalizePartialPackageName(packageNameParts[i]);
255
256             // check if fullPackageName contains class name at the end and
257             // capitalize last part of normalized package name
258             if (packageNameParts.length != 1 && i == packageNameParts.length - 1
259                     && Character.isUpperCase(packageNameParts[i].charAt(FIRST_CHAR))) {
260                 normalizedPartialPackageName = StringUtils.capitalize(normalizedPartialPackageName);
261             }
262
263             sb.append(normalizedPartialPackageName);
264
265             if (i != (packageNameParts.length - 1)) {
266                 sb.append(".");
267             }
268         }
269         return sb.toString();
270     }
271
272     /**
273      * Normalizing part of package name by non java chars.
274      *
275      * @param packageNamePart
276      *            - part of package name
277      * @return normalized name
278      */
279     public static String normalizePartialPackageName(final String packageNamePart) {
280         // if part of package name consist from java or windows reserved word, return it with
281         // underscore at the end and in lower case
282         if (BindingMapping.JAVA_RESERVED_WORDS.contains(packageNamePart.toLowerCase())
283                 || BindingMapping.WINDOWS_RESERVED_WORDS.contains(packageNamePart.toUpperCase())) {
284             return new StringBuilder(packageNamePart).append(UNDERSCORE).toString().toLowerCase();
285         }
286         String normalizedPackageNamePart = packageNamePart;
287         if (packageNamePart.contains(String.valueOf(DASH))) {
288             normalizedPackageNamePart = packageNamePart.replaceAll(String.valueOf(DASH), String.valueOf(UNDERSCORE));
289         }
290         final StringBuilder sb = new StringBuilder();
291         StringBuilder innserSb = new StringBuilder();
292         for (int i = 0; i < normalizedPackageNamePart.length(); i++) {
293             if (normalizedPackageNamePart.charAt(i) == UNDERSCORE) {
294                 if (!innserSb.toString().isEmpty()) {
295                     sb.append(normalizeSpecificIdentifier(innserSb.toString(), JavaIdentifier.PACKAGE));
296                     innserSb = new StringBuilder();
297                 }
298                 sb.append(UNDERSCORE);
299             } else {
300                 innserSb.append(normalizedPackageNamePart.charAt(i));
301             }
302         }
303         if (!innserSb.toString().isEmpty()) {
304             sb.append(normalizeSpecificIdentifier(innserSb.toString(), JavaIdentifier.PACKAGE));
305         }
306         // returned normalized part of package name
307         return sb.toString();
308     }
309
310     /**
311      * Find and convert non Java chars in identifiers of generated transfer objects, initially
312      * derived from corresponding YANG according to
313      * <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.8"> Java
314      * Specifications - Identifiers</a>. If there is more same class names at the same package, then
315      * append rank (serial number) to the end of them. Works for class, enum, interface.
316      *
317      * @param packageName
318      *            - package of identifier
319      * @param className
320      *            - name of identifier
321      * @return - java acceptable identifier
322      */
323     public static String normalizeClassIdentifier(final String packageName, final String className) {
324         for (final String reservedPath : SPECIAL_RESERVED_PATHS) {
325             if (packageName.startsWith(reservedPath)) {
326                 return className;
327             }
328         }
329         final String convertedClassName = normalizeSpecificIdentifier(className, JavaIdentifier.CLASS);
330         // if packageName contains class name at the end, then the className is
331         // name of inner class
332         final String[] packageNameParts = packageName.split("\\.");
333         String suppInnerClassPackageName = packageName;
334         if (packageNameParts.length > 1) {
335             if (Character.isUpperCase(packageNameParts[packageNameParts.length - 1].charAt(FIRST_CHAR))) {
336                 final StringBuilder sb = new StringBuilder();
337                 // ignore class name in package name - inner class name has
338                 // to be normalizing according to original package of parent
339                 // class
340                 for (int i = 0; i < packageNameParts.length - 1; i++) {
341                     sb.append(packageNameParts[i]);
342                     if (i != (packageNameParts.length - 2)) {
343                         sb.append('.');
344                     }
345                 }
346                 suppInnerClassPackageName = sb.toString();
347             }
348         }
349
350         return normalizeClassIdentifier(suppInnerClassPackageName, convertedClassName, convertedClassName, FIRST_INDEX);
351     }
352
353     /**
354      * Find and convert non Java chars in identifiers of generated transfer objects, initially
355      * derived from corresponding YANG.
356      *
357      * @param identifier
358      *            - name of identifier
359      * @param javaIdentifier
360      *            - java type of identifier
361      * @return - java acceptable identifier
362      */
363     public static String normalizeSpecificIdentifier(final String identifier, final JavaIdentifier javaIdentifier) {
364         final StringBuilder sb = new StringBuilder();
365
366         // if identifier isn't PACKAGE type then check it by reserved keywords
367         if(javaIdentifier != JavaIdentifier.PACKAGE) {
368             if (BindingMapping.JAVA_RESERVED_WORDS.contains(identifier.toLowerCase())
369                     || BindingMapping.WINDOWS_RESERVED_WORDS.contains(identifier.toUpperCase())) {
370                 return fixCasesByJavaType(
371                         sb.append(identifier).append(UNDERSCORE).append(RESERVED_KEYWORD).toString().toLowerCase(),
372                         javaIdentifier);
373             }
374         }
375
376         // check and convert first char in identifier if there is non-java char
377         final char firstChar = identifier.charAt(FIRST_CHAR);
378         if (!Character.isJavaIdentifierStart(firstChar)) {
379             // converting first char of identifier
380             sb.append(convertFirst(firstChar, existNext(identifier, FIRST_CHAR)));
381         } else {
382             sb.append(firstChar);
383         }
384         // check and convert other chars in identifier, if there is non-java char
385         for (int i = 1; i < identifier.length(); i++) {
386             final char actualChar = identifier.charAt(i);
387             // ignore single dash as non java char - if there is more dashes in a row or dash is as
388             // the last char in identifier then parse these dashes as non java chars
389             if ((actualChar == '-') && existNext(identifier, i)) {
390                 if ((identifier.charAt(i - 1) != DASH) && (identifier.charAt(i + 1) != DASH)) {
391                     sb.append(UNDERSCORE);
392                     continue;
393                 }
394             }
395             if (!Character.isJavaIdentifierPart(actualChar)) {
396                 // prepare actual string of sb for checking if underscore exist on position of the
397                 // last char
398                 final String partialConvertedIdentifier = sb.toString();
399                 sb.append(convert(actualChar, existNext(identifier, i),
400                         partialConvertedIdentifier.charAt(partialConvertedIdentifier.length() - 1)));
401             } else {
402                 sb.append(actualChar);
403             }
404         }
405         // apply camel case in appropriate way
406         return fixCasesByJavaType(sb.toString().replace("__", "_").toLowerCase(), javaIdentifier);
407     }
408
409     /**
410      * Checking while there doesn't exist any class name with the same name
411      * (regardless of camel cases) in package.
412      *
413      * @param packageName
414      *            - package of class name
415      * @param origClassName
416      *            - original class name
417      * @param actualClassName
418      *            - actual class name with rank (serial number)
419      * @param rank
420      *            - actual rank (serial number)
421      * @return converted identifier
422      */
423     private static String normalizeClassIdentifier(final String packageName, final String origClassName,
424             final String actualClassName, final int rank) {
425         if (PACKAGES_MAP.containsKey(packageName)) {
426             for (final String existingName : PACKAGES_MAP.get(packageName)) {
427                 if (existingName.toLowerCase().equals(actualClassName.toLowerCase())) {
428                     final int nextRank = rank + 1;
429                     return normalizeClassIdentifier(packageName, origClassName,
430                             new StringBuilder(origClassName).append(rank).toString(), nextRank);
431                 }
432             }
433         }
434         PACKAGES_MAP.put(packageName, actualClassName);
435         return actualClassName;
436     }
437
438     /**
439      * Fix cases of converted identifiers by Java type
440      *
441      * @param string
442      *            - converted identifier
443      * @param javaIdentifier
444      *            - java type of identifier
445      * @return converted identifier with right cases according to java type
446      */
447     private static String fixCasesByJavaType(final String convertedIdentifier, final JavaIdentifier javaIdentifier) {
448         switch (javaIdentifier) {
449             case CLASS:
450             case ENUM:
451             case INTERFACE:
452                 return capitalize(fixCases(convertedIdentifier));
453             case ENUM_VALUE:
454             case CONSTANT:
455                 return convertedIdentifier.toUpperCase();
456             case METHOD:
457             case VARIABLE:
458                 return fixCases(convertedIdentifier);
459             case PACKAGE:
460                 return convertedIdentifier.replaceAll(String.valueOf(UNDERSCORE), EMPTY_STRING);
461             default:
462                 throw new IllegalArgumentException("Unknown java type of identifier : " + javaIdentifier.toString());
463         }
464     }
465
466     /**
467      * Delete unnecessary chars in converted identifier and apply camel case in appropriate way.
468      *
469      * @param convertedIdentifier
470      *            - original converted identifier
471      * @return resolved identifier
472      */
473     private static String fixCases(final String convertedIdentifier) {
474         final StringBuilder sb = new StringBuilder();
475         if (convertedIdentifier.contains(String.valueOf(UNDERSCORE))) {
476             boolean isFirst = true;
477             for (final String part : convertedIdentifier.split(String.valueOf(UNDERSCORE))) {
478                 if (isFirst) {
479                     isFirst = false;
480                     sb.append(part);
481                 } else {
482                     sb.append(capitalize(part));
483                 }
484             }
485         } else {
486             sb.append(convertedIdentifier);
487         }
488         return sb.toString();
489     }
490
491     /**
492      * Check if there exist next char in identifier behind actual char position
493      *
494      * @param identifier
495      *            - original identifier
496      * @param actual
497      *            - actual char position
498      * @return true if there is another char, false otherwise
499      */
500     private static boolean existNext(final String identifier, final int actual) {
501       return (identifier.length() - 1) < (actual + 1) ? false : true;
502     }
503
504     /**
505      * Converting first char of identifier. This happen only if this char is
506      * non-java char
507      *
508      * @param c
509      *            - first char
510      * @param existNext
511      *            - existing of next char behind actual char
512      * @return converted char
513      */
514     private static String convertFirst(final char c, final boolean existNext) {
515         String name = Character.getName(c);
516         if (name.contains(String.valueOf(DASH))) {
517             name = name.replaceAll(String.valueOf(DASH), String.valueOf(UNDERSCORE));
518         }
519         name = existNext ? (name + "_") : name;
520         return name.contains(" ") ? name.replaceAll(" ", "_") : name;
521     }
522
523     /**
524      * Converting any char in java identifier, This happen only if this char is
525      * non-java char
526      *
527      * @param c
528      *            - actual char
529      * @param existNext
530      *            - existing of next char behind actual char
531      * @param partialLastChar
532      *            - last char of partial converted identifier
533      * @return converted char
534      */
535     private static String convert(final char c, final boolean existNext, final char partialLastChar) {
536         return partialLastChar == '_' ? convertFirst(c, existNext) : "_" + convertFirst(c, existNext);
537     }
538
539     /**
540      * Capitalize input string
541      *
542      * @param identifier
543      *            - string to be capitalized
544      */
545     private static String capitalize(final String identifier) {
546         return identifier.substring(FIRST_CHAR, FIRST_CHAR + 1).toUpperCase() + identifier.substring(1);
547     }
548
549     private static String convertIdentifierEnumValue(final String name, final String origName, final List<Pair> values,
550             final int rank) {
551         String newName = name;
552         for (final Pair pair : values) {
553             if (pair.getName().toLowerCase().equals(name.toLowerCase())
554                     || pair.getMappedName().toLowerCase().equals(name.toLowerCase())) {
555                 int actualRank = rank;
556                 final StringBuilder actualNameBuilder =
557                         new StringBuilder(origName).append(UNDERSCORE).append(actualRank);
558                 newName = convertIdentifierEnumValue(actualNameBuilder.toString(), origName, values, ++actualRank);
559             }
560         }
561         return normalizeSpecificIdentifier(newName, JavaIdentifier.ENUM_VALUE);
562     }
563 }