Consolidate IntegralTypeEffectiveStatementImpl
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / type / AbstractTypeStatementSupport.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.parser.rfc7950.stmt.type;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableMap;
14 import java.math.BigDecimal;
15 import java.util.Collection;
16 import java.util.Optional;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.common.Uint32;
20 import org.opendaylight.yangtools.yang.common.YangVersion;
21 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
22 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
23 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
24 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
25 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.BitEffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.EnumEffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.FractionDigitsEffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.LengthEffectiveStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.PatternEffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.stmt.RangeEffectiveStatement;
32 import org.opendaylight.yangtools.yang.model.api.stmt.RequireInstanceEffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.TypeEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.TypeStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
36 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefStatement;
37 import org.opendaylight.yangtools.yang.model.api.stmt.ValueEffectiveStatement;
38 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
41 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
46 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.Int16TypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.Int32TypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.Int64TypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.Int8TypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
54 import org.opendaylight.yangtools.yang.model.api.type.RangeRestrictedTypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.Uint16TypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.Uint32TypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.Uint64TypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.Uint8TypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.util.type.BitsTypeBuilder;
62 import org.opendaylight.yangtools.yang.model.util.type.EnumerationTypeBuilder;
63 import org.opendaylight.yangtools.yang.model.util.type.InstanceIdentifierTypeBuilder;
64 import org.opendaylight.yangtools.yang.model.util.type.InvalidLengthConstraintException;
65 import org.opendaylight.yangtools.yang.model.util.type.InvalidRangeConstraintException;
66 import org.opendaylight.yangtools.yang.model.util.type.LengthRestrictedTypeBuilder;
67 import org.opendaylight.yangtools.yang.model.util.type.RangeRestrictedTypeBuilder;
68 import org.opendaylight.yangtools.yang.model.util.type.RequireInstanceRestrictedTypeBuilder;
69 import org.opendaylight.yangtools.yang.model.util.type.RestrictedTypes;
70 import org.opendaylight.yangtools.yang.model.util.type.StringTypeBuilder;
71 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
72 import org.opendaylight.yangtools.yang.parser.spi.TypeNamespace;
73 import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
74 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder;
75 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceAction;
76 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.InferenceContext;
77 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelActionBuilder.Prerequisite;
78 import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
79 import org.opendaylight.yangtools.yang.parser.spi.meta.StatementSupport;
80 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
81 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext.Mutable;
82 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
83 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
84 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87
88 abstract class AbstractTypeStatementSupport
89         extends BaseStatementSupport<String, TypeStatement, EffectiveStatement<String, TypeStatement>> {
90     private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeStatementSupport.class);
91
92     private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(
93         YangStmtMapping.TYPE)
94         .addOptional(YangStmtMapping.BASE)
95         .addAny(YangStmtMapping.BIT)
96         .addAny(YangStmtMapping.ENUM)
97         .addOptional(YangStmtMapping.FRACTION_DIGITS)
98         .addOptional(YangStmtMapping.LENGTH)
99         .addOptional(YangStmtMapping.PATH)
100         .addAny(YangStmtMapping.PATTERN)
101         .addOptional(YangStmtMapping.RANGE)
102         .addOptional(YangStmtMapping.REQUIRE_INSTANCE)
103         .addAny(YangStmtMapping.TYPE)
104         .build();
105
106     static final String BINARY = "binary";
107     static final String BITS = "bits";
108     static final String BOOLEAN = "boolean";
109     static final String DECIMAL64 = "decimal64";
110     static final String EMPTY = "empty";
111     static final String ENUMERATION = "enumeration";
112     static final String IDENTITY_REF = "identityref";
113     static final String INSTANCE_IDENTIFIER = "instance-identifier";
114     static final String INT8 = "int8";
115     static final String INT16 = "int16";
116     static final String INT32 = "int32";
117     static final String INT64 = "int64";
118     static final String LEAF_REF = "leafref";
119     static final String STRING = "string";
120     static final String UINT8 = "uint8";
121     static final String UINT16 = "uint16";
122     static final String UINT32 = "uint32";
123     static final String UINT64 = "uint64";
124     static final String UNION = "union";
125
126     private static final ImmutableMap<String, String> BUILT_IN_TYPES = ImmutableMap.<String, String>builder()
127         .put(BINARY, BINARY)
128         .put(BITS, BITS)
129         .put(BOOLEAN, BOOLEAN)
130         .put(DECIMAL64, DECIMAL64)
131         .put(EMPTY, EMPTY)
132         .put(ENUMERATION, ENUMERATION)
133         .put(IDENTITY_REF,IDENTITY_REF)
134         .put(INSTANCE_IDENTIFIER, INSTANCE_IDENTIFIER)
135         .put(INT8, INT8)
136         .put(INT16, INT16)
137         .put(INT32, INT32)
138         .put(INT64, INT64)
139         .put(LEAF_REF, LEAF_REF)
140         .put(STRING, STRING)
141         .put(UINT8, UINT8)
142         .put(UINT16, UINT16)
143         .put(UINT32, UINT32)
144         .put(UINT64, UINT64)
145         .put(UNION, UNION)
146         .build();
147
148     private static final ImmutableMap<String, StatementSupport<?, ?, ?>> ARGUMENT_SPECIFIC_SUPPORTS =
149             ImmutableMap.<String, StatementSupport<?, ?, ?>>builder()
150             .put(BITS, new BitsSpecificationSupport())
151             .put(DECIMAL64, new Decimal64SpecificationSupport())
152             .put(ENUMERATION, new EnumSpecificationSupport())
153             .put(IDENTITY_REF, new IdentityRefSpecificationRFC6020Support())
154             .put(INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationSupport())
155             .put(LEAF_REF, new LeafrefSpecificationRFC6020Support())
156             .put(UNION, new UnionSpecificationSupport())
157             .build();
158
159     AbstractTypeStatementSupport() {
160         super(YangStmtMapping.TYPE);
161     }
162
163     @Override
164     public final String parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
165         return value;
166     }
167
168     @Override
169     public final void onFullDefinitionDeclared(
170             final Mutable<String, TypeStatement, EffectiveStatement<String, TypeStatement>> stmt) {
171         super.onFullDefinitionDeclared(stmt);
172
173         // if it is yang built-in type, no prerequisite is needed, so simply return
174         if (BUILT_IN_TYPES.containsKey(stmt.getStatementArgument())) {
175             return;
176         }
177
178         final QName typeQName = StmtContextUtils.parseNodeIdentifier(stmt, stmt.getStatementArgument());
179         final ModelActionBuilder typeAction = stmt.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
180         final Prerequisite<StmtContext<?, ?, ?>> typePrereq = typeAction.requiresCtx(stmt, TypeNamespace.class,
181                 typeQName, ModelProcessingPhase.EFFECTIVE_MODEL);
182         typeAction.mutatesEffectiveCtx(stmt.getParentContext());
183
184         /*
185          * If the type does not exist, throw new InferenceException.
186          * Otherwise perform no operation.
187          */
188         typeAction.apply(new InferenceAction() {
189             @Override
190             public void apply(final InferenceContext ctx) {
191                 // Intentional NOOP
192             }
193
194             @Override
195             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
196                 InferenceException.throwIf(failed.contains(typePrereq), stmt.getStatementSourceReference(),
197                     "Type [%s] was not found.", typeQName);
198             }
199         });
200     }
201
202     @Override
203     public final String internArgument(final String rawArgument) {
204         final String found;
205         return (found = BUILT_IN_TYPES.get(rawArgument)) != null ? found : rawArgument;
206     }
207
208     @Override
209     public boolean hasArgumentSpecificSupports() {
210         return !ARGUMENT_SPECIFIC_SUPPORTS.isEmpty();
211     }
212
213     @Override
214     public StatementSupport<?, ?, ?> getSupportSpecificForArgument(final String argument) {
215         return ARGUMENT_SPECIFIC_SUPPORTS.get(argument);
216     }
217
218     @Override
219     protected final SubstatementValidator getSubstatementValidator() {
220         return SUBSTATEMENT_VALIDATOR;
221     }
222
223     @Override
224     protected final TypeStatement createDeclared(final StmtContext<String, TypeStatement, ?> ctx,
225             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
226         return new RegularTypeStatement(ctx, substatements);
227     }
228
229     @Override
230     protected final TypeStatement createEmptyDeclared(final StmtContext<String, TypeStatement, ?> ctx) {
231         final TypeStatement builtin;
232         return (builtin = BuiltinTypeStatement.lookup(ctx)) != null ? builtin : new EmptyTypeStatement(ctx);
233     }
234
235     @Override
236     protected final TypeEffectiveStatement<TypeStatement> createEffective(
237             final StmtContext<String, TypeStatement, EffectiveStatement<String, TypeStatement>> ctx,
238             final TypeStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
239         // First look up the proper base type
240         final TypeEffectiveStatement<TypeStatement> typeStmt = resolveType(ctx);
241         // Now instantiate the proper effective statement for that type
242         final TypeDefinition<?> baseType = typeStmt.getTypeDefinition();
243         if (baseType instanceof BinaryTypeDefinition) {
244             return createBinary(ctx, (BinaryTypeDefinition) baseType, declared, substatements);
245         } else if (baseType instanceof BitsTypeDefinition) {
246             return createBits(ctx, (BitsTypeDefinition) baseType, declared, substatements);
247         } else if (baseType instanceof BooleanTypeDefinition) {
248             return createBoolean(ctx, (BooleanTypeDefinition) baseType, declared, substatements);
249         } else if (baseType instanceof DecimalTypeDefinition) {
250             return createDecimal(ctx, (DecimalTypeDefinition) baseType, declared, substatements);
251         } else if (baseType instanceof EmptyTypeDefinition) {
252             return createEmpty(ctx, (EmptyTypeDefinition) baseType, declared, substatements);
253         } else if (baseType instanceof EnumTypeDefinition) {
254             return createEnum(ctx, (EnumTypeDefinition) baseType, declared, substatements);
255         } else if (baseType instanceof IdentityrefTypeDefinition) {
256             return createIdentityref(ctx, (IdentityrefTypeDefinition) baseType, declared, substatements);
257         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
258             return createInstanceIdentifier(ctx, (InstanceIdentifierTypeDefinition) baseType, declared, substatements);
259         } else if (baseType instanceof Int8TypeDefinition) {
260             return createIntegral(ctx, declared, substatements,
261                 RestrictedTypes.newInt8Builder((Int8TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
262         } else if (baseType instanceof Int16TypeDefinition) {
263             return createIntegral(ctx, declared, substatements,
264                     RestrictedTypes.newInt16Builder((Int16TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
265         } else if (baseType instanceof Int32TypeDefinition) {
266             return createIntegral(ctx, declared, substatements,
267                     RestrictedTypes.newInt32Builder((Int32TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
268         } else if (baseType instanceof Int64TypeDefinition) {
269             return createIntegral(ctx, declared, substatements,
270                     RestrictedTypes.newInt64Builder((Int64TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
271         } else if (baseType instanceof LeafrefTypeDefinition) {
272             return createLeafref(ctx, (LeafrefTypeDefinition) baseType, declared, substatements);
273         } else if (baseType instanceof StringTypeDefinition) {
274             return createString(ctx, (StringTypeDefinition) baseType, declared, substatements);
275         } else if (baseType instanceof Uint8TypeDefinition) {
276             return createIntegral(ctx, declared, substatements,
277                     RestrictedTypes.newUint8Builder((Uint8TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
278         } else if (baseType instanceof Uint16TypeDefinition) {
279             return createIntegral(ctx, declared, substatements,
280                     RestrictedTypes.newUint16Builder((Uint16TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
281         } else if (baseType instanceof Uint32TypeDefinition) {
282             return createIntegral(ctx, declared, substatements,
283                     RestrictedTypes.newUint32Builder((Uint32TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
284         } else if (baseType instanceof Uint64TypeDefinition) {
285             return createIntegral(ctx, declared, substatements,
286                     RestrictedTypes.newUint64Builder((Uint64TypeDefinition) baseType, typeEffectiveSchemaPath(ctx)));
287         } else if (baseType instanceof UnionTypeDefinition) {
288             return createUnion(ctx, (UnionTypeDefinition) baseType, declared, substatements);
289         } else {
290             throw new IllegalStateException("Unhandled base type " + baseType);
291         }
292     }
293
294     @Override
295     protected final EffectiveStatement<String, TypeStatement> createEmptyEffective(
296             final StmtContext<String, TypeStatement, EffectiveStatement<String, TypeStatement>> ctx,
297             final TypeStatement declared) {
298         return resolveType(ctx);
299     }
300
301     static final SchemaPath typeEffectiveSchemaPath(final StmtContext<?, ?, ?> stmtCtx) {
302         final SchemaPath path = stmtCtx.getSchemaPath().get();
303         final SchemaPath parent = path.getParent();
304         final QName parentQName = parent.getLastComponent();
305         checkArgument(parentQName != null, "Path %s has an empty parent", path);
306
307         final QName qname = path.getLastComponent().bindTo(parentQName.getModule()).intern();
308         return parent.createChild(qname);
309     }
310
311     /**
312      * Resolve type reference, as pointed to by the context's argument.
313      *
314      * @param ctx Statement context
315      * @return Resolved type
316      * @throws SourceException if the target type cannot be found
317      */
318     private static @NonNull TypeEffectiveStatement<TypeStatement> resolveType(final StmtContext<String, ?, ?> ctx) {
319         final String argument = ctx.coerceStatementArgument();
320         switch (argument) {
321             case BINARY:
322                 return BuiltinEffectiveStatement.BINARY;
323             case BOOLEAN:
324                 return BuiltinEffectiveStatement.BOOLEAN;
325             case EMPTY:
326                 return BuiltinEffectiveStatement.EMPTY;
327             case INSTANCE_IDENTIFIER:
328                 return BuiltinEffectiveStatement.INSTANCE_IDENTIFIER;
329             case INT8:
330                 return BuiltinEffectiveStatement.INT8;
331             case INT16:
332                 return BuiltinEffectiveStatement.INT16;
333             case INT32:
334                 return BuiltinEffectiveStatement.INT32;
335             case INT64:
336                 return BuiltinEffectiveStatement.INT64;
337             case STRING:
338                 return BuiltinEffectiveStatement.STRING;
339             case UINT8:
340                 return BuiltinEffectiveStatement.UINT8;
341             case UINT16:
342                 return BuiltinEffectiveStatement.UINT16;
343             case UINT32:
344                 return BuiltinEffectiveStatement.UINT32;
345             case UINT64:
346                 return BuiltinEffectiveStatement.UINT64;
347             default:
348                 final QName qname = StmtContextUtils.parseNodeIdentifier(ctx, argument);
349                 final StmtContext<?, TypedefStatement, TypedefEffectiveStatement> typedef =
350                         SourceException.throwIfNull(ctx.getFromNamespace(TypeNamespace.class, qname),
351                             ctx.getStatementSourceReference(), "Type '%s' not found", qname);
352                 return typedef.buildEffective().asTypeEffectiveStatement();
353         }
354     }
355
356     private static @NonNull TypeEffectiveStatement<TypeStatement> createBinary(final StmtContext<?, ?, ?> ctx,
357             final BinaryTypeDefinition baseType, final TypeStatement declared,
358             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
359         final LengthRestrictedTypeBuilder<BinaryTypeDefinition> builder =
360                 RestrictedTypes.newBinaryBuilder(baseType, typeEffectiveSchemaPath(ctx));
361
362         for (EffectiveStatement<?, ?> stmt : substatements) {
363             if (stmt instanceof LengthEffectiveStatement) {
364                 final LengthEffectiveStatement length = (LengthEffectiveStatement)stmt;
365
366                 try {
367                     builder.setLengthConstraint(length, length.argument());
368                 } catch (IllegalStateException e) {
369                     throw new SourceException(ctx.getStatementSourceReference(), e,
370                         "Multiple length constraints encountered");
371                 } catch (InvalidLengthConstraintException e) {
372                     throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid length constraint %s",
373                         length.argument());
374                 }
375             }
376         }
377
378         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
379     }
380
381     private static @NonNull TypeEffectiveStatement<TypeStatement> createBits(final StmtContext<?, ?, ?> ctx,
382             final BitsTypeDefinition baseType, final TypeStatement declared,
383             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
384         final BitsTypeBuilder builder = RestrictedTypes.newBitsBuilder(baseType, ctx.getSchemaPath().get());
385
386         final YangVersion yangVersion = ctx.getRootVersion();
387         for (final EffectiveStatement<?, ?> stmt : substatements) {
388             if (stmt instanceof BitEffectiveStatement) {
389                 SourceException.throwIf(yangVersion != YangVersion.VERSION_1_1, ctx.getStatementSourceReference(),
390                         "Restricted bits type is allowed only in YANG 1.1 version.");
391                 final BitEffectiveStatement bitSubStmt = (BitEffectiveStatement) stmt;
392
393                 // FIXME: this looks like a duplicate of BitsSpecificationEffectiveStatement
394                 final Optional<Uint32> declaredPosition = bitSubStmt.getDeclaredPosition();
395                 final Uint32 effectivePos;
396                 if (declaredPosition.isEmpty()) {
397                     effectivePos = getBaseTypeBitPosition(bitSubStmt.argument(), baseType, ctx);
398                 } else {
399                     effectivePos = declaredPosition.get();
400                 }
401
402                 builder.addBit(EffectiveTypeUtil.buildBit(bitSubStmt, effectivePos));
403             }
404         }
405
406         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
407     }
408
409     private static @NonNull TypeEffectiveStatement<TypeStatement> createBoolean(final StmtContext<?, ?, ?> ctx,
410             final BooleanTypeDefinition baseType, final TypeStatement declared,
411             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
412         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newBooleanBuilder(baseType,
413             typeEffectiveSchemaPath(ctx)));
414     }
415
416     private static @NonNull TypeEffectiveStatement<TypeStatement> createDecimal(final StmtContext<?, ?, ?> ctx,
417             final DecimalTypeDefinition baseType, final TypeStatement declared,
418             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
419         final RangeRestrictedTypeBuilder<DecimalTypeDefinition, BigDecimal> builder =
420                 RestrictedTypes.newDecima64Builder(baseType, typeEffectiveSchemaPath(ctx));
421
422         for (EffectiveStatement<?, ?> stmt : substatements) {
423             if (stmt instanceof RangeEffectiveStatement) {
424                 final RangeEffectiveStatement range = (RangeEffectiveStatement) stmt;
425                 builder.setRangeConstraint(range, range.argument());
426             }
427             if (stmt instanceof FractionDigitsEffectiveStatement) {
428                 final Integer digits = ((FractionDigitsEffectiveStatement)stmt).argument();
429                 SourceException.throwIf(baseType.getFractionDigits() != digits, ctx.getStatementSourceReference(),
430                     "Cannot override fraction-digits from base type %s to %s", baseType, digits);
431             }
432         }
433
434         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
435     }
436
437     private static @NonNull TypeEffectiveStatement<TypeStatement> createEmpty(final StmtContext<?, ?, ?> ctx,
438             final EmptyTypeDefinition baseType, final TypeStatement declared,
439             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
440         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newEmptyBuilder(baseType,
441             typeEffectiveSchemaPath(ctx)));
442     }
443
444     private static @NonNull TypeEffectiveStatement<TypeStatement> createEnum(final StmtContext<?, ?, ?> ctx,
445             final EnumTypeDefinition baseType, final TypeStatement declared,
446             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
447         final EnumerationTypeBuilder builder = RestrictedTypes.newEnumerationBuilder(baseType,
448             ctx.getSchemaPath().get());
449
450         final YangVersion yangVersion = ctx.getRootVersion();
451         for (final EffectiveStatement<?, ?> stmt : substatements) {
452             if (stmt instanceof EnumEffectiveStatement) {
453                 SourceException.throwIf(yangVersion != YangVersion.VERSION_1_1, ctx.getStatementSourceReference(),
454                         "Restricted enumeration type is allowed only in YANG 1.1 version.");
455
456                 final EnumEffectiveStatement enumSubStmt = (EnumEffectiveStatement) stmt;
457                 final Optional<Integer> declaredValue =
458                         enumSubStmt.findFirstEffectiveSubstatementArgument(ValueEffectiveStatement.class);
459                 final int effectiveValue;
460                 if (declaredValue.isEmpty()) {
461                     effectiveValue = getBaseTypeEnumValue(enumSubStmt.getDeclared().rawArgument(), baseType, ctx);
462                 } else {
463                     effectiveValue = declaredValue.orElseThrow();
464                 }
465
466                 builder.addEnum(EffectiveTypeUtil.buildEnumPair(enumSubStmt, effectiveValue));
467             }
468         }
469
470         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
471     }
472
473     private static @NonNull TypeEffectiveStatement<TypeStatement> createIdentityref(final StmtContext<?, ?, ?> ctx,
474             final IdentityrefTypeDefinition baseType, final TypeStatement declared,
475             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
476         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newIdentityrefBuilder(baseType,
477             typeEffectiveSchemaPath(ctx)));
478     }
479
480     private static @NonNull TypeEffectiveStatement<TypeStatement> createInstanceIdentifier(
481             final StmtContext<?, ?, ?> ctx, final InstanceIdentifierTypeDefinition baseType,
482             final TypeStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
483         final InstanceIdentifierTypeBuilder builder = RestrictedTypes.newInstanceIdentifierBuilder(baseType,
484                     typeEffectiveSchemaPath(ctx));
485
486         for (EffectiveStatement<?, ?> stmt : substatements) {
487             if (stmt instanceof RequireInstanceEffectiveStatement) {
488                 builder.setRequireInstance(((RequireInstanceEffectiveStatement)stmt).argument());
489             }
490         }
491
492         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
493     }
494
495     private static <T extends RangeRestrictedTypeDefinition<T, N>, N extends Number & Comparable<N>>
496         @NonNull TypeEffectiveStatement<TypeStatement> createIntegral(final StmtContext<?, ?, ?> ctx,
497                 final TypeStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements,
498                 final RangeRestrictedTypeBuilder<T, N> builder) {
499         for (EffectiveStatement<?, ?> stmt : substatements) {
500             if (stmt instanceof RangeEffectiveStatement) {
501                 final RangeEffectiveStatement rangeStmt = (RangeEffectiveStatement)stmt;
502                 builder.setRangeConstraint(rangeStmt, rangeStmt.argument());
503             }
504         }
505
506         try {
507             return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
508         } catch (InvalidRangeConstraintException e) {
509             throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid range constraint: %s",
510                 e.getOffendingRanges());
511         }
512     }
513
514     private static @NonNull TypeEffectiveStatement<TypeStatement> createLeafref(final StmtContext<?, ?, ?> ctx,
515             final LeafrefTypeDefinition baseType, final TypeStatement declared,
516             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
517         final RequireInstanceRestrictedTypeBuilder<LeafrefTypeDefinition> builder =
518                 RestrictedTypes.newLeafrefBuilder(baseType, AbstractTypeStatementSupport.typeEffectiveSchemaPath(ctx));
519
520         for (final EffectiveStatement<?, ?> stmt : substatements) {
521             if (stmt instanceof RequireInstanceEffectiveStatement) {
522                 builder.setRequireInstance(((RequireInstanceEffectiveStatement) stmt).argument());
523             }
524         }
525         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
526     }
527
528     private static @NonNull TypeEffectiveStatement<TypeStatement> createString(final StmtContext<?, ?, ?> ctx,
529             final StringTypeDefinition baseType, final TypeStatement declared,
530             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
531         final StringTypeBuilder builder = RestrictedTypes.newStringBuilder(baseType,
532             AbstractTypeStatementSupport.typeEffectiveSchemaPath(ctx));
533
534         for (EffectiveStatement<?, ?> stmt : substatements) {
535             if (stmt instanceof LengthEffectiveStatement) {
536                 final LengthEffectiveStatement length = (LengthEffectiveStatement)stmt;
537
538                 try {
539                     builder.setLengthConstraint(length, length.argument());
540                 } catch (IllegalStateException e) {
541                     throw new SourceException(ctx.getStatementSourceReference(), e,
542                             "Multiple length constraints encountered");
543                 } catch (InvalidLengthConstraintException e) {
544                     throw new SourceException(ctx.getStatementSourceReference(), e, "Invalid length constraint %s",
545                         length.argument());
546                 }
547             }
548             if (stmt instanceof PatternEffectiveStatement) {
549                 final PatternConstraint pattern = ((PatternEffectiveStatement)stmt).argument();
550                 if (pattern != null) {
551                     builder.addPatternConstraint(pattern);
552                 } else {
553                     LOG.debug("Ignoring empty pattern statement {}", stmt);
554                 }
555             }
556         }
557
558         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
559     }
560
561     private static @NonNull TypeEffectiveStatement<TypeStatement> createUnion(final StmtContext<?, ?, ?> ctx,
562             final UnionTypeDefinition baseType, final TypeStatement declared,
563             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
564         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newUnionBuilder(baseType,
565             typeEffectiveSchemaPath(ctx)));
566     }
567
568     private static Uint32 getBaseTypeBitPosition(final String bitName, final BitsTypeDefinition baseType,
569             final StmtContext<?, ?, ?> ctx) {
570         for (Bit baseTypeBit : baseType.getBits()) {
571             if (bitName.equals(baseTypeBit.getName())) {
572                 return baseTypeBit.getPosition();
573             }
574         }
575
576         throw new SourceException(ctx.getStatementSourceReference(),
577                 "Bit '%s' is not a subset of its base bits type %s.", bitName, baseType.getQName());
578     }
579
580     private static int getBaseTypeEnumValue(final String enumName, final EnumTypeDefinition baseType,
581             final StmtContext<?, ?, ?> ctx) {
582         for (EnumPair baseTypeEnumPair : baseType.getValues()) {
583             if (enumName.equals(baseTypeEnumPair.getName())) {
584                 return baseTypeEnumPair.getValue();
585             }
586         }
587
588         throw new SourceException(ctx.getStatementSourceReference(),
589                 "Enum '%s' is not a subset of its base enumeration type %s.", enumName, baseType.getQName());
590     }
591 }