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.collect.ImmutableMap;
15 import com.google.common.collect.Maps;
16 import java.util.ArrayList;
17 import java.util.HashMap;
18 import java.util.List;
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.AccessModifier;
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.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;
72 * Common base class for {@link TypedefGenerator} and {@link AbstractTypeAwareGenerator}. This encompasses three
73 * different statements with two different semantics:
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>
83 * To throw a bit of confusion into the mix, there are three exceptions to those rules:
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.
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:
105 * which results in fine-looking
109 * Class<? extends Iden> getFoo();
115 * This gets more dicey if we decide to extend the previous snippet to also include:
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:
140 * public class BarRef extends ScalarTypeObject<Class<? extends Iden>> {
141 * Class<? extends Iden> getValue() {
156 * Class<? extends Iden> getBar();
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.
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.
174 * Take the example of the following model:
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.
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.
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.
225 abstract class AbstractTypeObjectGenerator<T extends EffectiveStatement<?, ?>> extends AbstractDependentGenerator<T> {
226 private static final class UnionDependencies implements Immutable {
227 private final Map<EffectiveStatement<?, ?>, TypeReference> identityTypes = new HashMap<>();
228 private final Map<EffectiveStatement<?, ?>, TypeReference> leafTypes = new HashMap<>();
229 private final Map<QName, TypedefGenerator> baseTypes = new HashMap<>();
231 UnionDependencies(final TypeEffectiveStatement<?> type, final GeneratorContext context) {
232 resolveUnionDependencies(context, type);
235 private void resolveUnionDependencies(final GeneratorContext context, final TypeEffectiveStatement<?> union) {
236 for (EffectiveStatement<?, ?> stmt : union.effectiveSubstatements()) {
237 if (stmt instanceof TypeEffectiveStatement) {
238 final TypeEffectiveStatement<?> type = (TypeEffectiveStatement<?>) stmt;
239 final QName typeName = type.argument();
240 if (TypeDefinitions.IDENTITYREF.equals(typeName)) {
241 if (!identityTypes.containsKey(stmt)) {
242 identityTypes.put(stmt, TypeReference.identityRef(
243 type.streamEffectiveSubstatements(BaseEffectiveStatement.class)
244 .map(BaseEffectiveStatement::argument)
245 .map(context::resolveIdentity)
246 .collect(Collectors.toUnmodifiableList())));
248 } else if (TypeDefinitions.LEAFREF.equals(typeName)) {
249 if (!leafTypes.containsKey(stmt)) {
250 leafTypes.put(stmt, TypeReference.leafRef(context.resolveLeafref(
251 type.findFirstEffectiveSubstatementArgument(PathEffectiveStatement.class)
254 } else if (TypeDefinitions.UNION.equals(typeName)) {
255 resolveUnionDependencies(context, type);
256 } else if (!isBuiltinName(typeName) && !baseTypes.containsKey(typeName)) {
257 baseTypes.put(typeName, context.resolveTypedef(typeName));
264 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeObjectGenerator.class);
265 static final ImmutableMap<QName, Type> SIMPLE_TYPES = ImmutableMap.<QName, Type>builder()
266 .put(TypeDefinitions.BINARY, BaseYangTypes.BINARY_TYPE)
267 .put(TypeDefinitions.BOOLEAN, BaseYangTypes.BOOLEAN_TYPE)
268 .put(TypeDefinitions.DECIMAL64, BaseYangTypes.DECIMAL64_TYPE)
269 .put(TypeDefinitions.EMPTY, BaseYangTypes.EMPTY_TYPE)
270 .put(TypeDefinitions.INSTANCE_IDENTIFIER, BaseYangTypes.INSTANCE_IDENTIFIER)
271 .put(TypeDefinitions.INT8, BaseYangTypes.INT8_TYPE)
272 .put(TypeDefinitions.INT16, BaseYangTypes.INT16_TYPE)
273 .put(TypeDefinitions.INT32, BaseYangTypes.INT32_TYPE)
274 .put(TypeDefinitions.INT64, BaseYangTypes.INT64_TYPE)
275 .put(TypeDefinitions.STRING, BaseYangTypes.STRING_TYPE)
276 .put(TypeDefinitions.UINT8, BaseYangTypes.UINT8_TYPE)
277 .put(TypeDefinitions.UINT16, BaseYangTypes.UINT16_TYPE)
278 .put(TypeDefinitions.UINT32, BaseYangTypes.UINT32_TYPE)
279 .put(TypeDefinitions.UINT64, BaseYangTypes.UINT64_TYPE)
282 private final TypeEffectiveStatement<?> type;
285 * The generator corresponding to our YANG base type. It produces the superclass of our encapsulated type. If it is
286 * {@code null}, this generator is the root of the hierarchy.
288 private TypedefGenerator baseGen;
289 private TypeReference refType;
290 private List<GeneratedType> auxiliaryGeneratedTypes = List.of();
291 private UnionDependencies unionDependencies;
292 private List<AbstractTypeObjectGenerator<?>> inferred = List.of();
294 AbstractTypeObjectGenerator(final T statement, final AbstractCompositeGenerator<?> parent) {
295 super(statement, parent);
296 type = statement().findFirstEffectiveSubstatement(TypeEffectiveStatement.class).orElseThrow();
300 public final List<GeneratedType> auxiliaryGeneratedTypes() {
301 return auxiliaryGeneratedTypes;
305 final void linkDependencies(final GeneratorContext context) {
306 verify(inferred != null, "Duplicate linking of %s", this);
308 final QName typeName = type.argument();
309 if (isBuiltinName(typeName)) {
310 verify(inferred.isEmpty(), "Unexpected non-empty downstreams in %s", this);
315 final AbstractExplicitGenerator<?> prev = previous();
317 verify(prev instanceof AbstractTypeObjectGenerator, "Unexpected previous %s", prev);
318 ((AbstractTypeObjectGenerator<?>) prev).linkInferred(this);
320 linkBaseGen(context.resolveTypedef(typeName));
324 private void linkInferred(final AbstractTypeObjectGenerator<?> downstream) {
325 if (inferred == null) {
326 downstream.linkBaseGen(verifyNotNull(baseGen, "Mismatch on linking between %s and %s", this, downstream));
330 if (inferred.isEmpty()) {
331 inferred = new ArrayList<>(2);
333 inferred.add(downstream);
336 private void linkBaseGen(final TypedefGenerator upstreamBaseGen) {
337 verify(baseGen == null, "Attempted to replace base %s with %s in %s", baseGen, upstreamBaseGen, this);
338 final List<AbstractTypeObjectGenerator<?>> downstreams = verifyNotNull(inferred,
339 "Duplicated linking of %s", this);
340 baseGen = verifyNotNull(upstreamBaseGen);
341 baseGen.addDerivedGenerator(this);
344 for (AbstractTypeObjectGenerator<?> downstream : downstreams) {
345 downstream.linkBaseGen(upstreamBaseGen);
349 void bindTypeDefinition(final GeneratorContext context) {
350 if (baseGen != null) {
351 // We have registered with baseGen, it will push the type to us
355 final QName arg = type.argument();
356 if (TypeDefinitions.IDENTITYREF.equals(arg)) {
357 refType = TypeReference.identityRef(type.streamEffectiveSubstatements(BaseEffectiveStatement.class)
358 .map(BaseEffectiveStatement::argument)
359 .map(context::resolveIdentity)
360 .collect(Collectors.toUnmodifiableList()));
361 } else if (TypeDefinitions.LEAFREF.equals(arg)) {
362 final AbstractTypeObjectGenerator<?> targetGenerator = context.resolveLeafref(
363 type.findFirstEffectiveSubstatementArgument(PathEffectiveStatement.class).orElseThrow());
364 checkArgument(targetGenerator != this, "Effective model contains self-referencing leaf %s",
365 statement().argument());
366 refType = TypeReference.leafRef(targetGenerator);
367 } else if (TypeDefinitions.UNION.equals(arg)) {
368 unionDependencies = new UnionDependencies(type, context);
369 LOG.trace("Resolved union {} to dependencies {}", type, unionDependencies);
372 LOG.trace("Resolved base {} to generator {}", type, refType);
373 bindDerivedGenerators(refType);
376 final void bindTypeDefinition(final @Nullable TypeReference reference) {
378 LOG.trace("Resolved derived {} to generator {}", type, refType);
381 private static boolean isBuiltinName(final QName typeName) {
382 return YangConstants.RFC6020_YANG_MODULE.equals(typeName.getModule());
385 abstract void bindDerivedGenerators(@Nullable TypeReference reference);
388 final ClassPlacement classPlacement() {
389 if (refType != null) {
390 // Reference types never create a new type
391 return ClassPlacement.NONE;
393 if (isDerivedEnumeration()) {
394 // Types derived from an enumeration never create a new type, as that would have to be a subclass of an enum
395 // and since enums are final, that can never happen.
396 return ClassPlacement.NONE;
398 return classPlacementImpl();
401 @NonNull ClassPlacement classPlacementImpl() {
402 // TODO: make this a lot more accurate by comparing the effective delta between the base type and the effective
403 // restricted type. We should not be generating a type for constructs like:
406 // type uint8 { range 0..255; }
412 // type uint8 { range 0..100; }
416 // type foo { range 0..100; }
419 // Which is relatively easy to do for integral types, but is way more problematic for 'pattern'
420 // restrictions. Nevertheless we can define the mapping in a way which can be implemented with relative
422 return baseGen != null || SIMPLE_TYPES.containsKey(type.argument()) || isAddedByUses() || isAugmenting()
423 ? ClassPlacement.NONE : ClassPlacement.MEMBER;
427 final GeneratedType getGeneratedType(final TypeBuilderFactory builderFactory) {
428 // For derived enumerations defer to base type
429 return isDerivedEnumeration() ? baseGen.getGeneratedType(builderFactory)
430 : super.getGeneratedType(builderFactory);
433 final boolean isEnumeration() {
434 return baseGen != null ? baseGen.isEnumeration() : TypeDefinitions.ENUMERATION.equals(type.argument());
437 final boolean isDerivedEnumeration() {
438 return baseGen != null && baseGen.isEnumeration();
442 Type methodReturnType(final TypeBuilderFactory builderFactory) {
443 return methodReturnElementType(builderFactory);
446 final @NonNull Type methodReturnElementType(final @NonNull TypeBuilderFactory builderFactory) {
447 final GeneratedType generatedType = tryGeneratedType(builderFactory);
448 if (generatedType != null) {
449 // We have generated a type here, so return it. This covers 'bits', 'enumeration' and 'union'.
450 return generatedType;
453 if (refType != null) {
454 // This is a reference type of some kind. Defer to its judgement as to what the return type is.
455 return refType.methodReturnType(builderFactory);
458 final AbstractExplicitGenerator<?> prev = previous();
460 // We have been added through augment/uses, defer to the original definition
461 return prev.methodReturnType(builderFactory);
465 if (baseGen == null) {
466 final QName qname = type.argument();
467 baseType = verifyNotNull(SIMPLE_TYPES.get(qname), "Cannot resolve type %s in %s", qname, this);
469 // We are derived from a base generator. Defer to its type for return.
470 baseType = baseGen.getGeneratedType(builderFactory);
473 return restrictType(baseType, computeRestrictions(), builderFactory);
476 private static @NonNull Type restrictType(final @NonNull Type baseType, final Restrictions restrictions,
477 final TypeBuilderFactory builderFactory) {
478 if (restrictions == null || restrictions.isEmpty()) {
479 // No additional restrictions, return base type
483 if (!(baseType instanceof GeneratedTransferObject)) {
484 // This is a simple Java type, just wrap it with new restrictions
485 return Types.restrictedType(baseType, restrictions);
488 // Base type is a GTO, we need to re-adjust it with new restrictions
489 final GeneratedTransferObject gto = (GeneratedTransferObject) baseType;
490 final GeneratedTOBuilder builder = builderFactory.newGeneratedTOBuilder(gto.getIdentifier());
491 final GeneratedTransferObject parent = gto.getSuperType();
492 if (parent != null) {
493 builder.setExtendsType(parent);
495 builder.setRestrictions(restrictions);
496 for (GeneratedProperty gp : gto.getProperties()) {
497 builder.addProperty(gp.getName())
498 .setValue(gp.getValue())
499 .setReadOnly(gp.isReadOnly())
500 .setAccessModifier(gp.getAccessModifier())
501 .setReturnType(gp.getReturnType())
502 .setFinal(gp.isFinal())
503 .setStatic(gp.isStatic());
505 return builder.build();
509 final void addAsGetterMethodOverride(final GeneratedTypeBuilderBase<?> builder,
510 final TypeBuilderFactory builderFactory) {
511 if (!(refType instanceof ResolvedLeafref)) {
512 // We are not dealing with a leafref or have nothing to add
516 final AbstractTypeObjectGenerator<?> prev =
517 (AbstractTypeObjectGenerator<?>) verifyNotNull(previous(), "Missing previous link in %s", this);
518 if (prev.refType instanceof ResolvedLeafref) {
519 // We should be already inheriting the correct type
523 // Note: this may we wrapped for leaf-list, hence we need to deal with that
524 final Type myType = methodReturnType(builderFactory);
525 LOG.trace("Override of {} to {}", this, myType);
526 final MethodSignatureBuilder getter = constructGetter(builder, myType);
527 getter.addAnnotation(OVERRIDE_ANNOTATION);
528 annotateDeprecatedIfNecessary(getter);
531 final @Nullable Restrictions computeRestrictions() {
532 final List<ValueRange> length = type.findFirstEffectiveSubstatementArgument(LengthEffectiveStatement.class)
534 final List<ValueRange> range = type.findFirstEffectiveSubstatementArgument(RangeEffectiveStatement.class)
536 final List<PatternExpression> patterns = type.streamEffectiveSubstatements(PatternEffectiveStatement.class)
537 .map(PatternEffectiveStatement::argument)
538 .collect(Collectors.toUnmodifiableList());
540 if (length.isEmpty() && range.isEmpty() && patterns.isEmpty()) {
544 return BindingGeneratorUtil.getRestrictions(extractTypeDefinition());
548 final GeneratedType createTypeImpl(final TypeBuilderFactory builderFactory) {
549 if (baseGen != null) {
550 final GeneratedType baseType = baseGen.getGeneratedType(builderFactory);
551 verify(baseType instanceof GeneratedTransferObject, "Unexpected base type %s", baseType);
552 return createDerivedType(builderFactory, (GeneratedTransferObject) baseType);
555 // FIXME: why do we need this boolean?
556 final boolean isTypedef = this instanceof TypedefGenerator;
557 final QName arg = type.argument();
558 if (TypeDefinitions.BITS.equals(arg)) {
559 return createBits(builderFactory, typeName(), currentModule(), extractTypeDefinition(), isTypedef);
560 } else if (TypeDefinitions.ENUMERATION.equals(arg)) {
561 return createEnumeration(builderFactory, typeName(), currentModule(),
562 (EnumTypeDefinition) extractTypeDefinition());
563 } else if (TypeDefinitions.UNION.equals(arg)) {
564 final List<GeneratedType> tmp = new ArrayList<>(1);
565 final GeneratedTransferObject ret = createUnion(tmp, builderFactory, statement(), unionDependencies,
566 typeName(), currentModule(), type, isTypedef, extractTypeDefinition());
567 auxiliaryGeneratedTypes = List.copyOf(tmp);
570 return createSimple(builderFactory, typeName(), currentModule(),
571 verifyNotNull(SIMPLE_TYPES.get(arg), "Unhandled type %s", arg), extractTypeDefinition());
575 private static @NonNull GeneratedTransferObject createBits(final TypeBuilderFactory builderFactory,
576 final JavaTypeName typeName, final ModuleGenerator module, final TypeDefinition<?> typedef,
577 final boolean isTypedef) {
578 final GeneratedTOBuilder builder = builderFactory.newGeneratedTOBuilder(typeName);
579 builder.setTypedef(isTypedef);
580 builder.addImplementsType(BindingTypes.TYPE_OBJECT);
581 builder.setBaseType(typedef);
583 for (Bit bit : ((BitsTypeDefinition) typedef).getBits()) {
584 final String name = bit.getName();
585 GeneratedPropertyBuilder genPropertyBuilder = builder.addProperty(BindingMapping.getPropertyName(name));
586 genPropertyBuilder.setReadOnly(true);
587 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
589 builder.addEqualsIdentity(genPropertyBuilder);
590 builder.addHashIdentity(genPropertyBuilder);
591 builder.addToStringProperty(genPropertyBuilder);
594 // builder.setSchemaPath(typedef.getPath());
595 builder.setModuleName(module.statement().argument().getLocalName());
596 addCodegenInformation(typedef, builder);
597 annotateDeprecatedIfNecessary(typedef, builder);
598 makeSerializable(builder);
599 return builder.build();
602 private static @NonNull Enumeration createEnumeration(final TypeBuilderFactory builderFactory,
603 final JavaTypeName typeName, final ModuleGenerator module, final EnumTypeDefinition typedef) {
604 // TODO units for typedef enum
605 final AbstractEnumerationBuilder builder = builderFactory.newEnumerationBuilder(typeName);
607 typedef.getDescription().map(BindingGeneratorUtil::encodeAngleBrackets)
608 .ifPresent(builder::setDescription);
609 typedef.getReference().ifPresent(builder::setReference);
611 builder.setModuleName(module.statement().argument().getLocalName());
612 builder.updateEnumPairsFromEnumTypeDef(typedef);
613 return builder.toInstance();
616 private static @NonNull GeneratedType createSimple(final TypeBuilderFactory builderFactory,
617 final JavaTypeName typeName, final ModuleGenerator module, final Type javaType,
618 final TypeDefinition<?> typedef) {
619 final String moduleName = module.statement().argument().getLocalName();
620 final GeneratedTOBuilder builder = builderFactory.newGeneratedTOBuilder(typeName);
621 builder.setTypedef(true);
622 builder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
624 final GeneratedPropertyBuilder genPropBuilder = builder.addProperty(TypeConstants.VALUE_PROP);
625 genPropBuilder.setReturnType(javaType);
626 builder.addEqualsIdentity(genPropBuilder);
627 builder.addHashIdentity(genPropBuilder);
628 builder.addToStringProperty(genPropBuilder);
630 builder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
632 // builder.setSchemaPath(typedef.getPath());
633 builder.setModuleName(moduleName);
634 addCodegenInformation(typedef, builder);
636 annotateDeprecatedIfNecessary(typedef, builder);
638 if (javaType instanceof ConcreteType
639 // FIXME: This looks very suspicious: we should by checking for Types.STRING
640 && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
641 addStringRegExAsConstant(builder, resolveRegExpressions(typedef));
643 addUnits(builder, typedef);
645 makeSerializable(builder);
646 return builder.build();
649 private static @NonNull GeneratedTransferObject createUnion(final List<GeneratedType> auxiliaryGeneratedTypes,
650 final TypeBuilderFactory builderFactory, final EffectiveStatement<?, ?> definingStatement,
651 final UnionDependencies dependencies, final JavaTypeName typeName, final ModuleGenerator module,
652 final TypeEffectiveStatement<?> type, final boolean isTypedef, final TypeDefinition<?> typedef) {
653 final GeneratedUnionBuilder builder = builderFactory.newGeneratedUnionBuilder(typeName);
654 builder.addImplementsType(BindingTypes.TYPE_OBJECT);
655 builder.setIsUnion(true);
657 // builder.setSchemaPath(typedef.getPath());
658 builder.setModuleName(module.statement().argument().getLocalName());
659 addCodegenInformation(definingStatement, builder);
661 annotateDeprecatedIfNecessary(definingStatement, builder);
663 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
664 // also negation information and hence guarantees uniqueness.
665 final Map<String, String> expressions = new HashMap<>();
667 // Linear list of properties generated from subtypes. We need this information for runtime types, as it allows
668 // direct mapping of type to corresponding property -- without having to resort to re-resolving the leafrefs
670 final List<String> typeProperties = new ArrayList<>();
672 for (EffectiveStatement<?, ?> stmt : type.effectiveSubstatements()) {
673 if (stmt instanceof TypeEffectiveStatement) {
674 final TypeEffectiveStatement<?> subType = (TypeEffectiveStatement<?>) stmt;
675 final QName subName = subType.argument();
676 final String localName = subName.getLocalName();
678 String propSource = localName;
679 final Type generatedType;
680 if (TypeDefinitions.UNION.equals(subName)) {
681 final JavaTypeName subUnionName = typeName.createEnclosed(
682 provideAvailableNameForGenTOBuilder(typeName.simpleName()));
683 final GeneratedTransferObject subUnion = createUnion(auxiliaryGeneratedTypes, builderFactory,
684 definingStatement, dependencies, subUnionName, module, subType, isTypedef,
685 subType.getTypeDefinition());
686 builder.addEnclosingTransferObject(subUnion);
687 propSource = subUnionName.simpleName();
688 generatedType = subUnion;
689 } else if (TypeDefinitions.ENUMERATION.equals(subName)) {
690 final Enumeration subEnumeration = createEnumeration(builderFactory,
691 typeName.createEnclosed(BindingMapping.getClassName(localName), "$"), module,
692 (EnumTypeDefinition) subType.getTypeDefinition());
693 builder.addEnumeration(subEnumeration);
694 generatedType = subEnumeration;
695 } else if (TypeDefinitions.BITS.equals(subName)) {
696 final GeneratedTransferObject subBits = createBits(builderFactory,
697 typeName.createEnclosed(BindingMapping.getClassName(localName), "$"), module,
698 subType.getTypeDefinition(), isTypedef);
699 builder.addEnclosingTransferObject(subBits);
700 generatedType = subBits;
701 } else if (TypeDefinitions.IDENTITYREF.equals(subName)) {
702 generatedType = verifyNotNull(dependencies.identityTypes.get(stmt),
703 "Cannot resolve identityref %s in %s", stmt, definingStatement)
704 .methodReturnType(builderFactory);
705 } else if (TypeDefinitions.LEAFREF.equals(subName)) {
706 generatedType = verifyNotNull(dependencies.leafTypes.get(stmt),
707 "Cannot resolve leafref %s in %s", stmt, definingStatement)
708 .methodReturnType(builderFactory);
710 Type baseType = SIMPLE_TYPES.get(subName);
711 if (baseType == null) {
712 // This has to be a reference to a typedef, let's lookup it up and pick up its type
713 final AbstractTypeObjectGenerator<?> baseGen = verifyNotNull(
714 dependencies.baseTypes.get(subName), "Cannot resolve base type %s in %s", subName,
716 baseType = baseGen.methodReturnType(builderFactory);
718 // FIXME: This is legacy behaviour for leafrefs:
719 if (baseGen.refType instanceof TypeReference.Leafref) {
720 // if there already is a compatible property, do not generate a new one
721 final Type search = baseType;
723 final String matching = builder.getProperties().stream()
724 .filter(prop -> search == ((GeneratedPropertyBuilderImpl) prop).getReturnType())
726 .map(GeneratedPropertyBuilder::getName)
728 if (matching != null) {
729 typeProperties.add(matching);
733 // ... otherwise generate this weird property name
734 propSource = BindingMapping.getUnionLeafrefMemberName(builder.getName(),
739 expressions.putAll(resolveRegExpressions(subType.getTypeDefinition()));
741 generatedType = restrictType(baseType,
742 BindingGeneratorUtil.getRestrictions(type.getTypeDefinition()), builderFactory);
745 final String propName = BindingMapping.getPropertyName(propSource);
746 typeProperties.add(propName);
748 if (builder.containsProperty(propName)) {
750 * FIXME: this is not okay, as we are ignoring multiple base types. For example in the case of:
761 * We are ending up losing the information about 8..10 being an alternative. This is also the case
762 * for leafrefs -- we are performing property compression as well (see above). While it is alluring
763 * to merge these into 'length 1..5|8..10', that may not be generally feasible.
765 * We should resort to a counter of conflicting names, i.e. the second string would be mapped to
766 * 'string1' or similar.
771 final GeneratedPropertyBuilder propBuilder = builder
772 .addProperty(propName)
773 .setReturnType(generatedType);
775 builder.addEqualsIdentity(propBuilder);
776 builder.addHashIdentity(propBuilder);
777 builder.addToStringProperty(propBuilder);
781 // Record property names if needed
782 builder.setTypePropertyNames(typeProperties);
784 addStringRegExAsConstant(builder, expressions);
785 addUnits(builder, typedef);
787 makeSerializable(builder);
788 final GeneratedTransferObject ret = builder.build();
790 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
791 // so we are placing the builder alongside the union.
792 final GeneratedTOBuilder unionBuilder = builderFactory.newGeneratedTOBuilder(unionBuilderName(typeName));
793 unionBuilder.setIsUnionBuilder(true);
794 unionBuilder.addMethod("getDefaultInstance")
795 .setAccessModifier(AccessModifier.PUBLIC)
798 .addParameter(Types.STRING, "defaultValue");
799 auxiliaryGeneratedTypes.add(unionBuilder.build());
804 // FIXME: this can be a source of conflicts as we are not guarding against nesting
805 private static @NonNull JavaTypeName unionBuilderName(final JavaTypeName unionName) {
806 final StringBuilder sb = new StringBuilder();
807 for (String part : unionName.localNameComponents()) {
810 return JavaTypeName.create(unionName.packageName(), sb.append(BindingMapping.BUILDER_SUFFIX).toString());
813 // FIXME: we should not rely on TypeDefinition
814 abstract @NonNull TypeDefinition<?> extractTypeDefinition();
816 abstract @NonNull GeneratedTransferObject createDerivedType(@NonNull TypeBuilderFactory builderFactory,
817 @NonNull GeneratedTransferObject baseType);
820 * Adds to the {@code genTOBuilder} the constant which contains regular expressions from the {@code expressions}.
822 * @param genTOBuilder generated TO builder to which are {@code regular expressions} added
823 * @param expressions list of string which represent regular expressions
825 static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final Map<String, String> expressions) {
826 if (!expressions.isEmpty()) {
827 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
828 ImmutableMap.copyOf(expressions));
833 * Converts the pattern constraints from {@code typedef} to the list of the strings which represents these
836 * @param typedef extended type in which are the pattern constraints sought
837 * @return list of strings which represents the constraint patterns
838 * @throws IllegalArgumentException if <code>typedef</code> equals null
840 static Map<String, String> resolveRegExpressions(final TypeDefinition<?> typedef) {
841 return typedef instanceof StringTypeDefinition
842 // TODO: run diff against base ?
843 ? resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints())
848 * Converts the pattern constraints to the list of the strings which represents these constraints.
850 * @param patternConstraints list of pattern constraints
851 * @return list of strings which represents the constraint patterns
853 private static Map<String, String> resolveRegExpressions(final List<PatternConstraint> patternConstraints) {
854 if (patternConstraints.isEmpty()) {
855 return ImmutableMap.of();
858 final Map<String, String> regExps = Maps.newHashMapWithExpectedSize(patternConstraints.size());
859 for (PatternConstraint patternConstraint : patternConstraints) {
860 String regEx = patternConstraint.getJavaPatternString();
862 // The pattern can be inverted
863 final Optional<ModifierKind> optModifier = patternConstraint.getModifier();
864 if (optModifier.isPresent()) {
865 regEx = applyModifier(optModifier.get(), regEx);
868 regExps.put(regEx, patternConstraint.getRegularExpressionString());
875 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
876 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
877 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
879 * @param name string with name of augmented node
880 * @return string with the number suffix incremented by one (or 1 is added)
882 private static String provideAvailableNameForGenTOBuilder(final String name) {
883 final int dollar = name.indexOf('$');
888 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
889 verify(newSuffix > 0, "Suffix counter overflow");
890 return name.substring(0, dollar + 1) + newSuffix;
893 private static String applyModifier(final ModifierKind modifier, final String pattern) {
896 return RegexPatterns.negatePatternString(pattern);
898 LOG.warn("Ignoring unhandled modifier {}", modifier);