Improve QNAME field definition
[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.util.Collection;
20 import java.util.Locale;
21 import java.util.Optional;
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 import org.opendaylight.yangtools.yang.common.Revision;
28
29 public final class BindingMapping {
30
31     public static final String VERSION = "0.6";
32
33     public static final Set<String> JAVA_RESERVED_WORDS = ImmutableSet.of(
34         // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.9
35         "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue",
36         "default", "do", "double", "else", "enum", "extends", "final", "finally", "float", "for", "goto", "if",
37         "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "package", "private",
38         "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this",
39         "throw", "throws", "transient", "try", "void", "volatile", "while", "_",
40         // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.3
41         "false", "true",
42         // https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.10.7
43         "null");
44
45     public static final String DATA_ROOT_SUFFIX = "Data";
46     public static final String RPC_SERVICE_SUFFIX = "Service";
47     public static final String NOTIFICATION_LISTENER_SUFFIX = "Listener";
48     public static final String QNAME_STATIC_FIELD_NAME = "QNAME";
49     public static final String PACKAGE_PREFIX = "org.opendaylight.yang.gen.v1";
50     public static final String AUGMENTATION_FIELD = "augmentation";
51
52     private static final Splitter CAMEL_SPLITTER = Splitter.on(CharMatcher.anyOf(" _.-/").precomputed())
53             .omitEmptyStrings().trimResults();
54     private static final Pattern COLON_SLASH_SLASH = Pattern.compile("://", Pattern.LITERAL);
55     private static final String QUOTED_DOT = Matcher.quoteReplacement(".");
56     private static final Splitter DOT_SPLITTER = Splitter.on('.');
57
58     public static final String MODULE_INFO_CLASS_NAME = "$YangModuleInfoImpl";
59     public static final String MODULE_INFO_QNAMEOF_METHOD_NAME = "qnameOf";
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 String NEGATED_PATTERN_PREFIX = "^(?!";
66     private static final String NEGATED_PATTERN_SUFFIX = ").*$";
67
68     private static final Interner<String> PACKAGE_INTERNER = Interners.newWeakInterner();
69
70     private BindingMapping() {
71         throw new UnsupportedOperationException("Utility class should not be instantiated");
72     }
73
74     public static String getRootPackageName(final QName module) {
75         return getRootPackageName(module.getModule());
76     }
77
78     public static String getRootPackageName(final QNameModule module) {
79         checkArgument(module != null, "Module must not be null");
80         checkArgument(module.getRevision() != null, "Revision must not be null");
81         checkArgument(module.getNamespace() != null, "Namespace must not be null");
82         final StringBuilder packageNameBuilder = new StringBuilder();
83
84         packageNameBuilder.append(BindingMapping.PACKAGE_PREFIX);
85         packageNameBuilder.append('.');
86
87         String namespace = module.getNamespace().toString();
88         namespace = COLON_SLASH_SLASH.matcher(namespace).replaceAll(QUOTED_DOT);
89
90         final char[] chars = namespace.toCharArray();
91         for (int i = 0; i < chars.length; ++i) {
92             switch (chars[i]) {
93                 case '/':
94                 case ':':
95                 case '-':
96                 case '@':
97                 case '$':
98                 case '#':
99                 case '\'':
100                 case '*':
101                 case '+':
102                 case ',':
103                 case ';':
104                 case '=':
105                     chars[i] = '.';
106                     break;
107                 default:
108                     // no-op
109             }
110         }
111
112         packageNameBuilder.append(chars);
113         if (chars[chars.length - 1] != '.') {
114             packageNameBuilder.append('.');
115         }
116
117         final Optional<Revision> optRev = module.getRevision();
118         if (optRev.isPresent()) {
119             // Revision is in format 2017-10-26, we want the output to be 171026, which is a matter of picking the
120             // right characters.
121             final String rev = optRev.get().toString();
122             checkArgument(rev.length() == 10, "Unsupported revision %s", rev);
123             packageNameBuilder.append("rev");
124             packageNameBuilder.append(rev.substring(2, 4)).append(rev.substring(5, 7)).append(rev.substring(8));
125         } else {
126             // No-revision packages are special
127             packageNameBuilder.append("norev");
128         }
129
130         return normalizePackageName(packageNameBuilder.toString());
131     }
132
133     public static String normalizePackageName(final String packageName) {
134         if (packageName == null) {
135             return null;
136         }
137
138         final StringBuilder builder = new StringBuilder();
139         boolean first = true;
140
141         for (String p : DOT_SPLITTER.split(packageName.toLowerCase())) {
142             if (first) {
143                 first = false;
144             } else {
145                 builder.append('.');
146             }
147
148             if (Character.isDigit(p.charAt(0)) || BindingMapping.JAVA_RESERVED_WORDS.contains(p)) {
149                 builder.append('_');
150             }
151             builder.append(p);
152         }
153
154         // Prevent duplication of input string
155         return PACKAGE_INTERNER.intern(builder.toString());
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 getClassName(final QName name) {
164         checkArgument(name != null, "Name should not be null.");
165         return toFirstUpper(toCamelCase(name.getLocalName()));
166     }
167
168     public static String getMethodName(final String yangIdentifier) {
169         checkArgument(yangIdentifier != null,"Identifier should not be null");
170         return toFirstLower(toCamelCase(yangIdentifier));
171     }
172
173     public static String getMethodName(final QName name) {
174         checkArgument(name != null, "Name should not be null.");
175         return getMethodName(name.getLocalName());
176     }
177
178     public static String getGetterSuffix(final QName name) {
179         checkArgument(name != null, "Name should not be null.");
180         final String candidate = toFirstUpper(toCamelCase(name.getLocalName()));
181         return "Class".equals(candidate) ? "XmlClass" : candidate;
182     }
183
184     public static String getPropertyName(final String yangIdentifier) {
185         final String potential = toFirstLower(toCamelCase(yangIdentifier));
186         if ("class".equals(potential)) {
187             return "xmlClass";
188         }
189         return potential;
190     }
191
192     private static String toCamelCase(final String rawString) {
193         checkArgument(rawString != null, "String should not be null");
194         Iterable<String> components = CAMEL_SPLITTER.split(rawString);
195         StringBuilder builder = new StringBuilder();
196         for (String comp : components) {
197             builder.append(toFirstUpper(comp));
198         }
199         return checkNumericPrefix(builder.toString());
200     }
201
202     private static String checkNumericPrefix(final String rawString) {
203         if (rawString == null || rawString.isEmpty()) {
204             return rawString;
205         }
206         char firstChar = rawString.charAt(0);
207         if (firstChar >= '0' && firstChar <= '9') {
208             return "_" + rawString;
209         } else {
210             return rawString;
211         }
212     }
213
214     /**
215      * Create a {@link Pattern} expression which performs inverted match to the specified pattern. The input pattern
216      * is expected to be a valid regular expression passing {@link Pattern#compile(String)} and to have both start and
217      * end of string anchors as the first and last characters.
218      *
219      * @param pattern Pattern regular expression to negate
220      * @return Negated regular expression
221      * @throws IllegalArgumentException if the pattern does not conform to expected structure
222      * @throws NullPointerException if pattern is null
223      */
224     public static String negatePatternString(final String pattern) {
225         checkArgument(pattern.charAt(0) == '^' && pattern.charAt(pattern.length() - 1) == '$',
226                 "Pattern '%s' does not have expected format", pattern);
227
228         /*
229          * Converting the expression into a negation is tricky. For example, when we have:
230          *
231          *   pattern "a|b" { modifier invert-match; }
232          *
233          * this gets escaped into either "^a|b$" or "^(?:a|b)$". Either format can occur, as the non-capturing group
234          * strictly needed only in some cases. From that we want to arrive at:
235          *   "^(?!(?:a|b)$).*$".
236          *
237          *           ^^^         original expression
238          *        ^^^^^^^^       tail of a grouped expression (without head anchor)
239          *    ^^^^        ^^^^   inversion of match
240          *
241          * Inversion works by explicitly anchoring at the start of the string and then:
242          * - specifying a negative lookahead until the end of string
243          * - matching any string
244          * - anchoring at the end of the string
245          */
246         final boolean hasGroup = pattern.startsWith("^(?:") && pattern.endsWith(")$");
247         final int len = pattern.length();
248         final StringBuilder sb = new StringBuilder(len + (hasGroup ? 7 : 11)).append(NEGATED_PATTERN_PREFIX);
249
250         if (hasGroup) {
251             sb.append(pattern, 1, len);
252         } else {
253             sb.append("(?:").append(pattern, 1, len - 1).append(")$");
254         }
255         return sb.append(NEGATED_PATTERN_SUFFIX).toString();
256     }
257
258     /**
259      * Check if the specified {@link Pattern} is the result of {@link #negatePatternString(String)}. This method
260      * assumes the pattern was not hand-coded but rather was automatically-generated, such that its non-automated
261      * parts come from XSD regular expressions. If this constraint is violated, this method may result false positives.
262      *
263      * @param pattern Pattern to check
264      * @return True if this pattern is a negation.
265      * @throws NullPointerException if pattern is null
266      * @throws IllegalArgumentException if the pattern does not conform to expected structure
267      */
268     public static boolean isNegatedPattern(final Pattern pattern) {
269         return isNegatedPattern(pattern.toString());
270     }
271
272     private static boolean isNegatedPattern(final String pattern) {
273         return pattern.startsWith(NEGATED_PATTERN_PREFIX) && pattern.endsWith(NEGATED_PATTERN_SUFFIX);
274     }
275
276     /**
277      * Returns the {@link String} {@code s} with an {@link Character#isUpperCase(char) upper case} first character. This
278      * function is null-safe.
279      *
280      * @param str the string that should get an upper case first character. May be <code>null</code>.
281      * @return the {@link String} {@code str} with an upper case first character or <code>null</code> if the input
282      *         {@link String} {@code str} was <code>null</code>.
283      */
284     public static String toFirstUpper(final String str) {
285         if (str == null || str.length() == 0) {
286             return str;
287         }
288         if (Character.isUpperCase(str.charAt(0))) {
289             return str;
290         }
291         if (str.length() == 1) {
292             return str.toUpperCase();
293         }
294         return str.substring(0, 1).toUpperCase() + str.substring(1);
295     }
296
297     /**
298      * Returns the {@link String} {@code s} with a {@link Character#isLowerCase(char) lower case} first character. This
299      * function is null-safe.
300      *
301      * @param str the string that should get an lower case first character. May be <code>null</code>.
302      * @return the {@link String} {@code str} with an lower case first character or <code>null</code> if the input
303      *         {@link String} {@code str} was <code>null</code>.
304      */
305     private static String toFirstLower(final String str) {
306         if (str == null || str.length() == 0) {
307             return str;
308         }
309         if (Character.isLowerCase(str.charAt(0))) {
310             return str;
311         }
312         if (str.length() == 1) {
313             return str.toLowerCase();
314         }
315         return str.substring(0, 1).toLowerCase() + str.substring(1);
316     }
317
318     /**
319      * Returns Java identifiers, conforming to JLS9 Section 3.8 to use for specified YANG assigned names
320      * (RFC7950 Section 9.6.4). This method considers two distinct encodings: one the pre-Fluorine mapping, which is
321      * okay and convenient for sane strings, and an escaping-based bijective mapping which works for all possible
322      * Unicode strings.
323      *
324      * @param assignedNames Collection of assigned names
325      * @return A BiMap keyed by assigned name, with Java identifiers as values
326      * @throws NullPointerException if assignedNames is null or contains null items
327      * @throws IllegalArgumentException if any of the names is empty
328      */
329     public static BiMap<String, String> mapEnumAssignedNames(final Collection<String> assignedNames) {
330         /*
331          * Original mapping assumed strings encountered are identifiers, hence it used getClassName to map the names
332          * and that function is not an injection -- this is evidenced in MDSAL-208 and results in a failure to compile
333          * generated code. If we encounter such a conflict or if the result is not a valid identifier (like '*'), we
334          * abort and switch the mapping schema to mapEnumAssignedName(), which is a bijection.
335          *
336          * Note that assignedNames can contain duplicates, which must not trigger a duplication fallback.
337          */
338         final BiMap<String, String> javaToYang = HashBiMap.create(assignedNames.size());
339         boolean valid = true;
340         for (String name : assignedNames) {
341             checkArgument(!name.isEmpty());
342             if (!javaToYang.containsValue(name)) {
343                 final String mappedName = getClassName(name);
344                 if (!isValidJavaIdentifier(mappedName) || javaToYang.forcePut(mappedName, name) != null) {
345                     valid = false;
346                     break;
347                 }
348             }
349         }
350
351         if (!valid) {
352             // Fall back to bijective mapping
353             javaToYang.clear();
354             for (String name : assignedNames) {
355                 javaToYang.put(mapEnumAssignedName(name), name);
356             }
357         }
358
359         return javaToYang.inverse();
360     }
361
362     // See https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-3.8
363     private static boolean isValidJavaIdentifier(final String str) {
364         return !str.isEmpty() && !JAVA_RESERVED_WORDS.contains(str)
365                 && Character.isJavaIdentifierStart(str.codePointAt(0))
366                 && str.codePoints().skip(1).allMatch(Character::isJavaIdentifierPart);
367     }
368
369     private static String mapEnumAssignedName(final String assignedName) {
370         checkArgument(!assignedName.isEmpty());
371
372         // Mapping rules:
373         // - if the string is a valid java identifier and does not contain '$', use it as-is
374         if (assignedName.indexOf('$') == -1 && isValidJavaIdentifier(assignedName)) {
375             return assignedName;
376         }
377
378         // - otherwise prefix it with '$' and replace any invalid character (including '$') with '$XX$', where XX is
379         //   hex-encoded unicode codepoint (including plane, stripping leading zeroes)
380         final StringBuilder sb = new StringBuilder().append('$');
381         assignedName.codePoints().forEachOrdered(codePoint -> {
382             if (codePoint == '$' || !Character.isJavaIdentifierPart(codePoint)) {
383                 sb.append('$').append(Integer.toHexString(codePoint).toUpperCase(Locale.ROOT)).append('$');
384             } else {
385                 sb.appendCodePoint(codePoint);
386             }
387         });
388         return sb.toString();
389     }
390 }