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.verify;
11 import static com.google.common.base.Verify.verifyNotNull;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.base.MoreObjects.ToStringHelper;
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.mdsal.binding.spec.naming.BindingMapping;
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 public abstract class AbstractExplicitGenerator<S extends EffectiveStatement<?, ?>, R extends RuntimeType>
42 extends Generator implements CopyableNode, StatementRepresentation<S> {
43 private static final Logger LOG = LoggerFactory.getLogger(AbstractExplicitGenerator.class);
45 private final @NonNull S statement;
48 * Field tracking previous incarnation (along reverse of 'uses' and 'augment' axis) of this statement. This field
49 * can either be one of:
51 * <li>{@code null} when not resolved, i.e. access is not legal, or</li>
52 * <li>{@code this} object if this is the original definition, or</li>
53 * <li>a generator which is one step closer to the original definition</li>
56 private AbstractExplicitGenerator<S, R> prev;
58 * Field holding the original incarnation, i.e. the terminal node along {@link #prev} links.
60 private AbstractExplicitGenerator<S, R> orig;
62 * Field containing and indicator holding the runtime type, if applicable.
64 private @Nullable R runtimeType;
65 private boolean runtimeTypeInitialized;
67 AbstractExplicitGenerator(final S statement) {
68 this.statement = requireNonNull(statement);
71 AbstractExplicitGenerator(final S statement, final AbstractCompositeGenerator<?, ?> parent) {
73 this.statement = requireNonNull(statement);
77 public final @NonNull S statement() {
82 * Return the {@link RuntimeType} associated with this object, if applicable. This represents the
83 * externally-accessible view of this object when considered outside the schema tree or binding tree hierarchy.
85 * @return Associated run-time type, or empty
87 public final Optional<R> runtimeType() {
88 if (!runtimeTypeInitialized) {
89 final var type = runtimeJavaType();
91 runtimeType = createExternalRuntimeType(type);
93 runtimeTypeInitialized = true;
95 return Optional.ofNullable(runtimeType);
99 * Return the {@link Type} associated with this object at run-time, if applicable. This method often synonymous
100 * with {@code generatedType().orElseNull()}, but not always. For example
108 * Results in an empty {@link #generatedType()}, but still produces a {@code java.lang.String}-based
109 * {@link RuntimeType}.
111 * @return Associated {@link Type}
113 // FIXME: this should be a generic class argument
114 // FIXME: this needs a better name, but 'runtimeType' is already taken.
115 @Nullable Type runtimeJavaType() {
116 return generatedType().orElse(null);
120 * Create the externally-accessible {@link RuntimeType} view of this object. The difference between
121 * this method and {@link #createInternalRuntimeType(EffectiveStatement)} is that this method represents the view
122 * attached to {@link #statement()} and contains a separate global view of all available augmentations attached to
125 * @param type {@link Type} associated with this object, as returned by {@link #runtimeJavaType()}
126 * @return Externally-accessible RuntimeType
128 abstract @NonNull R createExternalRuntimeType(@NonNull Type type);
131 * Create the internally-accessible {@link RuntimeType} view of this object, if applicable. The difference between
132 * this method and {@link #createExternalRuntimeType()} is that this represents the view attached to the specified
133 * {@code stmt}, which is supplied by the parent statement. The returned {@link RuntimeType} always reports the
134 * global view of attached augmentations as empty.
136 * @param lookup context to use when looking up child statements
137 * @param stmt Statement for which to create the view
138 * @return Internally-accessible RuntimeType, or {@code null} if not applicable
140 final @Nullable R createInternalRuntimeType(final @NonNull AugmentResolver resolver, final @NonNull S stmt) {
141 // FIXME: cache requests: if we visited this statement, we obviously know what it entails. Note that we walk
142 // towards the original definition. As such, the cache may have to live in the generator we look up,
143 // but should operate on this statement to reflect lookups. This needs a bit of figuring out.
146 final var type = gen.runtimeJavaType();
148 return createInternalRuntimeType(resolver, stmt, type);
151 gen = gen.previous();
152 } while (gen != null);
157 abstract @NonNull R createInternalRuntimeType(@NonNull AugmentResolver resolver, @NonNull S statement,
161 public final boolean isAddedByUses() {
162 return statement instanceof AddedByUsesAware && ((AddedByUsesAware) statement).isAddedByUses();
166 public final boolean isAugmenting() {
167 return statement instanceof CopyableNode && ((CopyableNode) statement).isAugmenting();
171 * Attempt to link the generator corresponding to the original definition for this generator.
173 * @return {@code true} if this generator is linked
175 final boolean linkOriginalGenerator() {
177 // Original already linked
182 LOG.trace("Linking {}", this);
184 if (!isAddedByUses() && !isAugmenting()) {
186 LOG.trace("Linked {} to self", this);
190 final var link = getParent().<S, R>originalChild(getQName());
192 LOG.trace("Cannot link {} yet", this);
196 prev = link.previous();
197 orig = link.original();
199 LOG.trace("Linked {} to {} original {}", this, prev, orig);
203 LOG.trace("Linked {} to intermediate {}", this, prev);
207 orig = prev.originalLink().original();
209 LOG.trace("Linked {} to original {}", this, orig);
216 * Return the previous incarnation of this generator, or {@code null} if this is the original generator.
218 * @return Previous incarnation or {@code null}
220 final @Nullable AbstractExplicitGenerator<S, R> previous() {
221 final var local = verifyNotNull(prev, "Generator %s does not have linkage to previous instance resolved", this);
222 return local == this ? null : local;
226 * Return the original incarnation of this generator, or self if this is the original generator.
228 * @return Original incarnation of this generator
230 @NonNull AbstractExplicitGenerator<S, R> getOriginal() {
231 return verifyNotNull(orig, "Generator %s does not have linkage to original instance resolved", this);
234 @Nullable AbstractExplicitGenerator<S, R> tryOriginal() {
239 * Return the link towards the original generator.
241 * @return Link towards the original generator.
243 final @NonNull OriginalLink<S, R> originalLink() {
244 final var local = prev;
246 return OriginalLink.partial(this);
247 } else if (local == this) {
248 return OriginalLink.complete(this);
250 return OriginalLink.partial(local);
254 @Nullable AbstractExplicitGenerator<?, ?> findSchemaTreeGenerator(final QName qname) {
255 return findLocalSchemaTreeGenerator(qname);
258 final @Nullable AbstractExplicitGenerator<?, ?> findLocalSchemaTreeGenerator(final QName qname) {
259 for (Generator child : this) {
260 if (child instanceof AbstractExplicitGenerator) {
261 final AbstractExplicitGenerator<?, ?> gen = (AbstractExplicitGenerator<?, ?>) child;
262 final EffectiveStatement<?, ?> stmt = gen.statement();
263 if (stmt instanceof SchemaTreeEffectiveStatement && qname.equals(stmt.argument())) {
271 final @NonNull QName getQName() {
272 final Object arg = statement.argument();
273 verify(arg instanceof QName, "Unexpected argument %s", arg);
277 @NonNull AbstractQName localName() {
278 // FIXME: this should be done in a nicer way
279 final Object argument = statement.argument();
280 verify(argument instanceof AbstractQName, "Illegal argument %s", argument);
281 return (AbstractQName) argument;
285 ClassPlacement classPlacement() {
286 // We process nodes introduced through augment or uses separately
287 // FIXME: this is not quite right!
288 return isAddedByUses() || isAugmenting() ? ClassPlacement.NONE : ClassPlacement.TOP_LEVEL;
292 Member createMember(final CollisionDomain domain) {
293 return domain.addPrimary(this, new CamelCaseNamingStrategy(namespace(), localName()));
296 void addAsGetterMethod(final @NonNull GeneratedTypeBuilderBase<?> builder,
297 final @NonNull TypeBuilderFactory builderFactory) {
298 if (isAugmenting()) {
299 // Do not process augmented nodes: they will be taken care of in their home augmentation
302 if (isAddedByUses()) {
303 // If this generator has been added by a uses node, it is already taken care of by the corresponding
304 // grouping. There is one exception to this rule: 'type leafref' can use a relative path to point
305 // outside of its home grouping. In this case we need to examine the instantiation until we succeed in
306 // resolving the reference.
307 addAsGetterMethodOverride(builder, builderFactory);
311 final Type returnType = methodReturnType(builderFactory);
312 constructGetter(builder, returnType);
313 constructRequire(builder, returnType);
316 MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
317 return constructGetter(builder, returnType, BindingMapping.getGetterMethodName(localName().getLocalName()));
320 final MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder,
321 final Type returnType, final String methodName) {
322 final MethodSignatureBuilder getMethod = builder.addMethod(methodName).setReturnType(returnType);
324 annotateDeprecatedIfNecessary(getMethod);
326 statement.findFirstEffectiveSubstatementArgument(DescriptionEffectiveStatement.class)
327 .map(TypeMemberComment::referenceOf).ifPresent(getMethod::setComment);
332 void constructRequire(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
333 // No-op in most cases
336 final void constructRequireImpl(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
337 constructGetter(builder, returnType, BindingMapping.getRequireMethodName(localName().getLocalName()))
339 .setMechanics(ValueMechanics.NONNULL);
342 void addAsGetterMethodOverride(final @NonNull GeneratedTypeBuilderBase<?> builder,
343 final @NonNull TypeBuilderFactory builderFactory) {
344 // No-op for most cases
347 @NonNull Type methodReturnType(final @NonNull TypeBuilderFactory builderFactory) {
348 return getGeneratedType(builderFactory);
351 final void annotateDeprecatedIfNecessary(final AnnotableTypeBuilder builder) {
352 annotateDeprecatedIfNecessary(statement, builder);
356 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
357 helper.add("argument", statement.argument());
359 if (isAddedByUses()) {
360 helper.addValue("addedByUses");
362 if (isAugmenting()) {
363 helper.addValue("augmenting");