Bug 5200: Yang parser doesn't fill error-app-tag and error-message in constraints
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / rfc6020 / TypeUtils.java
index f2fb51e6443c65475e9ad5188ec769f7edcf3551..11f460ae540a802d3b9338c026aaf3b80a510823 100644 (file)
@@ -10,39 +10,25 @@ package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Splitter;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableMap.Builder;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 import java.math.BigDecimal;
 import java.math.BigInteger;
 import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
 import java.util.Iterator;
 import java.util.List;
-import java.util.Map;
 import java.util.Set;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
-import org.opendaylight.yangtools.yang.model.api.stmt.TypeDefinitionAware;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
 import org.opendaylight.yangtools.yang.model.api.type.RangeConstraint;
-import org.opendaylight.yangtools.yang.model.util.BinaryType;
-import org.opendaylight.yangtools.yang.model.util.BooleanType;
-import org.opendaylight.yangtools.yang.model.util.EmptyType;
-import org.opendaylight.yangtools.yang.model.util.Int16;
-import org.opendaylight.yangtools.yang.model.util.Int32;
-import org.opendaylight.yangtools.yang.model.util.Int64;
-import org.opendaylight.yangtools.yang.model.util.Int8;
-import org.opendaylight.yangtools.yang.model.util.StringType;
-import org.opendaylight.yangtools.yang.model.util.Uint16;
-import org.opendaylight.yangtools.yang.model.util.Uint32;
-import org.opendaylight.yangtools.yang.model.util.Uint64;
-import org.opendaylight.yangtools.yang.model.util.Uint8;
+import org.opendaylight.yangtools.yang.model.util.UnresolvedNumber;
+import org.opendaylight.yangtools.yang.parser.spi.meta.InferenceException;
+import org.opendaylight.yangtools.yang.parser.spi.meta.QNameCacheNamespace;
+import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
+import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.type.LengthConstraintEffectiveImpl;
 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.effective.type.RangeConstraintEffectiveImpl;
-import org.opendaylight.yangtools.yang.parser.util.UnknownBoundaryNumber;
 
 /**
 * util class for manipulating YANG base and extended types implementation
@@ -69,57 +55,30 @@ public final class TypeUtils {
     public static final String UINT64 = "uint64";
     public static final String UNION = "union";
 
-    private static final Set<String> BUILT_IN_TYPES = ImmutableSet.of(
-        BINARY, BITS, BOOLEAN, DECIMAL64, EMPTY, ENUMERATION, IDENTITY_REF, INSTANCE_IDENTIFIER,
-        INT8, INT16, INT32, INT64, LEAF_REF, STRING, UINT8, UINT16, UINT32, UINT64, UNION);
-
-    public static final Set<String> TYPE_BODY_STMTS = ImmutableSet.of(
-        DECIMAL64, ENUMERATION, LEAF_REF, IDENTITY_REF, INSTANCE_IDENTIFIER, BITS, UNION);
-
-    public static final Map<String, TypeDefinition<?>> PRIMITIVE_TYPES_MAP;
-    static {
-        Builder<String, TypeDefinition<?>> b = ImmutableMap.<String, TypeDefinition<?>>builder();
-        b.put(BINARY, BinaryType.getInstance());
-        b.put(BOOLEAN, BooleanType.getInstance());
-        b.put(EMPTY, EmptyType.getInstance());
-        b.put(INT8, Int8.getInstance());
-        b.put(INT16, Int16.getInstance());
-        b.put(INT32, Int32.getInstance());
-        b.put(INT64, Int64.getInstance());
-        b.put(STRING, StringType.getInstance());
-        b.put(UINT8, Uint8.getInstance());
-        b.put(UINT16, Uint16.getInstance());
-        b.put(UINT32, Uint32.getInstance());
-        b.put(UINT64, Uint64.getInstance());
-        PRIMITIVE_TYPES_MAP = b.build();
-    }
+    private static final Set<String> BUILT_IN_TYPES =
+            ImmutableSet.of(BINARY, BITS, BOOLEAN, DECIMAL64, EMPTY, ENUMERATION, IDENTITY_REF, INSTANCE_IDENTIFIER,
+                    INT8, INT16, INT32, INT64, LEAF_REF, STRING, UINT8, UINT16, UINT32, UINT64, UNION);
 
-    private static final Comparator<TypeDefinition<?>> TYPE_SORT_COMPARATOR = new Comparator<TypeDefinition<?>>() {
-        @Override
-        public int compare(final TypeDefinition<?> o1, final TypeDefinition<?> o2) {
-            return Boolean.compare(isBuiltInType(o2), isBuiltInType(o1));
-        }
-    };
+    private static final Set<String> TYPE_BODY_STMTS = ImmutableSet.of(
+        DECIMAL64, ENUMERATION, LEAF_REF, IDENTITY_REF, BITS, UNION);
+    private static final Splitter PIPE_SPLITTER = Splitter.on('|').trimResults();
+    private static final Splitter TWO_DOTS_SPLITTER = Splitter.on("..").trimResults();
 
     private TypeUtils() {
     }
 
-    private static final Splitter PIPE_SPLITTER = Splitter.on('|').trimResults();
-    private static final Splitter TWO_DOTS_SPLITTER = Splitter.on("..").trimResults();
-
     private static BigDecimal yangConstraintToBigDecimal(final Number number) {
-        if (number instanceof UnknownBoundaryNumber) {
-            if (number.toString().equals("min")) {
-                return RangeStatementImpl.YANG_MIN_NUM;
-            } else {
-                return RangeStatementImpl.YANG_MAX_NUM;
-            }
-        } else {
-            return new BigDecimal(number.toString());
+        if (UnresolvedNumber.max().equals(number)) {
+            return RangeStatementImpl.YANG_MAX_NUM;
         }
+        if (UnresolvedNumber.min().equals(number)) {
+            return RangeStatementImpl.YANG_MIN_NUM;
+        }
+
+        return new BigDecimal(number.toString());
     }
 
-    public static int compareNumbers(final Number n1, final Number n2) {
+    private static int compareNumbers(final Number n1, final Number n2) {
 
         final BigDecimal num1 = yangConstraintToBigDecimal(n1);
         final BigDecimal num2 = yangConstraintToBigDecimal(n2);
@@ -127,45 +86,40 @@ public final class TypeUtils {
         return new BigDecimal(num1.toString()).compareTo(new BigDecimal(num2.toString()));
     }
 
-    private static Number parseIntegerConstraintValue(final String value) {
-        Number result;
+    private static Number parseIntegerConstraintValue(final StmtContext<?, ?, ?> ctx, final String value) {
+        if ("max".equals(value)) {
+            return UnresolvedNumber.max();
+        }
+        if ("min".equals(value)) {
+            return UnresolvedNumber.min();
+        }
 
-        if (isMinOrMaxString(value)) {
-            result = new UnknownBoundaryNumber(value);
-        } else {
-            try {
-                result = new BigInteger(value);
-            } catch (NumberFormatException e) {
-                throw new IllegalArgumentException(String.format("Value %s is not a valid integer", value), e);
-            }
+        try {
+            return new BigInteger(value);
+        } catch (NumberFormatException e) {
+            throw new SourceException(String.format("Value %s is not a valid integer", value),
+                    ctx.getStatementSourceReference(), e);
         }
-        return result;
     }
 
-    private static Number parseDecimalConstraintValue(final String value) {
-        final Number result;
-
-        if (isMinOrMaxString(value)) {
-            result = new UnknownBoundaryNumber(value);
-        } else {
-            try {
-                if (value.indexOf('.') != -1) {
-                    result = new BigDecimal(value);
-                } else {
-                    result = new BigInteger(value);
-                }
-            } catch (NumberFormatException e) {
-                throw new IllegalArgumentException(String.format("Value %s is not a valid decimal number", value), e);
-            }
+    private static Number parseDecimalConstraintValue(final StmtContext<?, ?, ?> ctx, final String value) {
+        if ("max".equals(value)) {
+            return UnresolvedNumber.max();
+        }
+        if ("min".equals(value)) {
+            return UnresolvedNumber.min();
         }
-        return result;
-    }
 
-    private static boolean isMinOrMaxString(final String value) {
-        return "min".equals(value) || "max".equals(value);
+        try {
+            return value.indexOf('.') != -1 ? new BigDecimal(value) : new BigInteger(value);
+        } catch (NumberFormatException e) {
+            throw new SourceException(String.format("Value %s is not a valid decimal number", value),
+                    ctx.getStatementSourceReference(), e);
+        }
     }
 
-    public static List<RangeConstraint> parseRangeListFromString(final String rangeArgument) {
+    public static List<RangeConstraint> parseRangeListFromString(final StmtContext<?, ?, ?> ctx,
+                                                                 final String rangeArgument) {
 
         Optional<String> description = Optional.absent();
         Optional<String> reference = Optional.absent();
@@ -174,28 +128,26 @@ public final class TypeUtils {
 
         for (final String singleRange : PIPE_SPLITTER.split(rangeArgument)) {
             final Iterator<String> boundaries = TWO_DOTS_SPLITTER.splitToList(singleRange).iterator();
-            final Number min = parseDecimalConstraintValue(boundaries.next());
+            final Number min = parseDecimalConstraintValue(ctx, boundaries.next());
 
             final Number max;
             if (boundaries.hasNext()) {
-                max = parseDecimalConstraintValue(boundaries.next());
+                max = parseDecimalConstraintValue(ctx, boundaries.next());
 
                 // if min larger than max then error
-                if (compareNumbers(min, max) == 1) {
-                    throw new IllegalArgumentException(String.format(
-                            "Range constraint %s has descending order of boundaries; should be ascending", singleRange));
-                }
-                if (boundaries.hasNext()) {
-                    throw new IllegalArgumentException("Wrong number of boundaries in range constraint " + singleRange);
-                }
+                InferenceException.throwIf(compareNumbers(min, max) == 1, ctx.getStatementSourceReference(),
+                        "Range constraint %s has descending order of boundaries; should be ascending", singleRange);
+
+                SourceException.throwIf(boundaries.hasNext(), ctx.getStatementSourceReference(),
+                    "Wrong number of boundaries in range constraint %s", singleRange);
             } else {
                 max = min;
             }
 
             // some of intervals overlapping
             if (rangeConstraints.size() > 1 && compareNumbers(min, Iterables.getLast(rangeConstraints).getMax()) != 1) {
-                throw new IllegalArgumentException(String.format("Some of the ranges in %s are not disjoint",
-                        rangeArgument));
+                throw new InferenceException(ctx.getStatementSourceReference(),
+                    "Some of the ranges in %s are not disjoint", rangeArgument);
             }
 
             rangeConstraints.add(new RangeConstraintEffectiveImpl(min, max, description, reference));
@@ -204,73 +156,57 @@ public final class TypeUtils {
         return rangeConstraints;
     }
 
-    public static List<LengthConstraint> parseLengthListFromString(final String rangeArgument) {
-
+    public static List<LengthConstraint> parseLengthListFromString(final StmtContext<?, ?, ?> ctx,
+            final String lengthArgument) {
         Optional<String> description = Optional.absent();
         Optional<String> reference = Optional.absent();
 
-        List<LengthConstraint> rangeConstraints = new ArrayList<>();
+        List<LengthConstraint> lengthConstraints = new ArrayList<>();
 
-        for (final String singleRange : PIPE_SPLITTER.split(rangeArgument)) {
+        for (final String singleRange : PIPE_SPLITTER.split(lengthArgument)) {
             final Iterator<String> boundaries = TWO_DOTS_SPLITTER.splitToList(singleRange).iterator();
-            final Number min = parseIntegerConstraintValue(boundaries.next());
+            final Number min = parseIntegerConstraintValue(ctx, boundaries.next());
 
             final Number max;
             if (boundaries.hasNext()) {
-                max = parseIntegerConstraintValue(boundaries.next());
+                max = parseIntegerConstraintValue(ctx, boundaries.next());
 
                 // if min larger than max then error
                 Preconditions.checkArgument(compareNumbers(min, max) != 1,
-                        "Length constraint %s has descending order of boundaries; should be ascending", singleRange);
-                Preconditions.checkArgument(!boundaries.hasNext(), "Wrong number of boundaries in length constraint %s",
-                        singleRange);
+                        "Length constraint %s has descending order of boundaries; should be ascending. Statement source at %s",
+                        singleRange, ctx.getStatementSourceReference());
+                Preconditions.checkArgument(!boundaries.hasNext(),
+                        "Wrong number of boundaries in length constraint %s. Statement source at %s", singleRange,
+                        ctx.getStatementSourceReference());
             } else {
                 max = min;
             }
 
             // some of intervals overlapping
-            if (rangeConstraints.size() > 1 && compareNumbers(min, Iterables.getLast(rangeConstraints).getMax()) != 1) {
-                throw new IllegalArgumentException(String.format("Some of the length ranges in %s are not disjoint",
-                        rangeArgument));
+            if (lengthConstraints.size() > 1 && compareNumbers(min, Iterables.getLast(lengthConstraints).getMax()) != 1) {
+                throw new InferenceException(ctx.getStatementSourceReference(),
+                    "Some of the length ranges in %s are not disjoint", lengthArgument);
             }
 
-            rangeConstraints.add(new LengthConstraintEffectiveImpl(min, max, description, reference));
+            lengthConstraints.add(new LengthConstraintEffectiveImpl(min, max, description, reference));
         }
 
-        return rangeConstraints;
-    }
-
-    public static boolean isBuiltInType(final TypeDefinition<?> o1) {
-        return BUILT_IN_TYPES.contains(o1.getQName().getLocalName());
-    }
-
-    public static boolean isYangBuiltInTypeString(final String typeName) {
-        return BUILT_IN_TYPES.contains(typeName);
-    }
-
-    public static boolean isYangPrimitiveTypeString(final String typeName) {
-        return PRIMITIVE_TYPES_MAP.containsKey(typeName);
+        return lengthConstraints;
     }
 
     public static boolean isYangTypeBodyStmtString(final String typeName) {
         return TYPE_BODY_STMTS.contains(typeName);
     }
 
-    public static TypeDefinition<?> getYangPrimitiveTypeFromString(final String typeName) {
-        return PRIMITIVE_TYPES_MAP.get(typeName);
+    public static boolean isYangBuiltInTypeString(final String typeName) {
+        return BUILT_IN_TYPES.contains(typeName);
     }
 
-    public static TypeDefinition<?> getTypeFromEffectiveStatement(final EffectiveStatement<?, ?> effectiveStatement) {
-        if (effectiveStatement instanceof TypeDefinitionAware) {
-            TypeDefinitionAware typeDefEffectiveBuilder = (TypeDefinitionAware) effectiveStatement;
-            return typeDefEffectiveBuilder.getTypeDefinition();
-        } else {
-            final String typeName = ((TypeDefinition<?>) effectiveStatement).getQName().getLocalName();
-            return PRIMITIVE_TYPES_MAP.get(typeName);
-        }
-    }
 
-    public static void sortTypes(final List<TypeDefinition<?>> typesInit) {
-        Collections.sort(typesInit, TYPE_SORT_COMPARATOR);
+    public static SchemaPath typeEffectiveSchemaPath(final StmtContext<?, ?, ?> stmtCtx) {
+        final SchemaPath path = stmtCtx.getSchemaPath().get();
+        final QName qname = stmtCtx.getFromNamespace(QNameCacheNamespace.class,
+            QName.create(path.getParent().getLastComponent(), path.getLastComponent().getLocalName()));
+        return path.getParent().createChild(qname);
     }
 }