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.GeneratedType;
21 import org.opendaylight.mdsal.binding.model.api.MethodSignature.ValueMechanics;
22 import org.opendaylight.mdsal.binding.model.api.Type;
23 import org.opendaylight.mdsal.binding.model.api.TypeMemberComment;
24 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
25 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
26 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
27 import org.opendaylight.mdsal.binding.runtime.api.RuntimeType;
28 import org.opendaylight.yangtools.yang.binding.contract.Naming;
29 import org.opendaylight.yangtools.yang.common.AbstractQName;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.model.api.AddedByUsesAware;
32 import org.opendaylight.yangtools.yang.model.api.CopyableNode;
33 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.DescriptionEffectiveStatement;
35 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaTreeEffectiveStatement;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 * An explicit {@link Generator}, associated with a particular {@link EffectiveStatement}.
42 // FIXME: unify this with Generator
43 public abstract class AbstractExplicitGenerator<S extends EffectiveStatement<?, ?>, R extends RuntimeType>
44 extends Generator implements CopyableNode, StatementRepresentation<S> {
45 private static final Logger LOG = LoggerFactory.getLogger(AbstractExplicitGenerator.class);
47 private final @NonNull S statement;
50 * Field tracking previous incarnation (along reverse of 'uses' and 'augment' axis) of this statement. This field
51 * can either be one of:
53 * <li>{@code null} when not resolved, i.e. access is not legal, or</li>
54 * <li>{@code this} object if this is the original definition, or</li>
55 * <li>a generator which is one step closer to the original definition</li>
58 private AbstractExplicitGenerator<S, R> prev;
60 * Field holding the original incarnation, i.e. the terminal node along {@link #prev} links.
62 private AbstractExplicitGenerator<S, R> orig;
64 * Field containing and indicator holding the runtime type, if applicable.
66 private @Nullable R runtimeType;
67 private boolean runtimeTypeInitialized;
69 AbstractExplicitGenerator(final S statement) {
70 this.statement = requireNonNull(statement);
73 AbstractExplicitGenerator(final S statement, final AbstractCompositeGenerator<?, ?> parent) {
75 this.statement = requireNonNull(statement);
79 public final @NonNull S statement() {
84 * Return the {@link RuntimeType} associated with this object, if applicable. This represents the
85 * externally-accessible view of this object when considered outside the schema tree or binding tree hierarchy.
87 * @return Associated run-time type, or empty
89 public final Optional<R> runtimeType() {
90 if (!runtimeTypeInitialized) {
91 final var type = runtimeJavaType();
93 runtimeType = createExternalRuntimeType(type);
95 runtimeTypeInitialized = true;
97 return Optional.ofNullable(runtimeType);
101 * Return the {@link Type} associated with this object at run-time, if applicable. This method often synonymous
102 * with {@code generatedType().orElseNull()}, but not always. For example
110 * Results in an empty {@link #generatedType()}, but still produces a {@code java.lang.String}-based
111 * {@link RuntimeType}.
113 * @return Associated {@link Type}
115 // FIXME: this should be a generic class argument
116 // FIXME: this needs a better name, but 'runtimeType' is already taken.
117 @Nullable Type runtimeJavaType() {
118 return generatedType().orElse(null);
122 * Create the externally-accessible {@link RuntimeType} view of this object. The difference between
123 * this method and {@link #createInternalRuntimeType(EffectiveStatement)} is that this method represents the view
124 * attached to {@link #statement()} and contains a separate global view of all available augmentations attached to
127 * @param type {@link Type} associated with this object, as returned by {@link #runtimeJavaType()}
128 * @return Externally-accessible RuntimeType
130 abstract @NonNull R createExternalRuntimeType(@NonNull Type type);
133 * Create the internally-accessible {@link RuntimeType} view of this object, if applicable. The difference between
134 * this method and {@link #createExternalRuntimeType()} is that this represents the view attached to the specified
135 * {@code stmt}, which is supplied by the parent statement. The returned {@link RuntimeType} always reports the
136 * global view of attached augmentations as empty.
138 * @param lookup context to use when looking up child statements
139 * @param stmt Statement for which to create the view
140 * @return Internally-accessible RuntimeType, or {@code null} if not applicable
142 final @Nullable R createInternalRuntimeType(final @NonNull AugmentResolver resolver, final @NonNull S stmt) {
143 // FIXME: cache requests: if we visited this statement, we obviously know what it entails. Note that we walk
144 // towards the original definition. As such, the cache may have to live in the generator we look up,
145 // but should operate on this statement to reflect lookups. This needs a bit of figuring out.
148 final var type = gen.runtimeJavaType();
150 return createInternalRuntimeType(resolver, stmt, type);
153 gen = gen.previous();
154 } while (gen != null);
159 abstract @NonNull R createInternalRuntimeType(@NonNull AugmentResolver resolver, @NonNull S statement,
163 public final boolean isAddedByUses() {
164 return statement instanceof AddedByUsesAware aware && aware.isAddedByUses();
168 public final boolean isAugmenting() {
169 return statement instanceof CopyableNode copyable && copyable.isAugmenting();
173 * Attempt to link the generator corresponding to the original definition for this generator.
175 * @return {@code true} if this generator is linked
177 final boolean linkOriginalGenerator() {
179 // Original already linked
184 LOG.trace("Linking {}", this);
186 if (!isAddedByUses() && !isAugmenting()) {
188 LOG.trace("Linked {} to self", this);
192 final var link = getParent().<S, R>originalChild(getQName());
194 LOG.trace("Cannot link {} yet", this);
198 prev = link.previous();
199 orig = link.original();
201 LOG.trace("Linked {} to {} original {}", this, prev, orig);
205 LOG.trace("Linked {} to intermediate {}", this, prev);
209 orig = prev.originalLink().original();
211 LOG.trace("Linked {} to original {}", this, orig);
218 * Return the previous incarnation of this generator, or {@code null} if this is the original generator.
220 * @return Previous incarnation or {@code null}
222 final @Nullable AbstractExplicitGenerator<S, R> previous() {
223 final var local = verifyNotNull(prev, "Generator %s does not have linkage to previous instance resolved", this);
224 return local == this ? null : local;
228 * Return the original incarnation of this generator, or self if this is the original generator.
230 * @return Original incarnation of this generator
232 @NonNull AbstractExplicitGenerator<S, R> getOriginal() {
233 return verifyNotNull(orig, "Generator %s does not have linkage to original instance resolved", this);
236 @Nullable AbstractExplicitGenerator<S, R> tryOriginal() {
241 * Return the link towards the original generator.
243 * @return Link towards the original generator.
245 final @NonNull OriginalLink<S, R> originalLink() {
246 final var local = prev;
248 return OriginalLink.partial(this);
249 } else if (local == this) {
250 return OriginalLink.complete(this);
252 return OriginalLink.partial(local);
256 @Nullable AbstractExplicitGenerator<?, ?> findSchemaTreeGenerator(final QName qname) {
257 return findLocalSchemaTreeGenerator(qname);
260 final @Nullable AbstractExplicitGenerator<?, ?> findLocalSchemaTreeGenerator(final QName qname) {
261 for (Generator child : this) {
262 if (child instanceof AbstractExplicitGenerator<?, ?> gen
263 && gen.statement() instanceof SchemaTreeEffectiveStatement<?> stmt && qname.equals(stmt.argument())) {
270 final @NonNull QName getQName() {
271 final Object arg = statement.argument();
272 if (arg instanceof QName qname) {
275 throw new VerifyException("Unexpected argument " + arg);
278 @NonNull AbstractQName localName() {
279 // FIXME: this should be done in a nicer way
280 final Object arg = statement.argument();
281 if (arg instanceof AbstractQName aqn) {
284 throw new VerifyException("Illegal argument " + arg);
288 ClassPlacement classPlacement() {
289 // We process nodes introduced through augment or uses separately
290 // FIXME: this is not quite right!
291 return isAddedByUses() || isAugmenting() ? ClassPlacement.NONE : ClassPlacement.TOP_LEVEL;
295 Member createMember(final CollisionDomain domain) {
296 return domain.addPrimary(this, new CamelCaseNamingStrategy(namespace(), localName()));
299 void addAsGetterMethod(final @NonNull GeneratedTypeBuilderBase<?> builder,
300 final @NonNull TypeBuilderFactory builderFactory) {
301 if (isAugmenting()) {
302 // Do not process augmented nodes: they will be taken care of in their home augmentation
305 if (isAddedByUses()) {
306 // If this generator has been added by a uses node, it is already taken care of by the corresponding
307 // grouping. There is one exception to this rule: 'type leafref' can use a relative path to point
308 // outside of its home grouping. In this case we need to examine the instantiation until we succeed in
309 // resolving the reference.
310 addAsGetterMethodOverride(builder, builderFactory);
314 final Type returnType = methodReturnType(builderFactory);
315 constructGetter(builder, returnType);
316 constructRequire(builder, returnType);
319 MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
320 return constructGetter(builder, returnType, Naming.getGetterMethodName(localName().getLocalName()));
323 final MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder,
324 final Type returnType, final String methodName) {
325 final MethodSignatureBuilder getMethod = builder.addMethod(methodName).setReturnType(returnType);
327 annotateDeprecatedIfNecessary(getMethod);
329 statement.findFirstEffectiveSubstatementArgument(DescriptionEffectiveStatement.class)
330 .map(TypeMemberComment::referenceOf).ifPresent(getMethod::setComment);
335 void constructRequire(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
336 // No-op in most cases
339 final void constructRequireImpl(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
340 constructGetter(builder, returnType, Naming.getRequireMethodName(localName().getLocalName()))
342 .setMechanics(ValueMechanics.NONNULL);
345 void addAsGetterMethodOverride(final @NonNull GeneratedTypeBuilderBase<?> builder,
346 final @NonNull TypeBuilderFactory builderFactory) {
347 // No-op for most cases
350 @NonNull Type methodReturnType(final @NonNull TypeBuilderFactory builderFactory) {
351 return getGeneratedType(builderFactory);
354 final void annotateDeprecatedIfNecessary(final AnnotableTypeBuilder builder) {
355 annotateDeprecatedIfNecessary(statement, builder);
359 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
360 helper.add("argument", statement.argument());
362 if (isAddedByUses()) {
363 helper.addValue("addedByUses");
365 if (isAugmenting()) {
366 helper.addValue("augmenting");
371 static final @NonNull GeneratedType verifyGeneratedType(final Type type) {
372 if (type instanceof GeneratedType ret) {
375 throw new VerifyException("Unexpected type " + type);