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