Add alternative enum assigned name mapping
[mdsal.git] / binding / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / BindingMapping.java
1 /*
2  * Copyright (c) 2013 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.yangtools.yang.binding;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.base.CharMatcher;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.BiMap;
15 import com.google.common.collect.HashBiMap;
16 import com.google.common.collect.ImmutableSet;
17 import com.google.common.collect.Interner;
18 import com.google.common.collect.Interners;
19 import java.text.SimpleDateFormat;
20 import java.util.Collection;
21 import java.util.Locale;
22 import java.util.Set;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.QNameModule;
27
28 public final class BindingMapping {
29
30     public static final String VERSION = "0.6";
31
32     public static final Set<String> JAVA_RESERVED_WORDS = ImmutableSet.of(
33         // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.9
34         "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue",
35         "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if",
36         "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private",
37         "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this",
38         "throw", "throws", "transient", "try", "void", "volatile", "while",
39         // FIXME: _ is excluded to retain compatibility with previous releases
40         // "_",
41         // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.3
42         "false", "true",
43         // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.7
44         "null");
45
46     public static final String DATA_ROOT_SUFFIX = "Data";
47     public static final String RPC_SERVICE_SUFFIX = "Service";
48     public static final String NOTIFICATION_LISTENER_SUFFIX = "Listener";
49     public static final String QNAME_STATIC_FIELD_NAME = "QNAME";
50     public static final String PACKAGE_PREFIX = "org.opendaylight.yang.gen.v1";
51     public static final String AUGMENTATION_FIELD = "augmentation";
52
53     private static final Splitter CAMEL_SPLITTER = Splitter.on(CharMatcher.anyOf(" _.-/").precomputed())
54             .omitEmptyStrings().trimResults();
55     private static final Pattern COLON_SLASH_SLASH = Pattern.compile("://", Pattern.LITERAL);
56     private static final String QUOTED_DOT = Matcher.quoteReplacement(".");
57     private static final Splitter DOT_SPLITTER = Splitter.on('.');
58
59     public static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl";
60     public static final String MODEL_BINDING_PROVIDER_CLASS_NAME = "$YangModelBindingProvider";
61
62     public static final String RPC_INPUT_SUFFIX = "Input";
63     public static final String RPC_OUTPUT_SUFFIX = "Output";
64
65     private static final ThreadLocal<SimpleDateFormat> PACKAGE_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
66
67         @Override
68         protected SimpleDateFormat initialValue() {
69             return new SimpleDateFormat("yyMMdd");
70         }
71
72         @Override
73         public void set(final SimpleDateFormat value) {
74             throw new UnsupportedOperationException();
75         }
76     };
77
78     private static final Interner<String> PACKAGE_INTERNER = Interners.newWeakInterner();
79
80     private BindingMapping() {
81         throw new UnsupportedOperationException("Utility class should not be instantiated");
82     }
83
84     public static String getRootPackageName(final QName module) {
85         return getRootPackageName(module.getModule());
86     }
87
88     public static String getRootPackageName(final QNameModule module) {
89         checkArgument(module != null, "Module must not be null");
90         checkArgument(module.getRevision() != null, "Revision must not be null");
91         checkArgument(module.getNamespace() != null, "Namespace must not be null");
92         final StringBuilder packageNameBuilder = new StringBuilder();
93
94         packageNameBuilder.append(BindingMapping.PACKAGE_PREFIX);
95         packageNameBuilder.append('.');
96
97         String namespace = module.getNamespace().toString();
98         namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
99
100         final char[] chars = namespace.toCharArray();
101         for (int i = 0; i < chars.length; ++i) {
102             switch (chars[i]) {
103             case '/':
104             case ':':
105             case '-':
106             case '@':
107             case '$':
108             case '#':
109             case '\'':
110             case '*':
111             case '+':
112             case ',':
113             case ';':
114             case '=':
115                 chars[i] = '.';
116             }
117         }
118
119         packageNameBuilder.append(chars);
120         if (chars[chars.length - 1] != '.') {
121             packageNameBuilder.append('.');
122         }
123         packageNameBuilder.append("rev");
124         packageNameBuilder.append(PACKAGE_DATE_FORMAT.get().format(module.getRevision()));
125         return normalizePackageName(packageNameBuilder.toString());
126     }
127
128     public static String normalizePackageName(final String packageName) {
129         if (packageName == null) {
130             return null;
131         }
132
133         final StringBuilder builder = new StringBuilder();
134         boolean first = true;
135
136         for (String p : DOT_SPLITTER.split(packageName.toLowerCase())) {
137             if (first) {
138                 first = false;
139             } else {
140                 builder.append('.');
141             }
142
143             if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
144                 builder.append('_');
145             }
146             builder.append(p);
147         }
148
149         // Prevent duplication of input string
150         return PACKAGE_INTERNER.intern(builder.toString());
151     }
152
153     public static String getMethodName(final QName name) {
154         checkArgument(name != null, "Name should not be null.");
155         return getMethodName(name.getLocalName());
156     }
157
158     public static String getClassName(final String localName) {
159         checkArgument(localName != null, "Name should not be null.");
160         return toFirstUpper(toCamelCase(localName));
161     }
162
163     public static String getMethodName(final String yangIdentifier) {
164         checkArgument(yangIdentifier != null,"Identifier should not be null");
165         return toFirstLower(toCamelCase(yangIdentifier));
166     }
167
168     public static String getClassName(final QName name) {
169         checkArgument(name != null, "Name should not be null.");
170         return toFirstUpper(toCamelCase(name.getLocalName()));
171     }
172
173     public static String getGetterSuffix(final QName name) {
174         checkArgument(name != null, "Name should not be null.");
175         final String candidate = toFirstUpper(toCamelCase(name.getLocalName()));
176         return "Class".equals(candidate) ? "XmlClass" : candidate;
177     }
178
179     public static String getPropertyName(final String yangIdentifier) {
180         final String potential = toFirstLower(toCamelCase(yangIdentifier));
181         if ("class".equals(potential)) {
182             return "xmlClass";
183         }
184         return potential;
185     }
186
187     private static String toCamelCase(final String rawString) {
188         checkArgument(rawString != null, "String should not be null");
189         Iterable<String> components = CAMEL_SPLITTER.split(rawString);
190         StringBuilder builder = new StringBuilder();
191         for (String comp : components) {
192             builder.append(toFirstUpper(comp));
193         }
194         return checkNumericPrefix(builder.toString());
195     }
196
197     private static String checkNumericPrefix(final String rawString) {
198         if (rawString == null || rawString.isEmpty()) {
199             return rawString;
200         }
201         char firstChar = rawString.charAt(0);
202         if (firstChar >= '0' && firstChar <= '9') {
203             return "_" + rawString;
204         } else {
205             return rawString;
206         }
207     }
208
209     /**
210      * Returns the {@link String} {@code s} with an
211      * {@link Character#isUpperCase(char) upper case} first character. This
212      * function is null-safe.
213      *
214      * @param s
215      *            the string that should get an upper case first character. May
216      *            be <code>null</code>.
217      * @return the {@link String} {@code s} with an upper case first character
218      *         or <code>null</code> if the input {@link String} {@code s} was
219      *         <code>null</code>.
220      */
221     public static String toFirstUpper(final String s) {
222         if (s == null || s.length() == 0) {
223             return s;
224         }
225         if (Character.isUpperCase(s.charAt(0))) {
226             return s;
227         }
228         if (s.length() == 1) {
229             return s.toUpperCase();
230         }
231         return s.substring(0, 1).toUpperCase() + s.substring(1);
232     }
233
234     /**
235      * Returns the {@link String} {@code s} with an
236      * {@link Character#isLowerCase(char) lower case} first character. This
237      * function is null-safe.
238      *
239      * @param s
240      *            the string that should get an lower case first character. May
241      *            be <code>null</code>.
242      * @return the {@link String} {@code s} with an lower case first character
243      *         or <code>null</code> if the input {@link String} {@code s} was
244      *         <code>null</code>.
245      */
246     private static String toFirstLower(final String s) {
247         if (s == null || s.length() == 0) {
248             return s;
249         }
250         if (Character.isLowerCase(s.charAt(0))) {
251             return s;
252         }
253         if (s.length() == 1) {
254             return s.toLowerCase();
255         }
256         return s.substring(0, 1).toLowerCase() + s.substring(1);
257     }
258
259     /**
260      * Returns Java identifiers, conforming to JLS8 Section 3.8 to use for specified YANG assigned names
261      * (RFC7950 Section 9.6.4). This method considers two distinct encodings: one the pre-Fluorine mapping, which is
262      * okay and convenient for sane strings, and an escaping-based bijective mapping which works for all possible
263      * Unicode strings.
264      *
265      * @param assignedNames Collection of assigned names
266      * @return A BiMap keyed by assigned name, with Java identifiers as values
267      * @throws NullPointerException if assignedNames is null or contains null items
268      * @throws IllegalArgumentException if any of the names is empty
269      */
270     public static BiMap<String, String> mapEnumAssignedNames(final Collection<String> assignedNames) {
271         /*
272          * Original mapping assumed strings encountered are identifiers, hence it used getClassName to map the names
273          * and that function is not an injection -- this is evidenced in MDSAL-208 and results in a failure to compile
274          * generated code. If we encounter such a conflict or if the result is not a valid identifier (like '*'), we
275          * abort and switch the mapping schema to mapEnumAssignedName(), which is a bijection.
276          *
277          * Note that assignedNames can contain duplicates, which must not trigger a duplication fallback.
278          */
279         final BiMap<String, String> javaToYang = HashBiMap.create(assignedNames.size());
280         boolean valid = true;
281         for (String name : assignedNames) {
282             checkArgument(!name.isEmpty());
283             if (!javaToYang.containsValue(name)) {
284                 final String mappedName = getClassName(name);
285                 if (!isValidJavaIdentifier(mappedName) || javaToYang.forcePut(mappedName, name) != null) {
286                     valid = false;
287                     break;
288                 }
289             }
290         }
291
292         if (!valid) {
293             // Fall back to bijective mapping
294             javaToYang.clear();
295             for (String name : assignedNames) {
296                 javaToYang.put(mapEnumAssignedName(name), name);
297             }
298         }
299
300         return javaToYang.inverse();
301     }
302
303     // See https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.8
304     private static boolean isValidJavaIdentifier(final String str) {
305         return !str.isEmpty() && !JAVA_RESERVED_WORDS.contains(str)
306                 && Character.isJavaIdentifierStart(str.codePointAt(0))
307                 && str.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart);
308     }
309
310     private static String mapEnumAssignedName(final String assignedName) {
311         checkArgument(!assignedName.isEmpty());
312
313         // Mapping rules:
314         // - if the string is a valid java identifier and does not contain '$', use it as-is
315         if (assignedName.indexOf('$') == -1 && isValidJavaIdentifier(assignedName)) {
316             return assignedName;
317         }
318
319         // - otherwise prefix it with '$' and replace any invalid character (including '$') with '$XX$', where XX is
320         //   hex-encoded unicode codepoint (including plane, stripping leading zeroes)
321         final StringBuilder sb = new StringBuilder().append('$');
322         assignedName.codePoints().forEachOrdered(codePoint -> {
323             if (codePoint == '$' || !Character.isJavaIdentifierPart(codePoint)) {
324                 sb.append('$').append(Integer.toHexString(codePoint).toUpperCase(Locale.ROOT)).append('$');
325             } else {
326                 sb.appendCodePoint(codePoint);
327             }
328         });
329         return sb.toString();
330     }
331 }