Do not generate union builders
[mdsal.git] / binding / mdsal-binding-generator / src / main / java / org / opendaylight / mdsal / binding / generator / impl / reactor / AbstractTypeObjectGenerator.java
1 /*
2  * Copyright (c) 2021 PANTHEON.tech, s.r.o. 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.generator.impl.reactor;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.Maps;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Optional;
21 import java.util.stream.Collectors;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil;
25 import org.opendaylight.mdsal.binding.generator.impl.reactor.TypeReference.ResolvedLeafref;
26 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
27 import org.opendaylight.mdsal.binding.model.api.Enumeration;
28 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
29 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
30 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
31 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
32 import org.opendaylight.mdsal.binding.model.api.Restrictions;
33 import org.opendaylight.mdsal.binding.model.api.Type;
34 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
35 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
36 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
37 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
38 import org.opendaylight.mdsal.binding.model.ri.BaseYangTypes;
39 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
40 import org.opendaylight.mdsal.binding.model.ri.TypeConstants;
41 import org.opendaylight.mdsal.binding.model.ri.Types;
42 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.AbstractEnumerationBuilder;
43 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.GeneratedPropertyBuilderImpl;
44 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
45 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
46 import org.opendaylight.yangtools.concepts.Immutable;
47 import org.opendaylight.yangtools.yang.binding.RegexPatterns;
48 import org.opendaylight.yangtools.yang.binding.TypeObject;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.YangConstants;
51 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
53 import org.opendaylight.yangtools.yang.model.api.stmt.BaseEffectiveStatement;
54 import org.opendaylight.yangtools.yang.model.api.stmt.LengthEffectiveStatement;
55 import org.opendaylight.yangtools.yang.model.api.stmt.PathEffectiveStatement;
56 import org.opendaylight.yangtools.yang.model.api.stmt.PatternEffectiveStatement;
57 import org.opendaylight.yangtools.yang.model.api.stmt.PatternExpression;
58 import org.opendaylight.yangtools.yang.model.api.stmt.RangeEffectiveStatement;
59 import org.opendaylight.yangtools.yang.model.api.stmt.TypeEffectiveStatement;
60 import org.opendaylight.yangtools.yang.model.api.stmt.ValueRange;
61 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
63 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.ModifierKind;
65 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
66 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.TypeDefinitions;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 /**
72  * Common base class for {@link TypedefGenerator} and {@link AbstractTypeAwareGenerator}. This encompasses three
73  * different statements with two different semantics:
74  * <ul>
75  *   <li>{@link TypedefGenerator}s always result in a generated {@link TypeObject}, even if the semantics is exactly
76  *       the same as its base type. This aligns with {@code typedef} defining a new type.<li>
77  *   <li>{@link LeafGenerator}s and {@link LeafListGenerator}s, on the other hand, do not generate a {@link TypeObject}
78  *       unless absolutely necassary. This aligns with {@code leaf} and {@code leaf-list} being mapped onto a property
79  *       of its parent type.<li>
80  * </ul>
81  *
82  * <p>
83  * To throw a bit of confusion into the mix, there are three exceptions to those rules:
84  * <ul>
85  *   <li>
86  *     {@code identityref} definitions never result in a type definition being emitted. The reason for this has to do
87  *     with identity type mapping as well as history of our codebase.
88  *
89  *     <p>
90  *     The problem at hand is inconsistency between the fact that identity is mapped to a {@link Class}, which is also
91  *     returned from leaves which specify it like this:
92  *     <pre>
93  *       <code>
94  *         identity iden;
95  *
96  *         container foo {
97  *           leaf foo {
98  *             type identityref {
99  *               base iden;
100  *             }
101  *           }
102  *         }
103  *       </code>
104  *     </pre>
105  *     which results in fine-looking
106  *     <pre>
107  *       <code>
108  *         interface Foo {
109  *           Class&lt;? extends Iden&gt; getFoo();
110  *         }
111  *       </code>
112  *     </pre>
113  *
114  *     <p>
115  *     This gets more dicey if we decide to extend the previous snippet to also include:
116  *     <pre>
117  *       <code>
118  *         typedef bar-ref {
119  *           type identityref {
120  *             base iden;
121  *           }
122  *         }
123  *
124  *         container bar {
125  *           leaf bar {
126  *             type bar-ref;
127  *           }
128  *         }
129  *       </code>
130  *     </pre>
131  *
132  *     <p>
133  *     Now we have competing requirements: {@code typedef} would like us to use encapsulation to capture the defined
134  *     type, while {@code getBar()} wants us to retain shape with getFoo(), as it should not matter how the
135  *     {@code identityref} was formed. We need to pick between:
136  *     <ol>
137  *       <li>
138  *         <pre>
139  *           <code>
140  *             public class BarRef extends ScalarTypeObject&lt;Class&lt;? extends Iden&gt;&gt; {
141  *               Class&lt;? extends Iden&gt; getValue() {
142  *                 // ...
143  *               }
144  *             }
145  *
146  *             interface Bar {
147  *               BarRef getBar();
148  *             }
149  *           </code>
150  *         </pre>
151  *       </li>
152  *       <li>
153  *         <pre>
154  *           <code>
155  *             interface Bar {
156  *               Class&lt;? extends Iden&gt; getBar();
157  *             }
158  *           </code>
159  *         </pre>
160  *       </li>
161  *     </ol>
162  *
163  *     <p>
164  *     Here the second option is more user-friendly, as the type system works along the lines of <b>reference</b>
165  *     semantics, treating and {@code Bar.getBar()} and {@code Foo.getFoo()} as equivalent. The first option would
166  *     force users to go through explicit encapsulation, for no added benefit as the {@code typedef} cannot possibly add
167  *     anything useful to the actual type semantics.
168  *   </li>
169  *   <li>
170  *     {@code leafref} definitions never result in a type definition being emitted. The reasons for this are similar to
171  *     {@code identityref}, but have an additional twist: a {@leafref} can target a relative path, which may only be
172  *     resolved at a particular instantiation.
173  *
174  *     Take the example of the following model:
175  *     <pre>
176  *       <code>
177  *         grouping grp {
178  *           typedef ref {
179  *             type leafref {
180  *               path ../xyzzy;
181  *             }
182  *           }
183  *
184  *           leaf foo {
185  *             type ref;
186  *           }
187  *         }
188  *
189  *         container bar {
190              uses grp;
191  *
192  *           leaf xyzzy {
193  *             type string;
194  *           }
195  *         }
196  *
197  *         container baz {
198  *           uses grp;
199  *
200  *           leaf xyzzy {
201  *             type int32;
202  *           }
203  *         }
204  *       </code>
205  *     </pre>
206  *
207  *     The {@code typedef ref} points to outside of the grouping, and hence the type of {@code leaf foo} is polymorphic:
208  *     the definition in {@code grouping grp} needs to use {@code Object}, whereas the instantiations in
209  *     {@code container bar} and {@code container baz} need to use {@code String} and {@link Integer} respectively.
210  *     Expressing the resulting interface contracts requires return type specialization and run-time checks. An
211  *     intermediate class generated for the typedef would end up being a hindrance without any benefit.
212  *   <li>
213  *   <li>
214  *     {@code enumeration} definitions never result in a derived type. This is because these are mapped to Java
215  *     {@code enum}, which does not allow subclassing.
216  *   <li>
217  * </ul>
218  *
219  * <p>
220  * At the end of the day, the mechanic translation rules are giving way to correctly mapping the semantics -- which in
221  * both of the exception cases boil down to tracking type indirection. Intermediate constructs involved in tracking
222  * type indirection in YANG constructs is therefore explicitly excluded from the generated Java code, but the Binding
223  * Specification still takes them into account when determining types as outlined above.
224  */
225 abstract class AbstractTypeObjectGenerator<S extends EffectiveStatement<?, ?>, R extends RuntimeType>
226         extends AbstractDependentGenerator<S, R> {
227     private static final class UnionDependencies implements Immutable {
228         private final Map<EffectiveStatement<?, ?>, TypeReference> identityTypes = new HashMap<>();
229         private final Map<EffectiveStatement<?, ?>, TypeReference> leafTypes = new HashMap<>();
230         private final Map<QName, TypedefGenerator> baseTypes = new HashMap<>();
231
232         UnionDependencies(final TypeEffectiveStatement<?> type, final GeneratorContext context) {
233             resolveUnionDependencies(context, type);
234         }
235
236         private void resolveUnionDependencies(final GeneratorContext context, final TypeEffectiveStatement<?> union) {
237             for (EffectiveStatement<?, ?> stmt : union.effectiveSubstatements()) {
238                 if (stmt instanceof TypeEffectiveStatement) {
239                     final TypeEffectiveStatement<?> type = (TypeEffectiveStatement<?>) stmt;
240                     final QName typeName = type.argument();
241                     if (TypeDefinitions.IDENTITYREF.equals(typeName)) {
242                         if (!identityTypes.containsKey(stmt)) {
243                             identityTypes.put(stmt, TypeReference.identityRef(
244                                 type.streamEffectiveSubstatements(BaseEffectiveStatement.class)
245                                     .map(BaseEffectiveStatement::argument)
246                                     .map(context::resolveIdentity)
247                                     .collect(Collectors.toUnmodifiableList())));
248                         }
249                     } else if (TypeDefinitions.LEAFREF.equals(typeName)) {
250                         if (!leafTypes.containsKey(stmt)) {
251                             leafTypes.put(stmt, TypeReference.leafRef(context.resolveLeafref(
252                                 type.findFirstEffectiveSubstatementArgument(PathEffectiveStatement.class)
253                                 .orElseThrow())));
254                         }
255                     } else if (TypeDefinitions.UNION.equals(typeName)) {
256                         resolveUnionDependencies(context, type);
257                     } else if (!isBuiltinName(typeName) && !baseTypes.containsKey(typeName)) {
258                         baseTypes.put(typeName, context.resolveTypedef(typeName));
259                     }
260                 }
261             }
262         }
263     }
264
265     private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeObjectGenerator.class);
266     static final ImmutableMap<QName, Type> SIMPLE_TYPES = ImmutableMap.<QName, Type>builder()
267         .put(TypeDefinitions.BINARY, BaseYangTypes.BINARY_TYPE)
268         .put(TypeDefinitions.BOOLEAN, BaseYangTypes.BOOLEAN_TYPE)
269         .put(TypeDefinitions.DECIMAL64, BaseYangTypes.DECIMAL64_TYPE)
270         .put(TypeDefinitions.EMPTY, BaseYangTypes.EMPTY_TYPE)
271         .put(TypeDefinitions.INSTANCE_IDENTIFIER, BaseYangTypes.INSTANCE_IDENTIFIER)
272         .put(TypeDefinitions.INT8, BaseYangTypes.INT8_TYPE)
273         .put(TypeDefinitions.INT16, BaseYangTypes.INT16_TYPE)
274         .put(TypeDefinitions.INT32, BaseYangTypes.INT32_TYPE)
275         .put(TypeDefinitions.INT64, BaseYangTypes.INT64_TYPE)
276         .put(TypeDefinitions.STRING, BaseYangTypes.STRING_TYPE)
277         .put(TypeDefinitions.UINT8, BaseYangTypes.UINT8_TYPE)
278         .put(TypeDefinitions.UINT16, BaseYangTypes.UINT16_TYPE)
279         .put(TypeDefinitions.UINT32, BaseYangTypes.UINT32_TYPE)
280         .put(TypeDefinitions.UINT64, BaseYangTypes.UINT64_TYPE)
281         .build();
282
283     private final TypeEffectiveStatement<?> type;
284
285     // FIXME: these fields should be better-controlled with explicit sequencing guards. It it currently stands, we are
286     //        expending two (or more) additional fields to express downstream linking. If we had the concept of
287     //        resolution step (an enum), we could just get by with a simple queue of Step/Callback pairs, which would
288     //        trigger as needed. See how we manage baseGen/inferred fields.
289
290     /**
291      * The generator corresponding to our YANG base type. It produces the superclass of our encapsulated type. If it is
292      * {@code null}, this generator is the root of the hierarchy.
293      */
294     private TypedefGenerator baseGen;
295     private TypeReference refType;
296     private List<GeneratedType> auxiliaryGeneratedTypes = List.of();
297     private UnionDependencies unionDependencies;
298     private List<AbstractTypeObjectGenerator<?, ?>> inferred = List.of();
299
300     /**
301      * The type of single-element return type of the getter method associated with this generator. This is retained for
302      * run-time type purposes. It may be uninitialized, in which case this object must have a generated type.
303      */
304     private Type methodReturnTypeElement;
305
306     AbstractTypeObjectGenerator(final S statement, final AbstractCompositeGenerator<?, ?> parent) {
307         super(statement, parent);
308         type = statement().findFirstEffectiveSubstatement(TypeEffectiveStatement.class).orElseThrow();
309     }
310
311     @Override
312     public final List<GeneratedType> auxiliaryGeneratedTypes() {
313         return auxiliaryGeneratedTypes;
314     }
315
316     @Override
317     final void linkDependencies(final GeneratorContext context) {
318         verify(inferred != null, "Duplicate linking of %s", this);
319
320         final QName typeName = type.argument();
321         if (isBuiltinName(typeName)) {
322             verify(inferred.isEmpty(), "Unexpected non-empty downstreams in %s", this);
323             inferred = null;
324             return;
325         }
326
327         final AbstractExplicitGenerator<S, R> prev = previous();
328         if (prev != null) {
329             verify(prev instanceof AbstractTypeObjectGenerator, "Unexpected previous %s", prev);
330             ((AbstractTypeObjectGenerator<S, R>) prev).linkInferred(this);
331         } else {
332             linkBaseGen(context.resolveTypedef(typeName));
333         }
334     }
335
336     private void linkInferred(final AbstractTypeObjectGenerator<?, ?> downstream) {
337         if (inferred == null) {
338             downstream.linkBaseGen(verifyNotNull(baseGen, "Mismatch on linking between %s and %s", this, downstream));
339             return;
340         }
341
342         if (inferred.isEmpty()) {
343             inferred = new ArrayList<>(2);
344         }
345         inferred.add(downstream);
346     }
347
348     private void linkBaseGen(final TypedefGenerator upstreamBaseGen) {
349         verify(baseGen == null, "Attempted to replace base %s with %s in %s", baseGen, upstreamBaseGen, this);
350         final List<AbstractTypeObjectGenerator<?, ?>> downstreams = verifyNotNull(inferred,
351             "Duplicated linking of %s", this);
352         baseGen = verifyNotNull(upstreamBaseGen);
353         baseGen.addDerivedGenerator(this);
354         inferred = null;
355
356         for (AbstractTypeObjectGenerator<?, ?> downstream : downstreams) {
357             downstream.linkBaseGen(upstreamBaseGen);
358         }
359     }
360
361     void bindTypeDefinition(final GeneratorContext context) {
362         if (baseGen != null) {
363             // We have registered with baseGen, it will push the type to us
364             return;
365         }
366
367         final QName arg = type.argument();
368         if (TypeDefinitions.IDENTITYREF.equals(arg)) {
369             refType = TypeReference.identityRef(type.streamEffectiveSubstatements(BaseEffectiveStatement.class)
370                 .map(BaseEffectiveStatement::argument)
371                 .map(context::resolveIdentity)
372                 .collect(Collectors.toUnmodifiableList()));
373         } else if (TypeDefinitions.LEAFREF.equals(arg)) {
374             final AbstractTypeObjectGenerator<?, ?> targetGenerator = context.resolveLeafref(
375                 type.findFirstEffectiveSubstatementArgument(PathEffectiveStatement.class).orElseThrow());
376             checkArgument(targetGenerator != this, "Effective model contains self-referencing leaf %s",
377                 statement().argument());
378             refType = TypeReference.leafRef(targetGenerator);
379         } else if (TypeDefinitions.UNION.equals(arg)) {
380             unionDependencies = new UnionDependencies(type, context);
381             LOG.trace("Resolved union {} to dependencies {}", type, unionDependencies);
382         }
383
384         LOG.trace("Resolved base {} to generator {}", type, refType);
385         bindDerivedGenerators(refType);
386     }
387
388     final void bindTypeDefinition(final @Nullable TypeReference reference) {
389         refType = reference;
390         LOG.trace("Resolved derived {} to generator {}", type, refType);
391     }
392
393     private static boolean isBuiltinName(final QName typeName) {
394         return YangConstants.RFC6020_YANG_MODULE.equals(typeName.getModule());
395     }
396
397     abstract void bindDerivedGenerators(@Nullable TypeReference reference);
398
399     @Override
400     final ClassPlacement classPlacement() {
401         if (refType != null) {
402             // Reference types never create a new type
403             return ClassPlacement.NONE;
404         }
405         if (isDerivedEnumeration()) {
406             // Types derived from an enumeration never create a new type, as that would have to be a subclass of an enum
407             // and since enums are final, that can never happen.
408             return ClassPlacement.NONE;
409         }
410         return classPlacementImpl();
411     }
412
413     @NonNull ClassPlacement classPlacementImpl() {
414         // TODO: make this a lot more accurate by comparing the effective delta between the base type and the effective
415         //       restricted type. We should not be generating a type for constructs like:
416         //
417         //         leaf foo {
418         //           type uint8 { range 0..255; }
419         //         }
420         //
421         //       or
422         //
423         //         typedef foo {
424         //           type uint8 { range 0..100; }
425         //         }
426         //
427         //         leaf foo {
428         //           type foo { range 0..100; }
429         //         }
430         //
431         //       Which is relatively easy to do for integral types, but is way more problematic for 'pattern'
432         //       restrictions. Nevertheless we can define the mapping in a way which can be implemented with relative
433         //       ease.
434         return baseGen != null || SIMPLE_TYPES.containsKey(type.argument()) || isAddedByUses() || isAugmenting()
435             ? ClassPlacement.NONE : ClassPlacement.MEMBER;
436     }
437
438     @Override
439     final GeneratedType getGeneratedType(final TypeBuilderFactory builderFactory) {
440         // For derived enumerations defer to base type
441         return isDerivedEnumeration() ? baseGen.getGeneratedType(builderFactory)
442             : super.getGeneratedType(builderFactory);
443     }
444
445     final boolean isEnumeration() {
446         return baseGen != null ? baseGen.isEnumeration() : TypeDefinitions.ENUMERATION.equals(type.argument());
447     }
448
449     final boolean isDerivedEnumeration() {
450         return baseGen != null && baseGen.isEnumeration();
451     }
452
453     @Override
454     Type methodReturnType(final TypeBuilderFactory builderFactory) {
455         return methodReturnElementType(builderFactory);
456     }
457
458     @Override
459     final Type runtimeJavaType() {
460         if (methodReturnTypeElement != null) {
461             return methodReturnTypeElement;
462         }
463         final var genType = generatedType();
464         if (genType.isPresent()) {
465             return genType.orElseThrow();
466         }
467         final var prev = verifyNotNull(previous(), "No previous generator for %s", this);
468         return prev.runtimeJavaType();
469     }
470
471     final @NonNull Type methodReturnElementType(final @NonNull TypeBuilderFactory builderFactory) {
472         var local = methodReturnTypeElement;
473         if (local == null) {
474             methodReturnTypeElement = local = createMethodReturnElementType(builderFactory);
475         }
476         return local;
477     }
478
479     private @NonNull Type createMethodReturnElementType(final @NonNull TypeBuilderFactory builderFactory) {
480         final GeneratedType generatedType = tryGeneratedType(builderFactory);
481         if (generatedType != null) {
482             // We have generated a type here, so return it. This covers 'bits', 'enumeration' and 'union'.
483             return generatedType;
484         }
485
486         if (refType != null) {
487             // This is a reference type of some kind. Defer to its judgement as to what the return type is.
488             return refType.methodReturnType(builderFactory);
489         }
490
491         final AbstractExplicitGenerator<?, ?> prev = previous();
492         if (prev != null) {
493             // We have been added through augment/uses, defer to the original definition
494             return prev.methodReturnType(builderFactory);
495         }
496
497         final Type baseType;
498         if (baseGen == null) {
499             final QName qname = type.argument();
500             baseType = verifyNotNull(SIMPLE_TYPES.get(qname), "Cannot resolve type %s in %s", qname, this);
501         } else {
502             // We are derived from a base generator. Defer to its type for return.
503             baseType = baseGen.getGeneratedType(builderFactory);
504         }
505
506         return restrictType(baseType, computeRestrictions(), builderFactory);
507     }
508
509     private static @NonNull Type restrictType(final @NonNull Type baseType, final Restrictions restrictions,
510             final TypeBuilderFactory builderFactory) {
511         if (restrictions == null || restrictions.isEmpty()) {
512             // No additional restrictions, return base type
513             return baseType;
514         }
515
516         if (!(baseType instanceof GeneratedTransferObject)) {
517             // This is a simple Java type, just wrap it with new restrictions
518             return Types.restrictedType(baseType, restrictions);
519         }
520
521         // Base type is a GTO, we need to re-adjust it with new restrictions
522         final GeneratedTransferObject gto = (GeneratedTransferObject) baseType;
523         final GeneratedTOBuilder builder = builderFactory.newGeneratedTOBuilder(gto.getIdentifier());
524         final GeneratedTransferObject parent = gto.getSuperType();
525         if (parent != null) {
526             builder.setExtendsType(parent);
527         }
528         builder.setRestrictions(restrictions);
529         for (GeneratedProperty gp : gto.getProperties()) {
530             builder.addProperty(gp.getName())
531                 .setValue(gp.getValue())
532                 .setReadOnly(gp.isReadOnly())
533                 .setAccessModifier(gp.getAccessModifier())
534                 .setReturnType(gp.getReturnType())
535                 .setFinal(gp.isFinal())
536                 .setStatic(gp.isStatic());
537         }
538         return builder.build();
539     }
540
541     @Override
542     final void addAsGetterMethodOverride(final GeneratedTypeBuilderBase<?> builder,
543             final TypeBuilderFactory builderFactory) {
544         if (!(refType instanceof ResolvedLeafref)) {
545             // We are not dealing with a leafref or have nothing to add
546             return;
547         }
548
549         final AbstractTypeObjectGenerator<?, ?> prev =
550             (AbstractTypeObjectGenerator<?, ?>) verifyNotNull(previous(), "Missing previous link in %s", this);
551         if (prev.refType instanceof ResolvedLeafref) {
552             // We should be already inheriting the correct type
553             return;
554         }
555
556         // Note: this may we wrapped for leaf-list, hence we need to deal with that
557         final Type myType = methodReturnType(builderFactory);
558         LOG.trace("Override of {} to {}", this, myType);
559         final MethodSignatureBuilder getter = constructGetter(builder, myType);
560         getter.addAnnotation(OVERRIDE_ANNOTATION);
561         annotateDeprecatedIfNecessary(getter);
562     }
563
564     final @Nullable Restrictions computeRestrictions() {
565         final List<ValueRange> length = type.findFirstEffectiveSubstatementArgument(LengthEffectiveStatement.class)
566             .orElse(List.of());
567         final List<ValueRange> range = type.findFirstEffectiveSubstatementArgument(RangeEffectiveStatement.class)
568             .orElse(List.of());
569         final List<PatternExpression> patterns = type.streamEffectiveSubstatements(PatternEffectiveStatement.class)
570             .map(PatternEffectiveStatement::argument)
571             .collect(Collectors.toUnmodifiableList());
572
573         if (length.isEmpty() && range.isEmpty() && patterns.isEmpty()) {
574             return null;
575         }
576
577         return BindingGeneratorUtil.getRestrictions(extractTypeDefinition());
578     }
579
580     @Override
581     final GeneratedType createTypeImpl(final TypeBuilderFactory builderFactory) {
582         if (baseGen != null) {
583             final GeneratedType baseType = baseGen.getGeneratedType(builderFactory);
584             verify(baseType instanceof GeneratedTransferObject, "Unexpected base type %s", baseType);
585             return createDerivedType(builderFactory, (GeneratedTransferObject) baseType);
586         }
587
588         // FIXME: why do we need this boolean?
589         final boolean isTypedef = this instanceof TypedefGenerator;
590         final QName arg = type.argument();
591         if (TypeDefinitions.BITS.equals(arg)) {
592             return createBits(builderFactory, typeName(), currentModule(), extractTypeDefinition(), isTypedef);
593         } else if (TypeDefinitions.ENUMERATION.equals(arg)) {
594             return createEnumeration(builderFactory, typeName(), currentModule(),
595                 (EnumTypeDefinition) extractTypeDefinition());
596         } else if (TypeDefinitions.UNION.equals(arg)) {
597             final List<GeneratedType> tmp = new ArrayList<>(1);
598             final GeneratedTransferObject ret = createUnion(tmp, builderFactory, statement(), unionDependencies,
599                 typeName(), currentModule(), type, isTypedef, extractTypeDefinition());
600             auxiliaryGeneratedTypes = List.copyOf(tmp);
601             return ret;
602         } else {
603             return createSimple(builderFactory, typeName(), currentModule(),
604                 verifyNotNull(SIMPLE_TYPES.get(arg), "Unhandled type %s", arg), extractTypeDefinition());
605         }
606     }
607
608     private static @NonNull GeneratedTransferObject createBits(final TypeBuilderFactory builderFactory,
609             final JavaTypeName typeName, final ModuleGenerator module, final TypeDefinition<?> typedef,
610             final boolean isTypedef) {
611         final GeneratedTOBuilder builder = builderFactory.newGeneratedTOBuilder(typeName);
612         builder.setTypedef(isTypedef);
613         builder.addImplementsType(BindingTypes.TYPE_OBJECT);
614         builder.setBaseType(typedef);
615
616         for (Bit bit : ((BitsTypeDefinition) typedef).getBits()) {
617             final String name = bit.getName();
618             GeneratedPropertyBuilder genPropertyBuilder = builder.addProperty(BindingMapping.getPropertyName(name));
619             genPropertyBuilder.setReadOnly(true);
620             genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
621
622             builder.addEqualsIdentity(genPropertyBuilder);
623             builder.addHashIdentity(genPropertyBuilder);
624             builder.addToStringProperty(genPropertyBuilder);
625         }
626
627         // builder.setSchemaPath(typedef.getPath());
628         builder.setModuleName(module.statement().argument().getLocalName());
629         builderFactory.addCodegenInformation(typedef, builder);
630         annotateDeprecatedIfNecessary(typedef, builder);
631         makeSerializable(builder);
632         return builder.build();
633     }
634
635     private static @NonNull Enumeration createEnumeration(final TypeBuilderFactory builderFactory,
636             final JavaTypeName typeName, final ModuleGenerator module, final EnumTypeDefinition typedef) {
637         // TODO units for typedef enum
638         final AbstractEnumerationBuilder builder = builderFactory.newEnumerationBuilder(typeName);
639
640         typedef.getDescription().map(BindingGeneratorUtil::encodeAngleBrackets)
641             .ifPresent(builder::setDescription);
642         typedef.getReference().ifPresent(builder::setReference);
643
644         builder.setModuleName(module.statement().argument().getLocalName());
645         builder.updateEnumPairsFromEnumTypeDef(typedef);
646         return builder.toInstance();
647     }
648
649     private static @NonNull GeneratedType createSimple(final TypeBuilderFactory builderFactory,
650             final JavaTypeName typeName, final ModuleGenerator module, final Type javaType,
651             final TypeDefinition<?> typedef) {
652         final String moduleName = module.statement().argument().getLocalName();
653         final GeneratedTOBuilder builder = builderFactory.newGeneratedTOBuilder(typeName);
654         builder.setTypedef(true);
655         builder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
656
657         final GeneratedPropertyBuilder genPropBuilder = builder.addProperty(TypeConstants.VALUE_PROP);
658         genPropBuilder.setReturnType(javaType);
659         builder.addEqualsIdentity(genPropBuilder);
660         builder.addHashIdentity(genPropBuilder);
661         builder.addToStringProperty(genPropBuilder);
662
663         builder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
664
665 //        builder.setSchemaPath(typedef.getPath());
666         builder.setModuleName(moduleName);
667         builderFactory.addCodegenInformation(typedef, builder);
668
669         annotateDeprecatedIfNecessary(typedef, builder);
670
671         if (javaType instanceof ConcreteType
672             // FIXME: This looks very suspicious: we should by checking for Types.STRING
673             && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
674             addStringRegExAsConstant(builder, resolveRegExpressions(typedef));
675         }
676         addUnits(builder, typedef);
677
678         makeSerializable(builder);
679         return builder.build();
680     }
681
682     private static @NonNull GeneratedTransferObject createUnion(final List<GeneratedType> auxiliaryGeneratedTypes,
683             final TypeBuilderFactory builderFactory, final EffectiveStatement<?, ?> definingStatement,
684             final UnionDependencies dependencies, final JavaTypeName typeName, final ModuleGenerator module,
685             final TypeEffectiveStatement<?> type, final boolean isTypedef, final TypeDefinition<?> typedef) {
686         final GeneratedUnionBuilder builder = builderFactory.newGeneratedUnionBuilder(typeName);
687         builder.addImplementsType(BindingTypes.TYPE_OBJECT);
688         builder.setIsUnion(true);
689
690 //        builder.setSchemaPath(typedef.getPath());
691         builder.setModuleName(module.statement().argument().getLocalName());
692         builderFactory.addCodegenInformation(definingStatement, builder);
693
694         annotateDeprecatedIfNecessary(definingStatement, builder);
695
696         // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
697         // also negation information and hence guarantees uniqueness.
698         final Map<String, String> expressions = new HashMap<>();
699
700         // Linear list of properties generated from subtypes. We need this information for runtime types, as it allows
701         // direct mapping of type to corresponding property -- without having to resort to re-resolving the leafrefs
702         // again.
703         final List<String> typeProperties = new ArrayList<>();
704
705         for (EffectiveStatement<?, ?> stmt : type.effectiveSubstatements()) {
706             if (stmt instanceof TypeEffectiveStatement) {
707                 final TypeEffectiveStatement<?> subType = (TypeEffectiveStatement<?>) stmt;
708                 final QName subName = subType.argument();
709                 final String localName = subName.getLocalName();
710
711                 String propSource = localName;
712                 final Type generatedType;
713                 if (TypeDefinitions.UNION.equals(subName)) {
714                     final JavaTypeName subUnionName = typeName.createEnclosed(
715                         provideAvailableNameForGenTOBuilder(typeName.simpleName()));
716                     final GeneratedTransferObject subUnion = createUnion(auxiliaryGeneratedTypes, builderFactory,
717                         definingStatement, dependencies, subUnionName, module, subType, isTypedef,
718                         subType.getTypeDefinition());
719                     builder.addEnclosingTransferObject(subUnion);
720                     propSource = subUnionName.simpleName();
721                     generatedType = subUnion;
722                 } else if (TypeDefinitions.ENUMERATION.equals(subName)) {
723                     final Enumeration subEnumeration = createEnumeration(builderFactory,
724                         typeName.createEnclosed(BindingMapping.getClassName(localName), "$"), module,
725                         (EnumTypeDefinition) subType.getTypeDefinition());
726                     builder.addEnumeration(subEnumeration);
727                     generatedType = subEnumeration;
728                 } else if (TypeDefinitions.BITS.equals(subName)) {
729                     final GeneratedTransferObject subBits = createBits(builderFactory,
730                         typeName.createEnclosed(BindingMapping.getClassName(localName), "$"), module,
731                         subType.getTypeDefinition(), isTypedef);
732                     builder.addEnclosingTransferObject(subBits);
733                     generatedType = subBits;
734                 } else if (TypeDefinitions.IDENTITYREF.equals(subName)) {
735                     generatedType = verifyNotNull(dependencies.identityTypes.get(stmt),
736                         "Cannot resolve identityref %s in %s", stmt, definingStatement)
737                         .methodReturnType(builderFactory);
738                 } else if (TypeDefinitions.LEAFREF.equals(subName)) {
739                     generatedType = verifyNotNull(dependencies.leafTypes.get(stmt),
740                         "Cannot resolve leafref %s in %s", stmt, definingStatement)
741                         .methodReturnType(builderFactory);
742                 } else {
743                     Type baseType = SIMPLE_TYPES.get(subName);
744                     if (baseType == null) {
745                         // This has to be a reference to a typedef, let's lookup it up and pick up its type
746                         final AbstractTypeObjectGenerator<?, ?> baseGen = verifyNotNull(
747                             dependencies.baseTypes.get(subName), "Cannot resolve base type %s in %s", subName,
748                             definingStatement);
749                         baseType = baseGen.methodReturnType(builderFactory);
750
751                         // FIXME: This is legacy behaviour for leafrefs:
752                         if (baseGen.refType instanceof TypeReference.Leafref) {
753                             // if there already is a compatible property, do not generate a new one
754                             final Type search = baseType;
755
756                             final String matching = builder.getProperties().stream()
757                                 .filter(prop -> search == ((GeneratedPropertyBuilderImpl) prop).getReturnType())
758                                 .findFirst()
759                                 .map(GeneratedPropertyBuilder::getName)
760                                 .orElse(null);
761                             if (matching != null) {
762                                 typeProperties.add(matching);
763                                 continue;
764                             }
765
766                             // ... otherwise generate this weird property name
767                             propSource = BindingMapping.getUnionLeafrefMemberName(builder.getName(),
768                                 baseType.getName());
769                         }
770                     }
771
772                     expressions.putAll(resolveRegExpressions(subType.getTypeDefinition()));
773
774                     generatedType = restrictType(baseType,
775                         BindingGeneratorUtil.getRestrictions(type.getTypeDefinition()), builderFactory);
776                 }
777
778                 final String propName = BindingMapping.getPropertyName(propSource);
779                 typeProperties.add(propName);
780
781                 if (builder.containsProperty(propName)) {
782                     /*
783                      *  FIXME: this is not okay, as we are ignoring multiple base types. For example in the case of:
784                      *
785                      *    type union {
786                      *      type string {
787                      *        length 1..5;
788                      *      }
789                      *      type string {
790                      *        length 8..10;
791                      *      }
792                      *    }
793                      *
794                      *  We are ending up losing the information about 8..10 being an alternative. This is also the case
795                      *  for leafrefs -- we are performing property compression as well (see above). While it is alluring
796                      *  to merge these into 'length 1..5|8..10', that may not be generally feasible.
797                      *
798                      *  We should resort to a counter of conflicting names, i.e. the second string would be mapped to
799                      *  'string1' or similar.
800                      */
801                     continue;
802                 }
803
804                 final GeneratedPropertyBuilder propBuilder = builder
805                     .addProperty(propName)
806                     .setReturnType(generatedType);
807
808                 builder.addEqualsIdentity(propBuilder);
809                 builder.addHashIdentity(propBuilder);
810                 builder.addToStringProperty(propBuilder);
811             }
812         }
813
814         // Record property names if needed
815         builder.setTypePropertyNames(typeProperties);
816
817         addStringRegExAsConstant(builder, expressions);
818         addUnits(builder, typedef);
819
820         makeSerializable(builder);
821         return builder.build();
822     }
823
824     // FIXME: we should not rely on TypeDefinition
825     abstract @NonNull TypeDefinition<?> extractTypeDefinition();
826
827     abstract @NonNull GeneratedTransferObject createDerivedType(@NonNull TypeBuilderFactory builderFactory,
828         @NonNull GeneratedTransferObject baseType);
829
830     /**
831      * Adds to the {@code genTOBuilder} the constant which contains regular expressions from the {@code expressions}.
832      *
833      * @param genTOBuilder generated TO builder to which are {@code regular expressions} added
834      * @param expressions list of string which represent regular expressions
835      */
836     static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final Map<String, String> expressions) {
837         if (!expressions.isEmpty()) {
838             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
839                 ImmutableMap.copyOf(expressions));
840         }
841     }
842
843     /**
844      * Converts the pattern constraints from {@code typedef} to the list of the strings which represents these
845      * constraints.
846      *
847      * @param typedef extended type in which are the pattern constraints sought
848      * @return list of strings which represents the constraint patterns
849      * @throws IllegalArgumentException if <code>typedef</code> equals null
850      */
851     static Map<String, String> resolveRegExpressions(final TypeDefinition<?> typedef) {
852         return typedef instanceof StringTypeDefinition
853             // TODO: run diff against base ?
854             ? resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints())
855                 : ImmutableMap.of();
856     }
857
858     /**
859      * Converts the pattern constraints to the list of the strings which represents these constraints.
860      *
861      * @param patternConstraints list of pattern constraints
862      * @return list of strings which represents the constraint patterns
863      */
864     private static Map<String, String> resolveRegExpressions(final List<PatternConstraint> patternConstraints) {
865         if (patternConstraints.isEmpty()) {
866             return ImmutableMap.of();
867         }
868
869         final Map<String, String> regExps = Maps.newHashMapWithExpectedSize(patternConstraints.size());
870         for (PatternConstraint patternConstraint : patternConstraints) {
871             String regEx = patternConstraint.getJavaPatternString();
872
873             // The pattern can be inverted
874             final Optional<ModifierKind> optModifier = patternConstraint.getModifier();
875             if (optModifier.isPresent()) {
876                 regEx = applyModifier(optModifier.get(), regEx);
877             }
878
879             regExps.put(regEx, patternConstraint.getRegularExpressionString());
880         }
881
882         return regExps;
883     }
884
885     /**
886      * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
887      * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
888      * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
889      *
890      * @param name string with name of augmented node
891      * @return string with the number suffix incremented by one (or 1 is added)
892      */
893     private static String provideAvailableNameForGenTOBuilder(final String name) {
894         final int dollar = name.indexOf('$');
895         if (dollar == -1) {
896             return name + "$1";
897         }
898
899         final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
900         verify(newSuffix > 0, "Suffix counter overflow");
901         return name.substring(0, dollar + 1) + newSuffix;
902     }
903
904     private static String applyModifier(final ModifierKind modifier, final String pattern) {
905         switch (modifier) {
906             case INVERT_MATCH:
907                 return RegexPatterns.negatePatternString(pattern);
908             default:
909                 LOG.warn("Ignoring unhandled modifier {}", modifier);
910                 return pattern;
911         }
912     }
913 }