YANGTOOLS-706: add utility method for finding substatements
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / EffectiveStmtUtils.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.yangtools.yang.parser.rfc7950.stmt;
10
11 import java.util.Optional;
12 import org.opendaylight.yangtools.yang.model.api.ElementCountConstraint;
13 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
14 import org.opendaylight.yangtools.yang.model.api.stmt.MaxElementsEffectiveStatement;
15 import org.opendaylight.yangtools.yang.model.api.stmt.MinElementsEffectiveStatement;
16 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
17 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
18
19 public final class EffectiveStmtUtils {
20     // FIXME: this should reside somewhere in max_elements
21     private static final String UNBOUNDED_STR = "unbounded";
22
23     private EffectiveStmtUtils() {
24         throw new UnsupportedOperationException("Utility class");
25     }
26
27     public static SourceException createNameCollisionSourceException(final StmtContext<?, ?, ?> ctx,
28             final EffectiveStatement<?, ?> effectiveStatement) {
29         return new SourceException(ctx.getStatementSourceReference(),
30             "Error in module '%s': cannot add '%s'. Node name collision: '%s' already declared.",
31             ctx.getRoot().getStatementArgument(),
32             effectiveStatement.argument(),
33             effectiveStatement.argument());
34     }
35
36     public static Optional<ElementCountConstraint> createElementCountConstraint(final EffectiveStatement<?, ?> stmt) {
37         final Integer minElements;
38         final Optional<Integer> min = stmt.findFirstEffectiveSubstatementArgument(MinElementsEffectiveStatement.class);
39         if (min.isPresent()) {
40             final Integer m = min.get();
41             minElements = m > 0 ? m : null;
42         } else {
43             minElements = null;
44         }
45
46         final Integer maxElements;
47         final String max = stmt.findFirstEffectiveSubstatementArgument(MaxElementsEffectiveStatement.class)
48                 .orElse(UNBOUNDED_STR);
49         if (!UNBOUNDED_STR.equals(max)) {
50             final Integer m = Integer.valueOf(max);
51             maxElements = m < Integer.MAX_VALUE ? m : null;
52         } else {
53             maxElements = null;
54         }
55
56         return ElementCountConstraint.forNullable(minElements, maxElements);
57     }
58 }