2 * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.generator.impl.reactor;
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.base.MoreObjects.ToStringHelper;
14 import com.google.common.base.VerifyException;
15 import org.eclipse.jdt.annotation.NonNull;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.opendaylight.mdsal.binding.generator.impl.reactor.CollisionDomain.Member;
18 import org.opendaylight.mdsal.binding.generator.impl.tree.StatementRepresentation;
19 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
20 import org.opendaylight.mdsal.binding.model.api.MethodSignature.ValueMechanics;
21 import org.opendaylight.mdsal.binding.model.api.Type;
22 import org.opendaylight.mdsal.binding.model.api.TypeMemberComment;
23 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
24 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
25 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
26 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
27 import org.opendaylight.yangtools.yang.binding.contract.Naming;
28 import org.opendaylight.yangtools.yang.common.AbstractQName;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.model.api.AddedByUsesAware;
31 import org.opendaylight.yangtools.yang.model.api.CopyableNode;
32 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
33 import org.opendaylight.yangtools.yang.model.api.stmt.DescriptionEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
39 * An explicit {@link Generator}, associated with a particular {@link EffectiveStatement}.
41 // FIXME: unify this with Generator
42 public abstract class AbstractExplicitGenerator<S extends EffectiveStatement<?, ?>, R extends RuntimeType>
43 extends Generator implements CopyableNode, StatementRepresentation<S> {
44 private static final Logger LOG = LoggerFactory.getLogger(AbstractExplicitGenerator.class);
46 private final @NonNull S statement;
49 * Field tracking previous incarnation (along reverse of 'uses' and 'augment' axis) of this statement. This field
50 * can either be one of:
52 * <li>{@code null} when not resolved, i.e. access is not legal, or</li>
53 * <li>{@code this} object if this is the original definition, or</li>
54 * <li>a generator which is one step closer to the original definition</li>
57 private AbstractExplicitGenerator<S, R> prev;
59 * Field holding the original incarnation, i.e. the terminal node along {@link #prev} links.
61 private AbstractExplicitGenerator<S, R> orig;
63 * Field containing and indicator holding the runtime type, if applicable.
65 private @Nullable R runtimeType;
66 private boolean runtimeTypeInitialized;
68 AbstractExplicitGenerator(final S statement) {
69 this.statement = requireNonNull(statement);
72 AbstractExplicitGenerator(final S statement, final AbstractCompositeGenerator<?, ?> parent) {
74 this.statement = requireNonNull(statement);
78 public final @NonNull S statement() {
83 * Return the {@link RuntimeType} associated with this objec, if applicablet. This represents
84 * the externally-accessible view of this object when considered outside the schema tree or binding tree hierarchy.
86 * @return Associated run-time type, or {@code null}
88 public final @Nullable R generatedRuntimeType() {
89 final var type = generatedType();
90 return type == null ? null : runtimeType();
93 private @Nullable R runtimeType() {
94 if (!runtimeTypeInitialized) {
95 final var type = runtimeJavaType();
97 runtimeType = createExternalRuntimeType(type);
99 runtimeTypeInitialized = true;
105 * Return the {@link RuntimeType} associated with this object. This represents the externally-accessible view of
106 * this object when considered outside the schema tree or binding tree hierarchy.
108 * @return Associated run-time type
110 public final @NonNull R getRuntimeType() {
111 final var local = runtimeType();
113 throw new VerifyException(this + " does not have a run-time type");
119 * Return the {@link Type} associated with this object at run-time, if applicable. This method often synonymous
120 * with {@code generatedType().orElseNull()}, but not always. For example
128 * Results in an empty {@link #generatedType()}, but still produces a {@code java.lang.String}-based
129 * {@link RuntimeType}.
131 * @return Associated {@link Type}
133 // FIXME: this should be a generic class argument
134 // FIXME: this needs a better name, but 'runtimeType' is already taken.
135 @Nullable Type runtimeJavaType() {
136 return generatedType();
140 * Create the externally-accessible {@link RuntimeType} view of this object. The difference between
141 * this method and {@link #createInternalRuntimeType(EffectiveStatement)} is that this method represents the view
142 * attached to {@link #statement()} and contains a separate global view of all available augmentations attached to
145 * @param type {@link Type} associated with this object, as returned by {@link #runtimeJavaType()}
146 * @return Externally-accessible RuntimeType
148 abstract @NonNull R createExternalRuntimeType(@NonNull Type type);
151 * Create the internally-accessible {@link RuntimeType} view of this object, if applicable. The difference between
152 * this method and {@link #createExternalRuntimeType()} is that this represents the view attached to the specified
153 * {@code stmt}, which is supplied by the parent statement. The returned {@link RuntimeType} always reports the
154 * global view of attached augmentations as empty.
156 * @param lookup context to use when looking up child statements
157 * @param stmt Statement for which to create the view
158 * @return Internally-accessible RuntimeType, or {@code null} if not applicable
160 final @Nullable R createInternalRuntimeType(final @NonNull AugmentResolver resolver, final @NonNull S stmt) {
161 // FIXME: cache requests: if we visited this statement, we obviously know what it entails. Note that we walk
162 // towards the original definition. As such, the cache may have to live in the generator we look up,
163 // but should operate on this statement to reflect lookups. This needs a bit of figuring out.
166 final var type = gen.runtimeJavaType();
168 return createInternalRuntimeType(resolver, stmt, type);
171 gen = gen.previous();
172 } while (gen != null);
177 abstract @NonNull R createInternalRuntimeType(@NonNull AugmentResolver resolver, @NonNull S statement,
181 public final boolean isAddedByUses() {
182 return statement instanceof AddedByUsesAware aware && aware.isAddedByUses();
186 public final boolean isAugmenting() {
187 return statement instanceof CopyableNode copyable && copyable.isAugmenting();
191 * Attempt to link the generator corresponding to the original definition for this generator.
193 * @return {@code true} if this generator is linked
195 final boolean linkOriginalGenerator() {
197 // Original already linked
202 LOG.trace("Linking {}", this);
204 if (!isAddedByUses() && !isAugmenting()) {
206 LOG.trace("Linked {} to self", this);
210 final var link = getParent().<S, R>originalChild(getQName());
212 LOG.trace("Cannot link {} yet", this);
216 prev = link.previous();
217 orig = link.original();
219 LOG.trace("Linked {} to {} original {}", this, prev, orig);
223 LOG.trace("Linked {} to intermediate {}", this, prev);
227 orig = prev.originalLink().original();
229 LOG.trace("Linked {} to original {}", this, orig);
236 * Return the previous incarnation of this generator, or {@code null} if this is the original generator.
238 * @return Previous incarnation or {@code null}
240 final @Nullable AbstractExplicitGenerator<S, R> previous() {
241 final var local = verifyNotNull(prev, "Generator %s does not have linkage to previous instance resolved", this);
242 return local == this ? null : local;
246 * Return the original incarnation of this generator, or self if this is the original generator.
248 * @return Original incarnation of this generator
250 @NonNull AbstractExplicitGenerator<S, R> getOriginal() {
251 return verifyNotNull(orig, "Generator %s does not have linkage to original instance resolved", this);
254 @Nullable AbstractExplicitGenerator<S, R> tryOriginal() {
259 * Return the link towards the original generator.
261 * @return Link towards the original generator.
263 final @NonNull OriginalLink<S, R> originalLink() {
264 final var local = prev;
266 return OriginalLink.partial(this);
267 } else if (local == this) {
268 return OriginalLink.complete(this);
270 return OriginalLink.partial(local);
274 @Nullable AbstractExplicitGenerator<?, ?> findSchemaTreeGenerator(final QName qname) {
275 return findLocalSchemaTreeGenerator(qname);
278 final @Nullable AbstractExplicitGenerator<?, ?> findLocalSchemaTreeGenerator(final QName qname) {
279 for (Generator child : this) {
280 if (child instanceof AbstractExplicitGenerator<?, ?> gen
281 && gen.statement() instanceof SchemaTreeEffectiveStatement<?> stmt && qname.equals(stmt.argument())) {
288 final @NonNull QName getQName() {
289 final var arg = statement.argument();
290 if (arg instanceof QName qname) {
293 throw new VerifyException("Unexpected argument " + arg);
296 @NonNull AbstractQName localName() {
297 // FIXME: this should be done in a nicer way
298 final var arg = statement.argument();
299 if (arg instanceof AbstractQName aqn) {
302 throw new VerifyException("Illegal argument " + arg);
306 ClassPlacement classPlacement() {
307 // We process nodes introduced through augment or uses separately
308 // FIXME: this is not quite right!
309 return isAddedByUses() || isAugmenting() ? ClassPlacement.NONE : ClassPlacement.TOP_LEVEL;
313 Member createMember(final CollisionDomain domain) {
314 return domain.addPrimary(this, new CamelCaseNamingStrategy(namespace(), localName()));
317 void addAsGetterMethod(final @NonNull GeneratedTypeBuilderBase<?> builder,
318 final @NonNull TypeBuilderFactory builderFactory) {
319 if (isAugmenting()) {
320 // Do not process augmented nodes: they will be taken care of in their home augmentation
323 if (isAddedByUses()) {
324 // If this generator has been added by a uses node, it is already taken care of by the corresponding
325 // grouping. There is one exception to this rule: 'type leafref' can use a relative path to point
326 // outside of its home grouping. In this case we need to examine the instantiation until we succeed in
327 // resolving the reference.
328 addAsGetterMethodOverride(builder, builderFactory);
332 final var returnType = methodReturnType(builderFactory);
333 constructGetter(builder, returnType);
334 constructRequire(builder, returnType);
337 MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
338 return constructGetter(builder, returnType, Naming.getGetterMethodName(localName().getLocalName()));
341 final MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder,
342 final Type returnType, final String methodName) {
343 final var getMethod = builder.addMethod(methodName).setReturnType(returnType);
345 annotateDeprecatedIfNecessary(getMethod);
347 statement.findFirstEffectiveSubstatementArgument(DescriptionEffectiveStatement.class)
348 .map(TypeMemberComment::referenceOf).ifPresent(getMethod::setComment);
353 void constructRequire(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
354 // No-op in most cases
357 final void constructRequireImpl(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
358 constructGetter(builder, returnType, Naming.getRequireMethodName(localName().getLocalName()))
360 .setMechanics(ValueMechanics.NONNULL);
363 void addAsGetterMethodOverride(final @NonNull GeneratedTypeBuilderBase<?> builder,
364 final @NonNull TypeBuilderFactory builderFactory) {
365 // No-op for most cases
368 @NonNull Type methodReturnType(final @NonNull TypeBuilderFactory builderFactory) {
369 return getGeneratedType(builderFactory);
372 final void annotateDeprecatedIfNecessary(final AnnotableTypeBuilder builder) {
373 annotateDeprecatedIfNecessary(statement, builder);
377 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
378 helper.add("argument", statement.argument());
380 if (isAddedByUses()) {
381 helper.addValue("addedByUses");
383 if (isAugmenting()) {
384 helper.addValue("augmenting");
389 static final @NonNull GeneratedType verifyGeneratedType(final Type type) {
390 if (type instanceof GeneratedType ret) {
393 throw new VerifyException("Unexpected type " + type);