Refactor AbstractTypeStatementSupport.typeEffectiveQName()
[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 com.google.common.collect.ImmutableList;
11 import com.google.common.collect.ImmutableMap;
12 import java.math.BigDecimal;
13 import java.util.Collection;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.yangtools.yang.common.Empty;
16 import org.opendaylight.yangtools.yang.common.QName;
17 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
18 import org.opendaylight.yangtools.yang.model.api.YangStmtMapping;
19 import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
20 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
21 import org.opendaylight.yangtools.yang.model.api.stmt.BitEffectiveStatement;
22 import org.opendaylight.yangtools.yang.model.api.stmt.EnumEffectiveStatement;
23 import org.opendaylight.yangtools.yang.model.api.stmt.FractionDigitsEffectiveStatement;
24 import org.opendaylight.yangtools.yang.model.api.stmt.LengthEffectiveStatement;
25 import org.opendaylight.yangtools.yang.model.api.stmt.PatternEffectiveStatement;
26 import org.opendaylight.yangtools.yang.model.api.stmt.RangeEffectiveStatement;
27 import org.opendaylight.yangtools.yang.model.api.stmt.RequireInstanceEffectiveStatement;
28 import org.opendaylight.yangtools.yang.model.api.stmt.TypeEffectiveStatement;
29 import org.opendaylight.yangtools.yang.model.api.stmt.TypeStatement;
30 import org.opendaylight.yangtools.yang.model.api.stmt.TypedefEffectiveStatement;
31 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
32 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
33 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
34 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
35 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
36 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
37 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
38 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
39 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.Int16TypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.Int32TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.Int64TypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.Int8TypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.RangeRestrictedTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.Uint16TypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.Uint32TypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.Uint64TypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.Uint8TypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.util.type.BitsTypeBuilder;
54 import org.opendaylight.yangtools.yang.model.util.type.EnumerationTypeBuilder;
55 import org.opendaylight.yangtools.yang.model.util.type.InstanceIdentifierTypeBuilder;
56 import org.opendaylight.yangtools.yang.model.util.type.InvalidLengthConstraintException;
57 import org.opendaylight.yangtools.yang.model.util.type.InvalidRangeConstraintException;
58 import org.opendaylight.yangtools.yang.model.util.type.LengthRestrictedTypeBuilder;
59 import org.opendaylight.yangtools.yang.model.util.type.RangeRestrictedTypeBuilder;
60 import org.opendaylight.yangtools.yang.model.util.type.RequireInstanceRestrictedTypeBuilder;
61 import org.opendaylight.yangtools.yang.model.util.type.RestrictedTypes;
62 import org.opendaylight.yangtools.yang.model.util.type.StringTypeBuilder;
63 import org.opendaylight.yangtools.yang.parser.spi.TypeNamespace;
64 import org.opendaylight.yangtools.yang.parser.spi.meta.AbstractStatementSupport;
65 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx;
66 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
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 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
81
82 abstract class AbstractTypeStatementSupport
83         extends AbstractStatementSupport<String, TypeStatement, EffectiveStatement<String, TypeStatement>> {
84     private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeStatementSupport.class);
85
86     private static final SubstatementValidator SUBSTATEMENT_VALIDATOR = SubstatementValidator.builder(
87         YangStmtMapping.TYPE)
88         .addOptional(YangStmtMapping.BASE)
89         .addAny(YangStmtMapping.BIT)
90         .addAny(YangStmtMapping.ENUM)
91         .addOptional(YangStmtMapping.FRACTION_DIGITS)
92         .addOptional(YangStmtMapping.LENGTH)
93         .addOptional(YangStmtMapping.PATH)
94         .addAny(YangStmtMapping.PATTERN)
95         .addOptional(YangStmtMapping.RANGE)
96         .addOptional(YangStmtMapping.REQUIRE_INSTANCE)
97         .addAny(YangStmtMapping.TYPE)
98         .build();
99
100     static final String BINARY = "binary";
101     static final String BITS = "bits";
102     static final String BOOLEAN = "boolean";
103     static final String DECIMAL64 = "decimal64";
104     static final String EMPTY = "empty";
105     static final String ENUMERATION = "enumeration";
106     static final String IDENTITY_REF = "identityref";
107     static final String INSTANCE_IDENTIFIER = "instance-identifier";
108     static final String INT8 = "int8";
109     static final String INT16 = "int16";
110     static final String INT32 = "int32";
111     static final String INT64 = "int64";
112     static final String LEAF_REF = "leafref";
113     static final String STRING = "string";
114     static final String UINT8 = "uint8";
115     static final String UINT16 = "uint16";
116     static final String UINT32 = "uint32";
117     static final String UINT64 = "uint64";
118     static final String UNION = "union";
119
120     private static final ImmutableMap<String, String> BUILT_IN_TYPES = ImmutableMap.<String, String>builder()
121         .put(BINARY, BINARY)
122         .put(BITS, BITS)
123         .put(BOOLEAN, BOOLEAN)
124         .put(DECIMAL64, DECIMAL64)
125         .put(EMPTY, EMPTY)
126         .put(ENUMERATION, ENUMERATION)
127         .put(IDENTITY_REF,IDENTITY_REF)
128         .put(INSTANCE_IDENTIFIER, INSTANCE_IDENTIFIER)
129         .put(INT8, INT8)
130         .put(INT16, INT16)
131         .put(INT32, INT32)
132         .put(INT64, INT64)
133         .put(LEAF_REF, LEAF_REF)
134         .put(STRING, STRING)
135         .put(UINT8, UINT8)
136         .put(UINT16, UINT16)
137         .put(UINT32, UINT32)
138         .put(UINT64, UINT64)
139         .put(UNION, UNION)
140         .build();
141
142     private static final ImmutableMap<String, StatementSupport<?, ?, ?>> ARGUMENT_SPECIFIC_SUPPORTS =
143             ImmutableMap.<String, StatementSupport<?, ?, ?>>builder()
144             .put(BITS, new BitsSpecificationSupport())
145             .put(DECIMAL64, new Decimal64SpecificationSupport())
146             .put(ENUMERATION, new EnumSpecificationSupport())
147             .put(IDENTITY_REF, new IdentityRefSpecificationRFC6020Support())
148             .put(INSTANCE_IDENTIFIER, new InstanceIdentifierSpecificationSupport())
149             .put(LEAF_REF, new LeafrefSpecificationRFC6020Support())
150             .put(UNION, new UnionSpecificationSupport())
151             .build();
152
153     AbstractTypeStatementSupport() {
154         // FIXME: can a type statement be copied?
155         super(YangStmtMapping.TYPE, StatementPolicy.legacyDeclaredCopy());
156     }
157
158     @Override
159     public final String parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
160         return value;
161     }
162
163     @Override
164     public final void onFullDefinitionDeclared(
165             final Mutable<String, TypeStatement, EffectiveStatement<String, TypeStatement>> stmt) {
166         super.onFullDefinitionDeclared(stmt);
167
168         // if it is yang built-in type, no prerequisite is needed, so simply return
169         if (BUILT_IN_TYPES.containsKey(stmt.argument())) {
170             // FIXME: consider populating BaseTypeNamespace here, which could be done quite efficiently, moving the
171             //        logic from resolveType()
172             return;
173         }
174
175         final QName typeQName = StmtContextUtils.parseNodeIdentifier(stmt, stmt.argument());
176         final ModelActionBuilder typeAction = stmt.newInferenceAction(ModelProcessingPhase.EFFECTIVE_MODEL);
177         final Prerequisite<StmtContext<?, ?, ?>> typePrereq = typeAction.requiresCtx(stmt, TypeNamespace.class,
178                 typeQName, ModelProcessingPhase.EFFECTIVE_MODEL);
179         typeAction.mutatesEffectiveCtx(stmt.getParentContext());
180
181         /*
182          * If the type does not exist, throw an InferenceException.
183          * If the type exists, store a reference to it in BaseTypeNamespace.
184          */
185         typeAction.apply(new InferenceAction() {
186             @Override
187             public void apply(final InferenceContext ctx) {
188                 stmt.addToNs(BaseTypeNamespace.class, Empty.getInstance(), typePrereq.resolve(ctx));
189             }
190
191             @Override
192             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
193                 InferenceException.throwIf(failed.contains(typePrereq), stmt, "Type [%s] was not found.", typeQName);
194             }
195         });
196     }
197
198     @Override
199     public final String internArgument(final String rawArgument) {
200         final String found;
201         return (found = BUILT_IN_TYPES.get(rawArgument)) != null ? found : rawArgument;
202     }
203
204     @Override
205     public boolean hasArgumentSpecificSupports() {
206         return !ARGUMENT_SPECIFIC_SUPPORTS.isEmpty();
207     }
208
209     @Override
210     public StatementSupport<?, ?, ?> getSupportSpecificForArgument(final String argument) {
211         return ARGUMENT_SPECIFIC_SUPPORTS.get(argument);
212     }
213
214     @Override
215     protected final SubstatementValidator getSubstatementValidator() {
216         return SUBSTATEMENT_VALIDATOR;
217     }
218
219     @Override
220     protected final TypeStatement createDeclared(final StmtContext<String, TypeStatement, ?> ctx,
221             final ImmutableList<? extends DeclaredStatement<?>> substatements) {
222         return new RegularTypeStatement(ctx.getRawArgument(), substatements);
223     }
224
225     @Override
226     protected final TypeStatement createEmptyDeclared(final StmtContext<String, TypeStatement, ?> ctx) {
227         final TypeStatement builtin;
228         return (builtin = BuiltinTypeStatement.lookup(ctx)) != null ? builtin
229             : new EmptyTypeStatement(ctx.getRawArgument());
230     }
231
232     @Override
233     protected EffectiveStatement<String, TypeStatement> createEffective(final Current<String, TypeStatement> stmt,
234             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
235         // First look up the proper base type
236         final TypeEffectiveStatement<TypeStatement> typeStmt = resolveType(stmt);
237         if (substatements.isEmpty()) {
238             return typeStmt;
239         }
240
241         // Now instantiate the proper effective statement for that type
242         final TypeDefinition<?> baseType = typeStmt.getTypeDefinition();
243         final TypeStatement declared = stmt.declared();
244         if (baseType instanceof BinaryTypeDefinition) {
245             return createBinary(stmt, (BinaryTypeDefinition) baseType, declared, substatements);
246         } else if (baseType instanceof BitsTypeDefinition) {
247             return createBits(stmt, (BitsTypeDefinition) baseType, declared, substatements);
248         } else if (baseType instanceof BooleanTypeDefinition) {
249             return createBoolean(stmt, (BooleanTypeDefinition) baseType, declared, substatements);
250         } else if (baseType instanceof DecimalTypeDefinition) {
251             return createDecimal(stmt, (DecimalTypeDefinition) baseType, declared, substatements);
252         } else if (baseType instanceof EmptyTypeDefinition) {
253             return createEmpty(stmt, (EmptyTypeDefinition) baseType, declared, substatements);
254         } else if (baseType instanceof EnumTypeDefinition) {
255             return createEnum(stmt, (EnumTypeDefinition) baseType, declared, substatements);
256         } else if (baseType instanceof IdentityrefTypeDefinition) {
257             return createIdentityref(stmt, (IdentityrefTypeDefinition) baseType, declared, substatements);
258         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
259             return createInstanceIdentifier(stmt, (InstanceIdentifierTypeDefinition) baseType, declared, substatements);
260         } else if (baseType instanceof Int8TypeDefinition) {
261             return createIntegral(stmt, declared, substatements,
262                 RestrictedTypes.newInt8Builder((Int8TypeDefinition) baseType, typeEffectiveQName(stmt)));
263         } else if (baseType instanceof Int16TypeDefinition) {
264             return createIntegral(stmt, declared, substatements,
265                 RestrictedTypes.newInt16Builder((Int16TypeDefinition) baseType, typeEffectiveQName(stmt)));
266         } else if (baseType instanceof Int32TypeDefinition) {
267             return createIntegral(stmt, declared, substatements,
268                 RestrictedTypes.newInt32Builder((Int32TypeDefinition) baseType, typeEffectiveQName(stmt)));
269         } else if (baseType instanceof Int64TypeDefinition) {
270             return createIntegral(stmt, declared, substatements,
271                 RestrictedTypes.newInt64Builder((Int64TypeDefinition) baseType, typeEffectiveQName(stmt)));
272         } else if (baseType instanceof LeafrefTypeDefinition) {
273             return createLeafref(stmt, (LeafrefTypeDefinition) baseType, declared, substatements);
274         } else if (baseType instanceof StringTypeDefinition) {
275             return createString(stmt, (StringTypeDefinition) baseType, declared, substatements);
276         } else if (baseType instanceof Uint8TypeDefinition) {
277             return createIntegral(stmt, declared, substatements,
278                 RestrictedTypes.newUint8Builder((Uint8TypeDefinition) baseType, typeEffectiveQName(stmt)));
279         } else if (baseType instanceof Uint16TypeDefinition) {
280             return createIntegral(stmt, declared, substatements,
281                 RestrictedTypes.newUint16Builder((Uint16TypeDefinition) baseType, typeEffectiveQName(stmt)));
282         } else if (baseType instanceof Uint32TypeDefinition) {
283             return createIntegral(stmt, declared, substatements,
284                 RestrictedTypes.newUint32Builder((Uint32TypeDefinition) baseType, typeEffectiveQName(stmt)));
285         } else if (baseType instanceof Uint64TypeDefinition) {
286             return createIntegral(stmt, declared, substatements,
287                 RestrictedTypes.newUint64Builder((Uint64TypeDefinition) baseType, typeEffectiveQName(stmt)));
288         } else if (baseType instanceof UnionTypeDefinition) {
289             return createUnion(stmt, (UnionTypeDefinition) baseType, declared, substatements);
290         } else {
291             throw new IllegalStateException("Unhandled base type " + baseType);
292         }
293     }
294
295     static final @NonNull QName typeEffectiveQName(final Current<String, ?> stmt) {
296         // FIXME: this really should be handled through A=AbstractQName, with two values coming out of parseArgument():
297         //        -- either UnqualifiedQName or QualifiedQName. Each of those can easily be bound to parent module:
298         //          stmt.getArgument().bindTo(parentNamespace). We could perhaps also make it a QName and deal with this
299         //        bit during adaptArgument().
300         final String argument = stmt.getArgument();
301         return QName.create(stmt.getEffectiveParent().effectiveNamespace(),
302             // Split out localName event if it is prefixed. This should really be in parseArgument()
303             argument.substring(argument.indexOf(':') + 1)).intern();
304     }
305
306     /**
307      * Resolve type reference, as pointed to by the context's argument.
308      *
309      * @param ctx Statement context
310      * @return Resolved type
311      * @throws SourceException if the target type cannot be found
312      */
313     private static @NonNull TypeEffectiveStatement<TypeStatement> resolveType(final Current<String, ?> ctx) {
314         final StmtContext<?, ?, ?> baseType = ctx.namespaceItem(BaseTypeNamespace.class, Empty.getInstance());
315         if (baseType != null) {
316             return ((TypedefEffectiveStatement) baseType.buildEffective()).asTypeEffectiveStatement();
317         }
318
319         final String argument = ctx.getArgument();
320         switch (argument) {
321             case BINARY:
322                 return BuiltinEffectiveStatement.BINARY;
323             case BOOLEAN:
324                 return BuiltinEffectiveStatement.BOOLEAN;
325             case EMPTY:
326                 return BuiltinEffectiveStatement.EMPTY;
327             case INSTANCE_IDENTIFIER:
328                 return BuiltinEffectiveStatement.INSTANCE_IDENTIFIER;
329             case INT8:
330                 return BuiltinEffectiveStatement.INT8;
331             case INT16:
332                 return BuiltinEffectiveStatement.INT16;
333             case INT32:
334                 return BuiltinEffectiveStatement.INT32;
335             case INT64:
336                 return BuiltinEffectiveStatement.INT64;
337             case STRING:
338                 return BuiltinEffectiveStatement.STRING;
339             case UINT8:
340                 return BuiltinEffectiveStatement.UINT8;
341             case UINT16:
342                 return BuiltinEffectiveStatement.UINT16;
343             case UINT32:
344                 return BuiltinEffectiveStatement.UINT32;
345             case UINT64:
346                 return BuiltinEffectiveStatement.UINT64;
347             default:
348                 throw new IllegalStateException("Unhandled type argument " + argument);
349         }
350     }
351
352     private static @NonNull TypeEffectiveStatement<TypeStatement> createBinary(final Current<String, ?> ctx,
353             final BinaryTypeDefinition baseType, final TypeStatement declared,
354             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
355         final LengthRestrictedTypeBuilder<BinaryTypeDefinition> builder =
356                 RestrictedTypes.newBinaryBuilder(baseType, typeEffectiveQName(ctx));
357
358         for (EffectiveStatement<?, ?> stmt : substatements) {
359             if (stmt instanceof LengthEffectiveStatement) {
360                 final LengthEffectiveStatement length = (LengthEffectiveStatement)stmt;
361
362                 try {
363                     builder.setLengthConstraint(length, length.argument());
364                 } catch (IllegalStateException e) {
365                     throw new SourceException(ctx, e, "Multiple length constraints encountered");
366                 } catch (InvalidLengthConstraintException e) {
367                     throw new SourceException(ctx, e, "Invalid length constraint %s", length.argument());
368                 }
369             }
370         }
371
372         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
373     }
374
375     private @NonNull TypeEffectiveStatement<TypeStatement> createBits(final Current<?, ?> ctx,
376             final BitsTypeDefinition baseType, final TypeStatement declared,
377             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
378         final BitsTypeBuilder builder = RestrictedTypes.newBitsBuilder(baseType, ctx.argumentAsTypeQName());
379
380         for (final EffectiveStatement<?, ?> stmt : substatements) {
381             if (stmt instanceof BitEffectiveStatement) {
382                 builder.addBit(addRestrictedBit(ctx, baseType, (BitEffectiveStatement) stmt));
383             }
384         }
385
386         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
387     }
388
389     abstract @NonNull Bit addRestrictedBit(@NonNull EffectiveStmtCtx stmt, @NonNull BitsTypeDefinition base,
390         @NonNull BitEffectiveStatement bit);
391
392     private static @NonNull TypeEffectiveStatement<TypeStatement> createBoolean(final Current<String, ?> ctx,
393             final BooleanTypeDefinition baseType, final TypeStatement declared,
394             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
395         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newBooleanBuilder(baseType,
396             typeEffectiveQName(ctx)));
397     }
398
399     private static @NonNull TypeEffectiveStatement<TypeStatement> createDecimal(final Current<String, ?> ctx,
400             final DecimalTypeDefinition baseType, final TypeStatement declared,
401             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
402         final RangeRestrictedTypeBuilder<DecimalTypeDefinition, BigDecimal> builder =
403                 RestrictedTypes.newDecima64Builder(baseType, typeEffectiveQName(ctx));
404
405         for (EffectiveStatement<?, ?> stmt : substatements) {
406             if (stmt instanceof RangeEffectiveStatement) {
407                 final RangeEffectiveStatement range = (RangeEffectiveStatement) stmt;
408                 builder.setRangeConstraint(range, range.argument());
409             }
410             if (stmt instanceof FractionDigitsEffectiveStatement) {
411                 final Integer digits = ((FractionDigitsEffectiveStatement)stmt).argument();
412                 SourceException.throwIf(baseType.getFractionDigits() != digits, ctx,
413                     "Cannot override fraction-digits from base type %s to %s", baseType, digits);
414             }
415         }
416
417         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
418     }
419
420     private static @NonNull TypeEffectiveStatement<TypeStatement> createEmpty(final Current<String, ?> ctx,
421             final EmptyTypeDefinition baseType, final TypeStatement declared,
422             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
423         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newEmptyBuilder(baseType,
424             typeEffectiveQName(ctx)));
425     }
426
427     private @NonNull TypeEffectiveStatement<TypeStatement> createEnum(final Current<?, ?> ctx,
428             final EnumTypeDefinition baseType, final TypeStatement declared,
429             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
430         final EnumerationTypeBuilder builder = RestrictedTypes.newEnumerationBuilder(baseType,
431             ctx.argumentAsTypeQName());
432
433         for (final EffectiveStatement<?, ?> stmt : substatements) {
434             if (stmt instanceof EnumEffectiveStatement) {
435                 builder.addEnum(addRestrictedEnum(ctx, baseType, (EnumEffectiveStatement) stmt));
436             }
437         }
438
439         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
440     }
441
442     abstract @NonNull EnumPair addRestrictedEnum(@NonNull EffectiveStmtCtx stmt, @NonNull EnumTypeDefinition base,
443         @NonNull EnumEffectiveStatement enumStmt);
444
445     private static @NonNull TypeEffectiveStatement<TypeStatement> createIdentityref(final Current<String, ?> ctx,
446             final IdentityrefTypeDefinition baseType, final TypeStatement declared,
447             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
448         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newIdentityrefBuilder(baseType,
449             typeEffectiveQName(ctx)));
450     }
451
452     private static @NonNull TypeEffectiveStatement<TypeStatement> createInstanceIdentifier(final Current<String, ?> ctx,
453             final InstanceIdentifierTypeDefinition baseType, final TypeStatement declared,
454             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
455         final InstanceIdentifierTypeBuilder builder = RestrictedTypes.newInstanceIdentifierBuilder(baseType,
456                     typeEffectiveQName(ctx));
457
458         for (EffectiveStatement<?, ?> stmt : substatements) {
459             if (stmt instanceof RequireInstanceEffectiveStatement) {
460                 builder.setRequireInstance(((RequireInstanceEffectiveStatement)stmt).argument());
461             }
462         }
463
464         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
465     }
466
467     private static <T extends RangeRestrictedTypeDefinition<T, N>, N extends Number & Comparable<N>>
468         @NonNull TypeEffectiveStatement<TypeStatement> createIntegral(final Current<?, ?> ctx,
469                 final TypeStatement declared, final ImmutableList<? extends EffectiveStatement<?, ?>> substatements,
470                 final RangeRestrictedTypeBuilder<T, N> builder) {
471         for (EffectiveStatement<?, ?> stmt : substatements) {
472             if (stmt instanceof RangeEffectiveStatement) {
473                 final RangeEffectiveStatement rangeStmt = (RangeEffectiveStatement)stmt;
474                 builder.setRangeConstraint(rangeStmt, rangeStmt.argument());
475             }
476         }
477
478         try {
479             return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
480         } catch (InvalidRangeConstraintException e) {
481             throw new SourceException(ctx, e, "Invalid range constraint: %s", e.getOffendingRanges());
482         }
483     }
484
485     private static @NonNull TypeEffectiveStatement<TypeStatement> createLeafref(final Current<String, ?> ctx,
486             final LeafrefTypeDefinition baseType, final TypeStatement declared,
487             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
488         final RequireInstanceRestrictedTypeBuilder<LeafrefTypeDefinition> builder =
489                 RestrictedTypes.newLeafrefBuilder(baseType, AbstractTypeStatementSupport.typeEffectiveQName(ctx));
490
491         for (final EffectiveStatement<?, ?> stmt : substatements) {
492             if (stmt instanceof RequireInstanceEffectiveStatement) {
493                 builder.setRequireInstance(((RequireInstanceEffectiveStatement) stmt).argument());
494             }
495         }
496         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
497     }
498
499     private static @NonNull TypeEffectiveStatement<TypeStatement> createString(final Current<String, ?> ctx,
500             final StringTypeDefinition baseType, final TypeStatement declared,
501             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
502         final StringTypeBuilder builder = RestrictedTypes.newStringBuilder(baseType,
503             AbstractTypeStatementSupport.typeEffectiveQName(ctx));
504
505         for (EffectiveStatement<?, ?> stmt : substatements) {
506             if (stmt instanceof LengthEffectiveStatement) {
507                 final LengthEffectiveStatement length = (LengthEffectiveStatement)stmt;
508
509                 try {
510                     builder.setLengthConstraint(length, length.argument());
511                 } catch (IllegalStateException e) {
512                     throw new SourceException(ctx, e, "Multiple length constraints encountered");
513                 } catch (InvalidLengthConstraintException e) {
514                     throw new SourceException(ctx, e, "Invalid length constraint %s", length.argument());
515                 }
516             }
517             if (stmt instanceof PatternEffectiveStatement) {
518                 builder.addPatternConstraint((PatternEffectiveStatement) stmt);
519             }
520         }
521
522         return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
523     }
524
525     private static @NonNull TypeEffectiveStatement<TypeStatement> createUnion(final Current<String, ?> ctx,
526             final UnionTypeDefinition baseType, final TypeStatement declared,
527             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
528         return new TypeEffectiveStatementImpl<>(declared, substatements, RestrictedTypes.newUnionBuilder(baseType,
529             typeEffectiveQName(ctx)));
530     }
531 }