2 * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.generator.impl.reactor;
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;
14 import com.google.common.base.VerifyException;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.Maps;
17 import java.util.ArrayList;
18 import java.util.HashMap;
19 import java.util.List;
21 import java.util.Optional;
22 import java.util.stream.Collectors;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil;
26 import org.opendaylight.mdsal.binding.generator.impl.reactor.TypeReference.ResolvedLeafref;
27 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
28 import org.opendaylight.mdsal.binding.model.api.Enumeration;
29 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
30 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
31 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
32 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
33 import org.opendaylight.mdsal.binding.model.api.Restrictions;
34 import org.opendaylight.mdsal.binding.model.api.Type;
35 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
36 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
37 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
38 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
39 import org.opendaylight.mdsal.binding.model.ri.BaseYangTypes;
40 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
41 import org.opendaylight.mdsal.binding.model.ri.TypeConstants;
42 import org.opendaylight.mdsal.binding.model.ri.Types;
43 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.AbstractEnumerationBuilder;
44 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.GeneratedPropertyBuilderImpl;
45 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
46 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
47 import org.opendaylight.yangtools.concepts.Immutable;
48 import org.opendaylight.yangtools.yang.binding.RegexPatterns;
49 import org.opendaylight.yangtools.yang.binding.TypeObject;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.common.YangConstants;
52 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
53 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
54 import org.opendaylight.yangtools.yang.model.api.stmt.BaseEffectiveStatement;
55 import org.opendaylight.yangtools.yang.model.api.stmt.LengthEffectiveStatement;
56 import org.opendaylight.yangtools.yang.model.api.stmt.PathEffectiveStatement;
57 import org.opendaylight.yangtools.yang.model.api.stmt.PatternEffectiveStatement;
58 import org.opendaylight.yangtools.yang.model.api.stmt.PatternExpression;
59 import org.opendaylight.yangtools.yang.model.api.stmt.RangeEffectiveStatement;
60 import org.opendaylight.yangtools.yang.model.api.stmt.TypeEffectiveStatement;
61 import org.opendaylight.yangtools.yang.model.api.stmt.ValueRange;
62 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
64 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.ModifierKind;
66 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
67 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.TypeDefinitions;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
73 * Common base class for {@link TypedefGenerator} and {@link AbstractTypeAwareGenerator}. This encompasses three
74 * different statements with two different semantics:
76 * <li>{@link TypedefGenerator}s always result in a generated {@link TypeObject}, even if the semantics is exactly
77 * the same as its base type. This aligns with {@code typedef} defining a new type.<li>
78 * <li>{@link LeafGenerator}s and {@link LeafListGenerator}s, on the other hand, do not generate a {@link TypeObject}
79 * unless absolutely necassary. This aligns with {@code leaf} and {@code leaf-list} being mapped onto a property
80 * of its parent type.<li>
84 * To throw a bit of confusion into the mix, there are three exceptions to those rules:
87 * {@code identityref} definitions never result in a type definition being emitted. The reason for this has to do
88 * with identity type mapping as well as history of our codebase.
91 * The problem at hand is inconsistency between the fact that identity is mapped to a {@link Class}, which is also
92 * returned from leaves which specify it like this:
106 * which results in fine-looking
110 * Class<? extends Iden> getFoo();
116 * This gets more dicey if we decide to extend the previous snippet to also include:
134 * Now we have competing requirements: {@code typedef} would like us to use encapsulation to capture the defined
135 * type, while {@code getBar()} wants us to retain shape with getFoo(), as it should not matter how the
136 * {@code identityref} was formed. We need to pick between:
141 * public class BarRef extends ScalarTypeObject<Class<? extends Iden>> {
142 * Class<? extends Iden> getValue() {
157 * Class<? extends Iden> getBar();
165 * Here the second option is more user-friendly, as the type system works along the lines of <b>reference</b>
166 * semantics, treating and {@code Bar.getBar()} and {@code Foo.getFoo()} as equivalent. The first option would
167 * force users to go through explicit encapsulation, for no added benefit as the {@code typedef} cannot possibly add
168 * anything useful to the actual type semantics.
171 * {@code leafref} definitions never result in a type definition being emitted. The reasons for this are similar to
172 * {@code identityref}, but have an additional twist: a {@leafref} can target a relative path, which may only be
173 * resolved at a particular instantiation.
175 * Take the example of the following model:
208 * The {@code typedef ref} points to outside of the grouping, and hence the type of {@code leaf foo} is polymorphic:
209 * the definition in {@code grouping grp} needs to use {@code Object}, whereas the instantiations in
210 * {@code container bar} and {@code container baz} need to use {@code String} and {@link Integer} respectively.
211 * Expressing the resulting interface contracts requires return type specialization and run-time checks. An
212 * intermediate class generated for the typedef would end up being a hindrance without any benefit.
215 * {@code enumeration} definitions never result in a derived type. This is because these are mapped to Java
216 * {@code enum}, which does not allow subclassing.
221 * At the end of the day, the mechanic translation rules are giving way to correctly mapping the semantics -- which in
222 * both of the exception cases boil down to tracking type indirection. Intermediate constructs involved in tracking
223 * type indirection in YANG constructs is therefore explicitly excluded from the generated Java code, but the Binding
224 * Specification still takes them into account when determining types as outlined above.
226 abstract class AbstractTypeObjectGenerator<S extends EffectiveStatement<?, ?>, R extends RuntimeType>
227 extends AbstractDependentGenerator<S, R> {
228 private static final class UnionDependencies implements Immutable {
229 private final Map<EffectiveStatement<?, ?>, TypeReference> identityTypes = new HashMap<>();
230 private final Map<EffectiveStatement<?, ?>, TypeReference> leafTypes = new HashMap<>();
231 private final Map<QName, TypedefGenerator> baseTypes = new HashMap<>();
233 UnionDependencies(final TypeEffectiveStatement<?> type, final GeneratorContext context) {
234 resolveUnionDependencies(context, type);
237 private void resolveUnionDependencies(final GeneratorContext context, final TypeEffectiveStatement<?> union) {
238 for (EffectiveStatement<?, ?> stmt : union.effectiveSubstatements()) {
239 if (stmt instanceof TypeEffectiveStatement<?> type) {
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())));
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)
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));
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)
283 private final TypeEffectiveStatement<?> type;
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.
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.
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();
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.
304 private Type methodReturnTypeElement;
306 AbstractTypeObjectGenerator(final S statement, final AbstractCompositeGenerator<?, ?> parent) {
307 super(statement, parent);
308 type = statement().findFirstEffectiveSubstatement(TypeEffectiveStatement.class).orElseThrow();
312 public final List<GeneratedType> auxiliaryGeneratedTypes() {
313 return auxiliaryGeneratedTypes;
317 final void linkDependencies(final GeneratorContext context) {
318 verify(inferred != null, "Duplicate linking of %s", this);
320 final QName typeName = type.argument();
321 if (isBuiltinName(typeName)) {
322 verify(inferred.isEmpty(), "Unexpected non-empty downstreams in %s", this);
327 final AbstractExplicitGenerator<S, R> prev = previous();
329 verify(prev instanceof AbstractTypeObjectGenerator, "Unexpected previous %s", prev);
330 ((AbstractTypeObjectGenerator<S, R>) prev).linkInferred(this);
332 linkBaseGen(context.resolveTypedef(typeName));
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));
342 if (inferred.isEmpty()) {
343 inferred = new ArrayList<>(2);
345 inferred.add(downstream);
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);
356 for (AbstractTypeObjectGenerator<?, ?> downstream : downstreams) {
357 downstream.linkBaseGen(upstreamBaseGen);
361 void bindTypeDefinition(final GeneratorContext context) {
362 if (baseGen != null) {
363 // We have registered with baseGen, it will push the type to us
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);
384 LOG.trace("Resolved base {} to generator {}", type, refType);
385 bindDerivedGenerators(refType);
388 final void bindTypeDefinition(final @Nullable TypeReference reference) {
390 LOG.trace("Resolved derived {} to generator {}", type, refType);
393 private static boolean isBuiltinName(final QName typeName) {
394 return YangConstants.RFC6020_YANG_MODULE.equals(typeName.getModule());
397 abstract void bindDerivedGenerators(@Nullable TypeReference reference);
400 final ClassPlacement classPlacement() {
401 if (refType != null) {
402 // Reference types never create a new type
403 return ClassPlacement.NONE;
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;
410 return classPlacementImpl();
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:
418 // type uint8 { range 0..255; }
424 // type uint8 { range 0..100; }
428 // type foo { range 0..100; }
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
434 return baseGen != null || SIMPLE_TYPES.containsKey(type.argument()) || isAddedByUses() || isAugmenting()
435 ? ClassPlacement.NONE : ClassPlacement.MEMBER;
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);
445 final boolean isEnumeration() {
446 return baseGen != null ? baseGen.isEnumeration() : TypeDefinitions.ENUMERATION.equals(type.argument());
449 final boolean isDerivedEnumeration() {
450 return baseGen != null && baseGen.isEnumeration();
454 Type methodReturnType(final TypeBuilderFactory builderFactory) {
455 return methodReturnElementType(builderFactory);
459 final Type runtimeJavaType() {
460 if (methodReturnTypeElement != null) {
461 return methodReturnTypeElement;
463 final var genType = generatedType();
464 if (genType.isPresent()) {
465 return genType.orElseThrow();
467 final var prev = verifyNotNull(previous(), "No previous generator for %s", this);
468 return prev.runtimeJavaType();
471 final @NonNull Type methodReturnElementType(final @NonNull TypeBuilderFactory builderFactory) {
472 var local = methodReturnTypeElement;
474 methodReturnTypeElement = local = createMethodReturnElementType(builderFactory);
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;
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);
491 final AbstractExplicitGenerator<?, ?> prev = previous();
493 // We have been added through augment/uses, defer to the original definition
494 return prev.methodReturnType(builderFactory);
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);
502 // We are derived from a base generator. Defer to its type for return.
503 baseType = baseGen.getGeneratedType(builderFactory);
506 return restrictType(baseType, computeRestrictions(), builderFactory);
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
516 if (!(baseType instanceof GeneratedTransferObject gto)) {
517 // This is a simple Java type, just wrap it with new restrictions
518 return Types.restrictedType(baseType, restrictions);
521 // Base type is a GTO, we need to re-adjust it with new restrictions
522 final GeneratedTOBuilder builder = builderFactory.newGeneratedTOBuilder(gto.getIdentifier());
523 final GeneratedTransferObject parent = gto.getSuperType();
524 if (parent != null) {
525 builder.setExtendsType(parent);
527 builder.setRestrictions(restrictions);
528 for (GeneratedProperty gp : gto.getProperties()) {
529 builder.addProperty(gp.getName())
530 .setValue(gp.getValue())
531 .setReadOnly(gp.isReadOnly())
532 .setAccessModifier(gp.getAccessModifier())
533 .setReturnType(gp.getReturnType())
534 .setFinal(gp.isFinal())
535 .setStatic(gp.isStatic());
537 return builder.build();
541 final void addAsGetterMethodOverride(final GeneratedTypeBuilderBase<?> builder,
542 final TypeBuilderFactory builderFactory) {
543 if (!(refType instanceof ResolvedLeafref)) {
544 // We are not dealing with a leafref or have nothing to add
548 final AbstractTypeObjectGenerator<?, ?> prev =
549 (AbstractTypeObjectGenerator<?, ?>) verifyNotNull(previous(), "Missing previous link in %s", this);
550 if (prev.refType instanceof ResolvedLeafref) {
551 // We should be already inheriting the correct type
555 // Note: this may we wrapped for leaf-list, hence we need to deal with that
556 final Type myType = methodReturnType(builderFactory);
557 LOG.trace("Override of {} to {}", this, myType);
558 final MethodSignatureBuilder getter = constructGetter(builder, myType);
559 getter.addAnnotation(OVERRIDE_ANNOTATION);
560 annotateDeprecatedIfNecessary(getter);
563 final @Nullable Restrictions computeRestrictions() {
564 final List<ValueRange> length = type.findFirstEffectiveSubstatementArgument(LengthEffectiveStatement.class)
566 final List<ValueRange> range = type.findFirstEffectiveSubstatementArgument(RangeEffectiveStatement.class)
568 final List<PatternExpression> patterns = type.streamEffectiveSubstatements(PatternEffectiveStatement.class)
569 .map(PatternEffectiveStatement::argument)
570 .collect(Collectors.toUnmodifiableList());
572 if (length.isEmpty() && range.isEmpty() && patterns.isEmpty()) {
576 return BindingGeneratorUtil.getRestrictions(extractTypeDefinition());
580 final GeneratedType createTypeImpl(final TypeBuilderFactory builderFactory) {
581 if (baseGen != null) {
582 final GeneratedType baseType = baseGen.getGeneratedType(builderFactory);
583 verify(baseType instanceof GeneratedTransferObject, "Unexpected base type %s", baseType);
584 return createDerivedType(builderFactory, (GeneratedTransferObject) baseType);
587 // FIXME: why do we need this boolean?
588 final boolean isTypedef = this instanceof TypedefGenerator;
589 final QName arg = type.argument();
590 if (TypeDefinitions.BITS.equals(arg)) {
591 return createBits(builderFactory, typeName(), currentModule(), extractTypeDefinition(), isTypedef);
592 } else if (TypeDefinitions.ENUMERATION.equals(arg)) {
593 return createEnumeration(builderFactory, typeName(), currentModule(),
594 (EnumTypeDefinition) extractTypeDefinition());
595 } else if (TypeDefinitions.UNION.equals(arg)) {
596 final List<GeneratedType> tmp = new ArrayList<>(1);
597 final GeneratedTransferObject ret = createUnion(tmp, builderFactory, statement(), unionDependencies,
598 typeName(), currentModule(), type, isTypedef, extractTypeDefinition());
599 auxiliaryGeneratedTypes = List.copyOf(tmp);
602 return createSimple(builderFactory, typeName(), currentModule(),
603 verifyNotNull(SIMPLE_TYPES.get(arg), "Unhandled type %s", arg), extractTypeDefinition());
607 private static @NonNull GeneratedTransferObject createBits(final TypeBuilderFactory builderFactory,
608 final JavaTypeName typeName, final ModuleGenerator module, final TypeDefinition<?> typedef,
609 final boolean isTypedef) {
610 final GeneratedTOBuilder builder = builderFactory.newGeneratedTOBuilder(typeName);
611 builder.setTypedef(isTypedef);
612 builder.addImplementsType(BindingTypes.TYPE_OBJECT);
613 builder.setBaseType(typedef);
615 for (Bit bit : ((BitsTypeDefinition) typedef).getBits()) {
616 final String name = bit.getName();
617 GeneratedPropertyBuilder genPropertyBuilder = builder.addProperty(BindingMapping.getPropertyName(name));
618 genPropertyBuilder.setReadOnly(true);
619 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
621 builder.addEqualsIdentity(genPropertyBuilder);
622 builder.addHashIdentity(genPropertyBuilder);
623 builder.addToStringProperty(genPropertyBuilder);
626 // builder.setSchemaPath(typedef.getPath());
627 builder.setModuleName(module.statement().argument().getLocalName());
628 builderFactory.addCodegenInformation(typedef, builder);
629 annotateDeprecatedIfNecessary(typedef, builder);
630 makeSerializable(builder);
631 return builder.build();
634 private static @NonNull Enumeration createEnumeration(final TypeBuilderFactory builderFactory,
635 final JavaTypeName typeName, final ModuleGenerator module, final EnumTypeDefinition typedef) {
636 // TODO units for typedef enum
637 final AbstractEnumerationBuilder builder = builderFactory.newEnumerationBuilder(typeName);
639 typedef.getDescription().map(BindingGeneratorUtil::encodeAngleBrackets)
640 .ifPresent(builder::setDescription);
641 typedef.getReference().ifPresent(builder::setReference);
643 builder.setModuleName(module.statement().argument().getLocalName());
644 builder.updateEnumPairsFromEnumTypeDef(typedef);
645 return builder.toInstance();
648 private static @NonNull GeneratedType createSimple(final TypeBuilderFactory builderFactory,
649 final JavaTypeName typeName, final ModuleGenerator module, final Type javaType,
650 final TypeDefinition<?> typedef) {
651 final String moduleName = module.statement().argument().getLocalName();
652 final GeneratedTOBuilder builder = builderFactory.newGeneratedTOBuilder(typeName);
653 builder.setTypedef(true);
654 builder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
656 final GeneratedPropertyBuilder genPropBuilder = builder.addProperty(TypeConstants.VALUE_PROP);
657 genPropBuilder.setReturnType(javaType);
658 builder.addEqualsIdentity(genPropBuilder);
659 builder.addHashIdentity(genPropBuilder);
660 builder.addToStringProperty(genPropBuilder);
662 builder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
664 // builder.setSchemaPath(typedef.getPath());
665 builder.setModuleName(moduleName);
666 builderFactory.addCodegenInformation(typedef, builder);
668 annotateDeprecatedIfNecessary(typedef, builder);
670 if (javaType instanceof ConcreteType
671 // FIXME: This looks very suspicious: we should by checking for Types.STRING
672 && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
673 addStringRegExAsConstant(builder, resolveRegExpressions(typedef));
675 addUnits(builder, typedef);
677 makeSerializable(builder);
678 return builder.build();
681 private static @NonNull GeneratedTransferObject createUnion(final List<GeneratedType> auxiliaryGeneratedTypes,
682 final TypeBuilderFactory builderFactory, final EffectiveStatement<?, ?> definingStatement,
683 final UnionDependencies dependencies, final JavaTypeName typeName, final ModuleGenerator module,
684 final TypeEffectiveStatement<?> type, final boolean isTypedef, final TypeDefinition<?> typedef) {
685 final GeneratedUnionBuilder builder = builderFactory.newGeneratedUnionBuilder(typeName);
686 builder.addImplementsType(BindingTypes.TYPE_OBJECT);
687 builder.setIsUnion(true);
689 // builder.setSchemaPath(typedef.getPath());
690 builder.setModuleName(module.statement().argument().getLocalName());
691 builderFactory.addCodegenInformation(definingStatement, builder);
693 annotateDeprecatedIfNecessary(definingStatement, builder);
695 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
696 // also negation information and hence guarantees uniqueness.
697 final Map<String, String> expressions = new HashMap<>();
699 // Linear list of properties generated from subtypes. We need this information for runtime types, as it allows
700 // direct mapping of type to corresponding property -- without having to resort to re-resolving the leafrefs
702 final List<String> typeProperties = new ArrayList<>();
704 for (EffectiveStatement<?, ?> stmt : type.effectiveSubstatements()) {
705 if (stmt instanceof TypeEffectiveStatement<?> subType) {
706 final QName subName = subType.argument();
707 final String localName = subName.getLocalName();
709 String propSource = localName;
710 final Type generatedType;
711 if (TypeDefinitions.UNION.equals(subName)) {
712 final JavaTypeName subUnionName = typeName.createEnclosed(
713 provideAvailableNameForGenTOBuilder(typeName.simpleName()));
714 final GeneratedTransferObject subUnion = createUnion(auxiliaryGeneratedTypes, builderFactory,
715 definingStatement, dependencies, subUnionName, module, subType, isTypedef,
716 subType.getTypeDefinition());
717 builder.addEnclosingTransferObject(subUnion);
718 propSource = subUnionName.simpleName();
719 generatedType = subUnion;
720 } else if (TypeDefinitions.ENUMERATION.equals(subName)) {
721 final Enumeration subEnumeration = createEnumeration(builderFactory,
722 typeName.createEnclosed(BindingMapping.getClassName(localName), "$"), module,
723 (EnumTypeDefinition) subType.getTypeDefinition());
724 builder.addEnumeration(subEnumeration);
725 generatedType = subEnumeration;
726 } else if (TypeDefinitions.BITS.equals(subName)) {
727 final GeneratedTransferObject subBits = createBits(builderFactory,
728 typeName.createEnclosed(BindingMapping.getClassName(localName), "$"), module,
729 subType.getTypeDefinition(), isTypedef);
730 builder.addEnclosingTransferObject(subBits);
731 generatedType = subBits;
732 } else if (TypeDefinitions.IDENTITYREF.equals(subName)) {
733 propSource = stmt.findFirstEffectiveSubstatement(BaseEffectiveStatement.class)
734 .orElseThrow(() -> new VerifyException(String.format("Invalid identityref "
735 + "definition %s in %s, missing BASE statement", stmt, definingStatement)))
736 .argument().getLocalName();
737 generatedType = verifyNotNull(dependencies.identityTypes.get(stmt),
738 "Cannot resolve identityref %s in %s", stmt, definingStatement)
739 .methodReturnType(builderFactory);
740 } else if (TypeDefinitions.LEAFREF.equals(subName)) {
741 generatedType = verifyNotNull(dependencies.leafTypes.get(stmt),
742 "Cannot resolve leafref %s in %s", stmt, definingStatement)
743 .methodReturnType(builderFactory);
745 Type baseType = SIMPLE_TYPES.get(subName);
746 if (baseType == null) {
747 // This has to be a reference to a typedef, let's lookup it up and pick up its type
748 final AbstractTypeObjectGenerator<?, ?> baseGen = verifyNotNull(
749 dependencies.baseTypes.get(subName), "Cannot resolve base type %s in %s", subName,
751 baseType = baseGen.methodReturnType(builderFactory);
753 // FIXME: This is legacy behaviour for leafrefs:
754 if (baseGen.refType instanceof TypeReference.Leafref) {
755 // if there already is a compatible property, do not generate a new one
756 final Type search = baseType;
758 final String matching = builder.getProperties().stream()
759 .filter(prop -> search == ((GeneratedPropertyBuilderImpl) prop).getReturnType())
761 .map(GeneratedPropertyBuilder::getName)
763 if (matching != null) {
764 typeProperties.add(matching);
768 // ... otherwise generate this weird property name
769 propSource = BindingMapping.getUnionLeafrefMemberName(builder.getName(),
774 expressions.putAll(resolveRegExpressions(subType.getTypeDefinition()));
776 generatedType = restrictType(baseType,
777 BindingGeneratorUtil.getRestrictions(type.getTypeDefinition()), builderFactory);
780 final String propName = BindingMapping.getPropertyName(propSource);
781 typeProperties.add(propName);
783 if (builder.containsProperty(propName)) {
785 * FIXME: this is not okay, as we are ignoring multiple base types. For example in the case of:
796 * We are ending up losing the information about 8..10 being an alternative. This is also the case
797 * for leafrefs -- we are performing property compression as well (see above). While it is alluring
798 * to merge these into 'length 1..5|8..10', that may not be generally feasible.
800 * We should resort to a counter of conflicting names, i.e. the second string would be mapped to
801 * 'string1' or similar.
806 final GeneratedPropertyBuilder propBuilder = builder
807 .addProperty(propName)
808 .setReturnType(generatedType);
810 builder.addEqualsIdentity(propBuilder);
811 builder.addHashIdentity(propBuilder);
812 builder.addToStringProperty(propBuilder);
816 // Record property names if needed
817 builder.setTypePropertyNames(typeProperties);
819 addStringRegExAsConstant(builder, expressions);
820 addUnits(builder, typedef);
822 makeSerializable(builder);
823 return builder.build();
826 // FIXME: we should not rely on TypeDefinition
827 abstract @NonNull TypeDefinition<?> extractTypeDefinition();
829 abstract @NonNull GeneratedTransferObject createDerivedType(@NonNull TypeBuilderFactory builderFactory,
830 @NonNull GeneratedTransferObject baseType);
833 * Adds to the {@code genTOBuilder} the constant which contains regular expressions from the {@code expressions}.
835 * @param genTOBuilder generated TO builder to which are {@code regular expressions} added
836 * @param expressions list of string which represent regular expressions
838 static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final Map<String, String> expressions) {
839 if (!expressions.isEmpty()) {
840 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
841 ImmutableMap.copyOf(expressions));
846 * Converts the pattern constraints from {@code typedef} to the list of the strings which represents these
849 * @param typedef extended type in which are the pattern constraints sought
850 * @return list of strings which represents the constraint patterns
851 * @throws IllegalArgumentException if <code>typedef</code> equals null
853 static Map<String, String> resolveRegExpressions(final TypeDefinition<?> typedef) {
854 return typedef instanceof StringTypeDefinition stringTypedef
855 // TODO: run diff against base ?
856 ? resolveRegExpressions(stringTypedef.getPatternConstraints())
861 * Converts the pattern constraints to the list of the strings which represents these constraints.
863 * @param patternConstraints list of pattern constraints
864 * @return list of strings which represents the constraint patterns
866 private static Map<String, String> resolveRegExpressions(final List<PatternConstraint> patternConstraints) {
867 if (patternConstraints.isEmpty()) {
868 return ImmutableMap.of();
871 final Map<String, String> regExps = Maps.newHashMapWithExpectedSize(patternConstraints.size());
872 for (PatternConstraint patternConstraint : patternConstraints) {
873 String regEx = patternConstraint.getJavaPatternString();
875 // The pattern can be inverted
876 final Optional<ModifierKind> optModifier = patternConstraint.getModifier();
877 if (optModifier.isPresent()) {
878 regEx = applyModifier(optModifier.get(), regEx);
881 regExps.put(regEx, patternConstraint.getRegularExpressionString());
888 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
889 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
890 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
892 * @param name string with name of augmented node
893 * @return string with the number suffix incremented by one (or 1 is added)
895 private static String provideAvailableNameForGenTOBuilder(final String name) {
896 final int dollar = name.indexOf('$');
901 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
902 verify(newSuffix > 0, "Suffix counter overflow");
903 return name.substring(0, dollar + 1) + newSuffix;
906 private static String applyModifier(final ModifierKind modifier, final String pattern) {
907 return switch (modifier) {
908 case INVERT_MATCH -> RegexPatterns.negatePatternString(pattern);