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