Reformulate StatementContextFactory.createEffective()
[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.RangeRestrictedTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.Uint16TypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.Uint32TypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.Uint64TypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.Uint8TypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.util.type.BitsTypeBuilder;
61 import org.opendaylight.yangtools.yang.model.util.type.EnumerationTypeBuilder;
62 import org.opendaylight.yangtools.yang.model.util.type.InstanceIdentifierTypeBuilder;
63 import org.opendaylight.yangtools.yang.model.util.type.InvalidLengthConstraintException;
64 import org.opendaylight.yangtools.yang.model.util.type.InvalidRangeConstraintException;
65 import org.opendaylight.yangtools.yang.model.util.type.LengthRestrictedTypeBuilder;
66 import org.opendaylight.yangtools.yang.model.util.type.RangeRestrictedTypeBuilder;
67 import org.opendaylight.yangtools.yang.model.util.type.RequireInstanceRestrictedTypeBuilder;
68 import org.opendaylight.yangtools.yang.model.util.type.RestrictedTypes;
69 import org.opendaylight.yangtools.yang.model.util.type.StringTypeBuilder;
70 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.BaseStatementSupport;
71 import org.opendaylight.yangtools.yang.parser.spi.TypeNamespace;
72 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
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.coerceRawStatementArgument(), 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
233             : new EmptyTypeStatement(ctx.coerceRawStatementArgument());
234     }
235
236     @Override
237     protected EffectiveStatement<String, TypeStatement> createEffective(final Current<String, TypeStatement> stmt,
238             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
239         // First look up the proper base type
240         final TypeEffectiveStatement<TypeStatement> typeStmt = resolveType(stmt);
241         if (substatements.isEmpty()) {
242             return typeStmt;
243         }
244
245         // Now instantiate the proper effective statement for that type
246         final TypeDefinition<?> baseType = typeStmt.getTypeDefinition();
247         final TypeStatement declared = stmt.declared();
248         if (baseType instanceof BinaryTypeDefinition) {
249             return createBinary(stmt, (BinaryTypeDefinition) baseType, declared, substatements);
250         } else if (baseType instanceof BitsTypeDefinition) {
251             return createBits(stmt, (BitsTypeDefinition) baseType, declared, substatements);
252         } else if (baseType instanceof BooleanTypeDefinition) {
253             return createBoolean(stmt, (BooleanTypeDefinition) baseType, declared, substatements);
254         } else if (baseType instanceof DecimalTypeDefinition) {
255             return createDecimal(stmt, (DecimalTypeDefinition) baseType, declared, substatements);
256         } else if (baseType instanceof EmptyTypeDefinition) {
257             return createEmpty(stmt, (EmptyTypeDefinition) baseType, declared, substatements);
258         } else if (baseType instanceof EnumTypeDefinition) {
259             return createEnum(stmt, (EnumTypeDefinition) baseType, declared, substatements);
260         } else if (baseType instanceof IdentityrefTypeDefinition) {
261             return createIdentityref(stmt, (IdentityrefTypeDefinition) baseType, declared, substatements);
262         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
263             return createInstanceIdentifier(stmt, (InstanceIdentifierTypeDefinition) baseType, declared, substatements);
264         } else if (baseType instanceof Int8TypeDefinition) {
265             return createIntegral(stmt, declared, substatements,
266                 RestrictedTypes.newInt8Builder((Int8TypeDefinition) baseType, typeEffectiveSchemaPath(stmt)));
267         } else if (baseType instanceof Int16TypeDefinition) {
268             return createIntegral(stmt, declared, substatements,
269                 RestrictedTypes.newInt16Builder((Int16TypeDefinition) baseType, typeEffectiveSchemaPath(stmt)));
270         } else if (baseType instanceof Int32TypeDefinition) {
271             return createIntegral(stmt, declared, substatements,
272                 RestrictedTypes.newInt32Builder((Int32TypeDefinition) baseType, typeEffectiveSchemaPath(stmt)));
273         } else if (baseType instanceof Int64TypeDefinition) {
274             return createIntegral(stmt, declared, substatements,
275                 RestrictedTypes.newInt64Builder((Int64TypeDefinition) baseType, typeEffectiveSchemaPath(stmt)));
276         } else if (baseType instanceof LeafrefTypeDefinition) {
277             return createLeafref(stmt, (LeafrefTypeDefinition) baseType, declared, substatements);
278         } else if (baseType instanceof StringTypeDefinition) {
279             return createString(stmt, (StringTypeDefinition) baseType, declared, substatements);
280         } else if (baseType instanceof Uint8TypeDefinition) {
281             return createIntegral(stmt, declared, substatements,
282                 RestrictedTypes.newUint8Builder((Uint8TypeDefinition) baseType, typeEffectiveSchemaPath(stmt)));
283         } else if (baseType instanceof Uint16TypeDefinition) {
284             return createIntegral(stmt, declared, substatements,
285                 RestrictedTypes.newUint16Builder((Uint16TypeDefinition) baseType, typeEffectiveSchemaPath(stmt)));
286         } else if (baseType instanceof Uint32TypeDefinition) {
287             return createIntegral(stmt, declared, substatements,
288                 RestrictedTypes.newUint32Builder((Uint32TypeDefinition) baseType, typeEffectiveSchemaPath(stmt)));
289         } else if (baseType instanceof Uint64TypeDefinition) {
290             return createIntegral(stmt, declared, substatements,
291                 RestrictedTypes.newUint64Builder((Uint64TypeDefinition) baseType, typeEffectiveSchemaPath(stmt)));
292         } else if (baseType instanceof UnionTypeDefinition) {
293             return createUnion(stmt, (UnionTypeDefinition) baseType, declared, substatements);
294         } else {
295             throw new IllegalStateException("Unhandled base type " + baseType);
296         }
297     }
298
299     static final SchemaPath typeEffectiveSchemaPath(final Current<?, ?> stmt) {
300         final SchemaPath path = stmt.getSchemaPath();
301         final SchemaPath parent = path.getParent();
302         final QName parentQName = parent.getLastComponent();
303         checkArgument(parentQName != null, "Path %s has an empty parent", path);
304
305         final QName qname = path.getLastComponent().bindTo(parentQName.getModule()).intern();
306         return parent.createChild(qname);
307     }
308
309     /**
310      * Resolve type reference, as pointed to by the context's argument.
311      *
312      * @param ctx Statement context
313      * @return Resolved type
314      * @throws SourceException if the target type cannot be found
315      */
316     private static @NonNull TypeEffectiveStatement<TypeStatement> resolveType(final Current<String, ?> ctx) {
317         final String argument = ctx.coerceArgument();
318         switch (argument) {
319             case BINARY:
320                 return BuiltinEffectiveStatement.BINARY;
321             case BOOLEAN:
322                 return BuiltinEffectiveStatement.BOOLEAN;
323             case EMPTY:
324                 return BuiltinEffectiveStatement.EMPTY;
325             case INSTANCE_IDENTIFIER:
326                 return BuiltinEffectiveStatement.INSTANCE_IDENTIFIER;
327             case INT8:
328                 return BuiltinEffectiveStatement.INT8;
329             case INT16:
330                 return BuiltinEffectiveStatement.INT16;
331             case INT32:
332                 return BuiltinEffectiveStatement.INT32;
333             case INT64:
334                 return BuiltinEffectiveStatement.INT64;
335             case STRING:
336                 return BuiltinEffectiveStatement.STRING;
337             case UINT8:
338                 return BuiltinEffectiveStatement.UINT8;
339             case UINT16:
340                 return BuiltinEffectiveStatement.UINT16;
341             case UINT32:
342                 return BuiltinEffectiveStatement.UINT32;
343             case UINT64:
344                 return BuiltinEffectiveStatement.UINT64;
345             default:
346                 final QName qname = StmtContextUtils.parseNodeIdentifier(ctx.caerbannog(), argument);
347                 final StmtContext<?, TypedefStatement, TypedefEffectiveStatement> typedef =
348                         SourceException.throwIfNull(ctx.getFromNamespace(TypeNamespace.class, qname),
349                             ctx.sourceReference(), "Type '%s' not found", qname);
350                 return typedef.buildEffective().asTypeEffectiveStatement();
351         }
352     }
353
354     private static @NonNull TypeEffectiveStatement<TypeStatement> createBinary(final Current<?, ?> ctx,
355             final BinaryTypeDefinition baseType, final TypeStatement declared,
356             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
357         final LengthRestrictedTypeBuilder<BinaryTypeDefinition> builder =
358                 RestrictedTypes.newBinaryBuilder(baseType, typeEffectiveSchemaPath(ctx));
359
360         for (EffectiveStatement<?, ?> stmt : substatements) {
361             if (stmt instanceof LengthEffectiveStatement) {
362                 final LengthEffectiveStatement length = (LengthEffectiveStatement)stmt;
363
364                 try {
365                     builder.setLengthConstraint(length, length.argument());
366                 } catch (IllegalStateException e) {
367                     throw new SourceException(ctx.sourceReference(), e, "Multiple length constraints encountered");
368                 } catch (InvalidLengthConstraintException e) {
369                     throw new SourceException(ctx.sourceReference(), e, "Invalid length constraint %s",
370                         length.argument());
371                 }
372             }
373         }
374
375         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
376     }
377
378     private static @NonNull TypeEffectiveStatement<TypeStatement> createBits(final Current<?, ?> ctx,
379             final BitsTypeDefinition baseType, final TypeStatement declared,
380             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
381         final BitsTypeBuilder builder = RestrictedTypes.newBitsBuilder(baseType, ctx.getSchemaPath());
382
383         final YangVersion yangVersion = ctx.yangVersion();
384         for (final EffectiveStatement<?, ?> stmt : substatements) {
385             if (stmt instanceof BitEffectiveStatement) {
386                 SourceException.throwIf(yangVersion != YangVersion.VERSION_1_1, ctx.sourceReference(),
387                         "Restricted bits type is allowed only in YANG 1.1 version.");
388                 final BitEffectiveStatement bitSubStmt = (BitEffectiveStatement) stmt;
389
390                 // FIXME: this looks like a duplicate of BitsSpecificationEffectiveStatement
391                 final Optional<Uint32> declaredPosition = bitSubStmt.getDeclaredPosition();
392                 final Uint32 effectivePos;
393                 if (declaredPosition.isEmpty()) {
394                     effectivePos = getBaseTypeBitPosition(bitSubStmt.argument(), baseType, ctx);
395                 } else {
396                     effectivePos = declaredPosition.get();
397                 }
398
399                 builder.addBit(EffectiveTypeUtil.buildBit(bitSubStmt, effectivePos));
400             }
401         }
402
403         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
404     }
405
406     private static @NonNull TypeEffectiveStatement<TypeStatement> createBoolean(final Current<?, ?> ctx,
407             final BooleanTypeDefinition baseType, final TypeStatement declared,
408             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
409         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newBooleanBuilder(baseType,
410             typeEffectiveSchemaPath(ctx)));
411     }
412
413     private static @NonNull TypeEffectiveStatement<TypeStatement> createDecimal(final Current<?, ?> ctx,
414             final DecimalTypeDefinition baseType, final TypeStatement declared,
415             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
416         final RangeRestrictedTypeBuilder<DecimalTypeDefinition, BigDecimal> builder =
417                 RestrictedTypes.newDecima64Builder(baseType, typeEffectiveSchemaPath(ctx));
418
419         for (EffectiveStatement<?, ?> stmt : substatements) {
420             if (stmt instanceof RangeEffectiveStatement) {
421                 final RangeEffectiveStatement range = (RangeEffectiveStatement) stmt;
422                 builder.setRangeConstraint(range, range.argument());
423             }
424             if (stmt instanceof FractionDigitsEffectiveStatement) {
425                 final Integer digits = ((FractionDigitsEffectiveStatement)stmt).argument();
426                 SourceException.throwIf(baseType.getFractionDigits() != digits, ctx.sourceReference(),
427                     "Cannot override fraction-digits from base type %s to %s", baseType, digits);
428             }
429         }
430
431         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
432     }
433
434     private static @NonNull TypeEffectiveStatement<TypeStatement> createEmpty(final Current<?, ?> ctx,
435             final EmptyTypeDefinition baseType, final TypeStatement declared,
436             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
437         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newEmptyBuilder(baseType,
438             typeEffectiveSchemaPath(ctx)));
439     }
440
441     private static @NonNull TypeEffectiveStatement<TypeStatement> createEnum(final Current<?, ?> ctx,
442             final EnumTypeDefinition baseType, final TypeStatement declared,
443             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
444         final EnumerationTypeBuilder builder = RestrictedTypes.newEnumerationBuilder(baseType, ctx.getSchemaPath());
445
446         final YangVersion yangVersion = ctx.yangVersion();
447         for (final EffectiveStatement<?, ?> stmt : substatements) {
448             if (stmt instanceof EnumEffectiveStatement) {
449                 SourceException.throwIf(yangVersion != YangVersion.VERSION_1_1, ctx.sourceReference(),
450                         "Restricted enumeration type is allowed only in YANG 1.1 version.");
451
452                 final EnumEffectiveStatement enumSubStmt = (EnumEffectiveStatement) stmt;
453                 final Optional<Integer> declaredValue =
454                         enumSubStmt.findFirstEffectiveSubstatementArgument(ValueEffectiveStatement.class);
455                 final int effectiveValue;
456                 if (declaredValue.isEmpty()) {
457                     effectiveValue = getBaseTypeEnumValue(enumSubStmt.getDeclared().rawArgument(), baseType, ctx);
458                 } else {
459                     effectiveValue = declaredValue.orElseThrow();
460                 }
461
462                 builder.addEnum(EffectiveTypeUtil.buildEnumPair(enumSubStmt, effectiveValue));
463             }
464         }
465
466         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
467     }
468
469     private static @NonNull TypeEffectiveStatement<TypeStatement> createIdentityref(final Current<?, ?> ctx,
470             final IdentityrefTypeDefinition baseType, final TypeStatement declared,
471             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
472         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newIdentityrefBuilder(baseType,
473             typeEffectiveSchemaPath(ctx)));
474     }
475
476     private static @NonNull TypeEffectiveStatement<TypeStatement> createInstanceIdentifier(
477             final Current<?, ?> ctx, final InstanceIdentifierTypeDefinition baseType, final TypeStatement declared,
478             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
479         final InstanceIdentifierTypeBuilder builder = RestrictedTypes.newInstanceIdentifierBuilder(baseType,
480                     typeEffectiveSchemaPath(ctx));
481
482         for (EffectiveStatement<?, ?> stmt : substatements) {
483             if (stmt instanceof RequireInstanceEffectiveStatement) {
484                 builder.setRequireInstance(((RequireInstanceEffectiveStatement)stmt).argument());
485             }
486         }
487
488         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
489     }
490
491     private static <T extends RangeRestrictedTypeDefinition<T, N>, N extends Number & Comparable<N>>
492         @NonNull TypeEffectiveStatement<TypeStatement> createIntegral(final Current<?, ?> ctx,
493                 final TypeStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements,
494                 final RangeRestrictedTypeBuilder<T, N> builder) {
495         for (EffectiveStatement<?, ?> stmt : substatements) {
496             if (stmt instanceof RangeEffectiveStatement) {
497                 final RangeEffectiveStatement rangeStmt = (RangeEffectiveStatement)stmt;
498                 builder.setRangeConstraint(rangeStmt, rangeStmt.argument());
499             }
500         }
501
502         try {
503             return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
504         } catch (InvalidRangeConstraintException e) {
505             throw new SourceException(ctx.sourceReference(), e, "Invalid range constraint: %s",
506                 e.getOffendingRanges());
507         }
508     }
509
510     private static @NonNull TypeEffectiveStatement<TypeStatement> createLeafref(final Current<?, ?> ctx,
511             final LeafrefTypeDefinition baseType, final TypeStatement declared,
512             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
513         final RequireInstanceRestrictedTypeBuilder<LeafrefTypeDefinition> builder =
514                 RestrictedTypes.newLeafrefBuilder(baseType, AbstractTypeStatementSupport.typeEffectiveSchemaPath(ctx));
515
516         for (final EffectiveStatement<?, ?> stmt : substatements) {
517             if (stmt instanceof RequireInstanceEffectiveStatement) {
518                 builder.setRequireInstance(((RequireInstanceEffectiveStatement) stmt).argument());
519             }
520         }
521         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
522     }
523
524     private static @NonNull TypeEffectiveStatement<TypeStatement> createString(final Current<?, ?> ctx,
525             final StringTypeDefinition baseType, final TypeStatement declared,
526             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
527         final StringTypeBuilder builder = RestrictedTypes.newStringBuilder(baseType,
528             AbstractTypeStatementSupport.typeEffectiveSchemaPath(ctx));
529
530         for (EffectiveStatement<?, ?> stmt : substatements) {
531             if (stmt instanceof LengthEffectiveStatement) {
532                 final LengthEffectiveStatement length = (LengthEffectiveStatement)stmt;
533
534                 try {
535                     builder.setLengthConstraint(length, length.argument());
536                 } catch (IllegalStateException e) {
537                     throw new SourceException(ctx.sourceReference(), e, "Multiple length constraints encountered");
538                 } catch (InvalidLengthConstraintException e) {
539                     throw new SourceException(ctx.sourceReference(), e, "Invalid length constraint %s",
540                         length.argument());
541                 }
542             }
543             if (stmt instanceof PatternEffectiveStatement) {
544                 builder.addPatternConstraint((PatternEffectiveStatement) stmt);
545             }
546         }
547
548         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
549     }
550
551     private static @NonNull TypeEffectiveStatement<TypeStatement> createUnion(final Current<?, ?> ctx,
552             final UnionTypeDefinition baseType, final TypeStatement declared,
553             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
554         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newUnionBuilder(baseType,
555             typeEffectiveSchemaPath(ctx)));
556     }
557
558     private static Uint32 getBaseTypeBitPosition(final String bitName, final BitsTypeDefinition baseType,
559             final Current<?, ?> ctx) {
560         for (Bit baseTypeBit : baseType.getBits()) {
561             if (bitName.equals(baseTypeBit.getName())) {
562                 return baseTypeBit.getPosition();
563             }
564         }
565
566         throw new SourceException(ctx.sourceReference(), "Bit '%s' is not a subset of its base bits type %s.",
567             bitName, baseType.getQName());
568     }
569
570     private static int getBaseTypeEnumValue(final String enumName, final EnumTypeDefinition baseType,
571             final Current<?, ?> ctx) {
572         for (EnumPair baseTypeEnumPair : baseType.getValues()) {
573             if (enumName.equals(baseTypeEnumPair.getName())) {
574                 return baseTypeEnumPair.getValue();
575             }
576         }
577
578         throw new SourceException(ctx.sourceReference(), "Enum '%s' is not a subset of its base enumeration type %s.",
579             enumName, baseType.getQName());
580     }
581 }