Fix augmentation pointing to a grouping action's input
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / generator / impl / AbstractTypeGenerator.java
index c937a2fd54d2ceb8f37897b097d6a9603d726d31..f536e84bcdec3393482d0b197be211dc508c1ed0 100644 (file)
@@ -19,27 +19,29 @@ import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
+import static org.opendaylight.mdsal.binding.model.util.BindingTypes.QNAME;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_INPUT;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_OUTPUT;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.action;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
+import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentation;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
+import static org.opendaylight.mdsal.binding.model.util.BindingTypes.instanceNotification;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListAction;
+import static org.opendaylight.mdsal.binding.model.util.BindingTypes.keyedListNotification;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.opaqueObject;
 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
 import static org.opendaylight.mdsal.binding.model.util.Types.STRING;
-import static org.opendaylight.mdsal.binding.model.util.Types.augmentationTypeFor;
 import static org.opendaylight.mdsal.binding.model.util.Types.classType;
 import static org.opendaylight.mdsal.binding.model.util.Types.listTypeFor;
 import static org.opendaylight.mdsal.binding.model.util.Types.listenableFutureTypeFor;
 import static org.opendaylight.mdsal.binding.model.util.Types.primitiveVoidType;
-import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
 import static org.opendaylight.mdsal.binding.model.util.Types.wildcardTypeFor;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
@@ -51,6 +53,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.util.AbstractMap.SimpleImmutableEntry;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -99,6 +102,7 @@ import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
+import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
@@ -107,11 +111,11 @@ import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
+import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.api.Status;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.UsesNode;
@@ -119,7 +123,6 @@ import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
@@ -258,11 +261,8 @@ abstract class AbstractTypeGenerator {
     private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
         final Module module = context.module();
         checkArgument(module.getName() != null, "Module name cannot be NULL.");
-        final DataNodeIterator it = new DataNodeIterator(module);
-        final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
-        checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
 
-        for (final TypeDefinition<?> typedef : typeDefinitions) {
+        for (final TypeDefinition<?> typedef : SchemaNodeUtils.getAllTypeDefinitions(module)) {
             if (typedef != null) {
                 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef,  typedef);
                 if (type != null) {
@@ -280,7 +280,7 @@ abstract class AbstractTypeGenerator {
         }
         final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, baseInterface);
         defaultImplementedInterace(genType);
-        annotateDeprecatedIfNecessary(node.getStatus(), genType);
+        annotateDeprecatedIfNecessary(node, genType);
 
         final Module module = context.module();
         genType.setModuleName(module.getName());
@@ -301,6 +301,7 @@ abstract class AbstractTypeGenerator {
             constructGetter(parent, genType, node);
             resolveDataSchemaNodes(context, genType, genType, node.getChildNodes(), inGrouping);
             actionsToGenType(context, genType, node, null, inGrouping);
+            notificationsToGenType(context, genType, node, null, inGrouping);
         }
     }
 
@@ -308,35 +309,39 @@ abstract class AbstractTypeGenerator {
             final Type baseInterface, final ListSchemaNode node, final boolean inGrouping) {
         final GeneratedTypeBuilder genType = processDataSchemaNode(context, baseInterface, node, inGrouping);
         if (genType != null) {
+            final List<String> listKeys = listKeys(node);
+            final GeneratedTOBuilder keyTypeBuilder;
+            if (!listKeys.isEmpty()) {
+                keyTypeBuilder = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
+                    packageNameForGeneratedType(context.modulePackageName(), node.getPath()),
+                    BindingMapping.getClassName(node.getQName().getLocalName() + "Key")))
+                        .addImplementsType(identifier(genType));
+                genType.addImplementsType(identifiable(keyTypeBuilder));
+            } else {
+                keyTypeBuilder = null;
+            }
+
             final ParameterizedType listType = listTypeFor(genType);
             constructGetter(parent, listType, node);
             constructNonnull(parent, listType, node);
 
-            final List<String> listKeys = listKeys(node);
-            final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
-            if (genTOBuilder != null) {
-                final Type identifierMarker = identifier(genType);
-                final Type identifiableMarker = identifiable(genTOBuilder);
-                genTOBuilder.addImplementsType(identifierMarker);
-                genType.addImplementsType(identifiableMarker);
-
-            }
-            actionsToGenType(context, genType, node, genTOBuilder, inGrouping);
+            actionsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
+            notificationsToGenType(context, genType, node, keyTypeBuilder, inGrouping);
 
             for (final DataSchemaNode schemaNode : node.getChildNodes()) {
                 if (!schemaNode.isAugmenting()) {
-                    addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys, inGrouping);
+                    addSchemaNodeToListBuilders(context, schemaNode, genType, keyTypeBuilder, listKeys, inGrouping);
                 }
             }
 
             // serialVersionUID
-            if (genTOBuilder != null) {
+            if (keyTypeBuilder != null) {
                 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
-                prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
-                genTOBuilder.setSUID(prop);
+                prop.setValue(Long.toString(computeDefaultSUID(keyTypeBuilder)));
+                keyTypeBuilder.setSUID(prop);
             }
 
-            typeBuildersToGenTypes(context, genType, genTOBuilder);
+            typeBuildersToGenTypes(context, genType, keyTypeBuilder);
         }
     }
 
@@ -424,12 +429,19 @@ abstract class AbstractTypeGenerator {
     private <T extends DataNodeContainer & ActionNodeContainer> void actionsToGenType(final ModuleContext context,
             final Type parent, final T parentSchema, final Type keyType, final boolean inGrouping) {
         for (final ActionDefinition action : parentSchema.getActions()) {
+            if (action.isAugmenting()) {
+                continue;
+            }
+
             final GeneratedType input;
             final GeneratedType output;
             if (action.isAddedByUses()) {
                 final ActionDefinition orig = findOrigAction(parentSchema, action).get();
-                input = context.getChildNode(orig.getInput().getPath()).build();
-                output = context.getChildNode(orig.getOutput().getPath()).build();
+                // Original definition may live in a different module, make sure we account for that
+                final ModuleContext origContext = moduleContext(
+                    orig.getPath().getPathFromRoot().iterator().next().getModule());
+                input = context.addAliasType(origContext, orig.getInput(), action.getInput());
+                output = context.addAliasType(origContext, orig.getOutput(), action.getOutput());
             } else {
                 input = actionContainer(context, RPC_INPUT, action.getInput(), inGrouping);
                 output = actionContainer(context, RPC_OUTPUT, action.getOutput(), inGrouping);
@@ -446,7 +458,7 @@ abstract class AbstractTypeGenerator {
                 qnameConstant(builder, JavaTypeName.create(context.modulePackageName(),
                     BindingMapping.MODULE_INFO_CLASS_NAME), qname.getLocalName());
 
-                annotateDeprecatedIfNecessary(action.getStatus(), builder);
+                annotateDeprecatedIfNecessary(action, builder);
                 builder.addImplementsType(keyType != null ? keyedListAction(parent, keyType, input, output)
                         : action(parent, input, output));
 
@@ -457,10 +469,12 @@ abstract class AbstractTypeGenerator {
     }
 
     private Optional<ActionDefinition> findOrigAction(final DataNodeContainer parent, final ActionDefinition action) {
+        final QName qname = action.getQName();
         for (UsesNode uses : parent.getUses()) {
             final GroupingDefinition grp = findUsedGrouping(uses);
-            final Optional<ActionDefinition> found = grp.getActions().stream()
-                    .filter(act -> action.getQName().equals(act.getQName())).findFirst();
+            // Target grouping may reside in a different module, hence we need to rebind the QName to match grouping's
+            // namespace
+            final Optional<ActionDefinition> found = grp.findAction(qname.withModule(grp.getQName().getModule()));
             if (found.isPresent()) {
                 final ActionDefinition result = found.get();
                 return result.isAddedByUses() ? findOrigAction(grp, result) : found;
@@ -510,7 +524,7 @@ abstract class AbstractTypeGenerator {
         for (final RpcDefinition rpc : rpcDefinitions) {
             if (rpc != null) {
                 final String rpcName = BindingMapping.getClassName(rpc.getQName());
-                final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
+                final String rpcMethodName = BindingMapping.getRpcMethodName(rpc.getQName());
                 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
 
                 // Do not refer to annotation class, as it may not be available at runtime
@@ -536,7 +550,7 @@ abstract class AbstractTypeGenerator {
         outType.addImplementsType(type);
         outType.addImplementsType(augmentable(outType));
         defaultImplementedInterace(outType);
-        annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
+        annotateDeprecatedIfNecessary(rpc, outType);
         resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes(), false);
         context.addChildNodeType(schema, outType);
         return outType.build();
@@ -576,7 +590,7 @@ abstract class AbstractTypeGenerator {
                 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
                     context.modulePackageName(), notification, DATA_OBJECT, context);
                 defaultImplementedInterace(notificationInterface);
-                annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
+                annotateDeprecatedIfNecessary(notification, notificationInterface);
                 notificationInterface.addImplementsType(NOTIFICATION);
                 context.addChildNodeType(notification, notificationInterface);
 
@@ -594,6 +608,40 @@ abstract class AbstractTypeGenerator {
         context.addTopLevelNodeType(listenerInterface);
     }
 
+    private <T extends DataNodeContainer & NotificationNodeContainer> void notificationsToGenType(
+            final ModuleContext context, final Type parent, final T parentSchema, final Type keyType,
+            final boolean inGrouping) {
+        final Set<NotificationDefinition> notifications = parentSchema.getNotifications();
+        if (notifications.isEmpty()) {
+            return;
+        }
+
+        for (NotificationDefinition notif : notifications) {
+            if (notif.isAugmenting()) {
+                continue;
+            }
+            if (parentSchema instanceof GroupingDefinition) {
+                // Notifications cannot be really established, as they lack instantiation context, which would be
+                // completely described by an InstanceIdentifier -- hence we cannot create a binding class
+                continue;
+            }
+
+            processUsesAugments(notif, context, false);
+
+            final GeneratedTypeBuilder notifInterface = addDefaultInterfaceDefinition(
+                packageNameForGeneratedType(context.modulePackageName(), notif.getPath()), notif, DATA_OBJECT, context);
+            defaultImplementedInterace(notifInterface);
+            annotateDeprecatedIfNecessary(notif, notifInterface);
+
+            notifInterface.addImplementsType(keyType != null ? keyedListNotification(notifInterface, parent, keyType)
+                    : instanceNotification(notifInterface, parent));
+            context.addChildNodeType(notif, notifInterface);
+
+            // Notification object
+            resolveDataSchemaNodes(context, notifInterface, notifInterface, notif.getChildNodes(), false);
+        }
+    }
+
     /**
      * Converts all <b>identities</b> of the module to the list of
      * <code>Type</code> objects.
@@ -673,7 +721,7 @@ abstract class AbstractTypeGenerator {
 
     private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
             final JavaTypeName yangModuleInfo, final String localName) {
-        return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
+        return toBuilder.addConstant(QNAME, BindingMapping.QNAME_STATIC_FIELD_NAME,
             new SimpleImmutableEntry<>(yangModuleInfo, localName));
     }
 
@@ -696,12 +744,13 @@ abstract class AbstractTypeGenerator {
             // node of grouping is resolved to the method.
             final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
             narrowImplementedInterface(genType);
-            annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
+            annotateDeprecatedIfNecessary(grouping, genType);
             context.addGroupingType(grouping, genType);
             resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes(), true);
             groupingsToGenTypes(context, grouping.getGroupings());
             processUsesAugments(grouping, context, true);
             actionsToGenType(context, genType, grouping, null, true);
+            notificationsToGenType(context, genType, grouping, null, true);
         }
     }
 
@@ -785,22 +834,30 @@ abstract class AbstractTypeGenerator {
             throw new IllegalArgumentException("augment target not found: " + targetPath);
         }
 
-        GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
-        if (targetTypeBuilder == null) {
-            targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
-        }
-        if (targetTypeBuilder == null) {
-            throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
+        if (targetSchemaNode instanceof ChoiceSchemaNode) {
+            final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
+            checkState(builder != null, "Choice target type not generated for %s", targetSchemaNode);
+            generateTypesFromAugmentedChoiceCases(context, builder.build(), (ChoiceSchemaNode) targetSchemaNode,
+                augSchema.getChildNodes(), null, false);
+            return;
         }
 
-        if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
-            final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
-            addRawAugmentGenTypeDefinition(context, targetType, augSchema, false);
-
+        final JavaTypeName targetName;
+        if (targetSchemaNode instanceof CaseSchemaNode) {
+            final GeneratedTypeBuilder builder = findCaseByPath(targetSchemaNode.getPath());
+            checkState(builder != null, "Case target type not generated for %s", targetSchemaNode);
+            targetName = builder.getIdentifier();
         } else {
-            generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
-                    (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null, false);
+            final GeneratedTypeBuilder builder = findChildNodeByPath(targetSchemaNode.getPath());
+            if (builder == null) {
+                targetName = findAliasByPath(targetSchemaNode.getPath());
+                checkState(targetName != null, "Target type not yet generated: %s", targetSchemaNode);
+            } else {
+                targetName = builder.getIdentifier();
+            }
         }
+
+        addRawAugmentGenTypeDefinition(context, new ReferencedTypeImpl(targetName), augSchema, false);
     }
 
     private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
@@ -926,17 +983,20 @@ abstract class AbstractTypeGenerator {
         augTypeBuilder.addImplementsType(DATA_OBJECT);
         defaultImplementedInterace(augTypeBuilder);
 
-        augTypeBuilder.addImplementsType(augmentationTypeFor(targetTypeRef));
-        annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
+        augTypeBuilder.addImplementsType(augmentation(targetTypeRef));
+        annotateDeprecatedIfNecessary(augSchema, augTypeBuilder);
         addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
 
         augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes(), inGrouping);
+        actionsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
+        notificationsToGenType(context, augTypeBuilder, augSchema, null, inGrouping);
+
         augmentBuilders.put(augTypeName, augTypeBuilder);
 
         if (!augSchema.getChildNodes().isEmpty()) {
             context.addTypeToAugmentation(augTypeBuilder, augSchema);
-
         }
+
         context.addAugmentType(augTypeBuilder);
         return augTypeBuilder;
     }
@@ -1085,7 +1145,7 @@ abstract class AbstractTypeGenerator {
                 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
                 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
             choiceTypeBuilder.addImplementsType(choiceIn(parent));
-            annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
+            annotateDeprecatedIfNecessary(choiceNode, choiceTypeBuilder);
             context.addChildNodeType(choiceNode, choiceTypeBuilder);
 
             final GeneratedType choiceType = choiceTypeBuilder.build();
@@ -1103,7 +1163,7 @@ abstract class AbstractTypeGenerator {
                 BindingMapping.getClassName(anyNode.getQName())), anyNode);
             anyxmlTypeBuilder.addImplementsType(opaqueObject(anyxmlTypeBuilder)).addImplementsType(childOf(parent));
             defaultImplementedInterace(anyxmlTypeBuilder);
-            annotateDeprecatedIfNecessary(anyNode.getStatus(), anyxmlTypeBuilder);
+            annotateDeprecatedIfNecessary(anyNode, anyxmlTypeBuilder);
             context.addChildNodeType(anyNode, anyxmlTypeBuilder);
 
             constructGetter(parent, anyxmlTypeBuilder.build(), anyNode);
@@ -1135,7 +1195,7 @@ abstract class AbstractTypeGenerator {
                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
                 caseTypeBuilder.addImplementsType(refChoiceType);
                 defaultImplementedInterace(caseTypeBuilder);
-                annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
+                annotateDeprecatedIfNecessary(caseNode, caseTypeBuilder);
                 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
                 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
                 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
@@ -1701,7 +1761,7 @@ abstract class AbstractTypeGenerator {
             getterMethodName(node.getQName().getLocalName(), returnType));
         getMethod.setReturnType(returnType);
 
-        annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
+        annotateDeprecatedIfNecessary(node, getMethod);
         addComment(getMethod, node);
 
         return getMethod;
@@ -1712,7 +1772,7 @@ abstract class AbstractTypeGenerator {
         final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
             BindingMapping.getNonnullMethodName(node.getQName().getLocalName()));
         getMethod.setReturnType(returnType).setDefault(true);
-        annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
+        annotateDeprecatedIfNecessary(node, getMethod);
     }
 
     /**
@@ -1759,6 +1819,8 @@ abstract class AbstractTypeGenerator {
                 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode, inGrouping);
             } else if (schemaNode instanceof ListSchemaNode) {
                 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode, inGrouping);
+            } else if (schemaNode instanceof AnyXmlSchemaNode || schemaNode instanceof AnyDataSchemaNode) {
+                opaqueToGeneratedType(context, typeBuilder, schemaNode);
             }
         }
     }
@@ -1784,32 +1846,19 @@ abstract class AbstractTypeGenerator {
      *         an empty list is returned.
      */
     private static List<String> listKeys(final ListSchemaNode list) {
-        final List<String> listKeys = new ArrayList<>();
-
         final List<QName> keyDefinition = list.getKeyDefinition();
-        if (keyDefinition != null) {
-            for (final QName keyDef : keyDefinition) {
-                listKeys.add(keyDef.getLocalName());
-            }
-        }
-        return listKeys;
-    }
-
-    /**
-     * Generates for the <code>list</code> which contains any list keys special generated TO builder.
-     *
-     * @param packageName string with package name to which the list belongs
-     * @param list list schema node which is source of data about the list name
-     * @return generated TO builder which represents the keys of the <code>list</code> or null if <code>list</code> is
-     *         null or list of key definitions is null or empty.
-     */
-    private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
-        if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
-            return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
-                packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
-                BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
+        switch (keyDefinition.size()) {
+            case 0:
+                return Collections.emptyList();
+            case 1:
+                return Collections.singletonList(keyDefinition.get(0).getLocalName());
+            default:
+                final List<String> listKeys = new ArrayList<>(keyDefinition.size());
+                for (final QName keyDef : keyDefinition) {
+                    listKeys.add(keyDef.getLocalName());
+                }
+                return listKeys;
         }
-        return null;
     }
 
     /**
@@ -1826,8 +1875,7 @@ abstract class AbstractTypeGenerator {
     private Type addTOToTypeBuilder(final UnionTypeDefinition typeDef,
             final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
         final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
-            typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
-            typeDef, leaf);
+            allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, leaf);
 
         checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
         final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
@@ -1860,11 +1908,9 @@ abstract class AbstractTypeGenerator {
     private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
             final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
         final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
-            typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
-            typeDef, parentModule.getName());
+            allocateNestedType(typeBuilder.getIdentifier(), leaf.getQName()), typeDef, parentModule.getName());
         typeBuilder.addEnclosingTransferObject(genTOBuilder);
         return genTOBuilder;
-
     }
 
     /**
@@ -1891,6 +1937,16 @@ abstract class AbstractTypeGenerator {
         return builder;
     }
 
+    private JavaTypeName findAliasByPath(final SchemaPath path) {
+        for (final ModuleContext ctx : genCtx.values()) {
+            final JavaTypeName result = ctx.getAlias(path);
+            if (result != null) {
+                return result;
+            }
+        }
+        return null;
+    }
+
     private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
         for (final ModuleContext ctx : genCtx.values()) {
             final GeneratedTypeBuilder result = ctx.getChildNode(path);
@@ -1921,9 +1977,23 @@ abstract class AbstractTypeGenerator {
         return null;
     }
 
-    private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
-        if (status == Status.DEPRECATED) {
-            builder.addAnnotation(DEPRECATED_ANNOTATION);
+    private static JavaTypeName allocateNestedType(final JavaTypeName parent, final QName child) {
+        // Single '$' suffix cannot come from user, this mirrors AbstractGeneratedTypeBuilder.addEnumeration()
+        return parent.createEnclosed(BindingMapping.getClassName(child), "$");
+    }
+
+    private static void annotateDeprecatedIfNecessary(final WithStatus node, final AnnotableTypeBuilder builder) {
+        switch (node.getStatus()) {
+            case DEPRECATED:
+            case OBSOLETE:
+                // FIXME: we really want to use a pre-made annotation
+                builder.addAnnotation(DEPRECATED_ANNOTATION);
+                break;
+            case CURRENT:
+                // No-op
+                break;
+            default:
+                throw new IllegalStateException("Unhandled status in " + node);
         }
     }