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