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 java.util.Optional;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.eclipse.jdt.annotation.Nullable;
18 import org.opendaylight.mdsal.binding.generator.impl.reactor.CollisionDomain.Member;
19 import org.opendaylight.mdsal.binding.generator.impl.tree.StatementRepresentation;
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 object, if applicable. This represents the
84 * externally-accessible view of this object when considered outside the schema tree or binding tree hierarchy.
86 * @return Associated run-time type, or empty
88 public final Optional<R> runtimeType() {
89 if (!runtimeTypeInitialized) {
90 final var type = runtimeJavaType();
92 runtimeType = createExternalRuntimeType(type);
94 runtimeTypeInitialized = true;
96 return Optional.ofNullable(runtimeType);
100 * Return the {@link Type} associated with this object at run-time, if applicable. This method often synonymous
101 * with {@code generatedType().orElseNull()}, but not always. For example
109 * Results in an empty {@link #generatedType()}, but still produces a {@code java.lang.String}-based
110 * {@link RuntimeType}.
112 * @return Associated {@link Type}
114 // FIXME: this should be a generic class argument
115 // FIXME: this needs a better name, but 'runtimeType' is already taken.
116 @Nullable Type runtimeJavaType() {
117 return generatedType().orElse(null);
121 * Create the externally-accessible {@link RuntimeType} view of this object. The difference between
122 * this method and {@link #createInternalRuntimeType(EffectiveStatement)} is that this method represents the view
123 * attached to {@link #statement()} and contains a separate global view of all available augmentations attached to
126 * @param type {@link Type} associated with this object, as returned by {@link #runtimeJavaType()}
127 * @return Externally-accessible RuntimeType
129 abstract @NonNull R createExternalRuntimeType(@NonNull Type type);
132 * Create the internally-accessible {@link RuntimeType} view of this object, if applicable. The difference between
133 * this method and {@link #createExternalRuntimeType()} is that this represents the view attached to the specified
134 * {@code stmt}, which is supplied by the parent statement. The returned {@link RuntimeType} always reports the
135 * global view of attached augmentations as empty.
137 * @param lookup context to use when looking up child statements
138 * @param stmt Statement for which to create the view
139 * @return Internally-accessible RuntimeType, or {@code null} if not applicable
141 final @Nullable R createInternalRuntimeType(final @NonNull AugmentResolver resolver, final @NonNull S stmt) {
142 // FIXME: cache requests: if we visited this statement, we obviously know what it entails. Note that we walk
143 // towards the original definition. As such, the cache may have to live in the generator we look up,
144 // but should operate on this statement to reflect lookups. This needs a bit of figuring out.
147 final var type = gen.runtimeJavaType();
149 return createInternalRuntimeType(resolver, stmt, type);
152 gen = gen.previous();
153 } while (gen != null);
158 abstract @NonNull R createInternalRuntimeType(@NonNull AugmentResolver resolver, @NonNull S statement,
162 public final boolean isAddedByUses() {
163 return statement instanceof AddedByUsesAware aware && aware.isAddedByUses();
167 public final boolean isAugmenting() {
168 return statement instanceof CopyableNode copyable && copyable.isAugmenting();
172 * Attempt to link the generator corresponding to the original definition for this generator.
174 * @return {@code true} if this generator is linked
176 final boolean linkOriginalGenerator() {
178 // Original already linked
183 LOG.trace("Linking {}", this);
185 if (!isAddedByUses() && !isAugmenting()) {
187 LOG.trace("Linked {} to self", this);
191 final var link = getParent().<S, R>originalChild(getQName());
193 LOG.trace("Cannot link {} yet", this);
197 prev = link.previous();
198 orig = link.original();
200 LOG.trace("Linked {} to {} original {}", this, prev, orig);
204 LOG.trace("Linked {} to intermediate {}", this, prev);
208 orig = prev.originalLink().original();
210 LOG.trace("Linked {} to original {}", this, orig);
217 * Return the previous incarnation of this generator, or {@code null} if this is the original generator.
219 * @return Previous incarnation or {@code null}
221 final @Nullable AbstractExplicitGenerator<S, R> previous() {
222 final var local = verifyNotNull(prev, "Generator %s does not have linkage to previous instance resolved", this);
223 return local == this ? null : local;
227 * Return the original incarnation of this generator, or self if this is the original generator.
229 * @return Original incarnation of this generator
231 @NonNull AbstractExplicitGenerator<S, R> getOriginal() {
232 return verifyNotNull(orig, "Generator %s does not have linkage to original instance resolved", this);
235 @Nullable AbstractExplicitGenerator<S, R> tryOriginal() {
240 * Return the link towards the original generator.
242 * @return Link towards the original generator.
244 final @NonNull OriginalLink<S, R> originalLink() {
245 final var local = prev;
247 return OriginalLink.partial(this);
248 } else if (local == this) {
249 return OriginalLink.complete(this);
251 return OriginalLink.partial(local);
255 @Nullable AbstractExplicitGenerator<?, ?> findSchemaTreeGenerator(final QName qname) {
256 return findLocalSchemaTreeGenerator(qname);
259 final @Nullable AbstractExplicitGenerator<?, ?> findLocalSchemaTreeGenerator(final QName qname) {
260 for (Generator child : this) {
261 if (child instanceof AbstractExplicitGenerator<?, ?> gen
262 && gen.statement() instanceof SchemaTreeEffectiveStatement<?> stmt && qname.equals(stmt.argument())) {
269 final @NonNull QName getQName() {
270 final Object arg = statement.argument();
271 if (arg instanceof QName qname) {
274 throw new VerifyException("Unexpected argument " + arg);
277 @NonNull AbstractQName localName() {
278 // FIXME: this should be done in a nicer way
279 final Object arg = statement.argument();
280 if (arg instanceof AbstractQName aqn) {
283 throw new VerifyException("Illegal argument " + arg);
287 ClassPlacement classPlacement() {
288 // We process nodes introduced through augment or uses separately
289 // FIXME: this is not quite right!
290 return isAddedByUses() || isAugmenting() ? ClassPlacement.NONE : ClassPlacement.TOP_LEVEL;
294 Member createMember(final CollisionDomain domain) {
295 return domain.addPrimary(this, new CamelCaseNamingStrategy(namespace(), localName()));
298 void addAsGetterMethod(final @NonNull GeneratedTypeBuilderBase<?> builder,
299 final @NonNull TypeBuilderFactory builderFactory) {
300 if (isAugmenting()) {
301 // Do not process augmented nodes: they will be taken care of in their home augmentation
304 if (isAddedByUses()) {
305 // If this generator has been added by a uses node, it is already taken care of by the corresponding
306 // grouping. There is one exception to this rule: 'type leafref' can use a relative path to point
307 // outside of its home grouping. In this case we need to examine the instantiation until we succeed in
308 // resolving the reference.
309 addAsGetterMethodOverride(builder, builderFactory);
313 final Type returnType = methodReturnType(builderFactory);
314 constructGetter(builder, returnType);
315 constructRequire(builder, returnType);
318 MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
319 return constructGetter(builder, returnType, Naming.getGetterMethodName(localName().getLocalName()));
322 final MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder,
323 final Type returnType, final String methodName) {
324 final MethodSignatureBuilder getMethod = builder.addMethod(methodName).setReturnType(returnType);
326 annotateDeprecatedIfNecessary(getMethod);
328 statement.findFirstEffectiveSubstatementArgument(DescriptionEffectiveStatement.class)
329 .map(TypeMemberComment::referenceOf).ifPresent(getMethod::setComment);
334 void constructRequire(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
335 // No-op in most cases
338 final void constructRequireImpl(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
339 constructGetter(builder, returnType, Naming.getRequireMethodName(localName().getLocalName()))
341 .setMechanics(ValueMechanics.NONNULL);
344 void addAsGetterMethodOverride(final @NonNull GeneratedTypeBuilderBase<?> builder,
345 final @NonNull TypeBuilderFactory builderFactory) {
346 // No-op for most cases
349 @NonNull Type methodReturnType(final @NonNull TypeBuilderFactory builderFactory) {
350 return getGeneratedType(builderFactory);
353 final void annotateDeprecatedIfNecessary(final AnnotableTypeBuilder builder) {
354 annotateDeprecatedIfNecessary(statement, builder);
358 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
359 helper.add("argument", statement.argument());
361 if (isAddedByUses()) {
362 helper.addValue("addedByUses");
364 if (isAugmenting()) {
365 helper.addValue("augmenting");