Retain DeclarationReference in DeclaredStatements
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / type / AbstractTypeStatementSupport.java
index 65950677cc0a54f1bef68bc9baa5cbd9a0a346b5..f517f08f301629ed8cb83b70893a0c92fd8c3a62 100644 (file)
@@ -7,32 +7,30 @@
  */
 package org.opendaylight.yangtools.yang.parser.rfc7950.stmt.type;
 
-import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Verify.verifyNotNull;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import java.math.BigDecimal;
 import java.util.Collection;
-import java.util.Optional;
 import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.yangtools.yang.common.Empty;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.Uint32;
-import org.opendaylight.yangtools.yang.common.YangVersion;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
+import org.opendaylight.yangtools.yang.model.api.meta.DeclarationReference;
 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.BitEffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.EnumEffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.FractionDigitsEffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.LengthEffectiveStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.PatternEffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.RangeEffectiveStatement;
+import org.opendaylight.yangtools.yang.model.api.stmt.RequireInstanceEffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.TypeEffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.TypeStatement;
 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
-import org.opendaylight.yangtools.yang.model.api.stmt.TypedefStatement;
-import org.opendaylight.yangtools.yang.model.api.stmt.ValueEffectiveStatement;
 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
@@ -48,20 +46,30 @@ import org.opendaylight.yangtools.yang.model.api.type.Int32TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.Int64TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.Int8TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.RangeRestrictedTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.TypeDefinitions;
 import org.opendaylight.yangtools.yang.model.api.type.Uint16TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.Uint32TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.Uint64TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.Uint8TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.type.BitsTypeBuilder;
-import org.opendaylight.yangtools.yang.model.util.type.EnumerationTypeBuilder;
-import org.opendaylight.yangtools.yang.model.util.type.InvalidLengthConstraintException;
-import org.opendaylight.yangtools.yang.model.util.type.LengthRestrictedTypeBuilder;
-import org.opendaylight.yangtools.yang.model.util.type.RangeRestrictedTypeBuilder;
-import org.opendaylight.yangtools.yang.model.util.type.RestrictedTypes;
-import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
+import org.opendaylight.yangtools.yang.model.parser.api.YangParserConfiguration;
+import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatementDecorators;
+import org.opendaylight.yangtools.yang.model.ri.stmt.DeclaredStatements;
+import org.opendaylight.yangtools.yang.model.ri.type.BitsTypeBuilder;
+import org.opendaylight.yangtools.yang.model.ri.type.EnumerationTypeBuilder;
+import org.opendaylight.yangtools.yang.model.ri.type.InstanceIdentifierTypeBuilder;
+import org.opendaylight.yangtools.yang.model.ri.type.InvalidLengthConstraintException;
+import org.opendaylight.yangtools.yang.model.ri.type.InvalidRangeConstraintException;
+import org.opendaylight.yangtools.yang.model.ri.type.LengthRestrictedTypeBuilder;
+import org.opendaylight.yangtools.yang.model.ri.type.RangeRestrictedTypeBuilder;
+import org.opendaylight.yangtools.yang.model.ri.type.RequireInstanceRestrictedTypeBuilder;
+import org.opendaylight.yangtools.yang.model.ri.type.RestrictedTypes;
+import org.opendaylight.yangtools.yang.model.ri.type.StringTypeBuilder;
 import org.opendaylight.yangtools.yang.parser.spi.TypeNamespace;
+import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx;
+import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
@@ -71,136 +79,101 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
-import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 
-abstract class AbstractTypeStatementSupport
-        extends BaseStatementSupport<String, TypeStatement, EffectiveStatement<String, TypeStatement>> {
-    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(
-        YangStmtMapping.TYPE)
-        .addOptional(YangStmtMapping.BASE)
-        .addAny(YangStmtMapping.BIT)
-        .addAny(YangStmtMapping.ENUM)
-        .addOptional(YangStmtMapping.FRACTION_DIGITS)
-        .addOptional(YangStmtMapping.LENGTH)
-        .addOptional(YangStmtMapping.PATH)
-        .addAny(YangStmtMapping.PATTERN)
-        .addOptional(YangStmtMapping.RANGE)
-        .addOptional(YangStmtMapping.REQUIRE_INSTANCE)
-        .addAny(YangStmtMapping.TYPE)
-        .build();
-
-    static final String BINARY = "binary";
-    static final String BITS = "bits";
-    static final String BOOLEAN = "boolean";
-    static final String DECIMAL64 = "decimal64";
-    static final String EMPTY = "empty";
-    static final String ENUMERATION = "enumeration";
-    static final String IDENTITY_REF = "identityref";
-    static final String INSTANCE_IDENTIFIER = "instance-identifier";
-    static final String INT8 = "int8";
-    static final String INT16 = "int16";
-    static final String INT32 = "int32";
-    static final String INT64 = "int64";
-    static final String LEAF_REF = "leafref";
-    static final String STRING = "string";
-    static final String UINT8 = "uint8";
-    static final String UINT16 = "uint16";
-    static final String UINT32 = "uint32";
-    static final String UINT64 = "uint64";
-    static final String UNION = "union";
-
-    private static final ImmutableMap<String, String> BUILT_IN_TYPES = ImmutableMap.<String, String>builder()
-        .put(BINARY, BINARY)
-        .put(BITS, BITS)
-        .put(BOOLEAN, BOOLEAN)
-        .put(DECIMAL64, DECIMAL64)
-        .put(EMPTY, EMPTY)
-        .put(ENUMERATION, ENUMERATION)
-        .put(IDENTITY_REF,IDENTITY_REF)
-        .put(INSTANCE_IDENTIFIER, INSTANCE_IDENTIFIER)
-        .put(INT8, INT8)
-        .put(INT16, INT16)
-        .put(INT32, INT32)
-        .put(INT64, INT64)
-        .put(LEAF_REF, LEAF_REF)
-        .put(STRING, STRING)
-        .put(UINT8, UINT8)
-        .put(UINT16, UINT16)
-        .put(UINT32, UINT32)
-        .put(UINT64, UINT64)
-        .put(UNION, UNION)
-        .build();
-
-    private static final ImmutableMap<String, StatementSupport<?, ?, ?>> ARGUMENT_SPECIFIC_SUPPORTS =
-            ImmutableMap.<String, StatementSupport<?, ?, ?>>builder()
-            .put(BITS, new BitsSpecificationSupport())
-            .put(DECIMAL64, new Decimal64SpecificationSupport())
-            .put(ENUMERATION, new EnumSpecificationSupport())
-            .put(IDENTITY_REF, new IdentityRefSpecificationRFC6020Support())
-            .put(INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationSupport())
-            .put(LEAF_REF, new LeafrefSpecificationRFC6020Support())
-            .put(UNION, new UnionSpecificationSupport())
+abstract class AbstractTypeStatementSupport extends AbstractTypeSupport<TypeStatement> {
+    private static final SubstatementValidator SUBSTATEMENT_VALIDATOR =
+        SubstatementValidator.builder(YangStmtMapping.TYPE)
+            .addOptional(YangStmtMapping.BASE)
+            .addAny(YangStmtMapping.BIT)
+            .addAny(YangStmtMapping.ENUM)
+            .addOptional(YangStmtMapping.FRACTION_DIGITS)
+            .addOptional(YangStmtMapping.LENGTH)
+            .addOptional(YangStmtMapping.PATH)
+            .addAny(YangStmtMapping.PATTERN)
+            .addOptional(YangStmtMapping.RANGE)
+            .addOptional(YangStmtMapping.REQUIRE_INSTANCE)
+            .addAny(YangStmtMapping.TYPE)
             .build();
 
-    AbstractTypeStatementSupport() {
-        super(YangStmtMapping.TYPE);
-    }
+    private static final ImmutableMap<String, BuiltinEffectiveStatement> STATIC_BUILT_IN_TYPES =
+        ImmutableMap.<String, BuiltinEffectiveStatement>builder()
+            .put(TypeDefinitions.BINARY.getLocalName(), BuiltinEffectiveStatement.BINARY)
+            .put(TypeDefinitions.BOOLEAN.getLocalName(), BuiltinEffectiveStatement.BOOLEAN)
+            .put(TypeDefinitions.EMPTY.getLocalName(), BuiltinEffectiveStatement.EMPTY)
+            // FIXME: this overlaps with DYNAMIC_BUILT_IN_TYPES. One of these is not needed, but we need to decide
+            //        what to do. I think we should gradually use per-statement validators, hence go towards dynamic?
+            .put(TypeDefinitions.INSTANCE_IDENTIFIER.getLocalName(), BuiltinEffectiveStatement.INSTANCE_IDENTIFIER)
+            .put(TypeDefinitions.INT8.getLocalName(), BuiltinEffectiveStatement.INT8)
+            .put(TypeDefinitions.INT16.getLocalName(), BuiltinEffectiveStatement.INT16)
+            .put(TypeDefinitions.INT32.getLocalName(), BuiltinEffectiveStatement.INT32)
+            .put(TypeDefinitions.INT64.getLocalName(), BuiltinEffectiveStatement.INT64)
+            .put(TypeDefinitions.STRING.getLocalName(), BuiltinEffectiveStatement.STRING)
+            .put(TypeDefinitions.UINT8.getLocalName(), BuiltinEffectiveStatement.UINT8)
+            .put(TypeDefinitions.UINT16.getLocalName(), BuiltinEffectiveStatement.UINT16)
+            .put(TypeDefinitions.UINT32.getLocalName(), BuiltinEffectiveStatement.UINT32)
+            .put(TypeDefinitions.UINT64.getLocalName(), BuiltinEffectiveStatement.UINT64)
+            .build();
 
-    @Override
-    public final String parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
-        return value;
+    private final ImmutableMap<String, StatementSupport<?, ?, ?>> dynamicBuiltInTypes;
+
+    AbstractTypeStatementSupport(final YangParserConfiguration config) {
+        super(config);
+        dynamicBuiltInTypes = ImmutableMap.<String, StatementSupport<?, ?, ?>>builder()
+            .put(TypeDefinitions.BITS.getLocalName(), new BitsSpecificationSupport(config))
+            .put(TypeDefinitions.DECIMAL64.getLocalName(), new Decimal64SpecificationSupport(config))
+            .put(TypeDefinitions.ENUMERATION.getLocalName(), new EnumSpecificationSupport(config))
+            .put(TypeDefinitions.IDENTITYREF.getLocalName(), new IdentityRefSpecificationRFC6020Support(config))
+            .put(TypeDefinitions.INSTANCE_IDENTIFIER.getLocalName(), new InstanceIdentifierSpecificationSupport(config))
+            .put(TypeDefinitions.LEAFREF.getLocalName(), new LeafrefSpecificationRFC6020Support(config))
+            .put(TypeDefinitions.UNION.getLocalName(), new UnionSpecificationSupport(config))
+            .build();
     }
 
     @Override
     public final void onFullDefinitionDeclared(
-            final Mutable<String, TypeStatement, EffectiveStatement<String, TypeStatement>> stmt) {
+            final Mutable<QName, TypeStatement, EffectiveStatement<QName, TypeStatement>> stmt) {
         super.onFullDefinitionDeclared(stmt);
 
-        // if it is yang built-in type, no prerequisite is needed, so simply return
-        if (BUILT_IN_TYPES.containsKey(stmt.getStatementArgument())) {
+        final BuiltinEffectiveStatement builtin = STATIC_BUILT_IN_TYPES.get(stmt.getRawArgument());
+        if (builtin != null) {
+            stmt.addToNs(BaseTypeNamespace.class, Empty.getInstance(), builtin);
             return;
         }
 
-        final QName typeQName = StmtContextUtils.parseNodeIdentifier(stmt, stmt.getStatementArgument());
+        final QName typeQName = stmt.getArgument();
         final ModelActionBuilder typeAction = stmt.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
         final Prerequisite<StmtContext<?, ?, ?>> typePrereq = typeAction.requiresCtx(stmt, TypeNamespace.class,
                 typeQName, ModelProcessingPhase.EFFECTIVE_MODEL);
         typeAction.mutatesEffectiveCtx(stmt.getParentContext());
 
         /*
-         * If the type does not exist, throw new InferenceException.
-         * Otherwise perform no operation.
+         * If the type does not exist, throw an InferenceException.
+         * If the type exists, store a reference to it in BaseTypeNamespace.
          */
         typeAction.apply(new InferenceAction() {
             @Override
             public void apply(final InferenceContext ctx) {
-                // Intentional NOOP
+                // Note: do not attempt to call buildEffective() here
+                stmt.addToNs(BaseTypeNamespace.class, Empty.getInstance(), typePrereq.resolve(ctx));
             }
 
             @Override
             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
-                InferenceException.throwIf(failed.contains(typePrereq), stmt.getStatementSourceReference(),
-                    "Type [%s] was not found.", typeQName);
+                InferenceException.throwIf(failed.contains(typePrereq), stmt, "Type [%s] was not found.", typeQName);
             }
         });
     }
 
-    @Override
-    public final String internArgument(final String rawArgument) {
-        final String found;
-        return (found = BUILT_IN_TYPES.get(rawArgument)) != null ? found : rawArgument;
-    }
-
     @Override
     public boolean hasArgumentSpecificSupports() {
-        return !ARGUMENT_SPECIFIC_SUPPORTS.isEmpty();
+        return !dynamicBuiltInTypes.isEmpty();
     }
 
     @Override
     public StatementSupport<?, ?, ?> getSupportSpecificForArgument(final String argument) {
-        return ARGUMENT_SPECIFIC_SUPPORTS.get(argument);
+        return dynamicBuiltInTypes.get(argument);
     }
 
     @Override
@@ -209,92 +182,89 @@ abstract class AbstractTypeStatementSupport
     }
 
     @Override
-    protected final TypeStatement createDeclared(final StmtContext<String, TypeStatement, ?> ctx,
+    protected final TypeStatement createDeclared(final StmtContext<QName, TypeStatement, ?> ctx,
             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
-        return new RegularTypeStatement(ctx, substatements);
+        if (substatements.isEmpty()) {
+            final TypeStatement builtin = BuiltinTypeStatement.lookup(ctx.getRawArgument());
+            if (builtin != null) {
+                return builtin;
+            }
+        }
+        return DeclaredStatements.createType(ctx.getRawArgument(), ctx.getArgument(), substatements);
     }
 
     @Override
-    protected final TypeStatement createEmptyDeclared(final StmtContext<String, TypeStatement, ?> ctx) {
-        final TypeStatement builtin;
-        return (builtin = BuiltinTypeStatement.lookup(ctx)) != null ? builtin : new EmptyTypeStatement(ctx);
+    protected final TypeStatement attachDeclarationReference(final TypeStatement stmt,
+            final DeclarationReference reference) {
+        return DeclaredStatementDecorators.decorateType(stmt, reference);
     }
 
     @Override
-    protected final TypeEffectiveStatement<TypeStatement> createEffective(
-            final StmtContext<String, TypeStatement, EffectiveStatement<String, TypeStatement>> ctx,
-            final TypeStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
+    protected EffectiveStatement<QName, TypeStatement> createEffective(final Current<QName, TypeStatement> stmt,
+            final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
         // First look up the proper base type
-        final TypeEffectiveStatement<TypeStatement> typeStmt = resolveType(ctx);
+        final TypeEffectiveStatement<TypeStatement> typeStmt = resolveType(stmt);
+        if (substatements.isEmpty()) {
+            return typeStmt;
+        }
+
         // Now instantiate the proper effective statement for that type
         final TypeDefinition<?> baseType = typeStmt.getTypeDefinition();
+        final TypeStatement declared = stmt.declared();
         if (baseType instanceof BinaryTypeDefinition) {
-            return createBinary(ctx, (BinaryTypeDefinition) baseType, declared, substatements);
+            return createBinary(stmt, (BinaryTypeDefinition) baseType, declared, substatements);
         } else if (baseType instanceof BitsTypeDefinition) {
-            return createBits(ctx, (BitsTypeDefinition) baseType, declared, substatements);
+            return createBits(stmt, (BitsTypeDefinition) baseType, declared, substatements);
         } else if (baseType instanceof BooleanTypeDefinition) {
-            return createBoolean(ctx, (BooleanTypeDefinition) baseType, declared, substatements);
+            return createBoolean(stmt, (BooleanTypeDefinition) baseType, declared, substatements);
         } else if (baseType instanceof DecimalTypeDefinition) {
-            return createDecimal(ctx, (DecimalTypeDefinition) baseType, declared, substatements);
+            return createDecimal(stmt, (DecimalTypeDefinition) baseType, declared, substatements);
         } else if (baseType instanceof EmptyTypeDefinition) {
-            return createEmpty(ctx, (EmptyTypeDefinition) baseType, declared, substatements);
+            return createEmpty(stmt, (EmptyTypeDefinition) baseType, declared, substatements);
         } else if (baseType instanceof EnumTypeDefinition) {
-            return createEnum(ctx, (EnumTypeDefinition) baseType, declared, substatements);
+            return createEnum(stmt, (EnumTypeDefinition) baseType, declared, substatements);
         } else if (baseType instanceof IdentityrefTypeDefinition) {
-            return createIdentityref(ctx, (IdentityrefTypeDefinition) baseType, declared, substatements);
+            return createIdentityref(stmt, (IdentityrefTypeDefinition) baseType, declared, substatements);
         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
-            return new InstanceIdentifierTypeEffectiveStatementImpl(ctx,
-                (InstanceIdentifierTypeDefinition) baseType);
+            return createInstanceIdentifier(stmt, (InstanceIdentifierTypeDefinition) baseType, declared, substatements);
         } else if (baseType instanceof Int8TypeDefinition) {
-            return new IntegralTypeEffectiveStatementImpl<>(ctx,
-                    RestrictedTypes.newInt8Builder((Int8TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
+            return createIntegral(stmt, declared, substatements,
+                RestrictedTypes.newInt8Builder((Int8TypeDefinition) baseType, typeEffectiveQName(stmt)));
         } else if (baseType instanceof Int16TypeDefinition) {
-            return new IntegralTypeEffectiveStatementImpl<>(ctx,
-                    RestrictedTypes.newInt16Builder((Int16TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
+            return createIntegral(stmt, declared, substatements,
+                RestrictedTypes.newInt16Builder((Int16TypeDefinition) baseType, typeEffectiveQName(stmt)));
         } else if (baseType instanceof Int32TypeDefinition) {
-            return new IntegralTypeEffectiveStatementImpl<>(ctx,
-                    RestrictedTypes.newInt32Builder((Int32TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
+            return createIntegral(stmt, declared, substatements,
+                RestrictedTypes.newInt32Builder((Int32TypeDefinition) baseType, typeEffectiveQName(stmt)));
         } else if (baseType instanceof Int64TypeDefinition) {
-            return new IntegralTypeEffectiveStatementImpl<>(ctx,
-                    RestrictedTypes.newInt64Builder((Int64TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
+            return createIntegral(stmt, declared, substatements,
+                RestrictedTypes.newInt64Builder((Int64TypeDefinition) baseType, typeEffectiveQName(stmt)));
         } else if (baseType instanceof LeafrefTypeDefinition) {
-            return new LeafrefTypeEffectiveStatementImpl(ctx, (LeafrefTypeDefinition) baseType);
+            return createLeafref(stmt, (LeafrefTypeDefinition) baseType, declared, substatements);
         } else if (baseType instanceof StringTypeDefinition) {
-            return new StringTypeEffectiveStatementImpl(ctx, (StringTypeDefinition) baseType);
+            return createString(stmt, (StringTypeDefinition) baseType, declared, substatements);
         } else if (baseType instanceof Uint8TypeDefinition) {
-            return new IntegralTypeEffectiveStatementImpl<>(ctx,
-                    RestrictedTypes.newUint8Builder((Uint8TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
+            return createIntegral(stmt, declared, substatements,
+                RestrictedTypes.newUint8Builder((Uint8TypeDefinition) baseType, typeEffectiveQName(stmt)));
         } else if (baseType instanceof Uint16TypeDefinition) {
-            return new IntegralTypeEffectiveStatementImpl<>(ctx,
-                    RestrictedTypes.newUint16Builder((Uint16TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
+            return createIntegral(stmt, declared, substatements,
+                RestrictedTypes.newUint16Builder((Uint16TypeDefinition) baseType, typeEffectiveQName(stmt)));
         } else if (baseType instanceof Uint32TypeDefinition) {
-            return new IntegralTypeEffectiveStatementImpl<>(ctx,
-                    RestrictedTypes.newUint32Builder((Uint32TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
+            return createIntegral(stmt, declared, substatements,
+                RestrictedTypes.newUint32Builder((Uint32TypeDefinition) baseType, typeEffectiveQName(stmt)));
         } else if (baseType instanceof Uint64TypeDefinition) {
-            return new IntegralTypeEffectiveStatementImpl<>(ctx,
-                    RestrictedTypes.newUint64Builder((Uint64TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
+            return createIntegral(stmt, declared, substatements,
+                RestrictedTypes.newUint64Builder((Uint64TypeDefinition) baseType, typeEffectiveQName(stmt)));
         } else if (baseType instanceof UnionTypeDefinition) {
-            return createUnion(ctx, (UnionTypeDefinition) baseType, declared, substatements);
+            return createUnion(stmt, (UnionTypeDefinition) baseType, declared, substatements);
         } else {
             throw new IllegalStateException("Unhandled base type " + baseType);
         }
     }
 
-    @Override
-    protected final EffectiveStatement<String, TypeStatement> createEmptyEffective(
-            final StmtContext<String, TypeStatement, EffectiveStatement<String, TypeStatement>> ctx,
-            final TypeStatement declared) {
-        return resolveType(ctx);
-    }
-
-    static final SchemaPath typeEffectiveSchemaPath(final StmtContext<?, ?, ?> stmtCtx) {
-        final SchemaPath path = stmtCtx.getSchemaPath().get();
-        final SchemaPath parent = path.getParent();
-        final QName parentQName = parent.getLastComponent();
-        checkArgument(parentQName != null, "Path %s has an empty parent", path);
-
-        final QName qname = path.getLastComponent().bindTo(parentQName.getModule()).intern();
-        return parent.createChild(qname);
+    // FIXME: YANGTOOLS-1208: this needs to happen during onFullDefinitionDeclared() and stored (again) in a namespace
+    static final @NonNull QName typeEffectiveQName(final Current<QName, ?> stmt) {
+        return stmt.getArgument().bindTo(stmt.getEffectiveParent().effectiveNamespace()).intern();
     }
 
     /**
@@ -304,49 +274,23 @@ abstract class AbstractTypeStatementSupport
      * @return Resolved type
      * @throws SourceException if the target type cannot be found
      */
-    private static @NonNull TypeEffectiveStatement<TypeStatement> resolveType(final StmtContext<String, ?, ?> ctx) {
-        final String argument = ctx.coerceStatementArgument();
-        switch (argument) {
-            case BINARY:
-                return BuiltinEffectiveStatement.BINARY;
-            case BOOLEAN:
-                return BuiltinEffectiveStatement.BOOLEAN;
-            case EMPTY:
-                return BuiltinEffectiveStatement.EMPTY;
-            case INSTANCE_IDENTIFIER:
-                return BuiltinEffectiveStatement.INSTANCE_IDENTIFIER;
-            case INT8:
-                return BuiltinEffectiveStatement.INT8;
-            case INT16:
-                return BuiltinEffectiveStatement.INT16;
-            case INT32:
-                return BuiltinEffectiveStatement.INT32;
-            case INT64:
-                return BuiltinEffectiveStatement.INT64;
-            case STRING:
-                return BuiltinEffectiveStatement.STRING;
-            case UINT8:
-                return BuiltinEffectiveStatement.UINT8;
-            case UINT16:
-                return BuiltinEffectiveStatement.UINT16;
-            case UINT32:
-                return BuiltinEffectiveStatement.UINT32;
-            case UINT64:
-                return BuiltinEffectiveStatement.UINT64;
-            default:
-                final QName qname = StmtContextUtils.parseNodeIdentifier(ctx, argument);
-                final StmtContext<?, TypedefStatement, TypedefEffectiveStatement> typedef =
-                        SourceException.throwIfNull(ctx.getFromNamespace(TypeNamespace.class, qname),
-                            ctx.getStatementSourceReference(), "Type '%s' not found", qname);
-                return typedef.buildEffective().asTypeEffectiveStatement();
+    private static @NonNull TypeEffectiveStatement<TypeStatement> resolveType(final Current<QName, ?> ctx) {
+        final Object obj = verifyNotNull(ctx.namespaceItem(BaseTypeNamespace.class, Empty.getInstance()));
+        if (obj instanceof BuiltinEffectiveStatement) {
+            return (BuiltinEffectiveStatement) obj;
+        } else if (obj instanceof StmtContext) {
+            return ((TypedefEffectiveStatement) ((StmtContext<?, ?, ?>) obj).buildEffective())
+                .asTypeEffectiveStatement();
+        } else {
+            throw new InferenceException(ctx, "Unexpected base object %s", obj);
         }
     }
 
-    private static @NonNull TypeEffectiveStatement<TypeStatement> createBinary(final StmtContext<?, ?, ?> ctx,
+    private static @NonNull TypeEffectiveStatement<TypeStatement> createBinary(final Current<QName, ?> ctx,
             final BinaryTypeDefinition baseType, final TypeStatement declared,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
         final LengthRestrictedTypeBuilder<BinaryTypeDefinition> builder =
-                RestrictedTypes.newBinaryBuilder(baseType, typeEffectiveSchemaPath(ctx));
+                RestrictedTypes.newBinaryBuilder(baseType, typeEffectiveQName(ctx));
 
         for (EffectiveStatement<?, ?> stmt : substatements) {
             if (stmt instanceof LengthEffectiveStatement) {
@@ -355,11 +299,9 @@ abstract class AbstractTypeStatementSupport
                 try {
                     builder.setLengthConstraint(length, length.argument());
                 } catch (IllegalStateException e) {
-                    throw new SourceException(ctx.getStatementSourceReference(), e,
-                        "Multiple length constraints encountered");
+                    throw new SourceException(ctx, e, "Multiple length constraints encountered");
                 } catch (InvalidLengthConstraintException e) {
-                    throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid length constraint %s",
-                        length.argument());
+                    throw new SourceException(ctx, e, "Invalid length constraint %s", length.argument());
                 }
             }
         }
@@ -367,46 +309,35 @@ abstract class AbstractTypeStatementSupport
         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
     }
 
-    private static @NonNull TypeEffectiveStatement<TypeStatement> createBits(final StmtContext<?, ?, ?> ctx,
+    private @NonNull TypeEffectiveStatement<TypeStatement> createBits(final Current<?, ?> ctx,
             final BitsTypeDefinition baseType, final TypeStatement declared,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
-        final BitsTypeBuilder builder = RestrictedTypes.newBitsBuilder(baseType, ctx.getSchemaPath().get());
+        final BitsTypeBuilder builder = RestrictedTypes.newBitsBuilder(baseType, ctx.argumentAsTypeQName());
 
-        final YangVersion yangVersion = ctx.getRootVersion();
         for (final EffectiveStatement<?, ?> stmt : substatements) {
             if (stmt instanceof BitEffectiveStatement) {
-                SourceException.throwIf(yangVersion != YangVersion.VERSION_1_1, ctx.getStatementSourceReference(),
-                        "Restricted bits type is allowed only in YANG 1.1 version.");
-                final BitEffectiveStatement bitSubStmt = (BitEffectiveStatement) stmt;
-
-                // FIXME: this looks like a duplicate of BitsSpecificationEffectiveStatement
-                final Optional<Uint32> declaredPosition = bitSubStmt.getDeclaredPosition();
-                final Uint32 effectivePos;
-                if (declaredPosition.isEmpty()) {
-                    effectivePos = getBaseTypeBitPosition(bitSubStmt.argument(), baseType, ctx);
-                } else {
-                    effectivePos = declaredPosition.get();
-                }
-
-                builder.addBit(EffectiveTypeUtil.buildBit(bitSubStmt, effectivePos));
+                builder.addBit(addRestrictedBit(ctx, baseType, (BitEffectiveStatement) stmt));
             }
         }
 
         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
     }
 
-    private static @NonNull TypeEffectiveStatement<TypeStatement> createBoolean(final StmtContext<?, ?, ?> ctx,
+    abstract @NonNull Bit addRestrictedBit(@NonNull EffectiveStmtCtx stmt, @NonNull BitsTypeDefinition base,
+        @NonNull BitEffectiveStatement bit);
+
+    private static @NonNull TypeEffectiveStatement<TypeStatement> createBoolean(final Current<QName, ?> ctx,
             final BooleanTypeDefinition baseType, final TypeStatement declared,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newBooleanBuilder(baseType,
-            typeEffectiveSchemaPath(ctx)));
+            typeEffectiveQName(ctx)));
     }
 
-    private static @NonNull TypeEffectiveStatement<TypeStatement> createDecimal(final StmtContext<?, ?, ?> ctx,
+    private static @NonNull TypeEffectiveStatement<TypeStatement> createDecimal(final Current<QName, ?> ctx,
             final DecimalTypeDefinition baseType, final TypeStatement declared,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
         final RangeRestrictedTypeBuilder<DecimalTypeDefinition, BigDecimal> builder =
-                RestrictedTypes.newDecima64Builder(baseType, typeEffectiveSchemaPath(ctx));
+                RestrictedTypes.newDecima64Builder(baseType, typeEffectiveQName(ctx));
 
         for (EffectiveStatement<?, ?> stmt : substatements) {
             if (stmt instanceof RangeEffectiveStatement) {
@@ -415,7 +346,7 @@ abstract class AbstractTypeStatementSupport
             }
             if (stmt instanceof FractionDigitsEffectiveStatement) {
                 final Integer digits = ((FractionDigitsEffectiveStatement)stmt).argument();
-                SourceException.throwIf(baseType.getFractionDigits() != digits, ctx.getStatementSourceReference(),
+                SourceException.throwIf(baseType.getFractionDigits() != digits, ctx,
                     "Cannot override fraction-digits from base type %s to %s", baseType, digits);
             }
         }
@@ -423,77 +354,115 @@ abstract class AbstractTypeStatementSupport
         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
     }
 
-    private static @NonNull TypeEffectiveStatement<TypeStatement> createEmpty(final StmtContext<?, ?, ?> ctx,
+    private static @NonNull TypeEffectiveStatement<TypeStatement> createEmpty(final Current<QName, ?> ctx,
             final EmptyTypeDefinition baseType, final TypeStatement declared,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newEmptyBuilder(baseType,
-            typeEffectiveSchemaPath(ctx)));
+            typeEffectiveQName(ctx)));
     }
 
-    private static @NonNull TypeEffectiveStatement<TypeStatement> createEnum(final StmtContext<?, ?, ?> ctx,
+    private @NonNull TypeEffectiveStatement<TypeStatement> createEnum(final Current<?, ?> ctx,
             final EnumTypeDefinition baseType, final TypeStatement declared,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
         final EnumerationTypeBuilder builder = RestrictedTypes.newEnumerationBuilder(baseType,
-            ctx.getSchemaPath().get());
+            ctx.argumentAsTypeQName());
 
-        final YangVersion yangVersion = ctx.getRootVersion();
         for (final EffectiveStatement<?, ?> stmt : substatements) {
             if (stmt instanceof EnumEffectiveStatement) {
-                SourceException.throwIf(yangVersion != YangVersion.VERSION_1_1, ctx.getStatementSourceReference(),
-                        "Restricted enumeration type is allowed only in YANG 1.1 version.");
-
-                final EnumEffectiveStatement enumSubStmt = (EnumEffectiveStatement) stmt;
-                final Optional<Integer> declaredValue =
-                        enumSubStmt.findFirstEffectiveSubstatementArgument(ValueEffectiveStatement.class);
-                final int effectiveValue;
-                if (declaredValue.isEmpty()) {
-                    effectiveValue = getBaseTypeEnumValue(enumSubStmt.getDeclared().rawArgument(), baseType, ctx);
-                } else {
-                    effectiveValue = declaredValue.orElseThrow();
-                }
-
-                builder.addEnum(EffectiveTypeUtil.buildEnumPair(enumSubStmt, effectiveValue));
+                builder.addEnum(addRestrictedEnum(ctx, baseType, (EnumEffectiveStatement) stmt));
             }
         }
 
         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
     }
 
-    private static @NonNull TypeEffectiveStatement<TypeStatement> createIdentityref(final StmtContext<?, ?, ?> ctx,
+    abstract @NonNull EnumPair addRestrictedEnum(@NonNull EffectiveStmtCtx stmt, @NonNull EnumTypeDefinition base,
+        @NonNull EnumEffectiveStatement enumStmt);
+
+    private static @NonNull TypeEffectiveStatement<TypeStatement> createIdentityref(final Current<QName, ?> ctx,
             final IdentityrefTypeDefinition baseType, final TypeStatement declared,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newIdentityrefBuilder(baseType,
-            typeEffectiveSchemaPath(ctx)));
+            typeEffectiveQName(ctx)));
     }
 
-    private static @NonNull TypeEffectiveStatement<TypeStatement> createUnion(final StmtContext<?, ?, ?> ctx,
-            final UnionTypeDefinition baseType, final TypeStatement declared,
+    private static @NonNull TypeEffectiveStatement<TypeStatement> createInstanceIdentifier(final Current<QName, ?> ctx,
+            final InstanceIdentifierTypeDefinition baseType, final TypeStatement declared,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
-        return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newUnionBuilder(baseType,
-            typeEffectiveSchemaPath(ctx)));
+        final InstanceIdentifierTypeBuilder builder = RestrictedTypes.newInstanceIdentifierBuilder(baseType,
+                    typeEffectiveQName(ctx));
+
+        for (EffectiveStatement<?, ?> stmt : substatements) {
+            if (stmt instanceof RequireInstanceEffectiveStatement) {
+                builder.setRequireInstance(((RequireInstanceEffectiveStatement)stmt).argument());
+            }
+        }
+
+        return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
     }
 
-    private static Uint32 getBaseTypeBitPosition(final String bitName, final BitsTypeDefinition baseType,
-            final StmtContext<?, ?, ?> ctx) {
-        for (Bit baseTypeBit : baseType.getBits()) {
-            if (bitName.equals(baseTypeBit.getName())) {
-                return baseTypeBit.getPosition();
+    private static <T extends RangeRestrictedTypeDefinition<T, N>, N extends Number & Comparable<N>>
+        @NonNull TypeEffectiveStatement<TypeStatement> createIntegral(final Current<?, ?> ctx,
+                final TypeStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements,
+                final RangeRestrictedTypeBuilder<T, N> builder) {
+        for (EffectiveStatement<?, ?> stmt : substatements) {
+            if (stmt instanceof RangeEffectiveStatement) {
+                final RangeEffectiveStatement rangeStmt = (RangeEffectiveStatement)stmt;
+                builder.setRangeConstraint(rangeStmt, rangeStmt.argument());
             }
         }
 
-        throw new SourceException(ctx.getStatementSourceReference(),
-                "Bit '%s' is not a subset of its base bits type %s.", bitName, baseType.getQName());
+        try {
+            return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
+        } catch (InvalidRangeConstraintException e) {
+            throw new SourceException(ctx, e, "Invalid range constraint: %s", e.getOffendingRanges());
+        }
     }
 
-    private static int getBaseTypeEnumValue(final String enumName, final EnumTypeDefinition baseType,
-            final StmtContext<?, ?, ?> ctx) {
-        for (EnumPair baseTypeEnumPair : baseType.getValues()) {
-            if (enumName.equals(baseTypeEnumPair.getName())) {
-                return baseTypeEnumPair.getValue();
+    private static @NonNull TypeEffectiveStatement<TypeStatement> createLeafref(final Current<QName, ?> ctx,
+            final LeafrefTypeDefinition baseType, final TypeStatement declared,
+            final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
+        final RequireInstanceRestrictedTypeBuilder<LeafrefTypeDefinition> builder =
+                RestrictedTypes.newLeafrefBuilder(baseType, AbstractTypeStatementSupport.typeEffectiveQName(ctx));
+
+        for (final EffectiveStatement<?, ?> stmt : substatements) {
+            if (stmt instanceof RequireInstanceEffectiveStatement) {
+                builder.setRequireInstance(((RequireInstanceEffectiveStatement) stmt).argument());
+            }
+        }
+        return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
+    }
+
+    private static @NonNull TypeEffectiveStatement<TypeStatement> createString(final Current<QName, ?> ctx,
+            final StringTypeDefinition baseType, final TypeStatement declared,
+            final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
+        final StringTypeBuilder builder = RestrictedTypes.newStringBuilder(baseType,
+            AbstractTypeStatementSupport.typeEffectiveQName(ctx));
+
+        for (EffectiveStatement<?, ?> stmt : substatements) {
+            if (stmt instanceof LengthEffectiveStatement) {
+                final LengthEffectiveStatement length = (LengthEffectiveStatement)stmt;
+
+                try {
+                    builder.setLengthConstraint(length, length.argument());
+                } catch (IllegalStateException e) {
+                    throw new SourceException(ctx, e, "Multiple length constraints encountered");
+                } catch (InvalidLengthConstraintException e) {
+                    throw new SourceException(ctx, e, "Invalid length constraint %s", length.argument());
+                }
+            }
+            if (stmt instanceof PatternEffectiveStatement) {
+                builder.addPatternConstraint((PatternEffectiveStatement) stmt);
             }
         }
 
-        throw new SourceException(ctx.getStatementSourceReference(),
-                "Enum '%s' is not a subset of its base enumeration type %s.", enumName, baseType.getQName());
+        return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
+    }
+
+    private static @NonNull TypeEffectiveStatement<TypeStatement> createUnion(final Current<QName, ?> ctx,
+            final UnionTypeDefinition baseType, final TypeStatement declared,
+            final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
+        return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newUnionBuilder(baseType,
+            typeEffectiveQName(ctx)));
     }
 }
\ No newline at end of file