Integrate {Inference,Source}Exception with CommonStmtCtx 15/94015/7
authorRobert Varga <robert.varga@pantheon.tech>
Thu, 3 Dec 2020 02:16:12 +0000 (03:16 +0100)
committerRobert Varga <robert.varga@pantheon.tech>
Thu, 3 Dec 2020 15:42:26 +0000 (16:42 +0100)
We rarely need StatementSourceReference and we already define
a CommonStmtCtx which can provide it at almost any moment. Migrate
users, so that the reference is accessed only when needed.

This changes the balance of access, so that we may get away with
forwarding this through InferredStatementContext's prototype.

JIRA: YANGTOOLS-1194
Change-Id: I24e97cf10c68415caaa913014a9b6620f43cd94d
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
76 files changed:
yang/rfc6643-parser-support/src/main/java/org/opendaylight/yangtools/rfc6643/parser/MaxAccessStatementSupport.java
yang/rfc6643-parser-support/src/main/java/org/opendaylight/yangtools/rfc6643/parser/OidStatementSupport.java
yang/rfc7952-parser-support/src/main/java/org/opendaylight/yangtools/rfc7952/parser/AnnotationStatementSupport.java
yang/rfc8528-parser-support/src/main/java/org/opendaylight/yangtools/rfc8528/parser/MountPointStatementSupport.java
yang/yang-parser-reactor/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/InferredStatementContext.java
yang/yang-parser-reactor/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/ReactorStmtCtx.java
yang/yang-parser-reactor/src/main/java/org/opendaylight/yangtools/yang/parser/stmt/reactor/SourceSpecificContext.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/AbstractEffectiveModule.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/ArgumentUtils.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/BaseOperationContainerStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/EffectiveStmtUtils.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/XPathSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/action/ActionStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/augment/AbstractAugmentStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/augment/AugmentInferenceAction.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/base/BaseStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/belongs_to/BelongsToStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/case_/AbstractCaseStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/choice/AbstractChoiceStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/container/AbstractContainerStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/deviate/AbstractDeviateStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/deviation/DeviationStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/fraction_digits/FractionDigitsStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/grouping/AbstractGroupingStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/identity/AbstractIdentityStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/if_feature/AbstractIfFeatureStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/if_feature/IfFeaturePredicateVisitor.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/import_/AbstractImportStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/import_/RevisionImport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/import_/SemanticVersionImport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/include/AbstractIncludeStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/input/AbstractInputStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/key/KeyStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/leaf/LeafStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/leaf_list/AbstractLeafListStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/length/LengthStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/list/AbstractListStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/min_elements/MinElementsStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/modifier/ModifierStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/module/AbstractModuleStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/module/ModuleEffectiveStatementImpl.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/namespace/NamespaceStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/notification/AbstractNotificationStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/notification/NotificationStatementRFC7950Support.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/ordered_by/OrderedByStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/output/AbstractOutputStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/pattern/AbstractPatternStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/position/PositionStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/range/RangeStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/revision/RevisionStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/revision_date/RevisionDateStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/rpc/AbstractRpcStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/status/StatusStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/submodule/AbstractSubmoduleStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/submodule/SubmoduleEffectiveStatementImpl.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/type/AbstractIdentityRefSpecificationSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/type/AbstractLeafrefSpecificationSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/type/AbstractTypeStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/type/BitsSpecificationSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/type/Decimal64SpecificationSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/type/EnumSpecificationSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/type/TypeStatementRFC6020Support.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/type/TypeStatementRFC7950Support.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/type/UnionSpecificationSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/typedef/TypedefStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/unique/UniqueStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/uses/UsesStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/value/ValueStatementSupport.java
yang/yang-parser-rfc7950/src/main/java/org/opendaylight/yangtools/yang/parser/rfc7950/stmt/yang_version/YangVersionStatementSupport.java
yang/yang-parser-spi/src/main/java/org/opendaylight/yangtools/yang/parser/spi/SchemaTreeNamespace.java
yang/yang-parser-spi/src/main/java/org/opendaylight/yangtools/yang/parser/spi/meta/InferenceException.java
yang/yang-parser-spi/src/main/java/org/opendaylight/yangtools/yang/parser/spi/meta/InvalidSubstatementException.java
yang/yang-parser-spi/src/main/java/org/opendaylight/yangtools/yang/parser/spi/meta/MissingSubstatementException.java
yang/yang-parser-spi/src/main/java/org/opendaylight/yangtools/yang/parser/spi/meta/StmtContextUtils.java
yang/yang-parser-spi/src/main/java/org/opendaylight/yangtools/yang/parser/spi/meta/SubstatementValidator.java
yang/yang-parser-spi/src/main/java/org/opendaylight/yangtools/yang/parser/spi/source/SourceException.java

index 23d260879fbe4791f2415c5b61a470a8196dd779..5355e8f8dfcc0ec66a890ccfadecdfffb1ea6efe 100644 (file)
@@ -40,7 +40,7 @@ public final class MaxAccessStatementSupport
     public MaxAccess parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
         final MaxAccess val = MaxAccess.forStringLiteral(value);
         if (val == null) {
-            throw new SourceException(ctx.sourceReference(), "Invalid max-access value '%s'", value);
+            throw new SourceException(ctx, "Invalid max-access value '%s'", value);
         }
         return val;
     }
index 858c80f81828c7abfad4fabd53e40bd3e3233e27..9cb5a28b9351c846f9cab8c0181fb05f66db906d 100644 (file)
@@ -41,7 +41,7 @@ public final class OidStatementSupport
         try {
             return ObjectIdentifier.forString(value);
         } catch (IllegalArgumentException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Invalid object identifier '%s'", value);
+            throw new SourceException(ctx, e, "Invalid object identifier '%s'", value);
         }
     }
 
index 6436e44e0862bf51f18b3b85ff7685b3180cb140..7e306dbabca93e871e2f800cf6f4b592811ca76c 100644 (file)
@@ -55,7 +55,7 @@ public final class AnnotationStatementSupport
             path = stmt.getEffectiveParent().getSchemaPath().createChild(argument());
 
             final TypeEffectiveStatement<?> typeStmt = SourceException.throwIfNull(
-                firstSubstatementOfType(TypeEffectiveStatement.class), stmt.sourceReference(),
+                firstSubstatementOfType(TypeEffectiveStatement.class), stmt,
                 "AnnotationStatementSupport %s is missing a 'type' statement", argument());
 
             final ConcreteTypeBuilder<?> builder = ConcreteTypes.concreteTypeBuilder(typeStmt.getTypeDefinition(),
@@ -125,7 +125,7 @@ public final class AnnotationStatementSupport
     public void onStatementAdded(final Mutable<QName, AnnotationStatement, AnnotationEffectiveStatement> stmt) {
         final StatementDefinition parentDef = stmt.coerceParentContext().publicDefinition();
         SourceException.throwIf(YangStmtMapping.MODULE != parentDef && YangStmtMapping.SUBMODULE != parentDef,
-                stmt.sourceReference(), "Annotations may only be defined at root of either a module or a submodule");
+                stmt, "Annotations may only be defined at root of either a module or a submodule");
     }
 
     @Override
index 2785a07c04239ae9d4e438d7ea560cd2825c57d6..ca9222545068c0794b217b51babeb3f32eeea939 100644 (file)
@@ -100,8 +100,8 @@ public final class MountPointStatementSupport
     @Override
     public void onStatementAdded(final Mutable<QName, MountPointStatement, MountPointEffectiveStatement> stmt) {
         final StatementDefinition parentDef = stmt.coerceParentContext().publicDefinition();
-        SourceException.throwIf(YangStmtMapping.CONTAINER != parentDef && YangStmtMapping.LIST != parentDef,
-                stmt.sourceReference(), "Mount points may only be defined at either a container or a list");
+        SourceException.throwIf(YangStmtMapping.CONTAINER != parentDef && YangStmtMapping.LIST != parentDef, stmt,
+            "Mount points may only be defined at either a container or a list");
     }
 
     @Override
index b3f7278a884c32f1c12dded48f8ab356a05bac72..c355148b604c94c05ba2246169c6c4294fd9f87f 100644 (file)
@@ -247,8 +247,8 @@ final class InferredStatementContext<A, D extends DeclaredStatement<A>, E extend
 
         @SuppressWarnings("unchecked")
         final Mutable<QName, Y, Z> ret = (Mutable<QName, Y, Z>) copySubstatement((Mutable<?, ?, ?>) template)
-            .orElseThrow(() -> new InferenceException(sourceReference(),
-                "Failed to materialize child %s template %s", qname, template));
+            .orElseThrow(
+                () -> new InferenceException(this, "Failed to materialize child %s template %s", qname, template));
         ensureCompletedPhase(ret);
         addMaterialized(template, ret);
 
index b3d9dd7848ac903c393a880543d949f002bc97de..0ce875db9e4ab2f57a69cac7c8f85b5b743d64d5 100644 (file)
@@ -412,8 +412,8 @@ abstract class ReactorStmtCtx<A, D extends DeclaredStatement<A>, E extends Effec
             isConfig = optConfig.orElseThrow();
             if (isConfig) {
                 // Validity check: if parent is config=false this cannot be a config=true
-                InferenceException.throwIf(!parent.effectiveConfig(), sourceReference(),
-                        "Parent node has config=false, this node must not be specifed as config=true");
+                InferenceException.throwIf(!parent.effectiveConfig(), this,
+                    "Parent node has config=false, this node must not be specifed as config=true");
             }
         } else {
             // If "config" statement is not specified, the default is the same as the parent's "config" value.
index bbbd48e1461493d793a7f18f4aa9ad1c9de3f6a0..7c733cbad7ce1d8287027e0c4ebd45c94d607ea8 100644 (file)
@@ -333,7 +333,7 @@ final class SourceSpecificContext implements NamespaceStorageNode, NamespaceBeha
         }
 
         final String message = String.format("Yang model processing phase %s failed", identifier);
-        final InferenceException e = new InferenceException(message, root.sourceReference(), exceptions.get(0));
+        final InferenceException e = new InferenceException(message, root, exceptions.get(0));
         exceptions.listIterator(1).forEachRemaining(e::addSuppressed);
 
         return Optional.of(e);
index b6c285161d80a7720c3dcaefe2ce551a2bb577d2..8b5304e86c3da4344573e7fbf92da92dc05e7d70 100644 (file)
@@ -52,11 +52,11 @@ import org.opendaylight.yangtools.yang.model.api.stmt.YangVersionEffectiveStatem
 import org.opendaylight.yangtools.yang.model.api.stmt.compat.NotificationNodeContainerCompat;
 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.AbstractDeclaredEffectiveStatement.DefaultWithDataTree.WithSubstatements;
 import org.opendaylight.yangtools.yang.parser.rfc7950.stmt.EffectiveStatementMixins.DocumentedNodeMixin;
+import org.opendaylight.yangtools.yang.parser.spi.meta.CommonStmtCtx;
 import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
 import org.opendaylight.yangtools.yang.parser.spi.source.ImportPrefixToModuleCtx;
 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
 
 @Beta
 public abstract class AbstractEffectiveModule<D extends DeclaredStatement<UnqualifiedQName>,
@@ -213,13 +213,13 @@ public abstract class AbstractEffectiveModule<D extends DeclaredStatement<Unqual
                 .toString();
     }
 
-    protected static final @NonNull String findPrefix(final StatementSourceReference ref,
+    protected static final @NonNull String findPrefix(final CommonStmtCtx stmt,
             final Collection<? extends EffectiveStatement<?, ?>> substatements, final String type, final String name) {
         return substatements.stream()
             .filter(PrefixEffectiveStatement.class::isInstance)
             .map(prefix -> ((PrefixEffectiveStatement) prefix).argument())
             .findAny()
-            .orElseThrow(() -> new SourceException(ref, "Unable to resolve prefix for %s %s.", type, name));
+            .orElseThrow(() -> new SourceException(stmt, "Unable to resolve prefix for %s %s.", type, name));
     }
 
     // Alright. this is quite ugly
index 74f482b265562dfaad12976f03b20e2a635cb453..a43313d2243f8e43429e6f70e05947f9c1d24727 100644 (file)
@@ -70,8 +70,7 @@ public final class ArgumentUtils {
             return Boolean.FALSE;
         } else {
             final StatementDefinition def = ctx.publicDefinition();
-            throw new SourceException(ctx.sourceReference(),
-                "Invalid '%s' statement %s '%s', it can be either 'true' or 'false'",
+            throw new SourceException(ctx, "Invalid '%s' statement %s '%s', it can be either 'true' or 'false'",
                 def.getStatementName(), def.getArgumentDefinition().get().getArgumentName(), input);
         }
     }
@@ -103,14 +102,11 @@ public final class ArgumentUtils {
             try {
                 qnames.add(StmtContextUtils.parseNodeIdentifier(ctx, nodeName));
             } catch (final RuntimeException e) {
-                throw new SourceException(ctx.sourceReference(), e,
-                        "Failed to parse node '%s' in path '%s'", nodeName, path);
+                throw new SourceException(ctx, e, "Failed to parse node '%s' in path '%s'", nodeName, path);
             }
         }
 
-        if (qnames.isEmpty()) {
-            throw new SourceException("Schema node identifier must not be empty", ctx.sourceReference());
-        }
+        SourceException.throwIf(qnames.isEmpty(), ctx, "Schema node identifier must not be empty");
         return qnames;
     }
 
index b5c58e1322c4fa3aeaf0244f0bd419ef8b09a69d..42e5e9b02a33ecb134191883f5c4acd6896a872c 100644 (file)
@@ -52,7 +52,7 @@ public abstract class BaseOperationContainerStatementSupport<D extends DeclaredS
         try {
             return createDeclaredEffective(historyAndStatusFlags(stmt.history(), substatements), stmt, substatements);
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
index cea2e5fb500867483cb38a67b8f1442174aeee79..b29ed882faebbef22b3bf8a5866b5f968aa15311 100644 (file)
@@ -44,7 +44,7 @@ public final class EffectiveStmtUtils {
 
     public static SourceException createNameCollisionSourceException(final EffectiveStmtCtx.Current<?, ?> stmt,
             final EffectiveStatement<?, ?> effectiveStatement) {
-        return new SourceException(stmt.sourceReference(),
+        return new SourceException(stmt,
             "Error in module '%s': cannot add '%s'. Node name collision: '%s' already declared.",
             stmt.root().rawArgument(), effectiveStatement.argument(), effectiveStatement.argument());
     }
index 8ad738d499a152f4171c7105c530d1b88d39e37c..f407c3197c2b83fbbaef4215309e659efbead6b4 100644 (file)
@@ -39,7 +39,7 @@ public final class XPathSupport {
         try {
             parsed = parser.parseExpression(xpath);
         } catch (XPathExpressionException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Argument \"%s\" is not valid XPath string", xpath);
+            throw new SourceException(ctx, e, "Argument \"%s\" is not valid XPath string", xpath);
         }
 
         if (ctx.yangVersion().compareTo(parsed.getYangVersion()) < 0) {
index b277bf02568b364869ce53978ed621017916334f..0960e9ab62ac6683fddedc1898700542b2208c0c 100644 (file)
@@ -98,21 +98,21 @@ public final class ActionStatementSupport extends
         final StatementSourceReference ref = stmt.sourceReference();
         checkState(!substatements.isEmpty(), "Missing implicit input/output statements at %s", ref);
         final QName argument = stmt.getArgument();
-        SourceException.throwIf(StmtContextUtils.hasAncestorOfType(stmt, ILLEGAL_PARENTS), ref,
+        SourceException.throwIf(StmtContextUtils.hasAncestorOfType(stmt, ILLEGAL_PARENTS), stmt,
             "Action %s is defined within a notification, rpc or another action", argument);
         SourceException.throwIf(
-            !StmtContextUtils.hasAncestorOfTypeWithChildOfType(stmt, YangStmtMapping.LIST, YangStmtMapping.KEY), ref,
+            !StmtContextUtils.hasAncestorOfTypeWithChildOfType(stmt, YangStmtMapping.LIST, YangStmtMapping.KEY), stmt,
             "Action %s is defined within a list that has no key statement", argument);
-        SourceException.throwIf(StmtContextUtils.hasParentOfType(stmt, YangStmtMapping.CASE), ref,
+        SourceException.throwIf(StmtContextUtils.hasParentOfType(stmt, YangStmtMapping.CASE), stmt,
             "Action %s is defined within a case statement", argument);
-        SourceException.throwIf(StmtContextUtils.hasParentOfType(stmt, YangStmtMapping.MODULE), ref,
+        SourceException.throwIf(StmtContextUtils.hasParentOfType(stmt, YangStmtMapping.MODULE), stmt,
             "Action %s is defined at the top level of a module", argument);
 
         try {
             return new ActionEffectiveStatementImpl(stmt.declared(), stmt.wrapSchemaPath(),
                 historyAndStatusFlags(stmt.history(), substatements), substatements);
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 }
index 825a9a1774dffd27582883255ba2569e767fff6a..c13d83eb9c512b2f04725a778ed83f132a45ca2e 100644 (file)
@@ -53,9 +53,8 @@ abstract class AbstractAugmentStatementSupport
     @Override
     public final SchemaNodeIdentifier parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
         SourceException.throwIf(PATH_REL_PATTERN1.matcher(value).matches()
-            || PATH_REL_PATTERN2.matcher(value).matches(), ctx.sourceReference(),
-            "Augment argument \'%s\' is not valid, it can be only absolute path; or descendant if used in uses",
-            value);
+            || PATH_REL_PATTERN2.matcher(value).matches(), ctx,
+            "Augment argument \'%s\' is not valid, it can be only absolute path; or descendant if used in uses", value);
 
         // As per:
         //   https://tools.ietf.org/html/rfc6020#section-7.15
@@ -67,10 +66,10 @@ abstract class AbstractAugmentStatementSupport
         final SchemaNodeIdentifier result = ArgumentUtils.nodeIdentifierFromPath(ctx, value);
         final StatementDefinition parent = ctx.coerceParentContext().publicDefinition();
         if (parent == YangStmtMapping.USES) {
-            SourceException.throwIf(result instanceof Absolute, ctx.sourceReference(),
+            SourceException.throwIf(result instanceof Absolute, ctx,
                 "Absolute schema node identifier is not allowed when used within a uses statement");
         } else {
-            SourceException.throwIf(result instanceof Descendant, ctx.sourceReference(),
+            SourceException.throwIf(result instanceof Descendant, ctx,
                 "Descendant schema node identifier is not allowed when used outside of a uses statement");
         }
         return result;
@@ -137,7 +136,7 @@ abstract class AbstractAugmentStatementSupport
                 StmtContextUtils.getRootModuleQName(stmt.caerbannog()), substatements,
                 (AugmentationSchemaNode) stmt.original());
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
index 226faa363fcfe75b79cb59b6f17dcd748d6194cf..8c6e36dcd68d6be15459da547f9b3b18d275535f 100644 (file)
@@ -103,8 +103,7 @@ final class AugmentInferenceAction implements InferenceAction {
             }
         }
 
-        throw new InferenceException(augmentNode.sourceReference(), "Augment target '%s' not found",
-            augmentNode.argument());
+        throw new InferenceException(augmentNode, "Augment target '%s' not found", augmentNode.argument());
     }
 
     private void copyFromSourceToTarget(final StatementContextBase<?, ?, ?> sourceCtx,
@@ -163,8 +162,7 @@ final class AugmentInferenceAction implements InferenceAction {
         if (sourceCtx.producesDeclared(DataDefinitionStatement.class)) {
             for (final StmtContext<?, ?, ?> subStatement : targetCtx.allSubstatements()) {
                 if (subStatement.producesDeclared(DataDefinitionStatement.class)) {
-                    InferenceException.throwIf(Objects.equals(sourceCtx.argument(), subStatement.argument()),
-                        sourceCtx.sourceReference(),
+                    InferenceException.throwIf(Objects.equals(sourceCtx.argument(), subStatement.argument()), sourceCtx,
                         "An augment cannot add node named '%s' because this name is already used in target",
                         sourceCtx.rawArgument());
                 }
@@ -184,7 +182,7 @@ final class AugmentInferenceAction implements InferenceAction {
             sourceCtx.allSubstatementsStream().forEach(AugmentInferenceAction::checkForMandatoryNodes);
         }
 
-        InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx), sourceCtx.sourceReference(),
+        InferenceException.throwIf(StmtContextUtils.isMandatoryNode(sourceCtx), sourceCtx,
             "An augment cannot add node '%s' because it is mandatory and in module different than target",
             sourceCtx.rawArgument());
     }
index 1a351e4dd9f30a01093d805d0d877608ab991dc2..b590e7ba5abf2e6f5384a58c9e681759b449c2d6 100644 (file)
@@ -67,8 +67,7 @@ public final class BaseStatementSupport extends BaseQNameStatementSupport<BaseSt
 
                 @Override
                 public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
-                    throw new InferenceException(baseStmtCtx.sourceReference(),
-                        "Unable to resolve identity %s and base identity %s",
+                    throw new InferenceException(baseStmtCtx, "Unable to resolve identity %s and base identity %s",
                         baseParentCtx.argument(), baseStmtCtx.argument());
                 }
             });
index 6a8ef1727c6fdf59aa438fef83e4140130954926..d8dc213b26aafd82818e03a352d71ef821c9e35c 100644 (file)
@@ -75,8 +75,8 @@ public final class BelongsToStatementSupport
             @Override
             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
                 if (failed.contains(belongsToPrereq)) {
-                    throw new InferenceException(belongsToCtx.sourceReference(),
-                        "Module '%s' from belongs-to was not found", belongsToCtx.argument());
+                    throw new InferenceException(belongsToCtx, "Module '%s' from belongs-to was not found",
+                        belongsToCtx.argument());
                 }
             }
         });
index 1ccc86c3709b8f7a74877969b2715c394067c25f..bdae0506a088ffa3611f118a700a9b7f862d373a 100644 (file)
@@ -67,7 +67,7 @@ abstract class AbstractCaseStatementSupport
             return new DeclaredCaseEffectiveStatement(stmt.declared(), substatements, computeFlags(stmt, substatements),
                 stmt.wrapSchemaPath(), findOriginal(stmt));
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
@@ -78,7 +78,7 @@ abstract class AbstractCaseStatementSupport
             return new UndeclaredCaseEffectiveStatement(substatements, computeFlags(stmt, substatements),
                 stmt.wrapSchemaPath(), findOriginal(stmt));
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
index c5239aacd32c6192727c5ff92e07476b6713176f..48601244f6197b23651ead71d861604856ef006b 100644 (file)
@@ -68,13 +68,12 @@ abstract class AbstractChoiceStatementSupport
             try {
                 qname = QName.create(stmt.getArgument(), defaultArg);
             } catch (IllegalArgumentException e) {
-                throw new SourceException(stmt.sourceReference(), "Default statement has invalid name '%s'", defaultArg,
-                    e);
+                throw new SourceException(stmt, e, "Default statement has invalid name '%s'", defaultArg);
             }
 
             // FIXME: this does not work with submodules, as they are
-            defaultCase = InferenceException.throwIfNull(findCase(qname, substatements),
-                    stmt.sourceReference(), "Default statement refers to missing case %s", qname);
+            defaultCase = InferenceException.throwIfNull(findCase(qname, substatements), stmt,
+                "Default statement refers to missing case %s", qname);
         } else {
             defaultCase = null;
         }
@@ -89,7 +88,7 @@ abstract class AbstractChoiceStatementSupport
             return new ChoiceEffectiveStatementImpl(stmt.declared(), substatements, flags, stmt.wrapSchemaPath(),
                 defaultCase, (ChoiceSchemaNode) stmt.original());
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
index 2deaa5bc099c28abe46defcc555d52f55c961736..a618b78830fb78a988afe3f6ae150ff7b48a513a 100644 (file)
@@ -63,7 +63,7 @@ abstract class AbstractContainerStatementSupport
         try {
             return new ContainerEffectiveStatementImpl(stmt.declared(), substatements, flags, path, original);
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 }
index b16661d6b3d4193ea9ebddd84c7aae03e9364040..03a8fbcc481c01c061c9aa43b3e8ee7ad9a1d8d3 100644 (file)
@@ -105,7 +105,7 @@ abstract class AbstractDeviateStatementSupport
 
     @Override
     public final DeviateKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
-        return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value), ctx.sourceReference(),
+        return SourceException.throwIfNull(KEYWORD_TO_DEVIATE_MAP.get(value), ctx,
             "String '%s' is not valid deviate argument", value);
     }
 
@@ -162,8 +162,8 @@ abstract class AbstractDeviateStatementSupport
 
             @Override
             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
-                throw new InferenceException(deviateStmtCtx.coerceParentContext().sourceReference(),
-                    "Deviation target '%s' not found.", deviationTarget);
+                throw new InferenceException(deviateStmtCtx.coerceParentContext(), "Deviation target '%s' not found.",
+                    deviationTarget);
             }
         });
     }
@@ -261,7 +261,7 @@ abstract class AbstractDeviateStatementSupport
                     && YangStmtMapping.LEAF.equals(targetCtx.publicDefinition())) {
                 for (final StmtContext<?, ?, ?> targetCtxSubstatement : targetCtx.allSubstatements()) {
                     InferenceException.throwIf(stmtToBeAdded.equals(targetCtxSubstatement.publicDefinition()),
-                        stmtCtxToBeAdded.sourceReference(),
+                        stmtCtxToBeAdded,
                         "Deviation cannot add substatement %s to target node %s because it is already defined "
                         + "in target and can appear only once.",
                         stmtToBeAdded.getStatementName(), targetCtx.argument());
@@ -318,9 +318,9 @@ abstract class AbstractDeviateStatementSupport
             return;
         }
 
-        throw new InferenceException(stmtCtxToBeReplaced.sourceReference(), "Deviation cannot replace "
-                + "substatement %s in target node %s because it does not exist in target node.",
-                stmtToBeReplaced.getStatementName(), targetCtx.argument());
+        throw new InferenceException(stmtCtxToBeReplaced,
+            "Deviation cannot replace substatement %s in target node %s because it does not exist in target node.",
+            stmtToBeReplaced.getStatementName(), targetCtx.argument());
     }
 
     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
@@ -378,7 +378,7 @@ abstract class AbstractDeviateStatementSupport
     private static void validateDeviationTarget(final StmtContext<?, ?, ?> deviateSubStmtCtx,
             final StmtContext<?, ?, ?> targetCtx) {
         InferenceException.throwIf(!isSupportedDeviationTarget(deviateSubStmtCtx, targetCtx,
-            targetCtx.yangVersion()), deviateSubStmtCtx.sourceReference(),
+            targetCtx.yangVersion()), deviateSubStmtCtx,
             "%s is not a valid deviation target for substatement %s.", targetCtx.argument(),
             deviateSubStmtCtx.publicDefinition().getStatementName());
     }
index 6340eae3e853adee75e2009c8bc609b22896ee8f..eea25b2bb65b1310644e441761e981ff91568a6c 100644 (file)
@@ -55,7 +55,7 @@ public final class DeviationStatementSupport
         final QNameModule targetModule = Iterables.getLast(ctx.getArgument().getNodeIdentifiers()).getModule();
 
         if (currentModule.equals(targetModule)) {
-            throw new InferenceException(ctx.sourceReference(),
+            throw new InferenceException(ctx,
                     "Deviation must not target the same module as the one it is defined in: %s", currentModule);
         }
     }
index 693ef1f070530778311cfcaffebfdc97ba7491fe..a6d48149a88dd287d815afc93a3547801138a11c 100644 (file)
@@ -63,12 +63,10 @@ public final class FractionDigitsStatementSupport
         try {
             fractionDigits = Integer.parseInt(value);
         } catch (NumberFormatException e) {
-            throw new SourceException(ctx.sourceReference(), e, "%s is not valid fraction-digits integer argument",
-                value);
+            throw new SourceException(ctx, e, "%s is not valid fraction-digits integer argument", value);
         }
         if (fractionDigits < 1 || fractionDigits > 18) {
-            throw new SourceException("fraction-digits argument should be integer within [1..18]",
-                ctx.sourceReference());
+            throw new SourceException("fraction-digits argument should be integer within [1..18]", ctx);
         }
         return fractionDigits;
     }
index ba233c8536ba43544e178d528684a5d461c6b67f..ecca4c8ba7f3de64d43ae9e172ac56d8e6d2eb11 100644 (file)
@@ -70,7 +70,7 @@ abstract class AbstractGroupingStatementSupport
             return new GroupingEffectiveStatementImpl(stmt.declared(), substatements,
                 historyAndStatusFlags(stmt.history(), substatements), stmt.wrapSchemaPath());
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
@@ -89,6 +89,6 @@ abstract class AbstractGroupingStatementSupport
     private static void checkConflict(final StmtContext<?, ?, ?> parent, final StmtContext<QName, ?, ?> stmt) {
         final QName arg = stmt.getArgument();
         final StmtContext<?, ?, ?> existing = parent.getFromNamespace(GroupingNamespace.class, arg);
-        SourceException.throwIf(existing != null, stmt.sourceReference(), "Duplicate name for grouping %s", arg);
+        SourceException.throwIf(existing != null, stmt, "Duplicate name for grouping %s", arg);
     }
 }
\ No newline at end of file
index 705560e90258e6cbf0c2c4a63c198a6ac1652203..a042dabb833b1cb64a0d42f8eb1a233cff4cf6a2 100644 (file)
@@ -51,7 +51,7 @@ abstract class AbstractIdentityStatementSupport
             final Mutable<QName, IdentityStatement, IdentityEffectiveStatement> stmt) {
         final QName qname = stmt.getArgument();
         final StmtContext<?, ?, ?> prev = stmt.getFromNamespace(IdentityNamespace.class, qname);
-        SourceException.throwIf(prev != null, stmt.sourceReference(), "Duplicate identity definition %s", qname);
+        SourceException.throwIf(prev != null, stmt, "Duplicate identity definition %s", qname);
         stmt.addToNs(IdentityNamespace.class, qname, stmt);
     }
 
index 554f756dc779d1678d708cf00dbfe46011d915fe..98477a55f73f347c2b80b4539bcb820e290d79a7 100644 (file)
@@ -73,8 +73,8 @@ abstract class AbstractIfFeatureStatementSupport
                     unresolvedFeatures.add(verifyNotNull(backRef.get(prereq)));
                 }
 
-                throw new InferenceException(stmt.sourceReference(),
-                    "Failed to resolve feature references %s in \"%s\"", unresolvedFeatures, stmt.rawArgument());
+                throw new InferenceException(stmt, "Failed to resolve feature references %s in \"%s\"",
+                    unresolvedFeatures, stmt.rawArgument());
             }
         });
     }
index 54f0eeb06d77a205f9b3d5216a170fe4a2e6ee3d..d0777d279a3d80f95e0fd5f04cca32f2cc852135 100644 (file)
@@ -79,7 +79,7 @@ final class IfFeaturePredicateVisitor extends IfFeatureExpressionParserBaseVisit
         }
 
         throw new SourceException("Unexpected grammar context during parsing of IfFeature expression. "
-                + "Most probably IfFeature grammar has been changed.", stmtCtx.sourceReference());
+                + "Most probably IfFeature grammar has been changed.", stmtCtx);
     }
 
     @Override
index 5c7cfe0f6d76b4d5c731acfa71fe8d0d6864dced..2ad26bad3b2a0ba3b5386a151852338c444f6d8f 100644 (file)
@@ -73,7 +73,7 @@ abstract class AbstractImportStatementSupport
                         moduleName);
                 Verify.verifyNotNull(importedModuleNamespace);
                 final String impPrefix = SourceException.throwIfNull(
-                    firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class), stmt.sourceReference(),
+                    firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class), stmt,
                     "Missing prefix statement");
 
                 stmt.addToNs(ImpPrefixToNamespace.class, impPrefix, importedModuleNamespace);
@@ -81,8 +81,8 @@ abstract class AbstractImportStatementSupport
 
             @Override
             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
-                InferenceException.throwIf(failed.contains(imported), stmt.sourceReference(),
-                        "Imported module [%s] was not found.", moduleName);
+                InferenceException.throwIf(failed.contains(imported), stmt, "Imported module [%s] was not found.",
+                    moduleName);
             }
         });
     }
@@ -138,9 +138,9 @@ abstract class AbstractImportStatementSupport
             final String moduleName, final String prefix) {
         // When 'revision-date' of an import is not specified in yang source, we need to find revision of imported
         // module.
-        final QNameModule importedModule = StmtContextUtils.getModuleQNameByPrefix(ctx, prefix);
-        SourceException.throwIfNull(importedModule, ctx.sourceReference(),
-                "Unable to find import of module %s with prefix %s.", moduleName, prefix);
+        final QNameModule importedModule = SourceException.throwIfNull(
+            StmtContextUtils.getModuleQNameByPrefix(ctx, prefix), ctx,
+            "Unable to find import of module %s with prefix %s.", moduleName, prefix);
         return importedModule.getRevision().orElse(null);
     }
 }
index f319b7b38c5b925eedc9e92f9d64fa29825282e7..edf52d00aab5f6ba7ea5ae9c839c11e96ba1ad62 100644 (file)
@@ -66,8 +66,7 @@ final class RevisionImport {
                 final StmtContext<?, ?, ?> importedModule = imported.resolve(ctx);
 
                 final QNameModule mod = InferenceException.throwIfNull(stmt.getFromNamespace(
-                    ModuleCtxToModuleQName.class, importedModule), stmt.sourceReference(),
-                    "Failed to find module of %s", importedModule);
+                    ModuleCtxToModuleQName.class, importedModule), stmt, "Failed to find module of %s", importedModule);
 
                 linkageTarget.resolve(ctx).addToNs(ImportedModuleContext.class,
                     stmt.getFromNamespace(ModuleCtxToSourceIdentifier.class, importedModule), importedModule);
@@ -82,8 +81,7 @@ final class RevisionImport {
             @Override
             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
                 if (failed.contains(imported)) {
-                    throw new InferenceException(stmt.sourceReference(), "Imported module [%s] was not found.",
-                        moduleName);
+                    throw new InferenceException(stmt, "Imported module [%s] was not found.", moduleName);
                 }
             }
         });
index a6872b8b9d0bdc2d08616aca03deb50c853606b6..95d4188308fc269a9c13a4e2346cdd6aaa775cd2 100644 (file)
@@ -150,8 +150,7 @@ final class SemanticVersionImport {
                 stmt.addToNs(ImportPrefixToSemVerSourceIdentifier.class, impPrefix, semVerModuleIdentifier);
 
                 final QNameModule mod = InferenceException.throwIfNull(stmt.getFromNamespace(
-                    ModuleCtxToModuleQName.class, importedModule), stmt.sourceReference(),
-                    "Failed to find module of %s", importedModule);
+                    ModuleCtxToModuleQName.class, importedModule), stmt, "Failed to find module of %s", importedModule);
 
                 final URI modNs = firstAttributeOf(importedModule.declaredSubstatements(),
                     NamespaceStatement.class);
@@ -162,9 +161,9 @@ final class SemanticVersionImport {
             @Override
             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
                 if (failed.contains(imported)) {
-                    throw new InferenceException(stmt.sourceReference(),
-                            "Unable to find module compatible with requested import [%s(%s)].", moduleName,
-                            getRequestedImportVersionString(stmt));
+                    throw new InferenceException(stmt,
+                        "Unable to find module compatible with requested import [%s(%s)].", moduleName,
+                        getRequestedImportVersionString(stmt));
                 }
             }
         });
index fb8e43e159d50518920ea0d11511c5e6b35c7bc0..946292616b06930ed94cf24638d633c7b6e5d94a 100644 (file)
@@ -78,7 +78,7 @@ abstract class AbstractIncludeStatementSupport
 
             @Override
             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
-                InferenceException.throwIf(failed.contains(requiresCtxPrerequisite), stmt.sourceReference(),
+                InferenceException.throwIf(failed.contains(requiresCtxPrerequisite), stmt,
                     "Included submodule '%s' was not found: ", stmt.argument());
             }
         });
index 1465d662c006c15aec3c3b7197f697dea793ba17..ff1342a852d17a8a980930d1da279b15b4d1798a 100644 (file)
@@ -69,7 +69,7 @@ abstract class AbstractInputStatementSupport
         try {
             return new UndeclaredInputEffectiveStatement(flags, substatements, stmt.wrapSchemaPath());
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 }
index 300e5f71b1ae9770e2111d8baa8709a17071f1d2..cb5d1df08663ca6e4ea01115e8d1d01d238aa363 100644 (file)
@@ -56,8 +56,7 @@ public final class KeyStatementSupport
 
         // Throws NPE on nulls, retains first inserted value, cannot be modified
         final ImmutableSet<QName> ret = builder.build();
-        SourceException.throwIf(ret.size() != tokens, ctx.sourceReference(), "Key argument '%s' contains duplicates",
-            value);
+        SourceException.throwIf(ret.size() != tokens, ctx, "Key argument '%s' contains duplicates", value);
         return ret;
     }
 
index 9bc65da11eda19b5038a7a8105d31fe41a0339e3..7d779a7d7521b7e053e71d79229c83e118dbb46d 100644 (file)
@@ -82,12 +82,11 @@ public final class LeafStatementSupport extends BaseSchemaTreeStatementSupport<L
     protected LeafEffectiveStatement createEffective(final Current<QName, LeafStatement> stmt,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
         final TypeEffectiveStatement<?> typeStmt = SourceException.throwIfNull(
-            findFirstStatement(substatements, TypeEffectiveStatement.class), stmt.sourceReference(),
-                "Leaf is missing a 'type' statement");
+            findFirstStatement(substatements, TypeEffectiveStatement.class), stmt,
+            "Leaf is missing a 'type' statement");
         final String dflt = findFirstArgument(substatements, DefaultEffectiveStatement.class, null);
         SourceException.throwIf(
-            EffectiveStmtUtils.hasDefaultValueMarkedWithIfFeature(stmt.yangVersion(), typeStmt, dflt),
-            stmt.sourceReference(),
+            EffectiveStmtUtils.hasDefaultValueMarkedWithIfFeature(stmt.yangVersion(), typeStmt, dflt), stmt,
             "Leaf '%s' has default value '%s' marked with an if-feature statement.", stmt.argument(), dflt);
 
         final LeafSchemaNode original = (LeafSchemaNode) stmt.original();
index 502597824c06ed58d5bd15bd695d11b2f08716d3..78ac1c394ff2ddd01bfb9374f903871f466a53d5 100644 (file)
@@ -53,7 +53,7 @@ abstract class AbstractLeafListStatementSupport
     protected LeafListEffectiveStatement createEffective(final Current<QName, LeafListStatement> stmt,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
         final TypeEffectiveStatement<?> typeStmt = SourceException.throwIfNull(
-                findFirstStatement(substatements, TypeEffectiveStatement.class), stmt.sourceReference(),
+                findFirstStatement(substatements, TypeEffectiveStatement.class), stmt,
                 "Leaf-list is missing a 'type' statement");
 
         final LeafListSchemaNode original = (LeafListSchemaNode) stmt.original();
@@ -74,8 +74,7 @@ abstract class AbstractLeafListStatementSupport
         // FIXME: We need to interpret the default value in terms of supplied element type
         SourceException.throwIf(
                 EffectiveStmtUtils.hasDefaultValueMarkedWithIfFeature(stmt.yangVersion(), typeStmt, defaultValues),
-                stmt.sourceReference(),
-                "Leaf-list '%s' has one of its default values '%s' marked with an if-feature statement.",
+                stmt, "Leaf-list '%s' has one of its default values '%s' marked with an if-feature statement.",
                 stmt.argument(), defaultValues);
 
         // FIXME: RFC7950 section 7.7.4: we need to check for min-elements and defaultValues conflict
index a619f0971b5352ad1103f073081b89abfe6d5a35..120a7d870808f83acc15d73849432e1e1e72b1b2 100644 (file)
@@ -60,18 +60,18 @@ public final class LengthStatementSupport
                 max = parseIntegerConstraintValue(ctx, boundaries.next());
 
                 // if min larger than max then error
-                SourceException.throwIf(ArgumentUtils.compareNumbers(min, max) == 1, ctx.sourceReference(),
+                SourceException.throwIf(ArgumentUtils.compareNumbers(min, max) == 1, ctx,
                     "Length constraint %s has descending order of boundaries; should be ascending.", singleRange);
-                SourceException.throwIf(boundaries.hasNext(), ctx.sourceReference(),
+                SourceException.throwIf(boundaries.hasNext(), ctx,
                     "Wrong number of boundaries in length constraint %s.", singleRange);
             } else {
                 max = min;
             }
 
             // some of intervals overlapping
-            InferenceException.throwIf(ranges.size() > 1
-                && ArgumentUtils.compareNumbers(min, Iterables.getLast(ranges).upperBound()) != 1,
-                        ctx.sourceReference(),  "Some of the length ranges in %s are not disjoint", value);
+            InferenceException.throwIf(
+                ranges.size() > 1 && ArgumentUtils.compareNumbers(min, Iterables.getLast(ranges).upperBound()) != 1,
+                ctx, "Some of the length ranges in %s are not disjoint", value);
             ranges.add(ValueRange.of(min, max));
         }
 
@@ -112,7 +112,7 @@ public final class LengthStatementSupport
         try {
             return new BigInteger(value);
         } catch (final NumberFormatException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Value %s is not a valid integer", value);
+            throw new SourceException(ctx, e, "Value %s is not a valid integer", value);
         }
     }
 }
\ No newline at end of file
index c8a3cd753af9d3bb6f6201d0bcfdfafa41181042..7e91f97fc56b18cbeca8e3e59776ea547432e248 100644 (file)
@@ -87,9 +87,8 @@ abstract class AbstractListStatementSupport extends
             }
             for (final QName keyQName : keyStmt.argument()) {
                 if (!possibleLeafQNamesForKey.contains(keyQName)) {
-                    throw new InferenceException(stmt.sourceReference(),
-                        "Key '%s' misses node '%s' in list '%s'", keyStmt.getDeclared().rawArgument(),
-                        keyQName.getLocalName(), stmt.argument());
+                    throw new InferenceException(stmt, "Key '%s' misses node '%s' in list '%s'",
+                        keyStmt.getDeclared().rawArgument(), keyQName.getLocalName(), stmt.argument());
                 }
                 keyDefinitionInit.add(keyQName);
             }
@@ -124,7 +123,7 @@ abstract class AbstractListStatementSupport extends
                     : new RegularListEffectiveStatement(stmt.declared(), path, flags, substatements, keyDefinition,
                         elementCountConstraint.orElse(null), original);
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
index 6170a02c71da1b841f35ec2757fe115e7a32f809..16be0b441aaad8a400e808174a6e8a877d19c234 100644 (file)
@@ -38,7 +38,7 @@ public final class MinElementsStatementSupport
         try {
             return Integer.valueOf(value);
         } catch (NumberFormatException e) {
-            throw new SourceException("Invalid min-elements argument", ctx.sourceReference(), e);
+            throw new SourceException("Invalid min-elements argument", ctx, e);
         }
     }
 
index 467aa9884e0aa420b93f7fdcc3d3f9624bbb32c2..a5681b77f744e671b2cbebfcc5b8eaab0e18caff 100644 (file)
@@ -36,7 +36,7 @@ public final class ModifierStatementSupport
 
     @Override
     public ModifierKind parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
-        return SourceException.unwrap(ModifierKind.parse(value), ctx.sourceReference(),
+        return SourceException.unwrap(ModifierKind.parse(value), ctx,
             "'%s' is not valid argument of modifier statement", value);
     }
 
index b9bb358caa49b69f210d7d238c97e942e823c308..b8792eb447fd3e0f5bc08a16e9ec7608b5746108 100644 (file)
@@ -69,7 +69,7 @@ abstract class AbstractModuleStatementSupport
         try {
             return UnqualifiedQName.of(value);
         } catch (IllegalArgumentException e) {
-            throw new SourceException(e.getMessage(), ctx.sourceReference(), e);
+            throw new SourceException(e.getMessage(), ctx, e);
         }
     }
 
@@ -78,13 +78,13 @@ abstract class AbstractModuleStatementSupport
             final Mutable<UnqualifiedQName, ModuleStatement, ModuleEffectiveStatement> stmt) {
         final String moduleName = stmt.getRawArgument();
 
-        final URI moduleNs = firstAttributeOf(stmt.declaredSubstatements(), NamespaceStatement.class);
-        SourceException.throwIfNull(moduleNs, stmt.sourceReference(),
+        final URI moduleNs = SourceException.throwIfNull(
+            firstAttributeOf(stmt.declaredSubstatements(), NamespaceStatement.class), stmt,
             "Namespace of the module [%s] is missing", moduleName);
         stmt.addToNs(ModuleNameToNamespace.class, moduleName, moduleNs);
 
-        final String modulePrefix = firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class);
-        SourceException.throwIfNull(modulePrefix, stmt.sourceReference(),
+        final String modulePrefix = SourceException.throwIfNull(
+            firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class), stmt,
             "Prefix of the module [%s] is missing", moduleName);
         stmt.addToNs(ImpPrefixToNamespace.class, modulePrefix, moduleNs);
 
@@ -101,18 +101,17 @@ abstract class AbstractModuleStatementSupport
     public final void onLinkageDeclared(
             final Mutable<UnqualifiedQName, ModuleStatement, ModuleEffectiveStatement> stmt) {
 
-        final Optional<URI> moduleNs = Optional.ofNullable(firstAttributeOf(stmt.declaredSubstatements(),
-                NamespaceStatement.class));
-        SourceException.throwIf(!moduleNs.isPresent(), stmt.sourceReference(),
+        final URI moduleNs = SourceException.throwIfNull(
+            firstAttributeOf(stmt.declaredSubstatements(), NamespaceStatement.class), stmt,
             "Namespace of the module [%s] is missing", stmt.argument());
 
         final Optional<Revision> revisionDate = StmtContextUtils.getLatestRevision(stmt.declaredSubstatements());
-        final QNameModule qNameModule = QNameModule.create(moduleNs.get(), revisionDate.orElse(null)).intern();
+        final QNameModule qNameModule = QNameModule.create(moduleNs, revisionDate.orElse(null)).intern();
         final StmtContext<?, ModuleStatement, ModuleEffectiveStatement> possibleDuplicateModule =
                 stmt.getFromNamespace(NamespaceToModule.class, qNameModule);
         if (possibleDuplicateModule != null && possibleDuplicateModule != stmt) {
-            throw new SourceException(stmt.sourceReference(), "Module namespace collision: %s. At %s",
-                    qNameModule.getNamespace(), possibleDuplicateModule.sourceReference());
+            throw new SourceException(stmt, "Module namespace collision: %s. At %s", qNameModule.getNamespace(),
+                possibleDuplicateModule.sourceReference());
         }
 
         final String moduleName = stmt.getRawArgument();
@@ -122,8 +121,8 @@ abstract class AbstractModuleStatementSupport
         stmt.addContext(ModuleNamespaceForBelongsTo.class, moduleIdentifier.getName(), stmt);
         stmt.addContext(NamespaceToModule.class, qNameModule, stmt);
 
-        final String modulePrefix = firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class);
-        SourceException.throwIfNull(modulePrefix, stmt.sourceReference(),
+        final String modulePrefix = SourceException.throwIfNull(
+            firstAttributeOf(stmt.declaredSubstatements(), PrefixStatement.class), stmt,
             "Prefix of the module [%s] is missing", stmt.argument());
 
         stmt.addToNs(PrefixToModule.class, modulePrefix, qNameModule);
@@ -193,7 +192,7 @@ abstract class AbstractModuleStatementSupport
         try {
             return new ModuleEffectiveStatementImpl(stmt, substatements, submodules);
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
@@ -204,7 +203,7 @@ abstract class AbstractModuleStatementSupport
     }
 
     private static SourceException noNamespace(final @NonNull CommonStmtCtx stmt) {
-        return new SourceException("No namespace declared in module", stmt.sourceReference());
+        return new SourceException("No namespace declared in module", stmt);
     }
 
     private static void addToSemVerModuleNamespace(
index 72c80f175e56ae8cf2c40aad8a71d8c85b471222..c6480ee02569871e121d4f047b7818231735d1e1 100644 (file)
@@ -61,7 +61,7 @@ final class ModuleEffectiveStatementImpl extends AbstractEffectiveModule<ModuleS
     ModuleEffectiveStatementImpl(final Current<UnqualifiedQName, ModuleStatement> stmt,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements,
             final Collection<? extends Submodule> submodules) {
-        super(stmt, substatements, findPrefix(stmt.sourceReference(), substatements, "module", stmt.getRawArgument()));
+        super(stmt, substatements, findPrefix(stmt, substatements, "module", stmt.getRawArgument()));
 
         qnameModule = verifyNotNull(stmt.getFromNamespace(ModuleCtxToModuleQName.class, stmt.caerbannog()));
         this.submodules = ImmutableList.copyOf(submodules);
index 322010299674592a339c4027f6fe137f54e814ec..876b177c23f74c6ec83115bf0b13c7100a9b8b33 100644 (file)
@@ -42,7 +42,7 @@ public final class NamespaceStatementSupport
         try {
             return new URI(value);
         } catch (URISyntaxException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Invalid namespace \"%s\"", value);
+            throw new SourceException(ctx, e, "Invalid namespace \"%s\"", value);
         }
     }
 
index b46b754977297b236a55497689f32c8fa6ef7d11..5fa993bce58363e0715ad573ffd91c2eaa87c067 100644 (file)
@@ -46,7 +46,7 @@ abstract class AbstractNotificationStatementSupport
             return new NotificationEffectiveStatementImpl(stmt.declared(), substatements,
                 historyAndStatusFlags(stmt.history(), substatements), stmt.wrapSchemaPath());
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
index 0bead4a686cfd20e7dbc939096faf543b843b3d4..2e187935a35bbc17b85663bcf2c498a7dbdd6064 100644 (file)
@@ -17,7 +17,6 @@ import org.opendaylight.yangtools.yang.parser.spi.meta.EffectiveStmtCtx.Current;
 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
 import org.opendaylight.yangtools.yang.parser.spi.meta.SubstatementValidator;
 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
-import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
 
 /**
  * Class providing necessary support for processing YANG 1.1 Notification
@@ -65,13 +64,12 @@ public final class NotificationStatementRFC7950Support extends AbstractNotificat
     @Override
     void checkEffective(final Current<QName, NotificationStatement> stmt) {
         final QName argument = stmt.argument();
-        final StatementSourceReference ref = stmt.sourceReference();
-        SourceException.throwIf(StmtContextUtils.hasAncestorOfType(stmt, ILLEGAL_PARENTS), ref,
+        SourceException.throwIf(StmtContextUtils.hasAncestorOfType(stmt, ILLEGAL_PARENTS), stmt,
             "Notification %s is defined within an rpc, action, or another notification", argument);
         SourceException.throwIf(
-            !StmtContextUtils.hasAncestorOfTypeWithChildOfType(stmt, YangStmtMapping.LIST, YangStmtMapping.KEY), ref,
+            !StmtContextUtils.hasAncestorOfTypeWithChildOfType(stmt, YangStmtMapping.LIST, YangStmtMapping.KEY), stmt,
             "Notification %s is defined within a list that has no key statement", argument);
-        SourceException.throwIf(StmtContextUtils.hasParentOfType(stmt, YangStmtMapping.CASE), ref,
+        SourceException.throwIf(StmtContextUtils.hasParentOfType(stmt, YangStmtMapping.CASE), stmt,
             "Notification %s is defined within a case statement", argument);
     }
 }
index 316b574293010b9796ab34d0667d5bcc83af8b16..4928696f3506577d772952b6417d8064848fb904 100644 (file)
@@ -53,7 +53,7 @@ public final class OrderedByStatementSupport
         try {
             return Ordering.forArgument(value);
         } catch (IllegalArgumentException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Invalid ordered-by argument '%s'", value);
+            throw new SourceException(ctx, e, "Invalid ordered-by argument '%s'", value);
         }
     }
 
index e667de767eb4eda6119d8e63a877d72bcf8342c1..f69ed03096459a7300761b3cfaec62d06b5d3275 100644 (file)
@@ -69,7 +69,7 @@ abstract class AbstractOutputStatementSupport
         try {
             return new UndeclaredOutputEffectiveStatement(flags, substatements, stmt.wrapSchemaPath());
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 }
index 5e9fce833f17ccdb59ebe6e4498448a364284d85..ec4163f957bfeeb84a3f6b1b7fd0b929828d6022 100644 (file)
@@ -34,7 +34,7 @@ abstract class AbstractPatternStatementSupport
         try {
             Pattern.compile(pattern);
         } catch (final PatternSyntaxException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Pattern \"%s\" failed to compile", pattern);
+            throw new SourceException(ctx, e, "Pattern \"%s\" failed to compile", pattern);
         }
         return PatternExpression.of(value, pattern);
     }
index 03935e82d577033703cb7a859bf8505ab5e70213..82486588603bc017b3ccb3af0aca628188afa298 100644 (file)
@@ -38,7 +38,7 @@ public final class PositionStatementSupport
         try {
             return Uint32.valueOf(value).intern();
         } catch (IllegalArgumentException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Bit position value %s is not valid integer", value);
+            throw new SourceException(ctx, e, "Bit position value %s is not valid integer", value);
         }
     }
 
index 348913cccc2aea6e4fa36b503fe2ca482aa4d2e1..a40eaa2f7a95ec9bed6ebad3da58e6734b2fe2e9 100644 (file)
@@ -61,18 +61,18 @@ public final class RangeStatementSupport
                 max = parseDecimalConstraintValue(ctx, boundaries.next());
 
                 // if min larger than max then error
-                SourceException.throwIf(ArgumentUtils.compareNumbers(min, max) == 1, ctx.sourceReference(),
+                SourceException.throwIf(ArgumentUtils.compareNumbers(min, max) == 1, ctx,
                     "Range constraint %s has descending order of boundaries; should be ascending", singleRange);
-                SourceException.throwIf(boundaries.hasNext(), ctx.sourceReference(),
+                SourceException.throwIf(boundaries.hasNext(), ctx,
                     "Wrong number of boundaries in range constraint %s", singleRange);
             } else {
                 max = min;
             }
 
             // some of intervals overlapping
-            InferenceException.throwIf(ranges.size() > 1
-                && ArgumentUtils.compareNumbers(min, Iterables.getLast(ranges).upperBound()) != 1,
-                ctx.sourceReference(),  "Some of the value ranges in %s are not disjoint", rangeArgument);
+            InferenceException.throwIf(
+                ranges.size() > 1 && ArgumentUtils.compareNumbers(min, Iterables.getLast(ranges).upperBound()) != 1,
+                ctx, "Some of the value ranges in %s are not disjoint", rangeArgument);
             ranges.add(ValueRange.of(min, max));
         }
 
@@ -113,7 +113,7 @@ public final class RangeStatementSupport
         try {
             return value.indexOf('.') != -1 ? new BigDecimal(value) : new BigInteger(value);
         } catch (final NumberFormatException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Value %s is not a valid decimal number", value);
+            throw new SourceException(ctx, e, "Value %s is not a valid decimal number", value);
         }
     }
 }
\ No newline at end of file
index 89cceb540251255c15094639ba385ead1573d179..313b98ecf4fbf5519c85d10e182bfec27afe640b 100644 (file)
@@ -43,8 +43,7 @@ public final class RevisionStatementSupport
         try {
             return Revision.of(value);
         } catch (DateTimeParseException e) {
-            throw new SourceException(ctx.sourceReference(), e,
-                "Revision value %s is not in required format yyyy-MM-dd", value);
+            throw new SourceException(ctx, e, "Revision value %s is not in required format yyyy-MM-dd", value);
         }
     }
 
index 1b75579cce48eb032f7d8fc8af02968ced7258b3..a1bed54c2a8de0db200f64484d440d0dae2e06ac 100644 (file)
@@ -40,8 +40,7 @@ public final class RevisionDateStatementSupport
         try {
             return Revision.of(value);
         } catch (DateTimeParseException e) {
-            throw new SourceException(ctx.sourceReference(), e,
-                "Revision value %s is not in required format yyyy-MM-dd", value);
+            throw new SourceException(ctx, e, "Revision value %s is not in required format yyyy-MM-dd", value);
         }
     }
 
index 06909a6cd2d28f6a2e42df223b3f3a772a0f2d3d..197944dfd91163ca09d92066a35ae539962b1ad0 100644 (file)
@@ -88,7 +88,7 @@ abstract class AbstractRpcStatementSupport extends BaseSchemaTreeStatementSuppor
             return new RpcEffectiveStatementImpl(stmt.declared(), substatements, computeFlags(substatements),
                 stmt.wrapSchemaPath());
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
index c0c6f6f6410d84c7718171286b716830b0fab9d8..419a22234040d2250a54003a36b7038292943441 100644 (file)
@@ -63,7 +63,7 @@ public final class StatusStatementSupport
             case "obsolete":
                 return Status.OBSOLETE;
             default:
-                throw new SourceException(ctx.sourceReference(),
+                throw new SourceException(ctx,
                     "Invalid status '%s', must be one of 'current', 'deprecated' or 'obsolete'", value);
         }
     }
index 109bc33d79e03e702f510fc37ceebfcf7cf5ffc9..01f92681b9c346ff85e39391711d5d436791410b 100644 (file)
@@ -43,7 +43,7 @@ abstract class AbstractSubmoduleStatementSupport
         try {
             return UnqualifiedQName.of(value);
         } catch (IllegalArgumentException e) {
-            throw new SourceException(e.getMessage(), ctx.sourceReference(), e);
+            throw new SourceException(e.getMessage(), ctx, e);
         }
     }
 
@@ -63,17 +63,16 @@ abstract class AbstractSubmoduleStatementSupport
         final StmtContext<?, SubmoduleStatement, SubmoduleEffectiveStatement>
             possibleDuplicateSubmodule = stmt.getFromNamespace(SubmoduleNamespace.class, submoduleIdentifier);
         if (possibleDuplicateSubmodule != null && possibleDuplicateSubmodule != stmt) {
-            throw new SourceException(stmt.sourceReference(), "Submodule name collision: %s. At %s",
-                    stmt.rawArgument(), possibleDuplicateSubmodule.sourceReference());
+            throw new SourceException(stmt, "Submodule name collision: %s. At %s", stmt.rawArgument(),
+                possibleDuplicateSubmodule.sourceReference());
         }
 
         stmt.addContext(SubmoduleNamespace.class, submoduleIdentifier, stmt);
 
         final String belongsToModuleName = firstAttributeOf(stmt.declaredSubstatements(), BelongsToStatement.class);
-        final StmtContext<?, ?, ?> prefixSubStmtCtx = findFirstDeclaredSubstatement(stmt, 0,
-                BelongsToStatement.class, PrefixStatement.class);
-        SourceException.throwIfNull(prefixSubStmtCtx, stmt.sourceReference(),
-                "Prefix of belongsTo statement is missing in submodule [%s]", stmt.rawArgument());
+        final StmtContext<?, ?, ?> prefixSubStmtCtx = SourceException.throwIfNull(
+            findFirstDeclaredSubstatement(stmt, 0, BelongsToStatement.class, PrefixStatement.class), stmt,
+            "Prefix of belongsTo statement is missing in submodule [%s]", stmt.rawArgument());
 
         final String prefix = prefixSubStmtCtx.rawArgument();
         stmt.addToNs(BelongsToPrefixToModuleName.class, prefix, belongsToModuleName);
@@ -100,11 +99,11 @@ abstract class AbstractSubmoduleStatementSupport
         try {
             return new SubmoduleEffectiveStatementImpl(stmt, substatements);
         } catch (SubstatementIndexingException e) {
-            throw new SourceException(e.getMessage(), stmt.sourceReference(), e);
+            throw new SourceException(e.getMessage(), stmt, e);
         }
     }
 
     private static SourceException noBelongsTo(final CommonStmtCtx stmt) {
-        return new SourceException("No belongs-to declared in submodule", stmt.sourceReference());
+        return new SourceException("No belongs-to declared in submodule", stmt);
     }
 }
index fb8fc62443be4699c96bcbb63dd705054c7b3224..6141b8fcf7a300598cf66ad27a70fe1ba3f0c778 100644 (file)
@@ -150,14 +150,13 @@ final class SubmoduleEffectiveStatementImpl
         return substatements.stream()
             .filter(BelongsToEffectiveStatement.class::isInstance)
             .map(BelongsToEffectiveStatement.class::cast)
-            .findAny().orElseThrow(() -> new SourceException(stmt.sourceReference(),
+            .findAny().orElseThrow(() -> new SourceException(stmt,
                 "Unable to find belongs-to statement in submodule %s.", stmt.rawArgument()));
     }
 
     private static @NonNull String findSubmodulePrefix(final CommonStmtCtx stmt,
             final ImmutableList<? extends EffectiveStatement<?, ?>> substatements) {
-        final String name = stmt.getRawArgument();
-        final BelongsToEffectiveStatement belongsTo = findBelongsTo(stmt, substatements);
-        return findPrefix(stmt.sourceReference(), belongsTo.effectiveSubstatements(), "submodule", name);
+        return findPrefix(stmt, findBelongsTo(stmt, substatements).effectiveSubstatements(), "submodule",
+            stmt.getRawArgument());
     }
 }
index cd4456e04b08af9defc58880c50b4275f5fbd83c..c6c7ddc36d4d0678e0215a77b7ad415a39e78e85 100644 (file)
@@ -53,9 +53,9 @@ abstract class AbstractIdentityRefSpecificationSupport
         for (StmtContext<QName, BaseStatement, ?> baseStmt : baseStatements) {
             final QName baseIdentity = baseStmt.getArgument();
             final StmtContext<?, ?, ?> stmtCtx = stmt.getFromNamespace(IdentityNamespace.class, baseIdentity);
-            InferenceException.throwIfNull(stmtCtx, stmt.sourceReference(),
+            InferenceException.throwIfNull(stmtCtx, stmt,
                 "Referenced base identity '%s' doesn't exist in given scope (module, imported modules, submodules)",
-                    baseIdentity.getLocalName());
+                baseIdentity.getLocalName());
         }
     }
 
@@ -100,6 +100,6 @@ abstract class AbstractIdentityRefSpecificationSupport
          *     statement, MUST be present at least once if the type is
          *     "identityref".
          */
-        return new SourceException("At least one base statement has to be present", stmt.sourceReference());
+        return new SourceException("At least one base statement has to be present", stmt);
     }
 }
\ No newline at end of file
index 1ab6a1c0c215dbcba38baee08e975087ce822fde..11fd4f5424555650656121f203ce86fb0e1de5a5 100644 (file)
@@ -72,6 +72,6 @@ abstract class AbstractLeafrefSpecificationSupport
          *     When the type is "union", the "type" statement (Section 7.4) MUST be
          *     present.
          */
-        return new SourceException("A path statement has to be present", stmt.sourceReference());
+        return new SourceException("A path statement has to be present", stmt);
     }
 }
\ No newline at end of file
index 636473137a51db9f3127f6778ba4fdc065a6cae4..39103dafd0e9ef198b92eedb45d8b0149dae2650 100644 (file)
@@ -190,8 +190,7 @@ abstract class AbstractTypeStatementSupport
 
             @Override
             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
-                InferenceException.throwIf(failed.contains(typePrereq), stmt.sourceReference(),
-                    "Type [%s] was not found.", typeQName);
+                InferenceException.throwIf(failed.contains(typePrereq), stmt, "Type [%s] was not found.", typeQName);
             }
         });
     }
@@ -342,8 +341,7 @@ abstract class AbstractTypeStatementSupport
             default:
                 final QName qname = StmtContextUtils.parseNodeIdentifier(ctx.caerbannog(), argument);
                 final StmtContext<?, TypedefStatement, TypedefEffectiveStatement> typedef = SourceException.throwIfNull(
-                    ctx.getFromNamespace(TypeNamespace.class, qname), ctx.sourceReference(),
-                    "Type '%s' not found", qname);
+                    ctx.getFromNamespace(TypeNamespace.class, qname), ctx, "Type '%s' not found", qname);
                 return typedef.buildEffective().asTypeEffectiveStatement();
         }
     }
@@ -361,10 +359,9 @@ abstract class AbstractTypeStatementSupport
                 try {
                     builder.setLengthConstraint(length, length.argument());
                 } catch (IllegalStateException e) {
-                    throw new SourceException(ctx.sourceReference(), e, "Multiple length constraints encountered");
+                    throw new SourceException(ctx, e, "Multiple length constraints encountered");
                 } catch (InvalidLengthConstraintException e) {
-                    throw new SourceException(ctx.sourceReference(), e, "Invalid length constraint %s",
-                        length.argument());
+                    throw new SourceException(ctx, e, "Invalid length constraint %s", length.argument());
                 }
             }
         }
@@ -409,7 +406,7 @@ abstract class AbstractTypeStatementSupport
             }
             if (stmt instanceof FractionDigitsEffectiveStatement) {
                 final Integer digits = ((FractionDigitsEffectiveStatement)stmt).argument();
-                SourceException.throwIf(baseType.getFractionDigits() != digits, ctx.sourceReference(),
+                SourceException.throwIf(baseType.getFractionDigits() != digits, ctx,
                     "Cannot override fraction-digits from base type %s to %s", baseType, digits);
             }
         }
@@ -477,7 +474,7 @@ abstract class AbstractTypeStatementSupport
         try {
             return new TypeEffectiveStatementImpl<>(declared, substatements, builder);
         } catch (InvalidRangeConstraintException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Invalid range constraint: %s", e.getOffendingRanges());
+            throw new SourceException(ctx, e, "Invalid range constraint: %s", e.getOffendingRanges());
         }
     }
 
@@ -508,10 +505,9 @@ abstract class AbstractTypeStatementSupport
                 try {
                     builder.setLengthConstraint(length, length.argument());
                 } catch (IllegalStateException e) {
-                    throw new SourceException(ctx.sourceReference(), e, "Multiple length constraints encountered");
+                    throw new SourceException(ctx, e, "Multiple length constraints encountered");
                 } catch (InvalidLengthConstraintException e) {
-                    throw new SourceException(ctx.sourceReference(), e, "Invalid length constraint %s",
-                        length.argument());
+                    throw new SourceException(ctx, e, "Invalid length constraint %s", length.argument());
                 }
             }
             if (stmt instanceof PatternEffectiveStatement) {
index 61a004bdb38a3c09e9c9d241f774106468ea5d31..af37b6b3f71f142e6cc8c810020ca4c016c80910 100644 (file)
@@ -75,7 +75,7 @@ final class BitsSpecificationSupport
                 final Uint32 effectivePos;
                 if (declaredPosition.isEmpty()) {
                     if (highestPosition != null) {
-                        SourceException.throwIf(Uint32.MAX_VALUE.equals(highestPosition), stmt.sourceReference(),
+                        SourceException.throwIf(Uint32.MAX_VALUE.equals(highestPosition), stmt,
                             "Bit %s must have a position statement", bitSubStmt);
                         effectivePos = Uint32.fromIntBits(highestPosition.intValue() + 1);
                     } else {
@@ -104,6 +104,6 @@ final class BitsSpecificationSupport
          *     The "bit" statement, which is a substatement to the "type" statement,
          *     MUST be present if the type is "bits".
          */
-        return new SourceException("At least one bit statement has to be present", stmt.sourceReference());
+        return new SourceException("At least one bit statement has to be present", stmt);
     }
 }
index 3713c4583c395eae407d729ddb277c73b025392a..6c03125be1093bc42cfb3eedc4b03c1662d4d4ec 100644 (file)
@@ -85,6 +85,6 @@ final class Decimal64SpecificationSupport extends BaseStatementSupport<String, D
          *     The "fraction-digits" statement, which is a substatement to the
          *     "type" statement, MUST be present if the type is "decimal64".
          */
-        return new SourceException("At least one fraction-digits statement has to be present", stmt.sourceReference());
+        return new SourceException("At least one fraction-digits statement has to be present", stmt);
     }
 }
\ No newline at end of file
index 81f41987f41f61ee83077ef33064bcb86938b099..ecf079e7cbb046fca6f92a36ff2b634a64180c89 100644 (file)
@@ -74,8 +74,8 @@ final class EnumSpecificationSupport
                 final int effectiveValue;
                 if (declaredValue.isEmpty()) {
                     if (highestValue != null) {
-                        SourceException.throwIf(highestValue == 2147483647, stmt.sourceReference(),
-                                "Enum '%s' must have a value statement", enumSubStmt);
+                        SourceException.throwIf(highestValue == 2147483647, stmt,
+                            "Enum '%s' must have a value statement", enumSubStmt);
                         effectiveValue = highestValue + 1;
                     } else {
                         effectiveValue = 0;
@@ -103,7 +103,7 @@ final class EnumSpecificationSupport
          *     The "enum" statement, which is a substatement to the "type"
          *     statement, MUST be present if the type is "enumeration".
          */
-        return new SourceException("At least one enum statement has to be present", stmt.sourceReference());
+        return new SourceException("At least one enum statement has to be present", stmt);
     }
 
 }
\ No newline at end of file
index eca5f7aa6ac3530159733f178afc4831435e45bc..58b4cac396c4d7256d68e4073014ac61d0bc5542 100644 (file)
@@ -29,14 +29,13 @@ public final class TypeStatementRFC6020Support extends AbstractTypeStatementSupp
 
     @Override
     Bit addRestrictedBit(final EffectiveStmtCtx stmt, final BitsTypeDefinition base, final BitEffectiveStatement bit) {
-        throw new SourceException("Restricted bits type is not allowed in YANG version 1", stmt.sourceReference());
+        throw new SourceException("Restricted bits type is not allowed in YANG version 1", stmt);
     }
 
 
     @Override
     EnumPair addRestrictedEnum(final EffectiveStmtCtx stmt, final EnumTypeDefinition base,
             final EnumEffectiveStatement enumStmt) {
-        throw new SourceException("Restricted enumeration type is not allowed in YANG version 1",
-            stmt.sourceReference());
+        throw new SourceException("Restricted enumeration type is not allowed in YANG version 1", stmt);
     }
 }
\ No newline at end of file
index 5f78473409beba91acc998cb7b9343dff70449fb..5374e93a683d3d91e6f8241b2dc5b432f9766ed0 100644 (file)
@@ -89,7 +89,7 @@ public final class TypeStatementRFC7950Support extends AbstractTypeStatementSupp
             }
         }
 
-        throw new SourceException(stmt.sourceReference(), "Bit '%s' is not a subset of its base bits type %s.", bitName,
+        throw new SourceException(stmt, "Bit '%s' is not a subset of its base bits type %s.", bitName,
             baseType.getQName());
     }
 
@@ -102,8 +102,8 @@ public final class TypeStatementRFC7950Support extends AbstractTypeStatementSupp
             }
         }
 
-        throw new SourceException(ctx.sourceReference(), "Enum '%s' is not a subset of its base enumeration type %s.",
-            enumName, baseType.getQName());
+        throw new SourceException(ctx, "Enum '%s' is not a subset of its base enumeration type %s.", enumName,
+            baseType.getQName());
     }
 
 }
index 2fe4f3c281a6258fa5a3c1478a7721023737e502..b9ea4b28fd79afe9abb524b6b4e43c1e7e37b405 100644 (file)
@@ -81,6 +81,6 @@ final class UnionSpecificationSupport
          *     When the type is "union", the "type" statement (Section 7.4) MUST be
          *     present.
          */
-        return new SourceException("At least one type statement has to be present", stmt.sourceReference());
+        return new SourceException("At least one type statement has to be present", stmt);
     }
 }
index 64c0c50d4ebaab9fa7e9074126d7f8fc11e31caa..2f534f9b38f4d8aaea61d3d701861d575bf266af 100644 (file)
@@ -100,8 +100,7 @@ public final class TypedefStatementSupport extends
             TypeEffectiveStatement.class);
         final String dflt = findFirstArgument(substatements, DefaultEffectiveStatement.class, null);
         SourceException.throwIf(
-            EffectiveStmtUtils.hasDefaultValueMarkedWithIfFeature(stmt.yangVersion(), typeEffectiveStmt, dflt),
-            stmt.sourceReference(),
+            EffectiveStmtUtils.hasDefaultValueMarkedWithIfFeature(stmt.yangVersion(), typeEffectiveStmt, dflt), stmt,
             "Typedef '%s' has default value '%s' marked with an if-feature statement.", stmt.argument(), dflt);
 
         return new TypedefEffectiveStatementImpl(declared, stmt.wrapSchemaPath(), computeFlags(substatements),
@@ -112,7 +111,7 @@ public final class TypedefStatementSupport extends
         final QName arg = stmt.getArgument();
         final StmtContext<?, ?, ?> existing = parent.getFromNamespace(TypeNamespace.class, arg);
         // RFC7950 sections 5.5 and 6.2.1: identifiers must not be shadowed
-        SourceException.throwIf(existing != null, stmt.sourceReference(), "Duplicate name for typedef %s", arg);
+        SourceException.throwIf(existing != null, stmt, "Duplicate name for typedef %s", arg);
     }
 
     private static void checkDeclared(final StmtContext<QName, TypedefStatement, ?> ctx) {
index 4a190b8f9e9648156ee3c0b6532bd4f621792689..ea9c79f2206782dc3a3e19c09535afabd7cf85bd 100644 (file)
@@ -55,7 +55,7 @@ public final class UniqueStatementSupport
     @Override
     public ImmutableSet<Descendant> parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
         final ImmutableSet<Descendant> uniqueConstraints = parseUniqueConstraintArgument(ctx, value);
-        SourceException.throwIf(uniqueConstraints.isEmpty(), ctx.sourceReference(),
+        SourceException.throwIf(uniqueConstraints.isEmpty(), ctx,
             "Invalid argument value '%s' of unique statement. The value must contains at least one descendant schema "
                 + "node identifier.", value);
         return uniqueConstraints;
@@ -93,7 +93,7 @@ public final class UniqueStatementSupport
         final Set<Descendant> uniqueConstraintNodes = new HashSet<>();
         for (final String uniqueArgToken : SEP_SPLITTER.split(nocrlf)) {
             final SchemaNodeIdentifier nodeIdentifier = ArgumentUtils.nodeIdentifierFromPath(ctx, uniqueArgToken);
-            SourceException.throwIf(nodeIdentifier instanceof Absolute, ctx.sourceReference(),
+            SourceException.throwIf(nodeIdentifier instanceof Absolute, ctx,
                 "Unique statement argument '%s' contains schema node identifier '%s' which is not in the descendant "
                     + "node identifier form.", argumentValue, uniqueArgToken);
             uniqueConstraintNodes.add((Descendant) nodeIdentifier);
index 351be56bbba9a64d5d984be6dfbe4044b047f3e9..c2a6fbc052c9a87176a27f57007a1ea5e1328dc4 100644 (file)
@@ -117,9 +117,9 @@ public final class UsesStatementSupport
 
             @Override
             public void prerequisiteFailed(final Collection<? extends Prerequisite<?>> failed) {
-                InferenceException.throwIf(failed.contains(sourceGroupingPre), usesNode.sourceReference(),
+                InferenceException.throwIf(failed.contains(sourceGroupingPre), usesNode,
                     "Grouping '%s' was not resolved.", groupingName);
-                throw new InferenceException("Unknown error occurred.", usesNode.sourceReference());
+                throw new InferenceException("Unknown error occurred.", usesNode);
             }
         });
     }
@@ -293,13 +293,13 @@ public final class UsesStatementSupport
 
     private static void performRefine(final Mutable<?, ?, ?> subStmtCtx, final StmtContext<?, ?, ?> usesParentCtx) {
         final Object refineArgument = subStmtCtx.argument();
-        InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier), subStmtCtx.sourceReference(),
+        InferenceException.throwIf(!(refineArgument instanceof SchemaNodeIdentifier), subStmtCtx,
             "Invalid refine argument %s. It must be instance of SchemaNodeIdentifier.", refineArgument);
 
         final Optional<StmtContext<?, ?, ?>> optRefineTargetCtx = SchemaTreeNamespace.findNode(
             usesParentCtx, (SchemaNodeIdentifier) refineArgument);
-        InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx.sourceReference(),
-            "Refine target node %s not found.", refineArgument);
+        InferenceException.throwIf(!optRefineTargetCtx.isPresent(), subStmtCtx, "Refine target node %s not found.",
+            refineArgument);
 
         final StmtContext<?, ?, ?> refineTargetNodeCtx = optRefineTargetCtx.get();
         if (StmtContextUtils.isUnknownStatement(refineTargetNodeCtx)) {
@@ -331,7 +331,7 @@ public final class UsesStatementSupport
         final StatementDefinition refineSubstatementDef = refineSubstatementCtx.publicDefinition();
 
         SourceException.throwIf(!isSupportedRefineTarget(refineSubstatementCtx, refineTargetNodeCtx),
-                refineSubstatementCtx.sourceReference(),
+                refineSubstatementCtx,
                 "Error in module '%s' in the refine of uses '%s': can not perform refine of '%s' for the target '%s'.",
                 refineSubstatementCtx.getRoot().rawArgument(), refineSubstatementCtx.coerceParentContext().argument(),
                 refineSubstatementCtx.publicDefinition(), refineTargetNodeCtx.publicDefinition());
index b3d360634cb920bc7d0936f18a144fefb64fcab3..bd961d4a70396dd1c95da40c8061a219c29b5b98 100644 (file)
@@ -38,7 +38,7 @@ public final class ValueStatementSupport
         try {
             return Integer.valueOf(value);
         } catch (NumberFormatException e) {
-            throw new SourceException(ctx.sourceReference(), e,
+            throw new SourceException(ctx, e,
                 "%s is not valid value statement integer argument in a range of -2147483648..2147483647", value);
         }
     }
index c7676d4e4dfa206fc8e03746f8848b48cf3750de..7904eb4415f03818aa7e3b00aaf6d941685f4529 100644 (file)
@@ -48,8 +48,7 @@ public final class YangVersionStatementSupport
 
     @Override
     public YangVersion parseArgumentValue(final StmtContext<?, ?, ?> ctx, final String value) {
-        return SourceException.unwrap(YangVersion.parse(value), ctx.sourceReference(),  "Unsupported YANG version %s",
-            value);
+        return SourceException.unwrap(YangVersion.parse(value), ctx,  "Unsupported YANG version %s", value);
     }
 
     @Override
index 28a5dfc7880dfaa8e8182b43533bec1290ab5598..ff023709454a3b0d2a53d53cdb0bd125c9638232 100644 (file)
@@ -92,7 +92,7 @@ public final class SchemaTreeNamespace<D extends DeclaredStatement<QName>,
             SchemaTreeNamespace.class, key, value);
 
         if (prev != null) {
-            throw new SourceException(value.sourceReference(),
+            throw new SourceException(value,
                 "Error in module '%s': cannot add '%s'. Node name collision: '%s' already declared at %s",
                 value.getRoot().rawArgument(), key, prev.argument(), prev.sourceReference());
         }
index 35f49d0ee8b68b2e29dd510c5a0a4639c5aa44e7..091eb5b1f93f231c6601851cb1491fa48325e93a 100644 (file)
@@ -17,20 +17,33 @@ import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReferenc
 public class InferenceException extends SourceException {
     private static final long serialVersionUID = 1L;
 
+    public InferenceException(final @NonNull String message, final @NonNull StatementSourceReference source) {
+        super(message, source);
+    }
+
     public InferenceException(final @NonNull String message, final @NonNull StatementSourceReference source,
             final Throwable cause) {
         super(message, source, cause);
     }
 
-    public InferenceException(final @NonNull String message, final @NonNull StatementSourceReference source) {
-        super(message, source);
-    }
-
     public InferenceException(final @NonNull StatementSourceReference source, final @NonNull String format,
             final Object... args) {
         this(String.format(format, args), source);
     }
 
+    public InferenceException(final @NonNull String message, final @NonNull CommonStmtCtx stmt) {
+        super(message, stmt);
+    }
+
+    public InferenceException(final @NonNull String message, final @NonNull CommonStmtCtx stmt, final Throwable cause) {
+        super(message, stmt, cause);
+    }
+
+    public InferenceException(final @NonNull CommonStmtCtx stmt, final @NonNull String format,
+            final Object... args) {
+        this(stmt.sourceReference(), format, args);
+    }
+
     /**
      * Throw an instance of this exception if an expression evaluates to true. If the expression evaluates to false,
      * this method does nothing.
@@ -47,4 +60,21 @@ public class InferenceException extends SourceException {
             throw new InferenceException(source, format, args);
         }
     }
+
+    /**
+     * Throw an instance of this exception if an expression evaluates to true. If the expression evaluates to false,
+     * this method does nothing.
+     *
+     * @param expression Expression to be evaluated
+     * @param stmt Statement context
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     * @throws InferenceException if the expression evaluates to true.
+     */
+    public static void throwIf(final boolean expression, final @NonNull CommonStmtCtx stmt,
+            final @NonNull String format, final Object... args) {
+        if (expression) {
+            throw new InferenceException(stmt.sourceReference(), format, args);
+        }
+    }
 }
index 9c947166fd9ede351b7f47bcb8bc987b6897f58b..faf48539dc6c6762ba5d2c463e44042537b0f4b5 100644 (file)
@@ -26,6 +26,11 @@ public class InvalidSubstatementException extends SourceException {
         super(message, source, cause);
     }
 
+    public InvalidSubstatementException(final @NonNull CommonStmtCtx stmt, final @NonNull String format,
+            final Object... args) {
+        this(stmt.sourceReference(), format, args);
+    }
+
     public InvalidSubstatementException(final @NonNull StatementSourceReference source, final @NonNull String format,
             final Object... args) {
         this(String.format(format, args), source);
index 4919fb72be837104334af1650626f3c69ae566d8..f00329e76793823ebd4a8489c0440a748bd410ce 100644 (file)
@@ -26,6 +26,11 @@ public class MissingSubstatementException extends SourceException {
         super(message, source, cause);
     }
 
+    public MissingSubstatementException(final @NonNull CommonStmtCtx stmt, final @NonNull String format,
+            final Object... args) {
+        this(stmt.sourceReference(), format, args);
+    }
+
     public MissingSubstatementException(final @NonNull StatementSourceReference source, final @NonNull String format,
             final Object... args) {
         this(String.format(format, args), source);
index ca24ac8a0c2e35538940e490985274dfbc3e988a..3a0a1c8481b97d0247a17621011a057ed2efdead 100644 (file)
@@ -453,7 +453,7 @@ public final class StmtContextUtils {
         leafStmtCtx.allSubstatements().forEach(leafSubstmtCtx -> {
             final StatementDefinition statementDef = leafSubstmtCtx.publicDefinition();
             SourceException.throwIf(YangStmtMapping.IF_FEATURE.equals(statementDef)
-                    || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx.sourceReference(),
+                    || YangStmtMapping.WHEN.equals(statementDef), leafStmtCtx,
                     "%s statement is not allowed in %s leaf statement which is specified as a list key.",
                     statementDef.getStatementName(), leafStmtCtx.argument());
         });
@@ -489,7 +489,7 @@ public final class StmtContextUtils {
                 }
         }
 
-        return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx.sourceReference(),
+        return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx,
             "Cannot resolve QNameModule for '%s'", value), localName);
     }
 
@@ -503,14 +503,14 @@ public final class StmtContextUtils {
      * @throws SourceException if the string is not a valid YANG identifier
      */
     public static QName parseIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
-        SourceException.throwIf(str.isEmpty(), ctx.sourceReference(), "Identifier may not be an empty string");
+        SourceException.throwIf(str.isEmpty(), ctx, "Identifier may not be an empty string");
         return internedQName(ctx, str);
     }
 
     public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String prefix,
             final String localName) {
         return internedQName(ctx,
-            InferenceException.throwIfNull(getModuleQNameByPrefix(ctx, prefix), ctx.sourceReference(),
+            InferenceException.throwIfNull(getModuleQNameByPrefix(ctx, prefix), ctx,
                 "Cannot resolve QNameModule for '%s'", prefix),
             localName);
     }
@@ -525,7 +525,7 @@ public final class StmtContextUtils {
      * @throws SourceException if the string is not a valid YANG node identifier
      */
     public static QName parseNodeIdentifier(final StmtContext<?, ?, ?> ctx, final String str) {
-        SourceException.throwIf(str.isEmpty(), ctx.sourceReference(), "Node identifier may not be an empty string");
+        SourceException.throwIf(str.isEmpty(), ctx, "Node identifier may not be an empty string");
 
         final int colon = str.indexOf(':');
         if (colon == -1) {
@@ -533,9 +533,9 @@ public final class StmtContextUtils {
         }
 
         final String prefix = str.substring(0, colon);
-        SourceException.throwIf(prefix.isEmpty(), ctx.sourceReference(), "String '%s' has an empty prefix", str);
+        SourceException.throwIf(prefix.isEmpty(), ctx, "String '%s' has an empty prefix", str);
         final String localName = str.substring(colon + 1);
-        SourceException.throwIf(localName.isEmpty(), ctx.sourceReference(), "String '%s' has an empty identifier", str);
+        SourceException.throwIf(localName.isEmpty(), ctx, "String '%s' has an empty identifier", str);
 
         return parseNodeIdentifier(ctx, prefix, localName);
     }
@@ -550,7 +550,7 @@ public final class StmtContextUtils {
         try {
             template = QName.create(module, localName);
         } catch (IllegalArgumentException e) {
-            throw new SourceException(ctx.sourceReference(), e, "Invalid identifier '%s'", localName);
+            throw new SourceException(ctx, e, "Invalid identifier '%s'", localName);
         }
         return template.intern();
     }
index d80c428c3790d907b20f5f8da3427e0e1ef03c8e..8992f5f0b2ab89510bf745e6282116cb98e8a95f 100644 (file)
@@ -131,9 +131,8 @@ public final class SubstatementValidator {
             if (cardinality == null) {
                 if (ctx.getFromNamespace(ExtensionNamespace.class, key.getStatementName()) == null) {
                     final StmtContext<?, ?, ?> root = ctx.getRoot();
-                    throw new InvalidSubstatementException(ctx.sourceReference(),
-                        "%s is not valid for %s. Error in module %s (%s)", key, currentStatement, root.rawArgument(),
-                        ctx.getFromNamespace(ModuleCtxToModuleQName.class, root));
+                    throw new InvalidSubstatementException(ctx, "%s is not valid for %s. Error in module %s (%s)", key,
+                        currentStatement, root.rawArgument(), ctx.getFromNamespace(ModuleCtxToModuleQName.class, root));
                 }
 
                 continue;
@@ -142,7 +141,7 @@ public final class SubstatementValidator {
             if (cardinality.getMin() > 0) {
                 if (cardinality.getMin() > value) {
                     final StmtContext<?, ?, ?> root = ctx.getRoot();
-                    throw new InvalidSubstatementException(ctx.sourceReference(),
+                    throw new InvalidSubstatementException(ctx,
                         "Minimal count of %s for %s is %s, detected %s. Error in module %s (%s)", key, currentStatement,
                         cardinality.getMin(), value, root.rawArgument(),
                         ctx.getFromNamespace(ModuleCtxToModuleQName.class, root));
@@ -153,7 +152,7 @@ public final class SubstatementValidator {
             }
             if (cardinality.getMax() < value) {
                 final StmtContext<?, ?, ?> root = ctx.getRoot();
-                throw new InvalidSubstatementException(ctx.sourceReference(),
+                throw new InvalidSubstatementException(ctx,
                     "Maximal count of %s for %s is %s, detected %s. Error in module %s (%s)", key, currentStatement,
                     cardinality.getMax(), value, root.rawArgument(),
                     ctx.getFromNamespace(ModuleCtxToModuleQName.class, root));
@@ -165,7 +164,7 @@ public final class SubstatementValidator {
             final Entry<StatementDefinition, Cardinality> e = missingMandatory.entrySet().iterator().next();
             final StmtContext<?, ?, ?> root = ctx.getRoot();
 
-            throw new MissingSubstatementException(ctx.sourceReference(),
+            throw new MissingSubstatementException(ctx,
                 "%s is missing %s. Minimal count is %s. Error in module %s (%s)", currentStatement, e.getKey(),
                 e.getValue().getMin(), root.rawArgument(), ctx.getFromNamespace(ModuleCtxToModuleQName.class, root));
         }
index 4a277d30e04eb58da81b56090cab9abc4a28572a..a0ef7796ef9f260c9137760fc887ab3d76ab4830 100644 (file)
@@ -13,6 +13,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.util.Optional;
 import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.yangtools.yang.parser.spi.meta.CommonStmtCtx;
 
 /**
  * Thrown to indicate error in YANG model source.
@@ -76,6 +77,56 @@ public class SourceException extends RuntimeException {
         this(String.format(format, args), source, cause);
     }
 
+    /**
+     * Create a new instance with the specified message and source. The message will be appended with the source
+     * reference.
+     *
+     * @param message Context message
+     * @param stmt Statement context, not retained
+     */
+    public SourceException(final @NonNull String message, final @NonNull CommonStmtCtx stmt) {
+        this(message, stmt.sourceReference());
+    }
+
+    /**
+     * Create a new instance with the specified message and source. The message will be appended with
+     * the source reference.
+     *
+     * @param message Context message
+     * @param stmt Statement context, not retained
+     * @param cause Underlying cause of this exception
+     */
+    public SourceException(final @NonNull String message, final @NonNull CommonStmtCtx stmt, final Throwable cause) {
+        this(message, stmt.sourceReference(), cause);
+    }
+
+    /**
+     * Create a new instance with the specified source and a formatted message. The message will be appended with
+     * the source reference.
+     *
+     * @param stmt Statement context, not retained
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     */
+    public SourceException(final @NonNull CommonStmtCtx stmt, final @NonNull String format, final Object... args) {
+        this(stmt.sourceReference(), format, args);
+    }
+
+
+    /**
+     * Create a new instance with the specified source and a formatted message. The message will be appended with
+     * the source reference.
+     *
+     * @param stmt Statement context, not retained
+     * @param cause Underlying cause of this exception
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     */
+    public SourceException(final @NonNull CommonStmtCtx stmt, final Throwable cause,
+            final @NonNull String format, final Object... args) {
+        this(stmt.sourceReference(), cause, format, args);
+    }
+
     /**
      * Return the reference to the source which caused this exception.
      *
@@ -85,6 +136,23 @@ public class SourceException extends RuntimeException {
         return sourceRef;
     }
 
+    /**
+     * Throw an instance of this exception if an expression evaluates to true. If the expression evaluates to false,
+     * this method does nothing.
+     *
+     * @param expression Expression to be evaluated
+     * @param stmt Statement context, not retained
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     * @throws SourceException if the expression evaluates to true.
+     */
+    public static void throwIf(final boolean expression, final @NonNull CommonStmtCtx stmt,
+            final @NonNull String format, final Object... args) {
+        if (expression) {
+            throw new SourceException(stmt, format, args);
+        }
+    }
+
     /**
      * Throw an instance of this exception if an expression evaluates to true. If the expression evaluates to false,
      * this method does nothing.
@@ -121,6 +189,25 @@ public class SourceException extends RuntimeException {
         return obj;
     }
 
+    /**
+     * Throw an instance of this exception if an object is null. If the object is non-null, it will
+     * be returned as the result of this method.
+     *
+     * @param obj Object reference to be checked
+     * @param stmt Statement context, not retained
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     * @return Object if it is not null
+     * @throws SourceException if object is null
+     */
+    public static <T> @NonNull T throwIfNull(final @Nullable T obj, final @NonNull CommonStmtCtx stmt,
+            final @NonNull String format, final Object... args) {
+        if (obj == null) {
+            throw new SourceException(stmt.sourceReference(), format, args);
+        }
+        return obj;
+    }
+
     /**
      * Throw an instance of this exception if an optional is not present. If it is present, this method will return
      * the unwrapped value.
@@ -138,6 +225,23 @@ public class SourceException extends RuntimeException {
         return opt.get();
     }
 
+    /**
+     * Throw an instance of this exception if an optional is not present. If it is present, this method will return
+     * the unwrapped value.
+     *
+     * @param opt Optional to be checked
+     * @param stmt Statement context, not retained
+     * @param format Format string, according to {@link String#format(String, Object...)}.
+     * @param args Format string arguments, according to {@link String#format(String, Object...)}
+     * @return Object unwrapped from the opt optional
+     * @throws SourceException if the optional is not present
+     */
+    public static <T> @NonNull T unwrap(final Optional<T> opt, final @NonNull CommonStmtCtx stmt,
+            final @NonNull String format, final Object... args) {
+        throwIf(opt.isEmpty(), stmt, format, args);
+        return opt.get();
+    }
+
     private static String createMessage(final @NonNull String message, final @NonNull StatementSourceReference source) {
         return requireNonNull(message) + " [at " + requireNonNull(source) + ']';
     }