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