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