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 abstract @Nullable Type runtimeJavaType();
118 * Create the externally-accessible {@link RuntimeType} view of this object. The difference between
119 * this method and {@link #createInternalRuntimeType(EffectiveStatement)} is that this method represents the view
120 * attached to {@link #statement()} and contains a separate global view of all available augmentations attached to
123 * @param type {@link Type} associated with this object, as returned by {@link #runtimeJavaType()}
124 * @return Externally-accessible RuntimeType
126 abstract @NonNull R createExternalRuntimeType(@NonNull Type type);
129 * Create the internally-accessible {@link RuntimeType} view of this object, if applicable. The difference between
130 * this method and {@link #createExternalRuntimeType()} is that this represents the view attached to the specified
131 * {@code stmt}, which is supplied by the parent statement. The returned {@link RuntimeType} always reports the
132 * global view of attached augmentations as empty.
134 * @param lookup context to use when looking up child statements
135 * @param stmt Statement for which to create the view
136 * @return Internally-accessible RuntimeType, or {@code null} if not applicable
138 final @Nullable R createInternalRuntimeType(final @NonNull ChildLookup lookup, final @NonNull S stmt) {
139 // FIXME: cache requests: if we visited this statement, we obviously know what it entails. Note that we walk
140 // towards the original definition. As such, the cache may have to live in the generator we look up,
141 // but should operate on this statement to reflect lookups. This needs a bit of figuring out.
144 final var type = gen.runtimeJavaType();
146 return createInternalRuntimeType(lookup, stmt, type);
149 gen = gen.previous();
150 } while (gen != null);
155 abstract @NonNull R createInternalRuntimeType(@NonNull ChildLookup lookup, @NonNull S statement,
159 public final boolean isAddedByUses() {
160 return statement instanceof AddedByUsesAware && ((AddedByUsesAware) statement).isAddedByUses();
164 public final boolean isAugmenting() {
165 return statement instanceof CopyableNode && ((CopyableNode) statement).isAugmenting();
169 * Attempt to link the generator corresponding to the original definition for this generator.
171 * @return {@code true} if this generator is linked
173 final boolean linkOriginalGenerator() {
175 // Original already linked
180 LOG.trace("Linking {}", this);
182 if (!isAddedByUses() && !isAugmenting()) {
184 LOG.trace("Linked {} to self", this);
188 final var link = getParent().<S, R>originalChild(getQName());
190 LOG.trace("Cannot link {} yet", this);
194 prev = link.previous();
195 orig = link.original();
197 LOG.trace("Linked {} to {} original {}", this, prev, orig);
201 LOG.trace("Linked {} to intermediate {}", this, prev);
205 orig = prev.originalLink().original();
207 LOG.trace("Linked {} to original {}", this, orig);
214 * Return the previous incarnation of this generator, or {@code null} if this is the original generator.
216 * @return Previous incarnation or {@code null}
218 final @Nullable AbstractExplicitGenerator<S, R> previous() {
219 final var local = verifyNotNull(prev, "Generator %s does not have linkage to previous instance resolved", this);
220 return local == this ? null : local;
224 * Return the original incarnation of this generator, or self if this is the original generator.
226 * @return Original incarnation of this generator
228 @NonNull AbstractExplicitGenerator<S, R> getOriginal() {
229 return verifyNotNull(orig, "Generator %s does not have linkage to original instance resolved", this);
232 @Nullable AbstractExplicitGenerator<S, R> tryOriginal() {
237 * Return the link towards the original generator.
239 * @return Link towards the original generator.
241 final @NonNull OriginalLink<S, R> originalLink() {
242 final var local = prev;
244 return OriginalLink.partial(this);
245 } else if (local == this) {
246 return OriginalLink.complete(this);
248 return OriginalLink.partial(local);
252 @Nullable AbstractExplicitGenerator<?, ?> findSchemaTreeGenerator(final QName qname) {
253 return findLocalSchemaTreeGenerator(qname);
256 final @Nullable AbstractExplicitGenerator<?, ?> findLocalSchemaTreeGenerator(final QName qname) {
257 for (Generator child : this) {
258 if (child instanceof AbstractExplicitGenerator) {
259 final AbstractExplicitGenerator<?, ?> gen = (AbstractExplicitGenerator<?, ?>) child;
260 final EffectiveStatement<?, ?> stmt = gen.statement();
261 if (stmt instanceof SchemaTreeEffectiveStatement && qname.equals(stmt.argument())) {
269 final @NonNull QName getQName() {
270 final Object arg = statement.argument();
271 verify(arg instanceof QName, "Unexpected argument %s", arg);
275 @NonNull AbstractQName localName() {
276 // FIXME: this should be done in a nicer way
277 final Object argument = statement.argument();
278 verify(argument instanceof AbstractQName, "Illegal argument %s", argument);
279 return (AbstractQName) argument;
283 ClassPlacement classPlacement() {
284 // We process nodes introduced through augment or uses separately
285 // FIXME: this is not quite right!
286 return isAddedByUses() || isAugmenting() ? ClassPlacement.NONE : ClassPlacement.TOP_LEVEL;
290 Member createMember(final CollisionDomain domain) {
291 return domain.addPrimary(this, new CamelCaseNamingStrategy(namespace(), localName()));
294 void addAsGetterMethod(final @NonNull GeneratedTypeBuilderBase<?> builder,
295 final @NonNull TypeBuilderFactory builderFactory) {
296 if (isAugmenting()) {
297 // Do not process augmented nodes: they will be taken care of in their home augmentation
300 if (isAddedByUses()) {
301 // If this generator has been added by a uses node, it is already taken care of by the corresponding
302 // grouping. There is one exception to this rule: 'type leafref' can use a relative path to point
303 // outside of its home grouping. In this case we need to examine the instantiation until we succeed in
304 // resolving the reference.
305 addAsGetterMethodOverride(builder, builderFactory);
309 final Type returnType = methodReturnType(builderFactory);
310 constructGetter(builder, returnType);
311 constructRequire(builder, returnType);
314 MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
315 return constructGetter(builder, returnType, BindingMapping.getGetterMethodName(localName().getLocalName()));
318 final MethodSignatureBuilder constructGetter(final GeneratedTypeBuilderBase<?> builder,
319 final Type returnType, final String methodName) {
320 final MethodSignatureBuilder getMethod = builder.addMethod(methodName).setReturnType(returnType);
322 annotateDeprecatedIfNecessary(getMethod);
324 statement.findFirstEffectiveSubstatementArgument(DescriptionEffectiveStatement.class)
325 .map(TypeMemberComment::referenceOf).ifPresent(getMethod::setComment);
330 void constructRequire(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
331 // No-op in most cases
334 final void constructRequireImpl(final GeneratedTypeBuilderBase<?> builder, final Type returnType) {
335 constructGetter(builder, returnType, BindingMapping.getRequireMethodName(localName().getLocalName()))
337 .setMechanics(ValueMechanics.NONNULL);
340 void addAsGetterMethodOverride(final @NonNull GeneratedTypeBuilderBase<?> builder,
341 final @NonNull TypeBuilderFactory builderFactory) {
342 // No-op for most cases
345 @NonNull Type methodReturnType(final @NonNull TypeBuilderFactory builderFactory) {
346 return getGeneratedType(builderFactory);
349 final void annotateDeprecatedIfNecessary(final AnnotableTypeBuilder builder) {
350 annotateDeprecatedIfNecessary(statement, builder);
354 ToStringHelper addToStringAttributes(final ToStringHelper helper) {
355 helper.add("argument", statement.argument());
357 if (isAddedByUses()) {
358 helper.addValue("addedByUses");
360 if (isAugmenting()) {
361 helper.addValue("augmenting");