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;
}
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);
}
}
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(),
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
@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
@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);
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.
}
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);
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>,
.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
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);
}
}
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;
}
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);
}
}
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());
}
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) {
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);
}
}
}
@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
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;
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);
}
}
}
}
- 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,
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());
}
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());
}
@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());
}
});
@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());
}
}
});
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);
}
}
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);
}
}
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;
}
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);
}
}
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);
}
}
}
@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);
}
@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);
}
});
}
&& 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());
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",
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());
}
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);
}
}
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;
}
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);
}
}
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
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);
}
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());
}
});
}
}
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
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);
@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);
}
});
}
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);
}
}
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);
@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);
}
}
});
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);
@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));
}
}
});
@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());
}
});
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);
}
}
}
// 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;
}
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();
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();
// 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
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));
}
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
}
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);
}
: 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);
}
}
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);
}
}
@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);
}
try {
return UnqualifiedQName.of(value);
} catch (IllegalArgumentException e) {
- throw new SourceException(e.getMessage(), ctx.sourceReference(), e);
+ throw new SourceException(e.getMessage(), ctx, e);
}
}
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);
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();
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);
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);
}
}
}
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(
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);
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);
}
}
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);
}
}
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
@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);
}
}
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);
}
}
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);
}
}
}
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);
}
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);
}
}
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));
}
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
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);
}
}
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);
}
}
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);
}
}
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);
}
}
try {
return UnqualifiedQName.of(value);
} catch (IllegalArgumentException e) {
- throw new SourceException(e.getMessage(), ctx.sourceReference(), e);
+ throw new SourceException(e.getMessage(), ctx, e);
}
}
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);
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);
}
}
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());
}
}
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());
}
}
* 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
* 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
@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);
}
});
}
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();
}
}
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 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);
}
}
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());
}
}
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) {
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 {
* 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);
}
}
* 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
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;
* 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
@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
}
}
- 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());
}
}
}
- 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());
}
}
* 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);
}
}
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),
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) {
@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;
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);
@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);
}
});
}
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)) {
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());
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);
}
}
@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
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());
}
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.
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);
+ }
+ }
}
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);
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);
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());
});
}
}
- return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx.sourceReference(),
+ return internedQName(ctx, InferenceException.throwIfNull(qnameModule, ctx,
"Cannot resolve QNameModule for '%s'", value), localName);
}
* @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);
}
* @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) {
}
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);
}
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();
}
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;
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));
}
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));
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));
}
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.
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.
*
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.
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.
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) + ']';
}