563e58e36022d98990d07d5aa42da3c23f3aae32
[mdsal.git] / binding / mdsal-binding-generator-util / src / main / java / org / opendaylight / mdsal / binding / model / util / BindingGeneratorUtil.java
1 /*
2  * Copyright (c) 2014 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.model.util;
9
10 import com.google.common.base.CharMatcher;
11 import com.google.common.collect.Collections2;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableList.Builder;
14 import com.google.common.collect.Iterables;
15 import java.io.ByteArrayOutputStream;
16 import java.io.DataOutputStream;
17 import java.io.IOException;
18 import java.security.MessageDigest;
19 import java.security.NoSuchAlgorithmException;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.regex.Pattern;
28 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
29 import org.opendaylight.mdsal.binding.model.api.Restrictions;
30 import org.opendaylight.mdsal.binding.model.api.Type;
31 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
32 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
33 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
34 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
35 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
38 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
42 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
43 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
44 import org.opendaylight.yangtools.yang.model.api.type.RangeRestrictedTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
47 import org.opendaylight.yangtools.yang.model.util.type.DecimalTypeBuilder;
48
49 /**
50  * Contains the methods for converting strings to valid JAVA language strings
51  * (package names, class names, attribute names) and to valid javadoc comments.
52  */
53 public final class BindingGeneratorUtil {
54
55     /**
56      * Impossible to instantiate this class. All of the methods or attributes are static.
57      */
58     private BindingGeneratorUtil() {
59
60     }
61
62     /**
63      * Pre-compiled replacement pattern.
64      */
65     private static final CharMatcher DASH_COLON_MATCHER = CharMatcher.anyOf("-:");
66     private static final CharMatcher GT_MATCHER = CharMatcher.is('>');
67     private static final CharMatcher LT_MATCHER = CharMatcher.is('<');
68     private static final Pattern UNICODE_CHAR_PATTERN = Pattern.compile("\\\\+u");
69
70     private static final Restrictions EMPTY_RESTRICTIONS = new Restrictions() {
71         @Override
72         public Optional<LengthConstraint> getLengthConstraint() {
73             return Optional.empty();
74         }
75
76         @Override
77         public List<PatternConstraint> getPatternConstraints() {
78             return Collections.emptyList();
79         }
80
81         @Override
82         public Optional<RangeConstraint<?>> getRangeConstraint() {
83             return Optional.empty();
84         }
85
86         @Override
87         public boolean isEmpty() {
88             return true;
89         }
90     };
91
92     private static final Comparator<TypeMemberBuilder<?>> SUID_MEMBER_COMPARATOR =
93         Comparator.comparing(TypeMemberBuilder::getName);
94
95     private static final Comparator<Type> SUID_NAME_COMPARATOR = Comparator.comparing(Type::getFullyQualifiedName);
96
97     /**
98      * Converts <code>parameterName</code> to valid JAVA parameter name. If the <code>parameterName</code> is one
99      * of the JAVA reserved words then it is prefixed with underscore character.
100      *
101      * @param parameterName string with the parameter name
102      * @return string with the admissible parameter name
103      */
104     public static String resolveJavaReservedWordEquivalency(final String parameterName) {
105         if (parameterName != null && BindingMapping.JAVA_RESERVED_WORDS.contains(parameterName)) {
106             return "_" + parameterName;
107         }
108         return parameterName;
109     }
110
111     /**
112      * Creates package name from specified <code>basePackageName</code> (package name for module)
113      * and <code>schemaPath</code>. Resulting package name is concatenation of <code>basePackageName</code>
114      * and all local names of YANG nodes which are parents of some node for which <code>schemaPath</code> is specified.
115      *
116      * @param basePackageName string with package name of the module, MUST be normalized, otherwise this method may
117      *                        return an invalid string.
118      * @param schemaPath list of names of YANG nodes which are parents of some node + name of this node
119      * @return string with valid JAVA package name
120      * @throws NullPointerException if any of the arguments are null
121      */
122     public static String packageNameForGeneratedType(final String basePackageName, final SchemaPath schemaPath) {
123         final int size = Iterables.size(schemaPath.getPathTowardsRoot()) - 1;
124         if (size <= 0) {
125             return basePackageName;
126         }
127
128         return generateNormalizedPackageName(basePackageName, schemaPath.getPathFromRoot(), size);
129     }
130
131     /**
132      * Creates package name from specified <code>basePackageName</code> (package name for module)
133      * and <code>schemaPath</code> which crosses an augmentation. Resulting package name is concatenation
134      * of <code>basePackageName</code> and all local names of YANG nodes which are parents of some node for which
135      * <code>schemaPath</code> is specified.
136      *
137      * @param basePackageName string with package name of the module, MUST be normalized, otherwise this method may
138      *                        return an invalid string.
139      * @param schemaPath list of names of YANG nodes which are parents of some node + name of this node
140      * @return string with valid JAVA package name
141      * @throws NullPointerException if any of the arguments are null
142      */
143     public static String packageNameForAugmentedGeneratedType(final String basePackageName,
144             final SchemaPath schemaPath) {
145         final int size = Iterables.size(schemaPath.getPathTowardsRoot());
146         if (size == 0) {
147             return basePackageName;
148         }
149
150         return generateNormalizedPackageName(basePackageName, schemaPath.getPathFromRoot(), size);
151     }
152
153     private static String generateNormalizedPackageName(final String base, final Iterable<QName> path, final int size) {
154         final StringBuilder builder = new StringBuilder(base);
155         final Iterator<QName> iterator = path.iterator();
156         for (int i = 0; i < size; ++i) {
157             builder.append('.');
158             final String nodeLocalName = iterator.next().getLocalName();
159             // FIXME: Collon ":" is invalid in node local name as per RFC6020, identifier statement.
160             builder.append(DASH_COLON_MATCHER.replaceFrom(nodeLocalName, '.'));
161         }
162         return BindingMapping.normalizePackageName(builder.toString());
163     }
164
165     private static <T> Iterable<T> sortedCollection(final Comparator<? super T> comparator, final Collection<T> input) {
166         if (input.size() <= 1) {
167             return input;
168         }
169
170         final List<T> ret = new ArrayList<>(input);
171         ret.sort(comparator);
172         return ret;
173     }
174
175     private static final ThreadLocal<MessageDigest> SHA1_MD = ThreadLocal.withInitial(() -> {
176         try {
177             return MessageDigest.getInstance("SHA");
178         } catch (final NoSuchAlgorithmException e) {
179             throw new IllegalStateException("Failed to get a SHA digest provider", e);
180         }
181     });
182
183     public static long computeDefaultSUID(final GeneratedTypeBuilderBase<?> to) {
184         final ByteArrayOutputStream bout = new ByteArrayOutputStream();
185         try (DataOutputStream dout = new DataOutputStream(bout)) {
186             dout.writeUTF(to.getName());
187             dout.writeInt(to.isAbstract() ? 3 : 7);
188
189             for (final Type ifc : sortedCollection(SUID_NAME_COMPARATOR, filteredImplementsTypes(to))) {
190                 dout.writeUTF(ifc.getFullyQualifiedName());
191             }
192
193             for (final GeneratedPropertyBuilder gp : sortedCollection(SUID_MEMBER_COMPARATOR, to.getProperties())) {
194                 dout.writeUTF(gp.getName());
195             }
196
197             for (final MethodSignatureBuilder m : sortedCollection(SUID_MEMBER_COMPARATOR, to.getMethodDefinitions())) {
198                 if (!m.getAccessModifier().equals(AccessModifier.PRIVATE)) {
199                     dout.writeUTF(m.getName());
200                     dout.write(m.getAccessModifier().ordinal());
201                 }
202             }
203
204             dout.flush();
205         } catch (final IOException e) {
206             throw new IllegalStateException("Failed to hash object " + to, e);
207         }
208
209         final byte[] hashBytes = SHA1_MD.get().digest(bout.toByteArray());
210         long hash = 0;
211         for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
212             hash = hash << 8 | hashBytes[i] & 0xFF;
213         }
214         return hash;
215     }
216
217     private static Collection<Type> filteredImplementsTypes(final GeneratedTypeBuilderBase<?> to) {
218         return Collections2.filter(to.getImplementsTypes(), item -> !BindingTypes.TYPE_OBJECT.equals(item));
219     }
220
221     private static <T extends Optional<?>> T currentOrEmpty(final T current, final T base) {
222         return current.equals(base) ? (T)Optional.empty() : current;
223     }
224
225     private static boolean containsConstraint(final StringTypeDefinition type, final PatternConstraint constraint) {
226         for (StringTypeDefinition wlk = type; wlk != null; wlk = wlk.getBaseType()) {
227             if (wlk.getPatternConstraints().contains(constraint)) {
228                 return true;
229             }
230         }
231
232         return false;
233     }
234
235     private static List<PatternConstraint> uniquePatterns(final StringTypeDefinition type) {
236         final List<PatternConstraint> constraints = type.getPatternConstraints();
237         if (constraints.isEmpty()) {
238             return constraints;
239         }
240
241         final Builder<PatternConstraint> builder = ImmutableList.builder();
242         boolean filtered = false;
243         for (final PatternConstraint c : constraints) {
244             if (containsConstraint(type.getBaseType(), c)) {
245                 filtered = true;
246             } else {
247                 builder.add(c);
248             }
249         }
250
251         return filtered ? builder.build() : constraints;
252     }
253
254     public static Restrictions getRestrictions(final TypeDefinition<?> type) {
255         // Old parser generated types which actually contained based restrictions, but our code deals with that when
256         // binding to core Java types. Hence we'll emit empty restrictions for base types.
257         if (type == null || type.getBaseType() == null) {
258             // Handling of decimal64 has changed in the new parser. It contains range restrictions applied to the type
259             // directly, without an extended type. We need to capture such constraints. In order to retain behavior we
260             // need to analyze the new semantics and see if the constraints have been overridden. To do that we
261             // instantiate a temporary unconstrained type and compare them.
262             //
263             // FIXME: looking at the generated code it looks as though we need to pass the restrictions without
264             //        comparison
265             if (type instanceof DecimalTypeDefinition) {
266                 final DecimalTypeDefinition decimal = (DecimalTypeDefinition) type;
267                 final DecimalTypeBuilder tmpBuilder = BaseTypes.decimalTypeBuilder(decimal.getPath());
268                 tmpBuilder.setFractionDigits(decimal.getFractionDigits());
269                 final DecimalTypeDefinition tmp = tmpBuilder.build();
270
271                 if (!tmp.getRangeConstraint().equals(decimal.getRangeConstraint())) {
272                     return new Restrictions() {
273                         @Override
274                         public boolean isEmpty() {
275                             return false;
276                         }
277
278                         @Override
279                         public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
280                             return decimal.getRangeConstraint();
281                         }
282
283                         @Override
284                         public List<PatternConstraint> getPatternConstraints() {
285                             return ImmutableList.of();
286                         }
287
288                         @Override
289                         public Optional<LengthConstraint> getLengthConstraint() {
290                             return Optional.empty();
291                         }
292                     };
293                 }
294             }
295
296             return EMPTY_RESTRICTIONS;
297         }
298
299         final Optional<LengthConstraint> length;
300         final List<PatternConstraint> pattern;
301         final Optional<? extends RangeConstraint<?>> range;
302
303         /*
304          * Take care of extended types.
305          *
306          * Other types which support constraints are check afterwards. There is a slight twist with them, as returned
307          * constraints are the effective view, e.g. they are inherited from base type. Since the constraint is already
308          * enforced by the base type, we want to skip them and not perform duplicate checks.
309          *
310          * We end up emitting ConcreteType instances for YANG base types, which leads to their constraints not being
311          * enforced (most notably decimal64). Therefore we need to make sure we do not strip the next-to-last
312          * restrictions.
313          *
314          * FIXME: this probably not the best solution and needs further analysis.
315          */
316         if (type instanceof BinaryTypeDefinition) {
317             final BinaryTypeDefinition binary = (BinaryTypeDefinition)type;
318             final BinaryTypeDefinition base = binary.getBaseType();
319             if (base != null && base.getBaseType() != null) {
320                 length = currentOrEmpty(binary.getLengthConstraint(), base.getLengthConstraint());
321             } else {
322                 length = binary.getLengthConstraint();
323             }
324
325             pattern = ImmutableList.of();
326             range = Optional.empty();
327         } else if (type instanceof DecimalTypeDefinition) {
328             length = Optional.empty();
329             pattern = ImmutableList.of();
330
331             final DecimalTypeDefinition decimal = (DecimalTypeDefinition)type;
332             final DecimalTypeDefinition base = decimal.getBaseType();
333             if (base != null && base.getBaseType() != null) {
334                 range = currentOrEmpty(decimal.getRangeConstraint(), base.getRangeConstraint());
335             } else {
336                 range = decimal.getRangeConstraint();
337             }
338         } else if (type instanceof RangeRestrictedTypeDefinition) {
339             // Integer-like types
340             length = Optional.empty();
341             pattern = ImmutableList.of();
342             range = extractRangeConstraint((RangeRestrictedTypeDefinition<?, ?>)type);
343         } else if (type instanceof StringTypeDefinition) {
344             final StringTypeDefinition string = (StringTypeDefinition)type;
345             final StringTypeDefinition base = string.getBaseType();
346             if (base != null && base.getBaseType() != null) {
347                 length = currentOrEmpty(string.getLengthConstraint(), base.getLengthConstraint());
348             } else {
349                 length = string.getLengthConstraint();
350             }
351
352             pattern = uniquePatterns(string);
353             range = Optional.empty();
354         } else {
355             length = Optional.empty();
356             pattern = ImmutableList.of();
357             range = Optional.empty();
358         }
359
360         // Now, this may have ended up being empty, too...
361         if (!length.isPresent() && pattern.isEmpty() && !range.isPresent()) {
362             return EMPTY_RESTRICTIONS;
363         }
364
365         // Nope, not empty allocate a holder
366         return new Restrictions() {
367             @Override
368             public Optional<? extends RangeConstraint<?>> getRangeConstraint() {
369                 return range;
370             }
371
372             @Override
373             public List<PatternConstraint> getPatternConstraints() {
374                 return pattern;
375             }
376
377             @Override
378             public Optional<LengthConstraint> getLengthConstraint() {
379                 return length;
380             }
381
382             @Override
383             public boolean isEmpty() {
384                 return false;
385             }
386         };
387     }
388
389     private static <T extends RangeRestrictedTypeDefinition<?, ?>> Optional<? extends RangeConstraint<?>>
390             extractRangeConstraint(final T def) {
391         final T base = (T) def.getBaseType();
392         if (base != null && base.getBaseType() != null) {
393             return currentOrEmpty(def.getRangeConstraint(), base.getRangeConstraint());
394         }
395
396         return def.getRangeConstraint();
397     }
398
399     /**
400      * Encodes angle brackets in yang statement description.
401      *
402      * @param description description of a yang statement which is used to generate javadoc comments
403      * @return string with encoded angle brackets
404      */
405     public static String encodeAngleBrackets(String description) {
406         if (description != null) {
407             description = LT_MATCHER.replaceFrom(description, "&lt;");
408             description = GT_MATCHER.replaceFrom(description, "&gt;");
409         }
410         return description;
411     }
412
413     public static String replaceAllIllegalChars(final CharSequence stringBuilder) {
414         final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
415         return ret.isEmpty() ? "" : ret;
416     }
417 }