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