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