From b26f19dce0ae50d80b7a13e9caa006da629396c9 Mon Sep 17 00:00:00 2001 From: Michael Steindorfer Date: Wed, 21 Oct 2015 14:16:11 +0200 Subject: [PATCH] Extracting capsule and rascal-value implementation. Leaving API only in this project. --- capsule/LICENSE | 203 -- capsule/pom.xml | 53 - .../capsule/AbstractImmutableMap.java | 41 - .../capsule/AbstractImmutableSet.java | 81 - .../AbstractSpecialisedImmutableMap.java | 1549 --------- .../AbstractSpecialisedImmutableSet.java | 1269 -------- .../usethesource/capsule/ArrayIterator.java | 56 - .../ArrayKeyValueSupplierIterator.java | 67 - .../capsule/ArraySupplierIterator.java | 64 - .../io/usethesource/capsule/ArrayUtils.java | 96 - .../usethesource/capsule/DefaultTrieMap.java | 72 - .../usethesource/capsule/DefaultTrieSet.java | 69 - .../capsule/EmptySupplierIterator.java | 46 - .../io/usethesource/capsule/ImmutableMap.java | 55 - .../io/usethesource/capsule/ImmutableSet.java | 60 - .../io/usethesource/capsule/Supplier.java | 19 - .../capsule/SupplierIterator.java | 17 - .../io/usethesource/capsule/TransientMap.java | 52 - .../io/usethesource/capsule/TransientSet.java | 58 - .../usethesource/capsule/TrieMap_5Bits.java | 2806 ----------------- .../usethesource/capsule/TrieSet_5Bits.java | 2314 -------------- .../io/usethesource/capsule/TrieMapTests.java | 438 --- .../io/usethesource/capsule/TrieSetTests.java | 401 --- {value-core/doc => doc}/PBF-basic-spec.txt | 0 pom.xml | 12 +- .../org/rascalmpl/value/IAnnotatable.java | 0 .../main/java/org/rascalmpl/value/IBool.java | 0 .../org/rascalmpl/value/IConstructor.java | 0 .../java/org/rascalmpl/value/IDateTime.java | 0 .../org/rascalmpl/value/IExternalValue.java | 0 .../java/org/rascalmpl/value/IInteger.java | 0 .../main/java/org/rascalmpl/value/IList.java | 0 .../org/rascalmpl/value/IListAlgebra.java | 0 .../org/rascalmpl/value/IListRelation.java | 0 .../java/org/rascalmpl/value/IListWriter.java | 0 .../main/java/org/rascalmpl/value/IMap.java | 0 .../java/org/rascalmpl/value/IMapWriter.java | 0 .../main/java/org/rascalmpl/value/INode.java | 0 .../java/org/rascalmpl/value/INumber.java | 0 .../java/org/rascalmpl/value/IRational.java | 0 .../main/java/org/rascalmpl/value/IReal.java | 0 .../rascalmpl/value/IRelationalAlgebra.java | 0 .../main/java/org/rascalmpl/value/ISet.java | 0 .../java/org/rascalmpl/value/ISetAlgebra.java | 0 .../org/rascalmpl/value/ISetRelation.java | 0 .../java/org/rascalmpl/value/ISetWriter.java | 0 .../org/rascalmpl/value/ISourceLocation.java | 0 .../java/org/rascalmpl/value/IString.java | 0 .../main/java/org/rascalmpl/value/ITuple.java | 0 .../main/java/org/rascalmpl/value/IValue.java | 0 .../org/rascalmpl/value/IValueFactory.java | 0 .../value/IWithKeywordParameters.java | 0 .../java/org/rascalmpl/value/IWriter.java | 0 .../exceptions/EmptyIdentifierException.java | 0 .../value/exceptions/FactParseError.java | 0 .../FactTypeDeclarationException.java | 0 .../FactTypeRedeclaredException.java | 0 .../exceptions/FactTypeUseException.java | 0 .../FieldLabelMismatchException.java | 0 .../IllegalAnnotationDeclaration.java | 0 ...llegalConstructorApplicationException.java | 0 .../exceptions/IllegalFieldNameException.java | 0 .../exceptions/IllegalFieldTypeException.java | 0 .../IllegalIdentifierException.java | 0 ...InstantiatedAbstractDataTypeException.java | 0 ...lKeywordParameterDeclarationException.java | 0 .../exceptions/IllegalOperationException.java | 0 .../exceptions/InvalidDateTimeException.java | 0 .../value/exceptions/NullTypeException.java | 0 .../OverloadingNotSupportedException.java | 0 .../RedeclaredAnnotationException.java | 0 .../RedeclaredConstructorException.java | 0 .../RedeclaredFieldNameException.java | 0 .../RedeclaredKeywordParameterException.java | 0 .../UndeclaredAbstractDataTypeException.java | 0 .../UndeclaredAnnotationException.java | 0 .../UndeclaredConstructorException.java | 0 .../exceptions/UndeclaredFieldException.java | 0 .../UnexpectedAnnotationTypeException.java | 0 .../UnexpectedChildTypeException.java | 0 .../UnexpectedConstructorTypeException.java | 0 .../UnexpectedElementTypeException.java | 0 .../UnexpectedMapKeyTypeException.java | 0 .../UnexpectedMapValueTypeException.java | 0 .../UnexpectedResultTypeException.java | 0 .../exceptions/UnexpectedTypeException.java | 0 .../exceptions/UnsupportedTypeException.java | 0 .../value/io/IValueBinaryReader.java | 0 .../value/io/IValueBinaryWriter.java | 0 .../rascalmpl/value/io/IValueTextReader.java | 0 .../rascalmpl/value/io/IValueTextWriter.java | 0 .../rascalmpl/value/random/DataGenerator.java | 0 .../value/random/RandomGenerator.java | 0 .../value/random/RandomIntegerGenerator.java | 0 .../value/random/RandomNumberGenerator.java | 0 .../value/random/RandomRationalGenerator.java | 0 .../value/random/RandomRealGenerator.java | 0 .../value/random/RandomTypeGenerator.java | 0 .../value/type/AbstractDataType.java | 0 .../org/rascalmpl/value/type/AliasType.java | 0 .../org/rascalmpl/value/type/BoolType.java | 0 .../rascalmpl/value/type/ConstructorType.java | 0 .../rascalmpl/value/type/DateTimeType.java | 0 .../value/type/DefaultSubtypeOfValue.java | 0 .../value/type/DefaultTypeVisitor.java | 0 .../rascalmpl/value/type/ExternalType.java | 0 .../rascalmpl/value/type/ITypeVisitor.java | 0 .../org/rascalmpl/value/type/IntegerType.java | 0 .../org/rascalmpl/value/type/ListType.java | 0 .../org/rascalmpl/value/type/MapType.java | 0 .../org/rascalmpl/value/type/NodeType.java | 0 .../org/rascalmpl/value/type/NumberType.java | 0 .../rascalmpl/value/type/ParameterType.java | 0 .../rascalmpl/value/type/RationalType.java | 0 .../org/rascalmpl/value/type/RealType.java | 0 .../org/rascalmpl/value/type/SetType.java | 0 .../value/type/SourceLocationType.java | 0 .../org/rascalmpl/value/type/StringType.java | 0 .../org/rascalmpl/value/type/TupleType.java | 0 .../java/org/rascalmpl/value/type/Type.java | 0 .../org/rascalmpl/value/type/TypeFactory.java | 0 .../org/rascalmpl/value/type/TypeStore.java | 0 .../org/rascalmpl/value/type/ValueType.java | 0 .../org/rascalmpl/value/type/VoidType.java | 0 .../value/visitors/IValueVisitor.java | 0 value-api/LICENSE | 203 -- value-api/pom.xml | 16 - value-core/LICENSE | 203 -- value-core/pom.xml | 110 - .../impl/AbstractDefaultAnnotatable.java | 137 - .../AbstractDefaultWithKeywordParameters.java | 169 - .../value/impl/AbstractExternalValue.java | 221 -- .../rascalmpl/value/impl/AbstractList.java | 170 - .../org/rascalmpl/value/impl/AbstractMap.java | 118 - .../rascalmpl/value/impl/AbstractNode.java | 77 - .../org/rascalmpl/value/impl/AbstractSet.java | 123 - .../rascalmpl/value/impl/AbstractValue.java | 69 - .../impl/AbstractValueFactoryAdapter.java | 354 --- .../rascalmpl/value/impl/AbstractWriter.java | 24 - .../impl/AnnotatedConstructorFacade.java | 162 - .../value/impl/AnnotatedNodeFacade.java | 130 - ...onstructorWithKeywordParametersFacade.java | 201 -- .../value/impl/DefaultRelationViewOnList.java | 73 - .../value/impl/DefaultRelationViewOnSet.java | 73 - .../impl/NodeWithKeywordParametersFacade.java | 140 - .../value/impl/fast/Constructor.java | 309 -- .../org/rascalmpl/value/impl/fast/List.java | 376 --- .../rascalmpl/value/impl/fast/ListWriter.java | 186 -- .../org/rascalmpl/value/impl/fast/Map.java | 318 -- .../rascalmpl/value/impl/fast/MapWriter.java | 213 -- .../org/rascalmpl/value/impl/fast/Node.java | 185 -- .../value/impl/fast/RelationViewOnList.java | 69 - .../value/impl/fast/RelationViewOnSet.java | 69 - .../impl/fast/RelationalFunctionsOnList.java | 179 -- .../impl/fast/RelationalFunctionsOnSet.java | 380 --- .../org/rascalmpl/value/impl/fast/Set.java | 260 -- .../rascalmpl/value/impl/fast/SetWriter.java | 114 - .../org/rascalmpl/value/impl/fast/Tuple.java | 234 -- .../value/impl/fast/ValueFactory.java | 227 -- .../value/impl/func/ListFunctions.java | 522 --- .../value/impl/func/MapFunctions.java | 224 -- .../value/impl/func/NodeFunctions.java | 148 - .../value/impl/func/SetFunctions.java | 523 --- .../value/impl/persistent/MapWriter.java | 169 - .../impl/persistent/PDBPersistentHashMap.java | 310 -- .../impl/persistent/PDBPersistentHashSet.java | 328 -- .../value/impl/persistent/SetWriter.java | 114 - .../value/impl/persistent/ValueFactory.java | 100 - .../impl/primitive/AbstractNumberValue.java | 167 - .../AbstractPrimitiveValueFactory.java | 273 -- .../value/impl/primitive/BigDecimalValue.java | 434 --- .../value/impl/primitive/BigIntegerValue.java | 362 --- .../value/impl/primitive/BoolValue.java | 134 - .../value/impl/primitive/DateTimeValues.java | 877 ------ .../value/impl/primitive/ExternalValue.java | 69 - .../impl/primitive/ICanBecomeABigInteger.java | 29 - .../rascalmpl/value/impl/primitive/IURI.java | 16 - .../value/impl/primitive/IntegerValue.java | 543 ---- .../value/impl/primitive/RationalValue.java | 378 --- .../primitive/SourceLocationURIValues.java | 851 ----- .../impl/primitive/SourceLocationValues.java | 909 ------ .../value/impl/primitive/StringValue.java | 301 -- .../value/impl/reference/Constructor.java | 212 -- .../rascalmpl/value/impl/reference/List.java | 78 - .../value/impl/reference/ListWriter.java | 191 -- .../rascalmpl/value/impl/reference/Map.java | 95 - .../value/impl/reference/MapWriter.java | 156 - .../rascalmpl/value/impl/reference/Node.java | 212 -- .../rascalmpl/value/impl/reference/Set.java | 84 - .../value/impl/reference/SetWriter.java | 108 - .../rascalmpl/value/impl/reference/Tuple.java | 191 -- .../value/impl/reference/ValueFactory.java | 308 -- .../impl/util/BigDecimalCalculations.java | 539 ---- .../collections/ShareableValuesHashMap.java | 570 ---- .../collections/ShareableValuesHashSet.java | 462 --- .../util/collections/ShareableValuesList.java | 91 - .../value/impl/util/sharing/IShareable.java | 37 - .../value/impl/util/sharing/IndexedCache.java | 78 - .../util/sharing/ShareableValuesFactory.java | 553 ---- .../org/rascalmpl/value/io/ATermReader.java | 729 ----- .../org/rascalmpl/value/io/ATermWriter.java | 267 -- .../value/io/AbstractBinaryReader.java | 23 - .../value/io/AbstractTextReader.java | 23 - .../rascalmpl/value/io/BinaryValueReader.java | 95 - .../rascalmpl/value/io/BinaryValueWriter.java | 136 - .../rascalmpl/value/io/SerializableValue.java | 76 - .../value/io/StandardTextReader.java | 998 ------ .../value/io/StandardTextWriter.java | 711 ----- .../org/rascalmpl/value/io/XMLReader.java | 361 --- .../org/rascalmpl/value/io/XMLWriter.java | 256 -- .../value/io/binary/BinaryReader.java | 1020 ------ .../value/io/binary/BinaryWriter.java | 1092 ------- .../rascalmpl/value/util/AbstractTypeBag.java | 162 - .../rascalmpl/value/util/EqualityUtils.java | 55 - .../org/rascalmpl/value/util/IndexedSet.java | 167 - .../rascalmpl/value/util/ResizingArray.java | 78 - .../rascalmpl/value/util/RotatingQueue.java | 105 - .../value/util/ShareableHashMap.java | 802 ----- .../value/util/ShareableHashSet.java | 607 ---- .../rascalmpl/value/util/ShareableList.java | 637 ---- .../value/util/ValueIndexedHashMap.java | 802 ----- .../value/visitors/BottomUpTransformer.java | 120 - .../value/visitors/BottomUpVisitor.java | 121 - .../value/visitors/IdentityVisitor.java | 99 - .../rascalmpl/value/visitors/NullVisitor.java | 98 - .../value/visitors/VisitorAdapter.java | 103 - .../value/visitors/VisitorException.java | 32 - .../java/org/rascalmpl/value/AllTests.java | 81 - .../rascalmpl/value/BaseTestAnnotations.java | 293 -- .../rascalmpl/value/BaseTestBasicValues.java | 194 -- .../org/rascalmpl/value/BaseTestEquality.java | 114 - .../org/rascalmpl/value/BaseTestList.java | 330 -- .../rascalmpl/value/BaseTestListRelation.java | 478 --- .../java/org/rascalmpl/value/BaseTestMap.java | 551 ---- .../rascalmpl/value/BaseTestRandomValues.java | 629 ---- .../org/rascalmpl/value/BaseTestRelation.java | 557 ---- .../java/org/rascalmpl/value/BaseTestSet.java | 347 -- .../rascalmpl/value/BaseTestValueFactory.java | 382 --- .../value/TestBigDecimalCalculations.java | 189 -- .../org/rascalmpl/value/TestBinaryIO.java | 120 - .../test/java/org/rascalmpl/value/TestIO.java | 178 -- .../java/org/rascalmpl/value/TestType.java | 454 --- .../org/rascalmpl/value/TestTypeFactory.java | 407 --- .../rascalmpl/value/fast/TestAnnotations.java | 24 - .../rascalmpl/value/fast/TestBasicValues.java | 12 - .../rascalmpl/value/fast/TestEquality.java | 24 - .../org/rascalmpl/value/fast/TestList.java | 24 - .../value/fast/TestListRelation.java | 24 - .../org/rascalmpl/value/fast/TestMap.java | 22 - .../value/fast/TestRandomValues.java | 22 - .../rascalmpl/value/fast/TestRelation.java | 24 - .../org/rascalmpl/value/fast/TestSet.java | 24 - .../value/fast/TestValueFactory.java | 24 - .../value/persistent/TestAnnotations.java | 24 - .../value/persistent/TestBasicValues.java | 12 - .../value/persistent/TestEquality.java | 24 - .../rascalmpl/value/persistent/TestList.java | 24 - .../value/persistent/TestListRelation.java | 24 - .../rascalmpl/value/persistent/TestMap.java | 22 - .../value/persistent/TestRandomValues.java | 22 - .../value/persistent/TestRelation.java | 24 - .../rascalmpl/value/persistent/TestSet.java | 24 - .../value/persistent/TestValueFactory.java | 24 - .../value/reference/TestAnnotations.java | 24 - .../value/reference/TestBasicValues.java | 12 - .../value/reference/TestEquality.java | 24 - .../rascalmpl/value/reference/TestList.java | 24 - .../value/reference/TestListRelation.java | 24 - .../rascalmpl/value/reference/TestMap.java | 22 - .../value/reference/TestRandomValues.java | 22 - .../value/reference/TestRelation.java | 24 - .../rascalmpl/value/reference/TestSet.java | 24 - .../value/reference/TestValueFactory.java | 25 - .../rascalmpl/value/util/MixDistribution.java | 524 --- 274 files changed, 3 insertions(+), 43809 deletions(-) delete mode 100644 capsule/LICENSE delete mode 100644 capsule/pom.xml delete mode 100644 capsule/src/main/java/io/usethesource/capsule/AbstractImmutableMap.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/AbstractImmutableSet.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/AbstractSpecialisedImmutableMap.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/AbstractSpecialisedImmutableSet.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/ArrayIterator.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/ArrayKeyValueSupplierIterator.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/ArraySupplierIterator.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/ArrayUtils.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/DefaultTrieMap.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/DefaultTrieSet.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/EmptySupplierIterator.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/ImmutableMap.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/ImmutableSet.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/Supplier.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/SupplierIterator.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/TransientMap.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/TransientSet.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/TrieMap_5Bits.java delete mode 100644 capsule/src/main/java/io/usethesource/capsule/TrieSet_5Bits.java delete mode 100644 capsule/src/test/java/io/usethesource/capsule/TrieMapTests.java delete mode 100644 capsule/src/test/java/io/usethesource/capsule/TrieSetTests.java rename {value-core/doc => doc}/PBF-basic-spec.txt (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IAnnotatable.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IBool.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IConstructor.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IDateTime.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IExternalValue.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IInteger.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IList.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IListAlgebra.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IListRelation.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IListWriter.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IMap.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IMapWriter.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/INode.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/INumber.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IRational.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IReal.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IRelationalAlgebra.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/ISet.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/ISetAlgebra.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/ISetRelation.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/ISetWriter.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/ISourceLocation.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IString.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/ITuple.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IValue.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IValueFactory.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IWithKeywordParameters.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/IWriter.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/EmptyIdentifierException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/FactParseError.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/FactTypeDeclarationException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/FactTypeRedeclaredException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/FactTypeUseException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/FieldLabelMismatchException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/IllegalAnnotationDeclaration.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/IllegalConstructorApplicationException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/IllegalFieldNameException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/IllegalFieldTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/IllegalIdentifierException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/IllegalInstantiatedAbstractDataTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/IllegalKeywordParameterDeclarationException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/IllegalOperationException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/InvalidDateTimeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/NullTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/OverloadingNotSupportedException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/RedeclaredAnnotationException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/RedeclaredConstructorException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/RedeclaredFieldNameException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/RedeclaredKeywordParameterException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UndeclaredAbstractDataTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UndeclaredAnnotationException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UndeclaredConstructorException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UndeclaredFieldException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UnexpectedAnnotationTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UnexpectedChildTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UnexpectedConstructorTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UnexpectedElementTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UnexpectedMapKeyTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UnexpectedMapValueTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UnexpectedResultTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UnexpectedTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/exceptions/UnsupportedTypeException.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/io/IValueBinaryReader.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/io/IValueBinaryWriter.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/io/IValueTextReader.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/io/IValueTextWriter.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/random/DataGenerator.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/random/RandomGenerator.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/random/RandomIntegerGenerator.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/random/RandomNumberGenerator.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/random/RandomRationalGenerator.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/random/RandomRealGenerator.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/random/RandomTypeGenerator.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/AbstractDataType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/AliasType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/BoolType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/ConstructorType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/DateTimeType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/DefaultSubtypeOfValue.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/DefaultTypeVisitor.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/ExternalType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/ITypeVisitor.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/IntegerType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/ListType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/MapType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/NodeType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/NumberType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/ParameterType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/RationalType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/RealType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/SetType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/SourceLocationType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/StringType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/TupleType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/Type.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/TypeFactory.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/TypeStore.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/ValueType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/type/VoidType.java (100%) rename {value-api/src => src}/main/java/org/rascalmpl/value/visitors/IValueVisitor.java (100%) delete mode 100644 value-api/LICENSE delete mode 100644 value-api/pom.xml delete mode 100644 value-core/LICENSE delete mode 100644 value-core/pom.xml delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AbstractDefaultAnnotatable.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AbstractDefaultWithKeywordParameters.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AbstractExternalValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AbstractList.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AbstractMap.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AbstractNode.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AbstractSet.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AbstractValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AbstractValueFactoryAdapter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AbstractWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AnnotatedConstructorFacade.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/AnnotatedNodeFacade.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/ConstructorWithKeywordParametersFacade.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/DefaultRelationViewOnList.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/DefaultRelationViewOnSet.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/NodeWithKeywordParametersFacade.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/Constructor.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/List.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/ListWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/Map.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/MapWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/Node.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationViewOnList.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationViewOnSet.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationalFunctionsOnList.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationalFunctionsOnSet.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/Set.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/SetWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/Tuple.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/fast/ValueFactory.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/func/ListFunctions.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/func/MapFunctions.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/func/NodeFunctions.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/func/SetFunctions.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/persistent/MapWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/persistent/PDBPersistentHashMap.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/persistent/PDBPersistentHashSet.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/persistent/SetWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/persistent/ValueFactory.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/AbstractNumberValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/AbstractPrimitiveValueFactory.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/BigDecimalValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/BigIntegerValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/BoolValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/DateTimeValues.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/ExternalValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/ICanBecomeABigInteger.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/IURI.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/IntegerValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/RationalValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/SourceLocationURIValues.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/SourceLocationValues.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/primitive/StringValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/reference/Constructor.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/reference/List.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/reference/ListWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/reference/Map.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/reference/MapWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/reference/Node.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/reference/Set.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/reference/SetWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/reference/Tuple.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/reference/ValueFactory.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/util/BigDecimalCalculations.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesHashMap.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesHashSet.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesList.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/IShareable.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/IndexedCache.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/ShareableValuesFactory.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/ATermReader.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/ATermWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/AbstractBinaryReader.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/AbstractTextReader.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/BinaryValueReader.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/BinaryValueWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/SerializableValue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/StandardTextReader.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/StandardTextWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/XMLReader.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/XMLWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/binary/BinaryReader.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/io/binary/BinaryWriter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/util/AbstractTypeBag.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/util/EqualityUtils.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/util/IndexedSet.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/util/ResizingArray.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/util/RotatingQueue.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/util/ShareableHashMap.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/util/ShareableHashSet.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/util/ShareableList.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/util/ValueIndexedHashMap.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/visitors/BottomUpTransformer.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/visitors/BottomUpVisitor.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/visitors/IdentityVisitor.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/visitors/NullVisitor.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/visitors/VisitorAdapter.java delete mode 100644 value-core/src/main/java/org/rascalmpl/value/visitors/VisitorException.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/AllTests.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/BaseTestAnnotations.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/BaseTestBasicValues.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/BaseTestEquality.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/BaseTestList.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/BaseTestListRelation.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/BaseTestMap.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/BaseTestRandomValues.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/BaseTestRelation.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/BaseTestSet.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/BaseTestValueFactory.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/TestBigDecimalCalculations.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/TestBinaryIO.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/TestIO.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/TestType.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/TestTypeFactory.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/fast/TestAnnotations.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/fast/TestBasicValues.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/fast/TestEquality.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/fast/TestList.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/fast/TestListRelation.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/fast/TestMap.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/fast/TestRandomValues.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/fast/TestRelation.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/fast/TestSet.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/fast/TestValueFactory.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/persistent/TestAnnotations.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/persistent/TestBasicValues.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/persistent/TestEquality.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/persistent/TestList.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/persistent/TestListRelation.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/persistent/TestMap.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/persistent/TestRandomValues.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/persistent/TestRelation.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/persistent/TestSet.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/persistent/TestValueFactory.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/reference/TestAnnotations.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/reference/TestBasicValues.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/reference/TestEquality.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/reference/TestList.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/reference/TestListRelation.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/reference/TestMap.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/reference/TestRandomValues.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/reference/TestRelation.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/reference/TestSet.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/reference/TestValueFactory.java delete mode 100644 value-core/src/test/java/org/rascalmpl/value/util/MixDistribution.java diff --git a/capsule/LICENSE b/capsule/LICENSE deleted file mode 100644 index f735bee0e..000000000 --- a/capsule/LICENSE +++ /dev/null @@ -1,203 +0,0 @@ -Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC -LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM -CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - -a) in the case of the initial Contributor, the initial code and documentation - distributed under this Agreement, and -b) in the case of each subsequent Contributor: - i) changes to the Program, and - ii) additions to the Program; - - where such changes and/or additions to the Program originate from and are - distributed by that particular Contributor. A Contribution 'originates' - from a Contributor if it was added to the Program by such Contributor - itself or anyone acting on such Contributor's behalf. Contributions do not - include additions to the Program which: (i) are separate modules of - software distributed in conjunction with the Program under their own - license agreement, and (ii) are not derivative works of the Program. - -"Contributor" means any person or entity that distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which are -necessarily infringed by the use or sale of its Contribution alone or when -combined with the Program. - -"Program" means the Contributions distributed in accordance with this -Agreement. - -"Recipient" means anyone who receives the Program under this Agreement, -including all Contributors. - -2. GRANT OF RIGHTS - a) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free copyright license to - reproduce, prepare derivative works of, publicly display, publicly - perform, distribute and sublicense the Contribution of such Contributor, - if any, and such derivative works, in source code and object code form. - b) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free patent license under - Licensed Patents to make, use, sell, offer to sell, import and otherwise - transfer the Contribution of such Contributor, if any, in source code and - object code form. This patent license shall apply to the combination of - the Contribution and the Program if, at the time the Contribution is - added by the Contributor, such addition of the Contribution causes such - combination to be covered by the Licensed Patents. The patent license - shall not apply to any other combinations which include the Contribution. - No hardware per se is licensed hereunder. - c) Recipient understands that although each Contributor grants the licenses - to its Contributions set forth herein, no assurances are provided by any - Contributor that the Program does not infringe the patent or other - intellectual property rights of any other entity. Each Contributor - disclaims any liability to Recipient for claims brought by any other - entity based on infringement of intellectual property rights or - otherwise. As a condition to exercising the rights and licenses granted - hereunder, each Recipient hereby assumes sole responsibility to secure - any other intellectual property rights needed, if any. For example, if a - third party patent license is required to allow Recipient to distribute - the Program, it is Recipient's responsibility to acquire that license - before distributing the Program. - d) Each Contributor represents that to its knowledge it has sufficient - copyright rights in its Contribution, if any, to grant the copyright - license set forth in this Agreement. - -3. REQUIREMENTS - -A Contributor may choose to distribute the Program in object code form under -its own license agreement, provided that: - - a) it complies with the terms and conditions of this Agreement; and - b) its license agreement: - i) effectively disclaims on behalf of all Contributors all warranties - and conditions, express and implied, including warranties or - conditions of title and non-infringement, and implied warranties or - conditions of merchantability and fitness for a particular purpose; - ii) effectively excludes on behalf of all Contributors all liability for - damages, including direct, indirect, special, incidental and - consequential damages, such as lost profits; - iii) states that any provisions which differ from this Agreement are - offered by that Contributor alone and not by any other party; and - iv) states that source code for the Program is available from such - Contributor, and informs licensees how to obtain it in a reasonable - manner on or through a medium customarily used for software exchange. - -When the Program is made available in source code form: - - a) it must be made available under this Agreement; and - b) a copy of this Agreement must be included with each copy of the Program. - Contributors may not remove or alter any copyright notices contained - within the Program. - -Each Contributor must identify itself as the originator of its Contribution, -if -any, in a manner that reasonably allows subsequent Recipients to identify the -originator of the Contribution. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities with -respect to end users, business partners and the like. While this license is -intended to facilitate the commercial use of the Program, the Contributor who -includes the Program in a commercial product offering should do so in a manner -which does not create potential liability for other Contributors. Therefore, -if a Contributor includes the Program in a commercial product offering, such -Contributor ("Commercial Contributor") hereby agrees to defend and indemnify -every other Contributor ("Indemnified Contributor") against any losses, -damages and costs (collectively "Losses") arising from claims, lawsuits and -other legal actions brought by a third party against the Indemnified -Contributor to the extent caused by the acts or omissions of such Commercial -Contributor in connection with its distribution of the Program in a commercial -product offering. The obligations in this section do not apply to any claims -or Losses relating to any actual or alleged intellectual property -infringement. In order to qualify, an Indemnified Contributor must: -a) promptly notify the Commercial Contributor in writing of such claim, and -b) allow the Commercial Contributor to control, and cooperate with the -Commercial Contributor in, the defense and any related settlement -negotiations. The Indemnified Contributor may participate in any such claim at -its own expense. - -For example, a Contributor might include the Program in a commercial product -offering, Product X. That Contributor is then a Commercial Contributor. If -that Commercial Contributor then makes performance claims, or offers -warranties related to Product X, those performance claims and warranties are -such Commercial Contributor's responsibility alone. Under this section, the -Commercial Contributor would have to defend claims against the other -Contributors related to those performance claims and warranties, and if a -court requires any other Contributor to pay any damages as a result, the -Commercial Contributor must pay those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN -"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR -IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, -NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each -Recipient is solely responsible for determining the appropriateness of using -and distributing the Program and assumes all risks associated with its -exercise of rights under this Agreement , including but not limited to the -risks and costs of program errors, compliance with applicable laws, damage to -or loss of data, programs or equipment, and unavailability or interruption of -operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY -CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION -LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE -EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY -OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of the -remainder of the terms of this Agreement, and without further action by the -parties hereto, such provision shall be reformed to the minimum extent -necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Program itself -(excluding combinations of the Program with other software or hardware) -infringes such Recipient's patent(s), then such Recipient's rights granted -under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it fails to -comply with any of the material terms or conditions of this Agreement and does -not cure such failure in a reasonable period of time after becoming aware of -such noncompliance. If all Recipient's rights under this Agreement terminate, -Recipient agrees to cease use and distribution of the Program as soon as -reasonably practicable. However, Recipient's obligations under this Agreement -and any licenses granted by Recipient relating to the Program shall continue -and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, but in -order to avoid inconsistency the Agreement is copyrighted and may only be -modified in the following manner. The Agreement Steward reserves the right to -publish new versions (including revisions) of this Agreement from time to -time. No one other than the Agreement Steward has the right to modify this -Agreement. The Eclipse Foundation is the initial Agreement Steward. The -Eclipse Foundation may assign the responsibility to serve as the Agreement -Steward to a suitable separate entity. Each new version of the Agreement will -be given a distinguishing version number. The Program (including -Contributions) may always be distributed subject to the version of the -Agreement under which it was received. In addition, after a new version of the -Agreement is published, Contributor may elect to distribute the Program -(including its Contributions) under the new version. Except as expressly -stated in Sections 2(a) and 2(b) above, Recipient receives no rights or -licenses to the intellectual property of any Contributor under this Agreement, -whether expressly, by implication, estoppel or otherwise. All rights in the -Program not expressly granted under this Agreement are reserved. - -This Agreement is governed by the laws of the State of New York and the -intellectual property laws of the United States of America. No party to this -Agreement will bring a legal action under this Agreement more than one year -after the cause of action arose. Each party waives its rights to a jury trial in -any resulting litigation. diff --git a/capsule/pom.xml b/capsule/pom.xml deleted file mode 100644 index 7d491300a..000000000 --- a/capsule/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - 4.0.0 - - io.usethesource - capsule - 0.1.0-SNAPSHOT - jar - - - scm:git:https://github.com/cwi-swat/pdb.values.git - - - - - UTF-8 - 1.8 - 1.8 - - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - - - - - - - - junit - junit - 4.11 - test - - - - diff --git a/capsule/src/main/java/io/usethesource/capsule/AbstractImmutableMap.java b/capsule/src/main/java/io/usethesource/capsule/AbstractImmutableMap.java deleted file mode 100644 index a5edbb6d8..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/AbstractImmutableMap.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.AbstractMap; -import java.util.Map; - -@Deprecated -public abstract class AbstractImmutableMap extends AbstractMap implements ImmutableMap { - - @Override - public V remove(Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - - @Override - public V put(K key, V value) { - throw new UnsupportedOperationException(); - } - - @Override - public void putAll(Map m) { - throw new UnsupportedOperationException(); - } - -} - diff --git a/capsule/src/main/java/io/usethesource/capsule/AbstractImmutableSet.java b/capsule/src/main/java/io/usethesource/capsule/AbstractImmutableSet.java deleted file mode 100644 index 1a94a0fb1..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/AbstractImmutableSet.java +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.AbstractSet; -import java.util.Collection; -import java.util.Comparator; - -@Deprecated -public abstract class AbstractImmutableSet extends AbstractSet implements ImmutableSet { - - @Override - public boolean add(E e) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean remove(Object o) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addAll(Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeAll(Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean retainAll(Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isTransientSupported() { - return false; - } - - @Override - public TransientSet asTransient() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean containsAll(Collection c) { - for (Object item : c) { - if (!contains(item)) { - return false; - } - } - return true; - } - - @Override - public boolean containsAllEquivalent(Collection c, Comparator cmp) { - for (Object item : c) { - if (!containsEquivalent(item, cmp)) { - return false; - } - } - return true; - } - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/AbstractSpecialisedImmutableMap.java b/capsule/src/main/java/io/usethesource/capsule/AbstractSpecialisedImmutableMap.java deleted file mode 100644 index 2212deb77..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/AbstractSpecialisedImmutableMap.java +++ /dev/null @@ -1,1549 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.Set; - -public abstract class AbstractSpecialisedImmutableMap implements ImmutableMap, - Cloneable { - @SuppressWarnings("rawtypes") - private static ImmutableMap EMPTY_MAP = new Map0(); - - @SuppressWarnings("unchecked") - public static ImmutableMap mapOf() { - return EMPTY_MAP; - } - - @SuppressWarnings("unchecked") - public static final > T entryOf(final K key, final V val) { - return (T) new MapEntry(key, val); - } - - public static ImmutableMap mapOf(K key1, V val1) { - return new Map1(key1, val1); - } - - public static ImmutableMap mapOf(K key1, V val1, K key2, V val2) { - return new Map2(key1, val1, key2, val2); - } - - public static ImmutableMap mapOf(K key1, V val1, K key2, V val2, K key3, V val3) { - return new Map3(key1, val1, key2, val2, key3, val3); - } - - public static ImmutableMap mapOf(K key1, V val1, K key2, V val2, K key3, V val3, - K key4, V val4) { - return new Map4(key1, val1, key2, val2, key3, val3, key4, val4); - } - - public static ImmutableMap mapOf(K key1, V val1, K key2, V val2, K key3, V val3, - K key4, V val4, K key5, V val5) { - return new Map5(key1, val1, key2, val2, key3, val3, key4, val4, key5, val5); - } - - public static ImmutableMap mapOf(K key1, V val1, K key2, V val2, K key3, V val3, - K key4, V val4, K key5, V val5, K key6, V val6) { - final TransientMap tmp = DefaultTrieMap.transientOf(key1, val1, key2, val2, key3, - val3, key4, val4, key5, val5, key6, val6); - return tmp.freeze(); - } - - public static ImmutableMap mapOf(Map map) { - if (map instanceof ImmutableMap) { - return (ImmutableMap) map; - } else { - final TransientMap tmp = DefaultTrieMap.transientOf(); - tmp.__putAll(map); - return tmp.freeze(); - } - } - - @Override - public V remove(Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - - @Override - public V put(K key, V value) { - throw new UnsupportedOperationException(); - } - - @Override - public void putAll(Map m) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isEmpty() { - return size() == 0; - } - - @Override - public boolean equals(Object other) { - if (other == this) - return true; - if (other == null) - return false; - - if (other instanceof Map) { - try { - @SuppressWarnings("unchecked") - Map that = (Map) other; - - if (this.size() == that.size()) { - for (Entry e : this.entrySet()) { - if (!that.containsKey(e.getKey())) - return false; - if (!Objects.equals(e.getValue(), that.get(e.getKey()))) - return false; - } - return true; - } - } catch (ClassCastException unused) { - return false; - } - } - - return false; - } - - @Override - public Iterator valueIterator() { - return values().iterator(); - } - - @Override - public Iterator> entryIterator() { - return entrySet().iterator(); - } - - @Override - public ImmutableMap __putAll(Map map) { - TransientMap tmp = asTransient(); - if (tmp.__putAll(map)) { - return tmp.freeze(); - } else { - return this; - } - } - - @Override - public ImmutableMap __putAllEquivalent(Map map, - Comparator cmp) { - TransientMap tmp = asTransient(); - if (tmp.__putAllEquivalent(map, cmp)) { - return tmp.freeze(); - } else { - return this; - } - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - @Override - public boolean isTransientSupported() { - return true; - } -} - -class MapEntry implements Map.Entry { - - private final K key1; - private final V val1; - - MapEntry(final K key1, final V val1) { - this.key1 = key1; - this.val1 = val1; - } - - @Override - public K getKey() { - return key1; - } - - @Override - public V getValue() { - return val1; - } - - @Override - public V setValue(V value) { - throw new UnsupportedOperationException(); - } - -} - -class Map0 extends AbstractSpecialisedImmutableMap { - - Map0() { - - } - - @Override - public boolean containsKey(Object key) { - return false; - } - - @Override - public boolean containsKeyEquivalent(Object key, Comparator cmp) { - return false; - } - - @Override - public boolean containsValue(Object val) { - return false; - } - - @Override - public boolean containsValueEquivalent(Object val, Comparator cmp) { - return false; - } - - @Override - public V get(Object key) { - return null; - } - - @Override - public V getEquivalent(Object key, Comparator cmp) { - return null; - } - - @Override - public int size() { - return 0; - } - - @Override - public Set> entrySet() { - return Collections.emptySet(); - } - - @Override - public Set keySet() { - return Collections.emptySet(); - } - - @Override - public Collection values() { - return Collections.emptySet(); - } - - @Override - public SupplierIterator keyIterator() { - return EmptySupplierIterator.emptyIterator(); - } - - @Override - public ImmutableMap __put(K key, V val) { - return mapOf(key, val); - } - - @Override - public ImmutableMap __putEquivalent(K key, V val, Comparator cmp) { - return mapOf(key, val); - } - - @Override - public ImmutableMap __remove(K key) { - return this; - } - - @Override - public ImmutableMap __removeEquivalent(K key, Comparator cmp) { - return this; - } - - @Override - public TransientMap asTransient() { - return DefaultTrieMap.transientOf(); - } - - @Override - public int hashCode() { - return 0; - } - - @Override - public String toString() { - return "{}"; - } - -} - -class Map1 extends AbstractSpecialisedImmutableMap { - - private final K key1; - private final V val1; - - Map1(final K key1, final V val1) { - this.key1 = key1; - this.val1 = val1; - } - - @Override - public boolean containsKey(Object key) { - if (key.equals(key1)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsKeyEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsValue(Object val) { - if (val.equals(val1)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsValueEquivalent(Object val, Comparator cmp) { - if (cmp.compare(val, val1) == 0) { - return true; - } else { - return false; - } - } - - @Override - public V get(Object key) { - if (key.equals(key1)) { - return val1; - } else { - return null; - } - } - - @Override - public V getEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return val1; - } else { - return null; - } - } - - @Override - public int size() { - return 1; - } - - @Override - public Set> entrySet() { - return Collections.singleton(entryOf(key1, val1)); - } - - @Override - public Set keySet() { - return Collections.singleton(key1); - } - - @Override - public Collection values() { - return Collections.singleton(val1); - } - - @Override - public SupplierIterator keyIterator() { - return new SupplierIterator() { - int cursor = 1; - boolean hasGet; - - @Override - public boolean hasNext() { - return cursor <= Map1.this.size(); - } - - @Override - public K next() { - switch (cursor++) { - case 1: - return key1; - default: - throw new IllegalStateException(); - } - } - - @Override - public V get() { - if (hasGet) { - hasGet = false; - - switch (cursor) { - case 1: - return val1; - default: - throw new IllegalStateException(); - } - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public ImmutableMap __put(K key, V val) { - if (key.equals(key1)) { - return mapOf(key, val); - } else { - return mapOf(key1, val1, key, val); - } - } - - @Override - public ImmutableMap __putEquivalent(K key, V val, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return mapOf(key, val); - } else { - return mapOf(key1, val1, key, val); - } - } - - @Override - public ImmutableMap __remove(K key) { - if (key.equals(key1)) { - return mapOf(); - } else { - return this; - } - } - - @Override - public ImmutableMap __removeEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return mapOf(); - } else { - return this; - } - } - - @Override - public TransientMap asTransient() { - return DefaultTrieMap.transientOf(key1, val1); - } - - @Override - public int hashCode() { - return ((Objects.hashCode(key1) ^ Objects.hashCode(val1))); - } - - @Override - public String toString() { - return String.format("{%s=%s}", key1, val1); - } - -} - -class Map2 extends AbstractSpecialisedImmutableMap { - - private final K key1; - private final V val1; - - private final K key2; - private final V val2; - - Map2(final K key1, final V val1, final K key2, final V val2) { - if (key1.equals(key2)) { - throw new IllegalArgumentException("Duplicate keys are not allowed in specialised map."); - } - - this.key1 = key1; - this.val1 = val1; - - this.key2 = key2; - this.val2 = val2; - } - - @Override - public boolean containsKey(Object key) { - if (key.equals(key1)) { - return true; - } else if (key.equals(key2)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsKeyEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return true; - } else if (cmp.compare(key, key2) == 0) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsValue(Object val) { - if (val.equals(val1)) { - return true; - } else if (val.equals(val2)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsValueEquivalent(Object val, Comparator cmp) { - if (cmp.compare(val, val1) == 0) { - return true; - } else if (cmp.compare(val, val2) == 0) { - return true; - } else { - return false; - } - } - - @Override - public V get(Object key) { - if (key.equals(key1)) { - return val1; - } else if (key.equals(key2)) { - return val2; - } else { - return null; - } - } - - @Override - public V getEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return val1; - } else if (cmp.compare(key, key2) == 0) { - return val2; - } else { - return null; - } - } - - @Override - public int size() { - return 2; - } - - @Override - public Set> entrySet() { - return AbstractSpecialisedImmutableSet.> setOf(entryOf(key1, val1), - entryOf(key2, val2)); - } - - @Override - public Set keySet() { - return AbstractSpecialisedImmutableSet.setOf(key1, key2); - } - - @Override - public Collection values() { - // TODO: will fail if two values are equals; return listOf(...) - return AbstractSpecialisedImmutableSet.setOf(val1, val2); - } - - @Override - public SupplierIterator keyIterator() { - return new SupplierIterator() { - int cursor = 1; - boolean hasGet; - - @Override - public boolean hasNext() { - return cursor <= Map2.this.size(); - } - - @Override - public K next() { - switch (cursor++) { - case 1: - return key1; - case 2: - return key2; - default: - throw new IllegalStateException(); - } - } - - @Override - public V get() { - if (hasGet) { - hasGet = false; - - switch (cursor) { - case 1: - return val1; - case 2: - return val2; - default: - throw new IllegalStateException(); - } - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public ImmutableMap __put(K key, V val) { - if (key.equals(key1)) { - return mapOf(key, val, key2, val2); - } else if (key.equals(key2)) { - return mapOf(key1, val1, key, val); - } else { - return mapOf(key1, val1, key2, val2, key, val); - } - } - - @Override - public ImmutableMap __putEquivalent(K key, V val, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return mapOf(key, val, key2, val2); - } else if (cmp.compare(key, key2) == 0) { - return mapOf(key1, val1, key, val); - } else { - return mapOf(key1, val1, key2, val2, key, val); - } - } - - @Override - public ImmutableMap __remove(K key) { - if (key.equals(key1)) { - return mapOf(key2, val2); - } else if (key.equals(key2)) { - return mapOf(key1, val1); - } else { - return this; - } - } - - @Override - public ImmutableMap __removeEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return mapOf(key2, val2); - } else if (cmp.compare(key, key2) == 0) { - return mapOf(key1, val1); - } else { - return this; - } - } - - @Override - public TransientMap asTransient() { - return DefaultTrieMap.transientOf(key1, val1, key2, val2); - } - - @Override - public int hashCode() { - return ((Objects.hashCode(key1) ^ Objects.hashCode(val1)) + (Objects.hashCode(key2) ^ Objects - .hashCode(val2))); - } - - @Override - public String toString() { - return String.format("{%s=%s, %s=%s}", key1, val1, key2, val2); - } - -} - -class Map3 extends AbstractSpecialisedImmutableMap { - - private final K key1; - private final V val1; - - private final K key2; - private final V val2; - - private final K key3; - private final V val3; - - Map3(final K key1, final V val1, final K key2, final V val2, final K key3, final V val3) { - if (key1.equals(key2) || key1.equals(key3) || key2.equals(key3)) { - throw new IllegalArgumentException("Duplicate keys are not allowed in specialised map."); - } - - this.key1 = key1; - this.val1 = val1; - - this.key2 = key2; - this.val2 = val2; - - this.key3 = key3; - this.val3 = val3; - } - - @Override - public boolean containsKey(Object key) { - if (key.equals(key1)) { - return true; - } else if (key.equals(key2)) { - return true; - } else if (key.equals(key3)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsKeyEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return true; - } else if (cmp.compare(key, key2) == 0) { - return true; - } else if (cmp.compare(key, key3) == 0) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsValue(Object val) { - if (val.equals(val1)) { - return true; - } else if (val.equals(val2)) { - return true; - } else if (val.equals(val3)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsValueEquivalent(Object val, Comparator cmp) { - if (cmp.compare(val, val1) == 0) { - return true; - } else if (cmp.compare(val, val2) == 0) { - return true; - } else if (cmp.compare(val, val3) == 0) { - return true; - } else { - return false; - } - } - - @Override - public V get(Object key) { - if (key.equals(key1)) { - return val1; - } else if (key.equals(key2)) { - return val2; - } else if (key.equals(key3)) { - return val3; - } else { - return null; - } - } - - @Override - public V getEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return val1; - } else if (cmp.compare(key, key2) == 0) { - return val2; - } else if (cmp.compare(key, key3) == 0) { - return val3; - } else { - return null; - } - } - - @Override - public int size() { - return 3; - } - - @Override - public Set> entrySet() { - return AbstractSpecialisedImmutableSet.> setOf(entryOf(key1, val1), - entryOf(key2, val2), entryOf(key3, val3)); - } - - @Override - public Set keySet() { - return AbstractSpecialisedImmutableSet.setOf(key1, key2, key3); - } - - @Override - public Collection values() { - // TODO: will fail if two values are equals; return listOf(...) - return AbstractSpecialisedImmutableSet.setOf(val1, val2, val3); - } - - @Override - public SupplierIterator keyIterator() { - return new SupplierIterator() { - int cursor = 1; - boolean hasGet; - - @Override - public boolean hasNext() { - return cursor <= Map3.this.size(); - } - - @Override - public K next() { - switch (cursor++) { - case 1: - return key1; - case 2: - return key2; - case 3: - return key3; - default: - throw new IllegalStateException(); - } - } - - @Override - public V get() { - if (hasGet) { - hasGet = false; - - switch (cursor) { - case 1: - return val1; - case 2: - return val2; - case 3: - return val3; - default: - throw new IllegalStateException(); - } - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public ImmutableMap __put(K key, V val) { - if (key.equals(key1)) { - return mapOf(key, val, key2, val2, key3, val3); - } else if (key.equals(key2)) { - return mapOf(key1, val1, key, val, key3, val3); - } else if (key.equals(key3)) { - return mapOf(key1, val1, key2, val2, key, val); - } else { - return mapOf(key1, val1, key2, val2, key3, val3, key, val); - } - } - - @Override - public ImmutableMap __putEquivalent(K key, V val, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return mapOf(key, val, key2, val2, key3, val3); - } else if (cmp.compare(key, key2) == 0) { - return mapOf(key1, val1, key, val, key3, val3); - } else if (cmp.compare(key, key3) == 0) { - return mapOf(key1, val1, key2, val2, key, val); - } else { - return mapOf(key1, val1, key2, val2, key3, val3, key, val); - } - } - - @Override - public ImmutableMap __remove(K key) { - if (key.equals(key1)) { - return mapOf(key2, val2, key3, val3); - } else if (key.equals(key2)) { - return mapOf(key1, val1, key3, val3); - } else if (key.equals(key3)) { - return mapOf(key1, val1, key2, val2); - } else { - return this; - } - } - - @Override - public ImmutableMap __removeEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return mapOf(key2, val2, key3, val3); - } else if (cmp.compare(key, key2) == 0) { - return mapOf(key1, val1, key3, val3); - } else if (cmp.compare(key, key3) == 0) { - return mapOf(key1, val1, key2, val2); - } else { - return this; - } - } - - @Override - public TransientMap asTransient() { - return DefaultTrieMap.transientOf(key1, val1, key2, val2, key3, val3); - } - - @Override - public int hashCode() { - return ((Objects.hashCode(key1) ^ Objects.hashCode(val1)) - + (Objects.hashCode(key2) ^ Objects.hashCode(val2)) + (Objects - .hashCode(key3) ^ Objects.hashCode(val3))); - } - - @Override - public String toString() { - return String.format("{%s=%s, %s=%s, %s=%s}", key1, val1, key2, val2, key3, val3); - } - -} - -class Map4 extends AbstractSpecialisedImmutableMap { - - private final K key1; - private final V val1; - - private final K key2; - private final V val2; - - private final K key3; - private final V val3; - - private final K key4; - private final V val4; - - Map4(final K key1, final V val1, final K key2, final V val2, final K key3, final V val3, - final K key4, final V val4) { - if (key1.equals(key2) || key1.equals(key3) || key1.equals(key4) || key2.equals(key3) - || key2.equals(key4) || key3.equals(key4)) { - throw new IllegalArgumentException("Duplicate keys are not allowed in specialised map."); - } - - this.key1 = key1; - this.val1 = val1; - - this.key2 = key2; - this.val2 = val2; - - this.key3 = key3; - this.val3 = val3; - - this.key4 = key4; - this.val4 = val4; - } - - @Override - public boolean containsKey(Object key) { - if (key.equals(key1)) { - return true; - } else if (key.equals(key2)) { - return true; - } else if (key.equals(key3)) { - return true; - } else if (key.equals(key4)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsKeyEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return true; - } else if (cmp.compare(key, key2) == 0) { - return true; - } else if (cmp.compare(key, key3) == 0) { - return true; - } else if (cmp.compare(key, key4) == 0) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsValue(Object val) { - if (val.equals(val1)) { - return true; - } else if (val.equals(val2)) { - return true; - } else if (val.equals(val3)) { - return true; - } else if (val.equals(val4)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsValueEquivalent(Object val, Comparator cmp) { - if (cmp.compare(val, val1) == 0) { - return true; - } else if (cmp.compare(val, val2) == 0) { - return true; - } else if (cmp.compare(val, val3) == 0) { - return true; - } else if (cmp.compare(val, val4) == 0) { - return true; - } else { - return false; - } - } - - @Override - public V get(Object key) { - if (key.equals(key1)) { - return val1; - } else if (key.equals(key2)) { - return val2; - } else if (key.equals(key3)) { - return val3; - } else if (key.equals(key4)) { - return val4; - } else { - return null; - } - } - - @Override - public V getEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return val1; - } else if (cmp.compare(key, key2) == 0) { - return val2; - } else if (cmp.compare(key, key3) == 0) { - return val3; - } else if (cmp.compare(key, key4) == 0) { - return val4; - } else { - return null; - } - } - - @Override - public int size() { - return 4; - } - - @Override - public Set> entrySet() { - return AbstractSpecialisedImmutableSet.> setOf(entryOf(key1, val1), - entryOf(key2, val2), entryOf(key3, val3), entryOf(key4, val4)); - } - - @Override - public Set keySet() { - return AbstractSpecialisedImmutableSet.setOf(key1, key2, key3, key4); - } - - @Override - public Collection values() { - // TODO: will fail if two values are equals; return listOf(...) - return AbstractSpecialisedImmutableSet.setOf(val1, val2, val3, val4); - } - - @Override - public SupplierIterator keyIterator() { - return new SupplierIterator() { - int cursor = 1; - boolean hasGet; - - @Override - public boolean hasNext() { - return cursor <= Map4.this.size(); - } - - @Override - public K next() { - switch (cursor++) { - case 1: - return key1; - case 2: - return key2; - case 3: - return key3; - case 4: - return key4; - default: - throw new IllegalStateException(); - } - } - - @Override - public V get() { - if (hasGet) { - hasGet = false; - - switch (cursor) { - case 1: - return val1; - case 2: - return val2; - case 3: - return val3; - case 4: - return val4; - default: - throw new IllegalStateException(); - } - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public ImmutableMap __put(K key, V val) { - if (key.equals(key1)) { - return mapOf(key, val, key2, val2, key3, val3, key4, val4); - } else if (key.equals(key2)) { - return mapOf(key1, val1, key, val, key3, val3, key4, val4); - } else if (key.equals(key3)) { - return mapOf(key1, val1, key2, val2, key, val, key4, val4); - } else if (key.equals(key4)) { - return mapOf(key1, val1, key2, val2, key3, val3, key, val); - } else { - return mapOf(key1, val1, key2, val2, key3, val3, key4, val4, key, val); - } - } - - @Override - public ImmutableMap __putEquivalent(K key, V val, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return mapOf(key, val, key2, val2, key3, val3, key4, val4); - } else if (cmp.compare(key, key2) == 0) { - return mapOf(key1, val1, key, val, key3, val3, key4, val4); - } else if (cmp.compare(key, key3) == 0) { - return mapOf(key1, val1, key2, val2, key, val, key4, val4); - } else if (cmp.compare(key, key4) == 0) { - return mapOf(key1, val1, key2, val2, key3, val3, key, val); - } else { - return mapOf(key1, val1, key2, val2, key3, val3, key4, val4, key, val); - } - } - - @Override - public ImmutableMap __remove(K key) { - if (key.equals(key1)) { - return mapOf(key2, val2, key3, val3, key4, val4); - } else if (key.equals(key2)) { - return mapOf(key1, val1, key3, val3, key4, val4); - } else if (key.equals(key3)) { - return mapOf(key1, val1, key2, val2, key4, val4); - } else if (key.equals(key4)) { - return mapOf(key1, val1, key2, val2, key3, val3); - } else { - return this; - } - } - - @Override - public ImmutableMap __removeEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return mapOf(key2, val2, key3, val3, key4, val4); - } else if (cmp.compare(key, key2) == 0) { - return mapOf(key1, val1, key3, val3, key4, val4); - } else if (cmp.compare(key, key3) == 0) { - return mapOf(key1, val1, key2, val2, key4, val4); - } else if (cmp.compare(key, key4) == 0) { - return mapOf(key1, val1, key2, val2, key3, val3); - } else { - return this; - } - } - - @Override - public TransientMap asTransient() { - return DefaultTrieMap.transientOf(key1, val1, key2, val2, key3, val3, key4, val4); - } - - @Override - public int hashCode() { - return ((Objects.hashCode(key1) ^ Objects.hashCode(val1)) - + (Objects.hashCode(key2) ^ Objects.hashCode(val2)) - + (Objects.hashCode(key3) ^ Objects.hashCode(val3)) + (Objects - .hashCode(key4) ^ Objects.hashCode(val4))); - } - - @Override - public String toString() { - return String.format("{%s=%s, %s=%s, %s=%s, %s=%s}", key1, val1, key2, val2, key3, val3, - key4, val4); - } - -} - -class Map5 extends AbstractSpecialisedImmutableMap { - - private final K key1; - private final V val1; - - private final K key2; - private final V val2; - - private final K key3; - private final V val3; - - private final K key4; - private final V val4; - - private final K key5; - private final V val5; - - Map5(final K key1, final V val1, final K key2, final V val2, final K key3, final V val3, - final K key4, final V val4, final K key5, final V val5) { - if (key1.equals(key2) || key1.equals(key3) || key1.equals(key4) || key1.equals(key5) - || key2.equals(key3) || key2.equals(key4) || key2.equals(key5) - || key3.equals(key4) || key3.equals(key5) || key4.equals(key5)) { - throw new IllegalArgumentException("Duplicate keys are not allowed in specialised map."); - } - - this.key1 = key1; - this.val1 = val1; - - this.key2 = key2; - this.val2 = val2; - - this.key3 = key3; - this.val3 = val3; - - this.key4 = key4; - this.val4 = val4; - - this.key5 = key5; - this.val5 = val5; - } - - @Override - public boolean containsKey(Object key) { - if (key.equals(key1)) { - return true; - } else if (key.equals(key2)) { - return true; - } else if (key.equals(key3)) { - return true; - } else if (key.equals(key4)) { - return true; - } else if (key.equals(key5)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsKeyEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return true; - } else if (cmp.compare(key, key2) == 0) { - return true; - } else if (cmp.compare(key, key3) == 0) { - return true; - } else if (cmp.compare(key, key4) == 0) { - return true; - } else if (cmp.compare(key, key5) == 0) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsValue(Object val) { - if (val.equals(val1)) { - return true; - } else if (val.equals(val2)) { - return true; - } else if (val.equals(val3)) { - return true; - } else if (val.equals(val4)) { - return true; - } else if (val.equals(val5)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsValueEquivalent(Object val, Comparator cmp) { - if (cmp.compare(val, val1) == 0) { - return true; - } else if (cmp.compare(val, val2) == 0) { - return true; - } else if (cmp.compare(val, val3) == 0) { - return true; - } else if (cmp.compare(val, val4) == 0) { - return true; - } else if (cmp.compare(val, val5) == 0) { - return true; - } else { - return false; - } - } - - @Override - public V get(Object key) { - if (key.equals(key1)) { - return val1; - } else if (key.equals(key2)) { - return val2; - } else if (key.equals(key3)) { - return val3; - } else if (key.equals(key4)) { - return val4; - } else if (key.equals(key5)) { - return val5; - } else { - return null; - } - } - - @Override - public V getEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return val1; - } else if (cmp.compare(key, key2) == 0) { - return val2; - } else if (cmp.compare(key, key3) == 0) { - return val3; - } else if (cmp.compare(key, key4) == 0) { - return val4; - } else if (cmp.compare(key, key5) == 0) { - return val5; - } else { - return null; - } - } - - @Override - public int size() { - return 5; - } - - @Override - public Set> entrySet() { - return AbstractSpecialisedImmutableSet.> setOf(entryOf(key1, val1), - entryOf(key2, val2), entryOf(key3, val3), entryOf(key4, val4), - entryOf(key5, val5)); - } - - @Override - public Set keySet() { - return AbstractSpecialisedImmutableSet.setOf(key1, key2, key3, key4, key5); - } - - @Override - public Collection values() { - // TODO: will fail if two values are equals; return listOf(...) - return AbstractSpecialisedImmutableSet.setOf(val1, val2, val3, val4, val5); - } - - @Override - public SupplierIterator keyIterator() { - return new SupplierIterator() { - int cursor = 1; - boolean hasGet; - - @Override - public boolean hasNext() { - return cursor <= Map5.this.size(); - } - - @Override - public K next() { - switch (cursor++) { - case 1: - return key1; - case 2: - return key2; - case 3: - return key3; - case 4: - return key4; - case 5: - return key5; - default: - throw new IllegalStateException(); - } - } - - @Override - public V get() { - if (hasGet) { - hasGet = false; - - switch (cursor) { - case 1: - return val1; - case 2: - return val2; - case 3: - return val3; - case 4: - return val4; - case 5: - return val5; - default: - throw new IllegalStateException(); - } - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public ImmutableMap __put(K key, V val) { - if (key.equals(key1)) { - return mapOf(key, val, key2, val2, key3, val3, key4, val4, key5, val5); - } else if (key.equals(key2)) { - return mapOf(key1, val1, key, val, key3, val3, key4, val4, key5, val5); - } else if (key.equals(key3)) { - return mapOf(key1, val1, key2, val2, key, val, key4, val4, key5, val5); - } else if (key.equals(key4)) { - return mapOf(key1, val1, key2, val2, key3, val3, key, val, key5, val5); - } else if (key.equals(key5)) { - return mapOf(key1, val1, key2, val2, key3, val3, key4, val4, key, val); - } else { - return mapOf(key1, val1, key2, val2, key3, val3, key4, val4, key5, val5, key, val); - } - } - - @Override - public ImmutableMap __putEquivalent(K key, V val, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return mapOf(key, val, key2, val2, key3, val3, key4, val4, key5, val5); - } else if (cmp.compare(key, key2) == 0) { - return mapOf(key1, val1, key, val, key3, val3, key4, val4, key5, val5); - } else if (cmp.compare(key, key3) == 0) { - return mapOf(key1, val1, key2, val2, key, val, key4, val4, key5, val5); - } else if (cmp.compare(key, key4) == 0) { - return mapOf(key1, val1, key2, val2, key3, val3, key, val, key5, val5); - } else if (cmp.compare(key, key5) == 0) { - return mapOf(key1, val1, key2, val2, key3, val3, key4, val4, key, val); - } else { - return mapOf(key1, val1, key2, val2, key3, val3, key4, val4, key5, val5, key, val); - } - } - - @Override - public ImmutableMap __remove(K key) { - if (key.equals(key1)) { - return mapOf(key2, val2, key3, val3, key4, val4, key5, val5); - } else if (key.equals(key2)) { - return mapOf(key1, val1, key3, val3, key4, val4, key5, val5); - } else if (key.equals(key3)) { - return mapOf(key1, val1, key2, val2, key4, val4, key5, val5); - } else if (key.equals(key4)) { - return mapOf(key1, val1, key2, val2, key3, val3, key5, val5); - } else if (key.equals(key5)) { - return mapOf(key1, val1, key2, val2, key3, val3, key4, val4); - } else { - return this; - } - } - - @Override - public ImmutableMap __removeEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return mapOf(key2, val2, key3, val3, key4, val4, key5, val5); - } else if (cmp.compare(key, key2) == 0) { - return mapOf(key1, val1, key3, val3, key4, val4, key5, val5); - } else if (cmp.compare(key, key3) == 0) { - return mapOf(key1, val1, key2, val2, key4, val4, key5, val5); - } else if (cmp.compare(key, key4) == 0) { - return mapOf(key1, val1, key2, val2, key3, val3, key5, val5); - } else if (cmp.compare(key, key5) == 0) { - return mapOf(key1, val1, key2, val2, key3, val3, key4, val4); - } else { - return this; - } - } - - @Override - public TransientMap asTransient() { - return DefaultTrieMap.transientOf(key1, val1, key2, val2, key3, val3, key4, val4, key5, - val5); - } - - @Override - public int hashCode() { - return ((Objects.hashCode(key1) ^ Objects.hashCode(val1)) - + (Objects.hashCode(key2) ^ Objects.hashCode(val2)) - + (Objects.hashCode(key3) ^ Objects.hashCode(val3)) - + (Objects.hashCode(key4) ^ Objects.hashCode(val4)) + (Objects - .hashCode(key5) ^ Objects.hashCode(val5))); - } - - @Override - public String toString() { - return String.format("{%s=%s, %s=%s, %s=%s, %s=%s, %s=%s}", key1, val1, key2, val2, key3, - val3, key4, val4, key5, val5); - } - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/AbstractSpecialisedImmutableSet.java b/capsule/src/main/java/io/usethesource/capsule/AbstractSpecialisedImmutableSet.java deleted file mode 100644 index e9367199d..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/AbstractSpecialisedImmutableSet.java +++ /dev/null @@ -1,1269 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.Set; - -public abstract class AbstractSpecialisedImmutableSet extends AbstractImmutableSet implements - ImmutableSet, Cloneable { - - @SuppressWarnings("rawtypes") - private static ImmutableSet EMPTY_SET = new Set0(); - - @SuppressWarnings("unchecked") - public static ImmutableSet setOf() { - return EMPTY_SET; - } - - public static ImmutableSet setOf(K key1) { - return new Set1(key1); - } - - public static ImmutableSet setOf(K key1, K key2) { - return new Set2(key1, key2); - } - - public static ImmutableSet setOf(K key1, K key2, K key3) { - return new Set3(key1, key2, key3); - } - - public static ImmutableSet setOf(K key1, K key2, K key3, K key4) { - return new Set4(key1, key2, key3, key4); - } - - public static ImmutableSet setOf(K key1, K key2, K key3, K key4, K key5) { - return new Set5(key1, key2, key3, key4, key5); - } - - public static ImmutableSet setOf(K key1, K key2, K key3, K key4, K key5, K key6) { - final TransientSet tmp = DefaultTrieSet.transientOf(key1, key2, key3, key4, key5, key6); - return tmp.freeze(); - } - - public static ImmutableSet setOf(Set set) { - if (set instanceof AbstractSpecialisedImmutableSet) { - return (ImmutableSet) set; - } else { - final TransientSet tmp = DefaultTrieSet.transientOf(); - // TODO check interface definition of ImmutableSet.__insertAll() - for (K item : set) { - tmp.__insert(item); - } - return tmp.freeze(); - } - } - - @Override - public boolean add(K k) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean remove(Object o) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addAll(Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean removeAll(Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean retainAll(Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isEmpty() { - return size() == 0; - } - - @Override - public Iterator iterator() { - return keyIterator(); - } - - @Override - public boolean equals(Object other) { - if (other == this) - return true; - if (other == null) - return false; - - if (other instanceof Set) { - try { - @SuppressWarnings("unchecked") - Set that = (Set) other; - - if (this.size() == that.size()) { - for (K e : this) - if (!that.contains(e)) - return false; - return true; - } - } catch (ClassCastException unused) { - return false; - } - } - - return false; - } - - @Override - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - - @Override - public boolean isTransientSupported() { - return true; - } - - @Override - public ImmutableSet __insertAll(Set set) { - TransientSet tmp = asTransient(); - if (tmp.__insertAll(set)) { - return tmp.freeze(); - } else { - return this; - } - } - - @Override - public ImmutableSet __insertAllEquivalent(Set set, Comparator cmp) { - TransientSet tmp = asTransient(); - if (tmp.__insertAllEquivalent(set, cmp)) { - return tmp.freeze(); - } else { - return this; - } - } - - @Override - public ImmutableSet __retainAll(Set set) { - TransientSet tmp = asTransient(); - if (tmp.__retainAll(set)) { - return tmp.freeze(); - } else { - return this; - } - } - - @Override - public ImmutableSet __retainAllEquivalent(TransientSet set, - Comparator cmp) { - TransientSet tmp = asTransient(); - if (tmp.__retainAllEquivalent(set, cmp)) { - return tmp.freeze(); - } else { - return this; - } - } - - @Override - public ImmutableSet __removeAll(Set set) { - TransientSet tmp = asTransient(); - if (tmp.__removeAll(set)) { - return tmp.freeze(); - } else { - return this; - } - } - - @Override - public ImmutableSet __removeAllEquivalent(Set set, Comparator cmp) { - TransientSet tmp = asTransient(); - if (tmp.__removeAllEquivalent(set, cmp)) { - return tmp.freeze(); - } else { - return this; - } - } -} - -class Set0 extends AbstractSpecialisedImmutableSet { - - Set0() { - - } - - @Override - public boolean contains(Object key) { - return false; - } - - @Override - public boolean containsEquivalent(Object key, Comparator cmp) { - return false; - } - - @Override - public K get(Object key) { - return null; - } - - @Override - public K getEquivalent(Object key, Comparator cmp) { - return null; - } - - @Override - public int size() { - return 0; - } - - @Override - public SupplierIterator keyIterator() { - return EmptySupplierIterator.emptyIterator(); - } - - @Override - public ImmutableSet __insert(K key) { - return setOf(key); - } - - @Override - public ImmutableSet __insertEquivalent(K key, Comparator cmp) { - return setOf(key); - } - - @Override - public ImmutableSet __remove(K key) { - return this; - } - - @Override - public ImmutableSet __removeEquivalent(K key, Comparator cmp) { - return this; - } - - @Override - public TransientSet asTransient() { - return DefaultTrieSet.transientOf(); - } - - @Override - public int hashCode() { - return 0; - } - - @Override - public String toString() { - return "{}"; - } - -} - -class Set1 extends AbstractSpecialisedImmutableSet { - - private final K key1; - - Set1(final K key1) { - this.key1 = key1; - } - - @Override - public boolean contains(Object key) { - if (key.equals(key1)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return true; - } else { - return false; - } - } - - @Override - public K get(Object key) { - if (key.equals(key1)) { - return key1; - } else { - return null; - } - } - - @Override - public K getEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return key1; - } else { - return null; - } - } - - @Override - public int size() { - return 1; - } - - @Override - public SupplierIterator keyIterator() { - return new SupplierIterator() { - int cursor = 1; - boolean hasGet; - - @Override - public boolean hasNext() { - return cursor <= Set1.this.size(); - } - - @Override - public K next() { - switch (cursor++) { - case 1: - return key1; - default: - throw new IllegalStateException(); - } - } - - @Override - public K get() { - if (hasGet) { - hasGet = false; - - switch (cursor) { - case 1: - return key1; - default: - throw new IllegalStateException(); - } - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public ImmutableSet __insert(K key) { - if (key.equals(key1)) { - return setOf(key); - } else { - return setOf(key1, key); - } - } - - @Override - public ImmutableSet __insertEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return setOf(key); - } else { - return setOf(key1, key); - } - } - - @Override - public ImmutableSet __remove(K key) { - if (key.equals(key1)) { - return setOf(); - } else { - return this; - } - } - - @Override - public ImmutableSet __removeEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return setOf(); - } else { - return this; - } - } - - @Override - public TransientSet asTransient() { - return DefaultTrieSet.transientOf(key1); - } - - @Override - public int hashCode() { - return Objects.hashCode(key1); - } - - @Override - public String toString() { - return String.format("{%s}", key1); - } - -} - -class Set2 extends AbstractSpecialisedImmutableSet { - - private final K key1; - private final K key2; - - Set2(final K key1, final K key2) { - if (key1.equals(key2)) { - throw new IllegalArgumentException( - "Duplicate elements are not allowed in specialised set."); - } - - this.key1 = key1; - - this.key2 = key2; - } - - @Override - public boolean contains(Object key) { - if (key.equals(key1)) { - return true; - } else if (key.equals(key2)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return true; - } else if (cmp.compare(key, key2) == 0) { - return true; - } else { - return false; - } - } - - @Override - public K get(Object key) { - if (key.equals(key1)) { - return key1; - } else if (key.equals(key2)) { - return key2; - } else { - return null; - } - } - - @Override - public K getEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return key1; - } else if (cmp.compare(key, key2) == 0) { - return key2; - } else { - return null; - } - } - - @Override - public int size() { - return 2; - } - - @Override - public SupplierIterator keyIterator() { - return new SupplierIterator() { - int cursor = 1; - boolean hasGet; - - @Override - public boolean hasNext() { - return cursor <= Set2.this.size(); - } - - @Override - public K next() { - switch (cursor++) { - case 1: - return key1; - case 2: - return key2; - default: - throw new IllegalStateException(); - } - } - - @Override - public K get() { - if (hasGet) { - hasGet = false; - - switch (cursor) { - case 1: - return key1; - case 2: - return key2; - default: - throw new IllegalStateException(); - } - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public ImmutableSet __insert(K key) { - if (key.equals(key1)) { - return setOf(key, key2); - } else if (key.equals(key2)) { - return setOf(key1, key); - } else { - return setOf(key1, key2, key); - } - } - - @Override - public ImmutableSet __insertEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return setOf(key, key2); - } else if (cmp.compare(key, key2) == 0) { - return setOf(key1, key); - } else { - return setOf(key1, key2, key); - } - } - - @Override - public ImmutableSet __remove(K key) { - if (key.equals(key1)) { - return setOf(key2); - } else if (key.equals(key2)) { - return setOf(key1); - } else { - return this; - } - } - - @Override - public ImmutableSet __removeEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return setOf(key2); - } else if (cmp.compare(key, key2) == 0) { - return setOf(key1); - } else { - return this; - } - } - - @Override - public TransientSet asTransient() { - return DefaultTrieSet.transientOf(key1, key2); - } - - @Override - public int hashCode() { - return Objects.hashCode(key1) + Objects.hashCode(key2); - } - - @Override - public String toString() { - return String.format("{%s, %s}", key1, key2); - } - -} - -class Set3 extends AbstractSpecialisedImmutableSet { - - private final K key1; - private final K key2; - private final K key3; - - Set3(final K key1, final K key2, final K key3) { - if (key1.equals(key2) || key1.equals(key3) || key2.equals(key3)) { - throw new IllegalArgumentException( - "Duplicate elements are not allowed in specialised set."); - } - - this.key1 = key1; - - this.key2 = key2; - - this.key3 = key3; - } - - @Override - public boolean contains(Object key) { - if (key.equals(key1)) { - return true; - } else if (key.equals(key2)) { - return true; - } else if (key.equals(key3)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return true; - } else if (cmp.compare(key, key2) == 0) { - return true; - } else if (cmp.compare(key, key3) == 0) { - return true; - } else { - return false; - } - } - - @Override - public K get(Object key) { - if (key.equals(key1)) { - return key1; - } else if (key.equals(key2)) { - return key2; - } else if (key.equals(key3)) { - return key3; - } else { - return null; - } - } - - @Override - public K getEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return key1; - } else if (cmp.compare(key, key2) == 0) { - return key2; - } else if (cmp.compare(key, key3) == 0) { - return key3; - } else { - return null; - } - } - - @Override - public int size() { - return 3; - } - - @Override - public SupplierIterator keyIterator() { - return new SupplierIterator() { - int cursor = 1; - boolean hasGet; - - @Override - public boolean hasNext() { - return cursor <= Set3.this.size(); - } - - @Override - public K next() { - switch (cursor++) { - case 1: - return key1; - case 2: - return key2; - case 3: - return key3; - default: - throw new IllegalStateException(); - } - } - - @Override - public K get() { - if (hasGet) { - hasGet = false; - - switch (cursor) { - case 1: - return key1; - case 2: - return key2; - case 3: - return key3; - default: - throw new IllegalStateException(); - } - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public ImmutableSet __insert(K key) { - if (key.equals(key1)) { - return setOf(key, key2, key3); - } else if (key.equals(key2)) { - return setOf(key1, key, key3); - } else if (key.equals(key3)) { - return setOf(key1, key2, key); - } else { - return setOf(key1, key2, key3, key); - } - } - - @Override - public ImmutableSet __insertEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return setOf(key, key2, key3); - } else if (cmp.compare(key, key2) == 0) { - return setOf(key1, key, key3); - } else if (cmp.compare(key, key3) == 0) { - return setOf(key1, key2, key); - } else { - return setOf(key1, key2, key3, key); - } - } - - @Override - public ImmutableSet __remove(K key) { - if (key.equals(key1)) { - return setOf(key2, key3); - } else if (key.equals(key2)) { - return setOf(key1, key3); - } else if (key.equals(key3)) { - return setOf(key1, key2); - } else { - return this; - } - } - - @Override - public ImmutableSet __removeEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return setOf(key2, key3); - } else if (cmp.compare(key, key2) == 0) { - return setOf(key1, key3); - } else if (cmp.compare(key, key3) == 0) { - return setOf(key1, key2); - } else { - return this; - } - } - - @Override - public TransientSet asTransient() { - return DefaultTrieSet.transientOf(key1, key2, key3); - } - - @Override - public int hashCode() { - return Objects.hashCode(key1) + Objects.hashCode(key2) + Objects.hashCode(key3); - } - - @Override - public String toString() { - return String.format("{%s, %s, %s}", key1, key2, key3); - } - -} - -class Set4 extends AbstractSpecialisedImmutableSet { - - private final K key1; - private final K key2; - private final K key3; - private final K key4; - - Set4(final K key1, final K key2, final K key3, final K key4) { - if (key1.equals(key2) || key1.equals(key3) || key1.equals(key4) || key2.equals(key3) - || key2.equals(key4) || key3.equals(key4)) { - throw new IllegalArgumentException( - "Duplicate elements are not allowed in specialised set."); - } - - this.key1 = key1; - - this.key2 = key2; - - this.key3 = key3; - - this.key4 = key4; - } - - @Override - public boolean contains(Object key) { - if (key.equals(key1)) { - return true; - } else if (key.equals(key2)) { - return true; - } else if (key.equals(key3)) { - return true; - } else if (key.equals(key4)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return true; - } else if (cmp.compare(key, key2) == 0) { - return true; - } else if (cmp.compare(key, key3) == 0) { - return true; - } else if (cmp.compare(key, key4) == 0) { - return true; - } else { - return false; - } - } - - @Override - public K get(Object key) { - if (key.equals(key1)) { - return key1; - } else if (key.equals(key2)) { - return key2; - } else if (key.equals(key3)) { - return key3; - } else if (key.equals(key4)) { - return key4; - } else { - return null; - } - } - - @Override - public K getEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return key1; - } else if (cmp.compare(key, key2) == 0) { - return key2; - } else if (cmp.compare(key, key3) == 0) { - return key3; - } else if (cmp.compare(key, key4) == 0) { - return key4; - } else { - return null; - } - } - - @Override - public int size() { - return 4; - } - - @Override - public SupplierIterator keyIterator() { - return new SupplierIterator() { - int cursor = 1; - boolean hasGet; - - @Override - public boolean hasNext() { - return cursor <= Set4.this.size(); - } - - @Override - public K next() { - switch (cursor++) { - case 1: - return key1; - case 2: - return key2; - case 3: - return key3; - case 4: - return key4; - default: - throw new IllegalStateException(); - } - } - - @Override - public K get() { - if (hasGet) { - hasGet = false; - - switch (cursor) { - case 1: - return key1; - case 2: - return key2; - case 3: - return key3; - case 4: - return key4; - default: - throw new IllegalStateException(); - } - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public ImmutableSet __insert(K key) { - if (key.equals(key1)) { - return setOf(key, key2, key3, key4); - } else if (key.equals(key2)) { - return setOf(key1, key, key3, key4); - } else if (key.equals(key3)) { - return setOf(key1, key2, key, key4); - } else if (key.equals(key4)) { - return setOf(key1, key2, key3, key); - } else { - return setOf(key1, key2, key3, key4, key); - } - } - - @Override - public ImmutableSet __insertEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return setOf(key, key2, key3, key4); - } else if (cmp.compare(key, key2) == 0) { - return setOf(key1, key, key3, key4); - } else if (cmp.compare(key, key3) == 0) { - return setOf(key1, key2, key, key4); - } else if (cmp.compare(key, key4) == 0) { - return setOf(key1, key2, key3, key); - } else { - return setOf(key1, key2, key3, key4, key); - } - } - - @Override - public ImmutableSet __remove(K key) { - if (key.equals(key1)) { - return setOf(key2, key3, key4); - } else if (key.equals(key2)) { - return setOf(key1, key3, key4); - } else if (key.equals(key3)) { - return setOf(key1, key2, key4); - } else if (key.equals(key4)) { - return setOf(key1, key2, key3); - } else { - return this; - } - } - - @Override - public ImmutableSet __removeEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return setOf(key2, key3, key4); - } else if (cmp.compare(key, key2) == 0) { - return setOf(key1, key3, key4); - } else if (cmp.compare(key, key3) == 0) { - return setOf(key1, key2, key4); - } else if (cmp.compare(key, key4) == 0) { - return setOf(key1, key2, key3); - } else { - return this; - } - } - - @Override - public TransientSet asTransient() { - return DefaultTrieSet.transientOf(key1, key2, key3, key4); - } - - @Override - public int hashCode() { - return Objects.hashCode(key1) + Objects.hashCode(key2) + Objects.hashCode(key3) - + Objects.hashCode(key4); - } - - @Override - public String toString() { - return String.format("{%s, %s, %s, %s}", key1, key2, key3, key4); - } - -} - -class Set5 extends AbstractSpecialisedImmutableSet { - - private final K key1; - private final K key2; - private final K key3; - private final K key4; - private final K key5; - - Set5(final K key1, final K key2, final K key3, final K key4, final K key5) { - if (key1.equals(key2) || key1.equals(key3) || key1.equals(key4) || key1.equals(key5) - || key2.equals(key3) || key2.equals(key4) || key2.equals(key5) - || key3.equals(key4) || key3.equals(key5) || key4.equals(key5)) { - throw new IllegalArgumentException( - "Duplicate elements are not allowed in specialised set."); - } - - this.key1 = key1; - - this.key2 = key2; - - this.key3 = key3; - - this.key4 = key4; - - this.key5 = key5; - } - - @Override - public boolean contains(Object key) { - if (key.equals(key1)) { - return true; - } else if (key.equals(key2)) { - return true; - } else if (key.equals(key3)) { - return true; - } else if (key.equals(key4)) { - return true; - } else if (key.equals(key5)) { - return true; - } else { - return false; - } - } - - @Override - public boolean containsEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return true; - } else if (cmp.compare(key, key2) == 0) { - return true; - } else if (cmp.compare(key, key3) == 0) { - return true; - } else if (cmp.compare(key, key4) == 0) { - return true; - } else if (cmp.compare(key, key5) == 0) { - return true; - } else { - return false; - } - } - - @Override - public K get(Object key) { - if (key.equals(key1)) { - return key1; - } else if (key.equals(key2)) { - return key2; - } else if (key.equals(key3)) { - return key3; - } else if (key.equals(key4)) { - return key4; - } else if (key.equals(key5)) { - return key5; - } else { - return null; - } - } - - @Override - public K getEquivalent(Object key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return key1; - } else if (cmp.compare(key, key2) == 0) { - return key2; - } else if (cmp.compare(key, key3) == 0) { - return key3; - } else if (cmp.compare(key, key4) == 0) { - return key4; - } else if (cmp.compare(key, key5) == 0) { - return key5; - } else { - return null; - } - } - - @Override - public int size() { - return 5; - } - - @Override - public SupplierIterator keyIterator() { - return new SupplierIterator() { - int cursor = 1; - boolean hasGet; - - @Override - public boolean hasNext() { - return cursor <= Set5.this.size(); - } - - @Override - public K next() { - switch (cursor++) { - case 1: - return key1; - case 2: - return key2; - case 3: - return key3; - case 4: - return key4; - case 5: - return key5; - default: - throw new IllegalStateException(); - } - } - - @Override - public K get() { - if (hasGet) { - hasGet = false; - - switch (cursor) { - case 1: - return key1; - case 2: - return key2; - case 3: - return key3; - case 4: - return key4; - case 5: - return key5; - default: - throw new IllegalStateException(); - } - } else { - throw new NoSuchElementException(); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - - } - - @Override - public ImmutableSet __insert(K key) { - if (key.equals(key1)) { - return setOf(key, key2, key3, key4, key5); - } else if (key.equals(key2)) { - return setOf(key1, key, key3, key4, key5); - } else if (key.equals(key3)) { - return setOf(key1, key2, key, key4, key5); - } else if (key.equals(key4)) { - return setOf(key1, key2, key3, key, key5); - } else if (key.equals(key5)) { - return setOf(key1, key2, key3, key4, key); - } else { - return setOf(key1, key2, key3, key4, key5, key); - } - } - - @Override - public ImmutableSet __insertEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return setOf(key, key2, key3, key4, key5); - } else if (cmp.compare(key, key2) == 0) { - return setOf(key1, key, key3, key4, key5); - } else if (cmp.compare(key, key3) == 0) { - return setOf(key1, key2, key, key4, key5); - } else if (cmp.compare(key, key4) == 0) { - return setOf(key1, key2, key3, key, key5); - } else if (cmp.compare(key, key5) == 0) { - return setOf(key1, key2, key3, key4, key); - } else { - return setOf(key1, key2, key3, key4, key5, key); - } - } - - @Override - public ImmutableSet __remove(K key) { - if (key.equals(key1)) { - return setOf(key2, key3, key4, key5); - } else if (key.equals(key2)) { - return setOf(key1, key3, key4, key5); - } else if (key.equals(key3)) { - return setOf(key1, key2, key4, key5); - } else if (key.equals(key4)) { - return setOf(key1, key2, key3, key5); - } else if (key.equals(key5)) { - return setOf(key1, key2, key3, key4); - } else { - return this; - } - } - - @Override - public ImmutableSet __removeEquivalent(K key, Comparator cmp) { - if (cmp.compare(key, key1) == 0) { - return setOf(key2, key3, key4, key5); - } else if (cmp.compare(key, key2) == 0) { - return setOf(key1, key3, key4, key5); - } else if (cmp.compare(key, key3) == 0) { - return setOf(key1, key2, key4, key5); - } else if (cmp.compare(key, key4) == 0) { - return setOf(key1, key2, key3, key5); - } else if (cmp.compare(key, key5) == 0) { - return setOf(key1, key2, key3, key4); - } else { - return this; - } - } - - @Override - public TransientSet asTransient() { - return DefaultTrieSet.transientOf(key1, key2, key3, key4, key5); - } - - @Override - public int hashCode() { - return Objects.hashCode(key1) + Objects.hashCode(key2) + Objects.hashCode(key3) - + Objects.hashCode(key4) + Objects.hashCode(key5); - } - - @Override - public String toString() { - return String.format("{%s, %s, %s, %s, %s}", key1, key2, key3, key4, key5); - } - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/ArrayIterator.java b/capsule/src/main/java/io/usethesource/capsule/ArrayIterator.java deleted file mode 100644 index d68fc26b7..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/ArrayIterator.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -public class ArrayIterator implements Iterator { - - final E[] values; - final int end; - int currentIndex; - - public ArrayIterator(final E[] values, int start, int end) { - assert start <= end && end <= values.length; - - this.values = values; - this.end = end; - this.currentIndex = start; - } - - @Override - public boolean hasNext() { - return currentIndex < end; - } - - @Override - public E next() { - if (!hasNext()) throw new NoSuchElementException(); - return values[currentIndex++]; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @SafeVarargs - public static Iterator of(E... array) { - return new ArrayIterator<>(array, 0, array.length); - } - - public static Iterator of(E[] array, int start, int length) { - return new ArrayIterator<>(array, start, start + length); - } - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/ArrayKeyValueSupplierIterator.java b/capsule/src/main/java/io/usethesource/capsule/ArrayKeyValueSupplierIterator.java deleted file mode 100644 index 5ec559df3..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/ArrayKeyValueSupplierIterator.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.NoSuchElementException; - -public class ArrayKeyValueSupplierIterator implements SupplierIterator { - - final Object[] values; - final int end; - int currentIndex; - V currentValue; - - public ArrayKeyValueSupplierIterator(final Object[] values, int start, int end) { - assert start <= end && end <= values.length; - assert (end - start) % 2 == 0; - - this.values = values; - this.end = end; - this.currentIndex = start; - } - - @Override - public boolean hasNext() { - return currentIndex < end; - } - - @SuppressWarnings("unchecked") - @Override - public K next() { - if (!hasNext()) - throw new NoSuchElementException(); - - final K currentKey = (K) values[currentIndex++]; - currentValue = (V) values[currentIndex++]; - - return currentKey; - } - - @Override - public V get() { - return currentValue; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - public static ArrayKeyValueSupplierIterator of(Object[] array) { - return new ArrayKeyValueSupplierIterator<>(array, 0, array.length); - } - - public static ArrayKeyValueSupplierIterator of(Object[] array, int start, int length) { - return new ArrayKeyValueSupplierIterator<>(array, start, start + length); - } - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/ArraySupplierIterator.java b/capsule/src/main/java/io/usethesource/capsule/ArraySupplierIterator.java deleted file mode 100644 index c36f05912..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/ArraySupplierIterator.java +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.NoSuchElementException; - -public class ArraySupplierIterator implements SupplierIterator { - - final Object[] values; - final int end; - int currentIndex; - E currentElement; - - public ArraySupplierIterator(final Object[] values, int start, int end) { - assert start <= end && end <= values.length; - - this.values = values; - this.end = end; - this.currentIndex = start; - } - - @Override - public boolean hasNext() { - return currentIndex < end; - } - - @SuppressWarnings("unchecked") - @Override - public E next() { - if (!hasNext()) - throw new NoSuchElementException(); - - currentElement = (E) values[currentIndex++]; - return currentElement; - } - - @Override - public E get() { - return currentElement; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - public static SupplierIterator of(Object[] array) { - return new ArraySupplierIterator<>(array, 0, array.length); - } - - public static SupplierIterator of(Object[] array, int start, int length) { - return new ArraySupplierIterator<>(array, start, start + length); - } - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/ArrayUtils.java b/capsule/src/main/java/io/usethesource/capsule/ArrayUtils.java deleted file mode 100644 index bf8d24a0a..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/ArrayUtils.java +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -public class ArrayUtils { - - public static boolean equals(Object[] a1, Object[] a2) { - if (null == a1 || null == a2) { - return false; - } - if (a1 == a2) { - return true; - } - - int length = a1.length; - if (length != a2.length) { - return false; - } - - for (int i = 0; i < length; i++) { - Object o1 = a1[i]; - Object o2 = a2[i]; - - boolean areEqual = (o1 == o2) || (o1 != null && o1.equals(o2)); - - if (!areEqual) { - return false; - } - } - - return true; - } - - @Deprecated - public static Object[] copyAndSet(Object[] array, int index, Object elementNew) { - final Object[] arrayNew = new Object[array.length]; - System.arraycopy(array, 0, arrayNew, 0, array.length); - arrayNew[index] = elementNew; - return arrayNew; - } - - public static Object[] copyAndMoveToBack(Object[] array, int indexOld, int indexNew, Object elementNew) { - assert indexOld <= indexNew; - if (indexNew == indexOld) { - return copyAndSet(array, indexNew, elementNew); - } else { - final Object[] arrayNew = new Object[array.length]; - System.arraycopy(array, 0, arrayNew, 0, indexOld); - System.arraycopy(array, indexOld + 1, arrayNew, indexOld, indexNew - indexOld); - arrayNew[indexNew] = elementNew; - System.arraycopy(array, indexNew + 1, arrayNew, indexNew + 1, array.length - indexNew - 1); - return arrayNew; - } - } - - public static Object[] copyAndMoveToFront(Object[] array, int indexOld, int indexNew, Object elementNew) { - assert indexOld >= indexNew; - if (indexNew == indexOld ) { - return copyAndSet(array, indexOld, elementNew); - } else { - final Object[] arrayNew = new Object[array.length]; - System.arraycopy(array, 0, arrayNew, 0, indexNew); - arrayNew[indexNew] = elementNew; - System.arraycopy(array, indexNew, arrayNew, indexNew + 1, indexOld - indexNew); - System.arraycopy(array, indexOld + 1, arrayNew, indexOld + 1, array.length - indexOld - 1); - return arrayNew; - } - } - - @Deprecated - public static Object[] copyAndInsert(Object[] array, int index, Object elementNew) { - final Object[] arrayNew = new Object[array.length + 1]; - System.arraycopy(array, 0, arrayNew, 0, index); - arrayNew[index] = elementNew; - System.arraycopy(array, index, arrayNew, index + 1, array.length - index); - return arrayNew; - } - - @Deprecated - public static Object[] copyAndRemove(Object[] array, int index) { - final Object[] arrayNew = new Object[array.length - 1]; - System.arraycopy(array, 0, arrayNew, 0, index); - System.arraycopy(array, index + 1, arrayNew, index, array.length - index - 1); - return arrayNew; - } - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/DefaultTrieMap.java b/capsule/src/main/java/io/usethesource/capsule/DefaultTrieMap.java deleted file mode 100644 index 9ad448900..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/DefaultTrieMap.java +++ /dev/null @@ -1,72 +0,0 @@ -package io.usethesource.capsule; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class DefaultTrieMap { - - private static Class target = TrieMap_5Bits.class; - - private static Method persistentMapOfEmpty; - private static Method persistentMapOfKeyValuePairs; - - private static Method transientMapOfEmpty; - private static Method transientMapOfKeyValuePairs; - - public static Class getTargetClass() { - return target; - } - - static { - try { - persistentMapOfEmpty = target.getMethod("of"); - persistentMapOfKeyValuePairs = target.getMethod("of", Object[].class); - - transientMapOfEmpty = target.getMethod("transientOf"); - transientMapOfKeyValuePairs = target.getMethod("transientOf", Object[].class); - } catch (NoSuchMethodException | SecurityException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final ImmutableMap of() { - try { - return (ImmutableMap) persistentMapOfEmpty.invoke(null); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final ImmutableMap of(Object... keyValuePairs) { - try { - return (ImmutableMap) persistentMapOfKeyValuePairs.invoke(null, - (Object) keyValuePairs); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final TransientMap transientOf() { - try { - return (TransientMap) transientMapOfEmpty.invoke(null); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final TransientMap transientOf(Object... keyValuePairs) { - try { - return (TransientMap) transientMapOfKeyValuePairs.invoke(null, - (Object) keyValuePairs); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/DefaultTrieSet.java b/capsule/src/main/java/io/usethesource/capsule/DefaultTrieSet.java deleted file mode 100644 index d030a42cc..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/DefaultTrieSet.java +++ /dev/null @@ -1,69 +0,0 @@ -package io.usethesource.capsule; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class DefaultTrieSet { - - private static Class target = TrieSet_5Bits.class; - - private static Method persistentSetOfEmpty; - private static Method persistentSetOfKeyValuePairs; - - private static Method transientSetOfEmpty; - private static Method transientSetOfKeyValuePairs; - - public static Class getTargetClass() { - return target; - } - - static { - try { - persistentSetOfEmpty = target.getMethod("of"); - persistentSetOfKeyValuePairs = target.getMethod("of", Object[].class); - - transientSetOfEmpty = target.getMethod("transientOf"); - transientSetOfKeyValuePairs = target.getMethod("transientOf", Object[].class); - } catch (NoSuchMethodException | SecurityException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final ImmutableSet of() { - try { - return (ImmutableSet) persistentSetOfEmpty.invoke(null); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final ImmutableSet of(K... keys) { - try { - return (ImmutableSet) persistentSetOfKeyValuePairs.invoke(null, (Object) keys); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final TransientSet transientOf() { - try { - return (TransientSet) transientSetOfEmpty.invoke(null); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final TransientSet transientOf(K... keys) { - try { - return (TransientSet) transientSetOfKeyValuePairs.invoke(null, (Object) keys); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/EmptySupplierIterator.java b/capsule/src/main/java/io/usethesource/capsule/EmptySupplierIterator.java deleted file mode 100644 index 9b1b4215c..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/EmptySupplierIterator.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.NoSuchElementException; - -public class EmptySupplierIterator implements SupplierIterator { - - @SuppressWarnings("rawtypes") - private static final SupplierIterator EMPTY_ITERATOR = new EmptySupplierIterator(); - - @SuppressWarnings("unchecked") - public static SupplierIterator emptyIterator() { - return EMPTY_ITERATOR; - } - - @Override - public boolean hasNext() { - return false; - } - - @Override - public K next() { - throw new NoSuchElementException(); - } - - @Override - public V get() { - throw new NoSuchElementException(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - -} \ No newline at end of file diff --git a/capsule/src/main/java/io/usethesource/capsule/ImmutableMap.java b/capsule/src/main/java/io/usethesource/capsule/ImmutableMap.java deleted file mode 100644 index ba518b4f6..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/ImmutableMap.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.Comparator; -import java.util.Iterator; -import java.util.Map; - -public interface ImmutableMap extends Map { - - V get(final Object o); - - V getEquivalent(final Object o, final Comparator cmp); - - boolean containsKey(final Object o); - - boolean containsKeyEquivalent(final Object o, final Comparator cmp); - - boolean containsValue(final Object o); - - boolean containsValueEquivalent(final Object o, final Comparator cmp); - - ImmutableMap __put(final K key, final V val); - - ImmutableMap __putEquivalent(final K key, final V val, final Comparator cmp); - - ImmutableMap __putAll(final Map map); - - ImmutableMap __putAllEquivalent(final Map map, - final Comparator cmp); - - ImmutableMap __remove(final K key); - - ImmutableMap __removeEquivalent(final K key, final Comparator cmp); - - Iterator keyIterator(); - - Iterator valueIterator(); - - Iterator> entryIterator(); - - boolean isTransientSupported(); - - TransientMap asTransient(); - -} \ No newline at end of file diff --git a/capsule/src/main/java/io/usethesource/capsule/ImmutableSet.java b/capsule/src/main/java/io/usethesource/capsule/ImmutableSet.java deleted file mode 100644 index d1763a92d..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/ImmutableSet.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.Set; - -public interface ImmutableSet extends Set { - - boolean containsAll(final Collection c); - - boolean containsAllEquivalent(final Collection c, final Comparator cmp); - - K get(final Object o); - - K getEquivalent(final Object o, final Comparator cmp); - - boolean contains(final Object o); - - boolean containsEquivalent(final Object o, final Comparator cmp); - - ImmutableSet __insert(final K key); - - ImmutableSet __insertEquivalent(final K key, final Comparator cmp); - - ImmutableSet __insertAll(final Set set); - - ImmutableSet __insertAllEquivalent(final Set set, final Comparator cmp); - - ImmutableSet __remove(final K key); - - ImmutableSet __removeEquivalent(final K key, final Comparator cmp); - - ImmutableSet __removeAll(final Set set); - - ImmutableSet __removeAllEquivalent(final Set set, final Comparator cmp); - - ImmutableSet __retainAll(final Set set); - - ImmutableSet __retainAllEquivalent(final TransientSet transientSet, - final Comparator cmp); - - Iterator keyIterator(); - - boolean isTransientSupported(); - - TransientSet asTransient(); - -} \ No newline at end of file diff --git a/capsule/src/main/java/io/usethesource/capsule/Supplier.java b/capsule/src/main/java/io/usethesource/capsule/Supplier.java deleted file mode 100644 index 058ca912e..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/Supplier.java +++ /dev/null @@ -1,19 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -@Deprecated -public interface Supplier { - - T get(); - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/SupplierIterator.java b/capsule/src/main/java/io/usethesource/capsule/SupplierIterator.java deleted file mode 100644 index 857debce2..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/SupplierIterator.java +++ /dev/null @@ -1,17 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.Iterator; - -public interface SupplierIterator extends Iterator, Supplier { -} diff --git a/capsule/src/main/java/io/usethesource/capsule/TransientMap.java b/capsule/src/main/java/io/usethesource/capsule/TransientMap.java deleted file mode 100644 index 8b0acc9bc..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/TransientMap.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.Comparator; -import java.util.Iterator; -import java.util.Map; - -public interface TransientMap extends Map { - - V get(final Object o); - - V getEquivalent(final Object o, final Comparator cmp); - - boolean containsKey(final Object o); - - boolean containsKeyEquivalent(final Object o, final Comparator cmp); - - boolean containsValue(final Object o); - - boolean containsValueEquivalent(final Object o, final Comparator cmp); - - V __put(final K key, final V val); - - V __putEquivalent(final K key, final V val, final Comparator cmp); - - boolean __putAll(final Map map); - - boolean __putAllEquivalent(final Map map, final Comparator cmp); - - V __remove(final K key); - - V __removeEquivalent(final K key, final Comparator cmp); - - Iterator keyIterator(); - - Iterator valueIterator(); - - Iterator> entryIterator(); - - ImmutableMap freeze(); - -} \ No newline at end of file diff --git a/capsule/src/main/java/io/usethesource/capsule/TransientSet.java b/capsule/src/main/java/io/usethesource/capsule/TransientSet.java deleted file mode 100644 index e89d52610..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/TransientSet.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.Set; - -public interface TransientSet extends Set { - - boolean containsAll(final Collection c); - - boolean containsAllEquivalent(final Collection c, final Comparator cmp); - - K get(final Object o); - - K getEquivalent(final Object o, final Comparator cmp); - - boolean contains(final Object o); - - boolean containsEquivalent(final Object o, final Comparator cmp); - - boolean __insert(final K key); - - boolean __insertEquivalent(final K key, final Comparator cmp); - - boolean __insertAll(final Set set); - - boolean __insertAllEquivalent(final Set set, final Comparator cmp); - - boolean __remove(final K key); - - boolean __removeEquivalent(final K key, final Comparator cmp); - - boolean __removeAll(final Set set); - - boolean __removeAllEquivalent(final Set set, final Comparator cmp); - - boolean __retainAll(final Set set); - - boolean __retainAllEquivalent(final TransientSet transientSet, - final Comparator cmp); - - Iterator keyIterator(); - - ImmutableSet freeze(); - -} \ No newline at end of file diff --git a/capsule/src/main/java/io/usethesource/capsule/TrieMap_5Bits.java b/capsule/src/main/java/io/usethesource/capsule/TrieMap_5Bits.java deleted file mode 100644 index c55b74806..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/TrieMap_5Bits.java +++ /dev/null @@ -1,2806 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import static io.usethesource.capsule.AbstractSpecialisedImmutableMap.entryOf; - -import java.text.DecimalFormat; -import java.util.AbstractCollection; -import java.util.AbstractSet; -import java.util.ArrayDeque; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Deque; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; - -@SuppressWarnings("rawtypes") -public class TrieMap_5Bits implements ImmutableMap { - - @SuppressWarnings("unchecked") - private static final TrieMap_5Bits EMPTY_MAP = new TrieMap_5Bits(CompactMapNode.EMPTY_NODE, 0, - 0); - - private static final boolean DEBUG = false; - - private final AbstractMapNode rootNode; - private final int hashCode; - private final int cachedSize; - - TrieMap_5Bits(AbstractMapNode rootNode, int hashCode, int cachedSize) { - this.rootNode = rootNode; - this.hashCode = hashCode; - this.cachedSize = cachedSize; - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - } - - @SuppressWarnings("unchecked") - public static final ImmutableMap of() { - return TrieMap_5Bits.EMPTY_MAP; - } - - @SuppressWarnings("unchecked") - public static final ImmutableMap of(Object... keyValuePairs) { - if (keyValuePairs.length % 2 != 0) { - throw new IllegalArgumentException( - "Length of argument list is uneven: no key/value pairs."); - } - - ImmutableMap result = TrieMap_5Bits.EMPTY_MAP; - - for (int i = 0; i < keyValuePairs.length; i += 2) { - final K key = (K) keyValuePairs[i]; - final V val = (V) keyValuePairs[i + 1]; - - result = result.__put(key, val); - } - - return result; - } - - @SuppressWarnings("unchecked") - public static final TransientMap transientOf() { - return TrieMap_5Bits.EMPTY_MAP.asTransient(); - } - - @SuppressWarnings("unchecked") - public static final TransientMap transientOf(Object... keyValuePairs) { - if (keyValuePairs.length % 2 != 0) { - throw new IllegalArgumentException( - "Length of argument list is uneven: no key/value pairs."); - } - - final TransientMap result = TrieMap_5Bits.EMPTY_MAP.asTransient(); - - for (int i = 0; i < keyValuePairs.length; i += 2) { - final K key = (K) keyValuePairs[i]; - final V val = (V) keyValuePairs[i + 1]; - - result.__put(key, val); - } - - return result; - } - - private boolean checkHashCodeAndSize(final int targetHash, final int targetSize) { - int hash = 0; - int size = 0; - - for (Iterator> it = entryIterator(); it.hasNext();) { - final Map.Entry entry = it.next(); - final K key = entry.getKey(); - final V val = entry.getValue(); - - hash += key.hashCode() ^ val.hashCode(); - size += 1; - } - - return hash == targetHash && size == targetSize; - } - - public static final int transformHashCode(final int hash) { - return hash; - } - - public boolean containsKey(final Object o) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - return rootNode.containsKey(key, transformHashCode(key.hashCode()), 0); - } catch (ClassCastException unused) { - return false; - } - } - - public boolean containsKeyEquivalent(final Object o, final Comparator cmp) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - return rootNode.containsKey(key, transformHashCode(key.hashCode()), 0, cmp); - } catch (ClassCastException unused) { - return false; - } - } - - public boolean containsValue(final Object o) { - for (Iterator iterator = valueIterator(); iterator.hasNext();) { - if (iterator.next().equals(o)) { - return true; - } - } - return false; - } - - public boolean containsValueEquivalent(final Object o, final Comparator cmp) { - for (Iterator iterator = valueIterator(); iterator.hasNext();) { - if (cmp.compare(iterator.next(), o) == 0) { - return true; - } - } - return false; - } - - public V get(final Object o) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - final Optional result = rootNode - .findByKey(key, transformHashCode(key.hashCode()), 0); - - if (result.isPresent()) { - return result.get(); - } else { - return null; - } - } catch (ClassCastException unused) { - return null; - } - } - - public V getEquivalent(final Object o, final Comparator cmp) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - final Optional result = rootNode.findByKey(key, transformHashCode(key.hashCode()), - 0, cmp); - - if (result.isPresent()) { - return result.get(); - } else { - return null; - } - } catch (ClassCastException unused) { - return null; - } - } - - public ImmutableMap __put(final K key, final V val) { - final int keyHash = key.hashCode(); - final MapResult details = MapResult.unchanged(); - - final CompactMapNode newRootNode = rootNode.updated(null, key, val, - transformHashCode(keyHash), 0, details); - - if (details.isModified()) { - if (details.hasReplacedValue()) { - final int valHashOld = details.getReplacedValue().hashCode(); - final int valHashNew = val.hashCode(); - - return new TrieMap_5Bits(newRootNode, hashCode + ((keyHash ^ valHashNew)) - - ((keyHash ^ valHashOld)), cachedSize); - } - - final int valHash = val.hashCode(); - return new TrieMap_5Bits(newRootNode, hashCode + ((keyHash ^ valHash)), - cachedSize + 1); - } - - return this; - } - - public ImmutableMap __putEquivalent(final K key, final V val, final Comparator cmp) { - final int keyHash = key.hashCode(); - final MapResult details = MapResult.unchanged(); - - final CompactMapNode newRootNode = rootNode.updated(null, key, val, - transformHashCode(keyHash), 0, details, cmp); - - if (details.isModified()) { - if (details.hasReplacedValue()) { - final int valHashOld = details.getReplacedValue().hashCode(); - final int valHashNew = val.hashCode(); - - return new TrieMap_5Bits(newRootNode, hashCode + ((keyHash ^ valHashNew)) - - ((keyHash ^ valHashOld)), cachedSize); - } - - final int valHash = val.hashCode(); - return new TrieMap_5Bits(newRootNode, hashCode + ((keyHash ^ valHash)), - cachedSize + 1); - } - - return this; - } - - public ImmutableMap __putAll(final Map map) { - final TransientMap tmpTransient = this.asTransient(); - tmpTransient.__putAll(map); - return tmpTransient.freeze(); - } - - public ImmutableMap __putAllEquivalent(final Map map, - final Comparator cmp) { - final TransientMap tmpTransient = this.asTransient(); - tmpTransient.__putAllEquivalent(map, cmp); - return tmpTransient.freeze(); - } - - public ImmutableMap __remove(final K key) { - final int keyHash = key.hashCode(); - final MapResult details = MapResult.unchanged(); - - final CompactMapNode newRootNode = rootNode.removed(null, key, - transformHashCode(keyHash), 0, details); - - if (details.isModified()) { - assert details.hasReplacedValue(); - final int valHash = details.getReplacedValue().hashCode(); - return new TrieMap_5Bits(newRootNode, hashCode - ((keyHash ^ valHash)), - cachedSize - 1); - } - - return this; - } - - public ImmutableMap __removeEquivalent(final K key, final Comparator cmp) { - final int keyHash = key.hashCode(); - final MapResult details = MapResult.unchanged(); - - final CompactMapNode newRootNode = rootNode.removed(null, key, - transformHashCode(keyHash), 0, details, cmp); - - if (details.isModified()) { - assert details.hasReplacedValue(); - final int valHash = details.getReplacedValue().hashCode(); - return new TrieMap_5Bits(newRootNode, hashCode - ((keyHash ^ valHash)), - cachedSize - 1); - } - - return this; - } - - public V put(final K key, final V val) { - throw new UnsupportedOperationException(); - } - - public void putAll(final Map m) { - throw new UnsupportedOperationException(); - } - - public void clear() { - throw new UnsupportedOperationException(); - } - - public V remove(final Object key) { - throw new UnsupportedOperationException(); - } - - public int size() { - return cachedSize; - } - - public boolean isEmpty() { - return cachedSize == 0; - } - - public Iterator keyIterator() { - return new MapKeyIterator<>(rootNode); - } - - public Iterator valueIterator() { - return new MapValueIterator<>(rootNode); - } - - public Iterator> entryIterator() { - return new MapEntryIterator<>(rootNode); - } - - @Override - public Set keySet() { - Set keySet = null; - - if (keySet == null) { - keySet = new AbstractSet() { - @Override - public Iterator iterator() { - return TrieMap_5Bits.this.keyIterator(); - } - - @Override - public int size() { - return TrieMap_5Bits.this.size(); - } - - @Override - public boolean isEmpty() { - return TrieMap_5Bits.this.isEmpty(); - } - - @Override - public void clear() { - TrieMap_5Bits.this.clear(); - } - - @Override - public boolean contains(Object k) { - return TrieMap_5Bits.this.containsKey(k); - } - }; - } - - return keySet; - } - - @Override - public Collection values() { - Collection values = null; - - if (values == null) { - values = new AbstractCollection() { - @Override - public Iterator iterator() { - return TrieMap_5Bits.this.valueIterator(); - } - - @Override - public int size() { - return TrieMap_5Bits.this.size(); - } - - @Override - public boolean isEmpty() { - return TrieMap_5Bits.this.isEmpty(); - } - - @Override - public void clear() { - TrieMap_5Bits.this.clear(); - } - - @Override - public boolean contains(Object v) { - return TrieMap_5Bits.this.containsValue(v); - } - }; - } - - return values; - } - - @Override - public Set> entrySet() { - Set> entrySet = null; - - if (entrySet == null) { - entrySet = new AbstractSet>() { - @Override - public Iterator> iterator() { - return new Iterator>() { - private final Iterator> i = entryIterator(); - - @Override - public boolean hasNext() { - return i.hasNext(); - } - - @Override - public Map.Entry next() { - return i.next(); - } - - @Override - public void remove() { - i.remove(); - } - }; - } - - @Override - public int size() { - return TrieMap_5Bits.this.size(); - } - - @Override - public boolean isEmpty() { - return TrieMap_5Bits.this.isEmpty(); - } - - @Override - public void clear() { - TrieMap_5Bits.this.clear(); - } - - @Override - public boolean contains(Object k) { - return TrieMap_5Bits.this.containsKey(k); - } - }; - } - - return entrySet; - } - - @Override - public boolean equals(final Object other) { - if (other == this) { - return true; - } - if (other == null) { - return false; - } - - if (other instanceof TrieMap_5Bits) { - TrieMap_5Bits that = (TrieMap_5Bits) other; - - if (this.cachedSize != that.cachedSize) { - return false; - } - - if (this.hashCode != that.hashCode) { - return false; - } - - return rootNode.equals(that.rootNode); - } else if (other instanceof Map) { - Map that = (Map) other; - - if (this.size() != that.size()) - return false; - - for (@SuppressWarnings("unchecked") - Iterator it = that.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = it.next(); - - try { - @SuppressWarnings("unchecked") - final K key = (K) entry.getKey(); - final Optional result = rootNode.findByKey(key, - transformHashCode(key.hashCode()), 0); - - if (!result.isPresent()) { - return false; - } else { - @SuppressWarnings("unchecked") - final V val = (V) entry.getValue(); - - if (!result.get().equals(val)) { - return false; - } - } - } catch (ClassCastException unused) { - return false; - } - } - - return true; - } - - return false; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean isTransientSupported() { - return true; - } - - @Override - public TransientMap asTransient() { - return new TransientTrieMap_5Bits(this); - } - - /* - * For analysis purposes only. - */ - protected AbstractMapNode getRootNode() { - return rootNode; - } - - /* - * For analysis purposes only. - */ - protected Iterator> nodeIterator() { - return new TrieMap_5BitsNodeIterator<>(rootNode); - } - - /* - * For analysis purposes only. - */ - protected int getNodeCount() { - final Iterator> it = nodeIterator(); - int sumNodes = 0; - - for (; it.hasNext(); it.next()) { - sumNodes += 1; - } - - return sumNodes; - } - - /* - * For analysis purposes only. Payload X Node - */ - protected int[][] arityCombinationsHistogram() { - final Iterator> it = nodeIterator(); - final int[][] sumArityCombinations = new int[33][33]; - - while (it.hasNext()) { - final AbstractMapNode node = it.next(); - sumArityCombinations[node.payloadArity()][node.nodeArity()] += 1; - } - - return sumArityCombinations; - } - - /* - * For analysis purposes only. - */ - protected int[] arityHistogram() { - final int[][] sumArityCombinations = arityCombinationsHistogram(); - final int[] sumArity = new int[33]; - - final int maxArity = 32; // TODO: factor out constant - - for (int j = 0; j <= maxArity; j++) { - for (int maxRestArity = maxArity - j, k = 0; k <= maxRestArity - j; k++) { - sumArity[j + k] += sumArityCombinations[j][k]; - } - } - - return sumArity; - } - - /* - * For analysis purposes only. - */ - public void printStatistics() { - final int[][] sumArityCombinations = arityCombinationsHistogram(); - final int[] sumArity = arityHistogram(); - final int sumNodes = getNodeCount(); - - final int[] cumsumArity = new int[33]; - for (int cumsum = 0, i = 0; i < 33; i++) { - cumsum += sumArity[i]; - cumsumArity[i] = cumsum; - } - - final float threshhold = 0.01f; // for printing results - for (int i = 0; i < 33; i++) { - float arityPercentage = (float) (sumArity[i]) / sumNodes; - float cumsumArityPercentage = (float) (cumsumArity[i]) / sumNodes; - - if (arityPercentage != 0 && arityPercentage >= threshhold) { - // details per level - StringBuilder bldr = new StringBuilder(); - int max = i; - for (int j = 0; j <= max; j++) { - for (int k = max - j; k <= max - j; k++) { - float arityCombinationsPercentage = (float) (sumArityCombinations[j][k]) - / sumNodes; - - if (arityCombinationsPercentage != 0 - && arityCombinationsPercentage >= threshhold) { - bldr.append(String.format("%d/%d: %s, ", j, k, new DecimalFormat( - "0.00%").format(arityCombinationsPercentage))); - } - } - } - final String detailPercentages = bldr.toString(); - - // overview - System.out.println(String.format("%2d: %s\t[cumsum = %s]\t%s", i, - new DecimalFormat("0.00%").format(arityPercentage), - new DecimalFormat("0.00%").format(cumsumArityPercentage), - detailPercentages)); - } - } - } - - abstract static class Optional { - private static final Optional EMPTY = new Optional() { - @Override - boolean isPresent() { - return false; - } - - @Override - Object get() { - return null; - } - }; - - @SuppressWarnings("unchecked") - static Optional empty() { - return EMPTY; - } - - static Optional of(T value) { - return new Value(value); - } - - abstract boolean isPresent(); - - abstract T get(); - - private static final class Value extends Optional { - private final T value; - - private Value(T value) { - this.value = value; - } - - @Override - boolean isPresent() { - return true; - } - - @Override - T get() { - return value; - } - } - } - - static final class MapResult { - private V replacedValue; - private boolean isModified; - private boolean isReplaced; - - // update: inserted/removed single element, element count changed - public void modified() { - this.isModified = true; - } - - public void updated(V replacedValue) { - this.replacedValue = replacedValue; - this.isModified = true; - this.isReplaced = true; - } - - // update: neither element, nor element count changed - public static MapResult unchanged() { - return new MapResult<>(); - } - - private MapResult() { - } - - public boolean isModified() { - return isModified; - } - - public boolean hasReplacedValue() { - return isReplaced; - } - - public V getReplacedValue() { - return replacedValue; - } - } - - protected static interface INode { - } - - protected static abstract class AbstractMapNode implements INode { - - static final int TUPLE_LENGTH = 2; - - abstract boolean containsKey(final K key, final int keyHash, final int shift); - - abstract boolean containsKey(final K key, final int keyHash, final int shift, - final Comparator cmp); - - abstract Optional findByKey(final K key, final int keyHash, final int shift); - - abstract Optional findByKey(final K key, final int keyHash, final int shift, - final Comparator cmp); - - abstract CompactMapNode updated(final AtomicReference mutator, final K key, - final V val, final int keyHash, final int shift, - final MapResult details); - - abstract CompactMapNode updated(final AtomicReference mutator, final K key, - final V val, final int keyHash, final int shift, - final MapResult details, final Comparator cmp); - - abstract CompactMapNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final MapResult details); - - abstract CompactMapNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final MapResult details, - final Comparator cmp); - - static final boolean isAllowedToEdit(AtomicReference x, AtomicReference y) { - return x != null && y != null && (x == y || x.get() == y.get()); - } - - abstract boolean hasNodes(); - - abstract int nodeArity(); - - abstract AbstractMapNode getNode(final int index); - - @Deprecated - Iterator> nodeIterator() { - return new Iterator>() { - - int nextIndex = 0; - final int nodeArity = AbstractMapNode.this.nodeArity(); - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public AbstractMapNode next() { - if (!hasNext()) - throw new NoSuchElementException(); - return AbstractMapNode.this.getNode(nextIndex++); - } - - @Override - public boolean hasNext() { - return nextIndex < nodeArity; - } - }; - } - - abstract boolean hasPayload(); - - abstract int payloadArity(); - - abstract K getKey(final int index); - - abstract V getValue(final int index); - - abstract Map.Entry getKeyValueEntry(final int index); - - @Deprecated - abstract boolean hasSlots(); - - abstract int slotArity(); - - abstract Object getSlot(final int index); - - /** - * The arity of this trie node (i.e. number of values and nodes stored - * on this level). - * - * @return sum of nodes and values stored within - */ - - int arity() { - return payloadArity() + nodeArity(); - } - - int size() { - final Iterator it = new MapKeyIterator<>(this); - - int size = 0; - while (it.hasNext()) { - size += 1; - it.next(); - } - - return size; - } - } - - protected static abstract class CompactMapNode extends AbstractMapNode { - - static final int HASH_CODE_LENGTH = 32; - - static final int BIT_PARTITION_SIZE = 5; - static final int BIT_PARTITION_MASK = 0b11111; - - static final int mask(final int keyHash, final int shift) { - return (keyHash >>> shift) & BIT_PARTITION_MASK; - } - - static final int bitpos(final int mask) { - return (int) (1 << mask); - } - - abstract int nodeMap(); - - abstract int dataMap(); - - static final byte SIZE_EMPTY = 0b00; - static final byte SIZE_ONE = 0b01; - static final byte SIZE_MORE_THAN_ONE = 0b10; - - /** - * Abstract predicate over a node's size. Value can be either - * {@value #SIZE_EMPTY}, {@value #SIZE_ONE}, or - * {@value #SIZE_MORE_THAN_ONE}. - * - * @return size predicate - */ - abstract byte sizePredicate(); - - @Override - abstract CompactMapNode getNode(final int index); - - boolean nodeInvariant() { - boolean inv1 = (size() - payloadArity() >= 2 * (arity() - payloadArity())); - boolean inv2 = (this.arity() == 0) ? sizePredicate() == SIZE_EMPTY : true; - boolean inv3 = (this.arity() == 1 && payloadArity() == 1) ? sizePredicate() == SIZE_ONE - : true; - boolean inv4 = (this.arity() >= 2) ? sizePredicate() == SIZE_MORE_THAN_ONE : true; - - boolean inv5 = (this.nodeArity() >= 0) && (this.payloadArity() >= 0) - && ((this.payloadArity() + this.nodeArity()) == this.arity()); - - return inv1 && inv2 && inv3 && inv4 && inv5; - } - - abstract CompactMapNode copyAndSetValue(final AtomicReference mutator, - final int bitpos, final V val); - - abstract CompactMapNode copyAndInsertValue(final AtomicReference mutator, - final int bitpos, final K key, final V val); - - abstract CompactMapNode copyAndRemoveValue(final AtomicReference mutator, - final int bitpos); - - abstract CompactMapNode copyAndSetNode(final AtomicReference mutator, - final int bitpos, final CompactMapNode node); - - abstract CompactMapNode copyAndMigrateFromInlineToNode( - final AtomicReference mutator, final int bitpos, - final CompactMapNode node); - - abstract CompactMapNode copyAndMigrateFromNodeToInline( - final AtomicReference mutator, final int bitpos, - final CompactMapNode node); - - static final CompactMapNode mergeTwoKeyValPairs(final K key0, final V val0, - final int keyHash0, final K key1, final V val1, final int keyHash1, - final int shift) { - assert !(key0.equals(key1)); - - if (shift >= HASH_CODE_LENGTH) { - // throw new - // IllegalStateException("Hash collision not yet fixed."); - return new HashCollisionMapNode_5Bits<>(keyHash0, - (K[]) new Object[] { key0, key1 }, - (V[]) new Object[] { val0, val1 }); - } - - final int mask0 = mask(keyHash0, shift); - final int mask1 = mask(keyHash1, shift); - - if (mask0 != mask1) { - // both nodes fit on same level - final int dataMap = (int) (bitpos(mask0) | bitpos(mask1)); - - if (mask0 < mask1) { - return nodeOf(null, (int) (0), dataMap, new Object[] { key0, val0, key1, val1 }); - } else { - return nodeOf(null, (int) (0), dataMap, new Object[] { key1, val1, key0, val0 }); - } - } else { - final CompactMapNode node = mergeTwoKeyValPairs(key0, val0, keyHash0, key1, - val1, keyHash1, shift + BIT_PARTITION_SIZE); - // values fit on next level - - final int nodeMap = bitpos(mask0); - return nodeOf(null, nodeMap, (int) (0), new Object[] { node }); - } - } - - static final CompactMapNode EMPTY_NODE; - - static { - - EMPTY_NODE = new BitmapIndexedMapNode<>(null, (int) (0), (int) (0), new Object[] {}); - - }; - - static final CompactMapNode nodeOf(final AtomicReference mutator, - final int nodeMap, final int dataMap, final Object[] nodes) { - return new BitmapIndexedMapNode<>(mutator, nodeMap, dataMap, nodes); - } - - @SuppressWarnings("unchecked") - static final CompactMapNode nodeOf(AtomicReference mutator) { - return EMPTY_NODE; - } - - static final CompactMapNode nodeOf(AtomicReference mutator, - final int nodeMap, final int dataMap, final K key, final V val) { - assert nodeMap == 0; - return nodeOf(mutator, (int) (0), dataMap, new Object[] { key, val }); - } - - static final int index(final int bitmap, final int bitpos) { - return java.lang.Integer.bitCount(bitmap & (bitpos - 1)); - } - - static final int index(final int bitmap, final int mask, final int bitpos) { - return (bitmap == -1) ? mask : index(bitmap, bitpos); - } - - int dataIndex(final int bitpos) { - return java.lang.Integer.bitCount(dataMap() & (bitpos - 1)); - } - - int nodeIndex(final int bitpos) { - return java.lang.Integer.bitCount(nodeMap() & (bitpos - 1)); - } - - CompactMapNode nodeAt(final int bitpos) { - return getNode(nodeIndex(bitpos)); - } - - boolean containsKey(final K key, final int keyHash, final int shift) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - final int dataMap = dataMap(); - if ((dataMap & bitpos) != 0) { - final int index = index(dataMap, mask, bitpos); - return getKey(index).equals(key); - } - - final int nodeMap = nodeMap(); - if ((nodeMap & bitpos) != 0) { - final int index = index(nodeMap, mask, bitpos); - return getNode(index).containsKey(key, keyHash, shift + BIT_PARTITION_SIZE); - } - - return false; - } - - boolean containsKey(final K key, final int keyHash, final int shift, - final Comparator cmp) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - final int dataMap = dataMap(); - if ((dataMap & bitpos) != 0) { - final int index = index(dataMap, mask, bitpos); - return cmp.compare(getKey(index), key) == 0; - } - - final int nodeMap = nodeMap(); - if ((nodeMap & bitpos) != 0) { - final int index = index(nodeMap, mask, bitpos); - return getNode(index).containsKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); - } - - return false; - } - - Optional findByKey(final K key, final int keyHash, final int shift) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int index = dataIndex(bitpos); - if (getKey(index).equals(key)) { - final V result = getValue(index); - - return Optional.of(result); - } - - return Optional.empty(); - } - - if ((nodeMap() & bitpos) != 0) { // node (not value) - final AbstractMapNode subNode = nodeAt(bitpos); - - return subNode.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); - } - - return Optional.empty(); - } - - Optional findByKey(final K key, final int keyHash, final int shift, - final Comparator cmp) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int index = dataIndex(bitpos); - if (cmp.compare(getKey(index), key) == 0) { - final V result = getValue(index); - - return Optional.of(result); - } - - return Optional.empty(); - } - - if ((nodeMap() & bitpos) != 0) { // node (not value) - final AbstractMapNode subNode = nodeAt(bitpos); - - return subNode.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); - } - - return Optional.empty(); - } - - CompactMapNode updated(final AtomicReference mutator, final K key, - final V val, final int keyHash, final int shift, - final MapResult details) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int dataIndex = dataIndex(bitpos); - final K currentKey = getKey(dataIndex); - - if (currentKey.equals(key)) { - final V currentVal = getValue(dataIndex); - - // update mapping - details.updated(currentVal); - return copyAndSetValue(mutator, bitpos, val); - } else { - final V currentVal = getValue(dataIndex); - final CompactMapNode subNodeNew = mergeTwoKeyValPairs(currentKey, - currentVal, transformHashCode(currentKey.hashCode()), key, val, - keyHash, shift + BIT_PARTITION_SIZE); - - details.modified(); - return copyAndMigrateFromInlineToNode(mutator, bitpos, subNodeNew); - } - } else if ((nodeMap() & bitpos) != 0) { // node (not value) - final CompactMapNode subNode = nodeAt(bitpos); - final CompactMapNode subNodeNew = subNode.updated(mutator, key, val, keyHash, - shift + BIT_PARTITION_SIZE, details); - - if (details.isModified()) { - return copyAndSetNode(mutator, bitpos, subNodeNew); - } else { - return this; - } - } else { - // no value - details.modified(); - return copyAndInsertValue(mutator, bitpos, key, val); - } - } - - CompactMapNode updated(final AtomicReference mutator, final K key, - final V val, final int keyHash, final int shift, - final MapResult details, final Comparator cmp) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int dataIndex = dataIndex(bitpos); - final K currentKey = getKey(dataIndex); - - if (cmp.compare(currentKey, key) == 0) { - final V currentVal = getValue(dataIndex); - - // update mapping - details.updated(currentVal); - return copyAndSetValue(mutator, bitpos, val); - } else { - final V currentVal = getValue(dataIndex); - final CompactMapNode subNodeNew = mergeTwoKeyValPairs(currentKey, - currentVal, transformHashCode(currentKey.hashCode()), key, val, - keyHash, shift + BIT_PARTITION_SIZE); - - details.modified(); - return copyAndMigrateFromInlineToNode(mutator, bitpos, subNodeNew); - } - } else if ((nodeMap() & bitpos) != 0) { // node (not value) - final CompactMapNode subNode = nodeAt(bitpos); - final CompactMapNode subNodeNew = subNode.updated(mutator, key, val, keyHash, - shift + BIT_PARTITION_SIZE, details, cmp); - - if (details.isModified()) { - return copyAndSetNode(mutator, bitpos, subNodeNew); - } else { - return this; - } - } else { - // no value - details.modified(); - return copyAndInsertValue(mutator, bitpos, key, val); - } - } - - CompactMapNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final MapResult details) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int dataIndex = dataIndex(bitpos); - - if (getKey(dataIndex).equals(key)) { - final V currentVal = getValue(dataIndex); - details.updated(currentVal); - - if (this.payloadArity() == 2 && this.nodeArity() == 0) { - /* - * Create new node with remaining pair. The new node - * will a) either become the new root returned, or b) - * unwrapped and inlined during returning. - */ - final int newDataMap = (shift == 0) ? (int) (dataMap() ^ bitpos) - : bitpos(mask(keyHash, 0)); - - if (dataIndex == 0) { - return CompactMapNode. nodeOf(mutator, (int) 0, newDataMap, - getKey(1), getValue(1)); - } else { - return CompactMapNode. nodeOf(mutator, (int) 0, newDataMap, - getKey(0), getValue(0)); - } - } else { - return copyAndRemoveValue(mutator, bitpos); - } - } else { - return this; - } - } else if ((nodeMap() & bitpos) != 0) { // node (not value) - final CompactMapNode subNode = nodeAt(bitpos); - final CompactMapNode subNodeNew = subNode.removed(mutator, key, keyHash, - shift + BIT_PARTITION_SIZE, details); - - if (!details.isModified()) { - return this; - } - - switch (subNodeNew.sizePredicate()) { - case 0: { - throw new IllegalStateException("Sub-node must have at least one element."); - } - case 1: { - if (this.payloadArity() == 0 && this.nodeArity() == 1) { - // escalate (singleton or empty) result - return subNodeNew; - } else { - // inline value (move to front) - return copyAndMigrateFromNodeToInline(mutator, bitpos, subNodeNew); - } - } - default: { - // modify current node (set replacement node) - return copyAndSetNode(mutator, bitpos, subNodeNew); - } - } - } - - return this; - } - - CompactMapNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final MapResult details, - final Comparator cmp) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int dataIndex = dataIndex(bitpos); - - if (cmp.compare(getKey(dataIndex), key) == 0) { - final V currentVal = getValue(dataIndex); - details.updated(currentVal); - - if (this.payloadArity() == 2 && this.nodeArity() == 0) { - /* - * Create new node with remaining pair. The new node - * will a) either become the new root returned, or b) - * unwrapped and inlined during returning. - */ - final int newDataMap = (shift == 0) ? (int) (dataMap() ^ bitpos) - : bitpos(mask(keyHash, 0)); - - if (dataIndex == 0) { - return CompactMapNode. nodeOf(mutator, (int) 0, newDataMap, - getKey(1), getValue(1)); - } else { - return CompactMapNode. nodeOf(mutator, (int) 0, newDataMap, - getKey(0), getValue(0)); - } - } else { - return copyAndRemoveValue(mutator, bitpos); - } - } else { - return this; - } - } else if ((nodeMap() & bitpos) != 0) { // node (not value) - final CompactMapNode subNode = nodeAt(bitpos); - final CompactMapNode subNodeNew = subNode.removed(mutator, key, keyHash, - shift + BIT_PARTITION_SIZE, details, cmp); - - if (!details.isModified()) { - return this; - } - - switch (subNodeNew.sizePredicate()) { - case 0: { - throw new IllegalStateException("Sub-node must have at least one element."); - } - case 1: { - if (this.payloadArity() == 0 && this.nodeArity() == 1) { - // escalate (singleton or empty) result - return subNodeNew; - } else { - // inline value (move to front) - return copyAndMigrateFromNodeToInline(mutator, bitpos, subNodeNew); - } - } - default: { - // modify current node (set replacement node) - return copyAndSetNode(mutator, bitpos, subNodeNew); - } - } - } - - return this; - } - - /** - * @return 0 <= mask <= 2^BIT_PARTITION_SIZE - 1 - */ - static byte recoverMask(int map, byte i_th) { - assert 1 <= i_th && i_th <= 32; - - byte cnt1 = 0; - byte mask = 0; - - while (mask < 32) { - if ((map & 0x01) == 0x01) { - cnt1 += 1; - - if (cnt1 == i_th) { - return mask; - } - } - - map = (int) (map >> 1); - mask += 1; - } - - assert cnt1 != i_th; - throw new RuntimeException("Called with invalid arguments."); - } - - @Override - public String toString() { - final StringBuilder bldr = new StringBuilder(); - bldr.append('['); - - for (byte i = 0; i < payloadArity(); i++) { - final byte pos = recoverMask(dataMap(), (byte) (i + 1)); - bldr.append(String.format("@%d<#%d,#%d>", pos, Objects.hashCode(getKey(i)), - Objects.hashCode(getValue(i)))); - - if (!((i + 1) == payloadArity())) { - bldr.append(", "); - } - } - - if (payloadArity() > 0 && nodeArity() > 0) { - bldr.append(", "); - } - - for (byte i = 0; i < nodeArity(); i++) { - final byte pos = recoverMask(nodeMap(), (byte) (i + 1)); - bldr.append(String.format("@%d: %s", pos, getNode(i))); - - if (!((i + 1) == nodeArity())) { - bldr.append(", "); - } - } - - bldr.append(']'); - return bldr.toString(); - } - - } - - protected static abstract class CompactMixedMapNode extends CompactMapNode { - - private final int nodeMap; - private final int dataMap; - - CompactMixedMapNode(final AtomicReference mutator, final int nodeMap, - final int dataMap) { - this.nodeMap = nodeMap; - this.dataMap = dataMap; - } - - @Override - public int nodeMap() { - return nodeMap; - } - - @Override - public int dataMap() { - return dataMap; - } - - } - - private static final class BitmapIndexedMapNode extends CompactMixedMapNode { - - final AtomicReference mutator; - final Object[] nodes; - - private BitmapIndexedMapNode(final AtomicReference mutator, final int nodeMap, - final int dataMap, final Object[] nodes) { - super(mutator, nodeMap, dataMap); - - this.mutator = mutator; - this.nodes = nodes; - - if (DEBUG) { - - assert (TUPLE_LENGTH * java.lang.Integer.bitCount(dataMap) - + java.lang.Integer.bitCount(nodeMap) == nodes.length); - - for (int i = 0; i < TUPLE_LENGTH * payloadArity(); i++) { - assert ((nodes[i] instanceof CompactMapNode) == false); - } - for (int i = TUPLE_LENGTH * payloadArity(); i < nodes.length; i++) { - assert ((nodes[i] instanceof CompactMapNode) == true); - } - } - - assert nodeInvariant(); - } - - @SuppressWarnings("unchecked") - @Override - K getKey(final int index) { - return (K) nodes[TUPLE_LENGTH * index]; - } - - @SuppressWarnings("unchecked") - @Override - V getValue(final int index) { - return (V) nodes[TUPLE_LENGTH * index + 1]; - } - - Map.Entry getKeyValueEntry(final int index) { - return entryOf((K) nodes[TUPLE_LENGTH * index], (V) nodes[TUPLE_LENGTH * index + 1]); - } - - @SuppressWarnings("unchecked") - @Override - CompactMapNode getNode(final int index) { - return (CompactMapNode) nodes[nodes.length - 1 - index]; - } - - @Override - boolean hasPayload() { - return dataMap() != 0; - } - - @Override - int payloadArity() { - return java.lang.Integer.bitCount(dataMap()); - } - - @Override - boolean hasNodes() { - return nodeMap() != 0; - } - - @Override - int nodeArity() { - return java.lang.Integer.bitCount(nodeMap()); - } - - @Override - Object getSlot(final int index) { - return nodes[index]; - } - - @Override - boolean hasSlots() { - return nodes.length != 0; - } - - @Override - int slotArity() { - return nodes.length; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 0; - result = prime * result + ((int) dataMap()); - result = prime * result + ((int) dataMap()); - result = prime * result + Arrays.hashCode(nodes); - return result; - } - - @Override - public boolean equals(final Object other) { - if (null == other) { - return false; - } - if (this == other) { - return true; - } - if (getClass() != other.getClass()) { - return false; - } - BitmapIndexedMapNode that = (BitmapIndexedMapNode) other; - if (nodeMap() != that.nodeMap()) { - return false; - } - if (dataMap() != that.dataMap()) { - return false; - } - if (!ArrayUtils.equals(nodes, that.nodes)) { - return false; - } - return true; - } - - @Override - byte sizePredicate() { - if (this.nodeArity() == 0) { - switch (this.payloadArity()) { - case 0: - return SIZE_EMPTY; - case 1: - return SIZE_ONE; - default: - return SIZE_MORE_THAN_ONE; - } - } else { - return SIZE_MORE_THAN_ONE; - } - } - - @Override - CompactMapNode copyAndSetValue(final AtomicReference mutator, - final int bitpos, final V val) { - final int idx = TUPLE_LENGTH * dataIndex(bitpos) + 1; - - if (isAllowedToEdit(this.mutator, mutator)) { - // no copying if already editable - this.nodes[idx] = val; - return this; - } else { - final Object[] src = this.nodes; - final Object[] dst = (Object[]) new Object[src.length]; - - // copy 'src' and set 1 element(s) at position 'idx' - System.arraycopy(src, 0, dst, 0, src.length); - dst[idx + 0] = val; - - return nodeOf(mutator, nodeMap(), dataMap(), dst); - } - } - - @Override - CompactMapNode copyAndSetNode(final AtomicReference mutator, - final int bitpos, final CompactMapNode node) { - - final int idx = this.nodes.length - 1 - nodeIndex(bitpos); - - if (isAllowedToEdit(this.mutator, mutator)) { - // no copying if already editable - this.nodes[idx] = node; - return this; - } else { - final Object[] src = this.nodes; - final Object[] dst = (Object[]) new Object[src.length]; - - // copy 'src' and set 1 element(s) at position 'idx' - System.arraycopy(src, 0, dst, 0, src.length); - dst[idx + 0] = node; - - return nodeOf(mutator, nodeMap(), dataMap(), dst); - } - } - - @Override - CompactMapNode copyAndInsertValue(final AtomicReference mutator, - final int bitpos, final K key, final V val) { - final int idx = TUPLE_LENGTH * dataIndex(bitpos); - - final Object[] src = this.nodes; - final Object[] dst = (Object[]) new Object[src.length + 2]; - - // copy 'src' and insert 2 element(s) at position 'idx' - System.arraycopy(src, 0, dst, 0, idx); - dst[idx + 0] = key; - dst[idx + 1] = val; - System.arraycopy(src, idx, dst, idx + 2, src.length - idx); - - return nodeOf(mutator, nodeMap(), (int) (dataMap() | bitpos), dst); - } - - @Override - CompactMapNode copyAndRemoveValue(final AtomicReference mutator, - final int bitpos) { - final int idx = TUPLE_LENGTH * dataIndex(bitpos); - - final Object[] src = this.nodes; - final Object[] dst = (Object[]) new Object[src.length - 2]; - - // copy 'src' and remove 2 element(s) at position 'idx' - System.arraycopy(src, 0, dst, 0, idx); - System.arraycopy(src, idx + 2, dst, idx, src.length - idx - 2); - - return nodeOf(mutator, nodeMap(), (int) (dataMap() ^ bitpos), dst); - } - - @Override - CompactMapNode copyAndMigrateFromInlineToNode(final AtomicReference mutator, - final int bitpos, final CompactMapNode node) { - - final int idxOld = TUPLE_LENGTH * dataIndex(bitpos); - final int idxNew = this.nodes.length - TUPLE_LENGTH - nodeIndex(bitpos); - - final Object[] src = this.nodes; - final Object[] dst = new Object[src.length - 2 + 1]; - - // copy 'src' and remove 2 element(s) at position 'idxOld' and - // insert 1 element(s) at position 'idxNew' (TODO: carefully test) - assert idxOld <= idxNew; - System.arraycopy(src, 0, dst, 0, idxOld); - System.arraycopy(src, idxOld + 2, dst, idxOld, idxNew - idxOld); - dst[idxNew + 0] = node; - System.arraycopy(src, idxNew + 2, dst, idxNew + 1, src.length - idxNew - 2); - - return nodeOf(mutator, (int) (nodeMap() | bitpos), (int) (dataMap() ^ bitpos), dst); - } - - @Override - CompactMapNode copyAndMigrateFromNodeToInline(final AtomicReference mutator, - final int bitpos, final CompactMapNode node) { - - final int idxOld = this.nodes.length - 1 - nodeIndex(bitpos); - final int idxNew = TUPLE_LENGTH * dataIndex(bitpos); - - final Object[] src = this.nodes; - final Object[] dst = new Object[src.length - 1 + 2]; - - // copy 'src' and remove 1 element(s) at position 'idxOld' and - // insert 2 element(s) at position 'idxNew' (TODO: carefully test) - assert idxOld >= idxNew; - System.arraycopy(src, 0, dst, 0, idxNew); - dst[idxNew + 0] = node.getKey(0); - dst[idxNew + 1] = node.getValue(0); - System.arraycopy(src, idxNew, dst, idxNew + 2, idxOld - idxNew); - System.arraycopy(src, idxOld + 1, dst, idxOld + 2, src.length - idxOld - 1); - - return nodeOf(mutator, (int) (nodeMap() ^ bitpos), (int) (dataMap() | bitpos), dst); - } - - } - - private static final class HashCollisionMapNode_5Bits extends CompactMapNode { - private final K[] keys; - private final V[] vals; - private final int hash; - - HashCollisionMapNode_5Bits(final int hash, final K[] keys, final V[] vals) { - this.keys = keys; - this.vals = vals; - this.hash = hash; - - assert payloadArity() >= 2; - } - - boolean containsKey(final K key, final int keyHash, final int shift) { - if (this.hash == keyHash) { - for (K k : keys) { - if (k.equals(key)) { - return true; - } - } - } - return false; - } - - boolean containsKey(final K key, final int keyHash, final int shift, - final Comparator cmp) { - if (this.hash == keyHash) { - for (K k : keys) { - if (cmp.compare(k, key) == 0) { - return true; - } - } - } - return false; - } - - Optional findByKey(final K key, final int keyHash, final int shift) { - for (int i = 0; i < keys.length; i++) { - final K _key = keys[i]; - if (key.equals(_key)) { - final V val = vals[i]; - return Optional.of(val); - } - } - return Optional.empty(); - } - - Optional findByKey(final K key, final int keyHash, final int shift, - final Comparator cmp) { - for (int i = 0; i < keys.length; i++) { - final K _key = keys[i]; - if (cmp.compare(key, _key) == 0) { - final V val = vals[i]; - return Optional.of(val); - } - } - return Optional.empty(); - } - - CompactMapNode updated(final AtomicReference mutator, final K key, - final V val, final int keyHash, final int shift, - final MapResult details) { - assert this.hash == keyHash; - - for (int idx = 0; idx < keys.length; idx++) { - if (keys[idx].equals(key)) { - final V currentVal = vals[idx]; - - if (currentVal.equals(val)) { - return this; - } else { - // add new mapping - final V[] src = this.vals; - @SuppressWarnings("unchecked") - final V[] dst = (V[]) new Object[src.length]; - - // copy 'src' and set 1 element(s) at position 'idx' - System.arraycopy(src, 0, dst, 0, src.length); - dst[idx + 0] = val; - - final CompactMapNode thisNew = new HashCollisionMapNode_5Bits<>( - this.hash, this.keys, dst); - - details.updated(currentVal); - return thisNew; - } - } - } - - @SuppressWarnings("unchecked") - final K[] keysNew = (K[]) new Object[this.keys.length + 1]; - - // copy 'this.keys' and insert 1 element(s) at position - // 'keys.length' - System.arraycopy(this.keys, 0, keysNew, 0, keys.length); - keysNew[keys.length + 0] = key; - System.arraycopy(this.keys, keys.length, keysNew, keys.length + 1, this.keys.length - - keys.length); - - @SuppressWarnings("unchecked") - final V[] valsNew = (V[]) new Object[this.vals.length + 1]; - - // copy 'this.vals' and insert 1 element(s) at position - // 'vals.length' - System.arraycopy(this.vals, 0, valsNew, 0, vals.length); - valsNew[vals.length + 0] = val; - System.arraycopy(this.vals, vals.length, valsNew, vals.length + 1, this.vals.length - - vals.length); - - details.modified(); - return new HashCollisionMapNode_5Bits<>(keyHash, keysNew, valsNew); - } - - CompactMapNode updated(final AtomicReference mutator, final K key, - final V val, final int keyHash, final int shift, - final MapResult details, final Comparator cmp) { - assert this.hash == keyHash; - - for (int idx = 0; idx < keys.length; idx++) { - if (cmp.compare(keys[idx], key) == 0) { - final V currentVal = vals[idx]; - - if (cmp.compare(currentVal, val) == 0) { - return this; - } else { - // add new mapping - final V[] src = this.vals; - @SuppressWarnings("unchecked") - final V[] dst = (V[]) new Object[src.length]; - - // copy 'src' and set 1 element(s) at position 'idx' - System.arraycopy(src, 0, dst, 0, src.length); - dst[idx + 0] = val; - - final CompactMapNode thisNew = new HashCollisionMapNode_5Bits<>( - this.hash, this.keys, dst); - - details.updated(currentVal); - return thisNew; - } - } - } - - @SuppressWarnings("unchecked") - final K[] keysNew = (K[]) new Object[this.keys.length + 1]; - - // copy 'this.keys' and insert 1 element(s) at position - // 'keys.length' - System.arraycopy(this.keys, 0, keysNew, 0, keys.length); - keysNew[keys.length + 0] = key; - System.arraycopy(this.keys, keys.length, keysNew, keys.length + 1, this.keys.length - - keys.length); - - @SuppressWarnings("unchecked") - final V[] valsNew = (V[]) new Object[this.vals.length + 1]; - - // copy 'this.vals' and insert 1 element(s) at position - // 'vals.length' - System.arraycopy(this.vals, 0, valsNew, 0, vals.length); - valsNew[vals.length + 0] = val; - System.arraycopy(this.vals, vals.length, valsNew, vals.length + 1, this.vals.length - - vals.length); - - details.modified(); - return new HashCollisionMapNode_5Bits<>(keyHash, keysNew, valsNew); - } - - CompactMapNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final MapResult details) { - for (int idx = 0; idx < keys.length; idx++) { - if (keys[idx].equals(key)) { - final V currentVal = vals[idx]; - details.updated(currentVal); - - if (this.arity() == 1) { - return nodeOf(mutator); - } else if (this.arity() == 2) { - /* - * Create root node with singleton element. This node - * will be a) either be the new root returned, or b) - * unwrapped and inlined. - */ - final K theOtherKey = (idx == 0) ? keys[1] : keys[0]; - final V theOtherVal = (idx == 0) ? vals[1] : vals[0]; - return CompactMapNode. nodeOf(mutator).updated(mutator, theOtherKey, - theOtherVal, keyHash, 0, details); - } else { - @SuppressWarnings("unchecked") - final K[] keysNew = (K[]) new Object[this.keys.length - 1]; - - // copy 'this.keys' and remove 1 element(s) at position - // 'idx' - System.arraycopy(this.keys, 0, keysNew, 0, idx); - System.arraycopy(this.keys, idx + 1, keysNew, idx, this.keys.length - idx - - 1); - - @SuppressWarnings("unchecked") - final V[] valsNew = (V[]) new Object[this.vals.length - 1]; - - // copy 'this.vals' and remove 1 element(s) at position - // 'idx' - System.arraycopy(this.vals, 0, valsNew, 0, idx); - System.arraycopy(this.vals, idx + 1, valsNew, idx, this.vals.length - idx - - 1); - - return new HashCollisionMapNode_5Bits<>(keyHash, keysNew, valsNew); - } - } - } - return this; - } - - CompactMapNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final MapResult details, - final Comparator cmp) { - for (int idx = 0; idx < keys.length; idx++) { - if (cmp.compare(keys[idx], key) == 0) { - final V currentVal = vals[idx]; - details.updated(currentVal); - - if (this.arity() == 1) { - return nodeOf(mutator); - } else if (this.arity() == 2) { - /* - * Create root node with singleton element. This node - * will be a) either be the new root returned, or b) - * unwrapped and inlined. - */ - final K theOtherKey = (idx == 0) ? keys[1] : keys[0]; - final V theOtherVal = (idx == 0) ? vals[1] : vals[0]; - return CompactMapNode. nodeOf(mutator).updated(mutator, theOtherKey, - theOtherVal, keyHash, 0, details, cmp); - } else { - @SuppressWarnings("unchecked") - final K[] keysNew = (K[]) new Object[this.keys.length - 1]; - - // copy 'this.keys' and remove 1 element(s) at position - // 'idx' - System.arraycopy(this.keys, 0, keysNew, 0, idx); - System.arraycopy(this.keys, idx + 1, keysNew, idx, this.keys.length - idx - - 1); - - @SuppressWarnings("unchecked") - final V[] valsNew = (V[]) new Object[this.vals.length - 1]; - - // copy 'this.vals' and remove 1 element(s) at position - // 'idx' - System.arraycopy(this.vals, 0, valsNew, 0, idx); - System.arraycopy(this.vals, idx + 1, valsNew, idx, this.vals.length - idx - - 1); - - return new HashCollisionMapNode_5Bits<>(keyHash, keysNew, valsNew); - } - } - } - return this; - } - - @Override - boolean hasPayload() { - return true; - } - - @Override - int payloadArity() { - return keys.length; - } - - @Override - boolean hasNodes() { - return false; - } - - @Override - int nodeArity() { - return 0; - } - - @Override - int arity() { - return payloadArity(); - } - - @Override - byte sizePredicate() { - return SIZE_MORE_THAN_ONE; - } - - @Override - K getKey(final int index) { - return keys[index]; - } - - @Override - V getValue(final int index) { - return vals[index]; - } - - Map.Entry getKeyValueEntry(final int index) { - return entryOf(keys[index], vals[index]); - } - - @Override - public CompactMapNode getNode(int index) { - throw new IllegalStateException("Is leaf node."); - } - - @Override - Object getSlot(final int index) { - throw new UnsupportedOperationException(); - } - - @Override - boolean hasSlots() { - throw new UnsupportedOperationException(); - } - - @Override - int slotArity() { - throw new UnsupportedOperationException(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 0; - result = prime * result + hash; - result = prime * result + Arrays.hashCode(keys); - result = prime * result + Arrays.hashCode(vals); - return result; - } - - @Override - public boolean equals(Object other) { - if (null == other) { - return false; - } - if (this == other) { - return true; - } - if (getClass() != other.getClass()) { - return false; - } - - HashCollisionMapNode_5Bits that = (HashCollisionMapNode_5Bits) other; - - if (hash != that.hash) { - return false; - } - - if (arity() != that.arity()) { - return false; - } - - /* - * Linear scan for each key, because of arbitrary element order. - */ - outerLoop: for (int i = 0; i < that.payloadArity(); i++) { - final Object otherKey = that.getKey(i); - final Object otherVal = that.getValue(i); - - for (int j = 0; j < keys.length; j++) { - final K key = keys[j]; - final V val = vals[j]; - - if (key.equals(otherKey) && val.equals(otherVal)) { - continue outerLoop; - } - } - return false; - } - - return true; - } - - @Override - CompactMapNode copyAndSetValue(final AtomicReference mutator, - final int bitpos, final V val) { - throw new UnsupportedOperationException(); - } - - @Override - CompactMapNode copyAndInsertValue(final AtomicReference mutator, - final int bitpos, final K key, final V val) { - throw new UnsupportedOperationException(); - } - - @Override - CompactMapNode copyAndRemoveValue(final AtomicReference mutator, - final int bitpos) { - throw new UnsupportedOperationException(); - } - - @Override - CompactMapNode copyAndSetNode(final AtomicReference mutator, - final int bitpos, final CompactMapNode node) { - throw new UnsupportedOperationException(); - } - - @Override - CompactMapNode copyAndMigrateFromInlineToNode(final AtomicReference mutator, - final int bitpos, final CompactMapNode node) { - throw new UnsupportedOperationException(); - } - - @Override - CompactMapNode copyAndMigrateFromNodeToInline(final AtomicReference mutator, - final int bitpos, final CompactMapNode node) { - throw new UnsupportedOperationException(); - } - - @Override - int nodeMap() { - throw new UnsupportedOperationException(); - } - - @Override - int dataMap() { - throw new UnsupportedOperationException(); - } - - } - - /** - * Iterator skeleton that uses a fixed stack in depth. - */ - private static abstract class AbstractMapIterator { - - private static final int MAX_DEPTH = 7; - - protected int currentValueCursor; - protected int currentValueLength; - protected AbstractMapNode currentValueNode; - - private int currentStackLevel = -1; - private final int[] nodeCursorsAndLengths = new int[MAX_DEPTH * 2]; - - @SuppressWarnings("unchecked") - AbstractMapNode[] nodes = new AbstractMapNode[MAX_DEPTH]; - - AbstractMapIterator(AbstractMapNode rootNode) { - if (rootNode.hasNodes()) { - currentStackLevel = 0; - - nodes[0] = rootNode; - nodeCursorsAndLengths[0] = 0; - nodeCursorsAndLengths[1] = rootNode.nodeArity(); - } - - if (rootNode.hasPayload()) { - currentValueNode = rootNode; - currentValueCursor = 0; - currentValueLength = rootNode.payloadArity(); - } - } - - /* - * search for next node that contains values - */ - private boolean searchNextValueNode() { - while (currentStackLevel >= 0) { - final int currentCursorIndex = currentStackLevel * 2; - final int currentLengthIndex = currentCursorIndex + 1; - - final int nodeCursor = nodeCursorsAndLengths[currentCursorIndex]; - final int nodeLength = nodeCursorsAndLengths[currentLengthIndex]; - - if (nodeCursor < nodeLength) { - final AbstractMapNode nextNode = nodes[currentStackLevel] - .getNode(nodeCursor); - nodeCursorsAndLengths[currentCursorIndex]++; - - if (nextNode.hasNodes()) { - /* - * put node on next stack level for depth-first - * traversal - */ - final int nextStackLevel = ++currentStackLevel; - final int nextCursorIndex = nextStackLevel * 2; - final int nextLengthIndex = nextCursorIndex + 1; - - nodes[nextStackLevel] = nextNode; - nodeCursorsAndLengths[nextCursorIndex] = 0; - nodeCursorsAndLengths[nextLengthIndex] = nextNode.nodeArity(); - } - - if (nextNode.hasPayload()) { - /* - * found next node that contains values - */ - currentValueNode = nextNode; - currentValueCursor = 0; - currentValueLength = nextNode.payloadArity(); - return true; - } - } else { - currentStackLevel--; - } - } - - return false; - } - - public boolean hasNext() { - if (currentValueCursor < currentValueLength) { - return true; - } else { - return searchNextValueNode(); - } - } - - public void remove() { - throw new UnsupportedOperationException(); - } - } - - protected static class MapKeyIterator extends AbstractMapIterator implements - Iterator { - - MapKeyIterator(AbstractMapNode rootNode) { - super(rootNode); - } - - @Override - public K next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } else { - return currentValueNode.getKey(currentValueCursor++); - } - } - - } - - protected static class MapValueIterator extends AbstractMapIterator implements - Iterator { - - MapValueIterator(AbstractMapNode rootNode) { - super(rootNode); - } - - @Override - public V next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } else { - return currentValueNode.getValue(currentValueCursor++); - } - } - - } - - protected static class MapEntryIterator extends AbstractMapIterator implements - Iterator> { - - MapEntryIterator(AbstractMapNode rootNode) { - super(rootNode); - } - - @Override - public Map.Entry next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } else { - return currentValueNode.getKeyValueEntry(currentValueCursor++); - } - } - - } - - /** - * Iterator that first iterates over inlined-values and then continues depth - * first recursively. - */ - private static class TrieMap_5BitsNodeIterator implements Iterator> { - - final Deque>> nodeIteratorStack; - - TrieMap_5BitsNodeIterator(AbstractMapNode rootNode) { - nodeIteratorStack = new ArrayDeque<>(); - nodeIteratorStack.push(Collections.singleton(rootNode).iterator()); - } - - @Override - public boolean hasNext() { - while (true) { - if (nodeIteratorStack.isEmpty()) { - return false; - } else { - if (nodeIteratorStack.peek().hasNext()) { - return true; - } else { - nodeIteratorStack.pop(); - continue; - } - } - } - } - - @Override - public AbstractMapNode next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - - AbstractMapNode innerNode = nodeIteratorStack.peek().next(); - - if (innerNode.hasNodes()) { - nodeIteratorStack.push(innerNode.nodeIterator()); - } - - return innerNode; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - - static final class TransientTrieMap_5Bits implements TransientMap { - final private AtomicReference mutator; - private AbstractMapNode rootNode; - private int hashCode; - private int cachedSize; - - TransientTrieMap_5Bits(TrieMap_5Bits trieMap_5Bits) { - this.mutator = new AtomicReference(Thread.currentThread()); - this.rootNode = trieMap_5Bits.rootNode; - this.hashCode = trieMap_5Bits.hashCode; - this.cachedSize = trieMap_5Bits.cachedSize; - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - } - - private boolean checkHashCodeAndSize(final int targetHash, final int targetSize) { - int hash = 0; - int size = 0; - - for (Iterator> it = entryIterator(); it.hasNext();) { - final Map.Entry entry = it.next(); - final K key = entry.getKey(); - final V val = entry.getValue(); - - hash += key.hashCode() ^ val.hashCode(); - size += 1; - } - - return hash == targetHash && size == targetSize; - } - - public V put(final K key, final V val) { - throw new UnsupportedOperationException(); - } - - public void putAll(final Map m) { - throw new UnsupportedOperationException(); - } - - public void clear() { - throw new UnsupportedOperationException(); - } - - public V remove(final Object key) { - throw new UnsupportedOperationException(); - } - - public boolean containsKey(final Object o) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - return rootNode.containsKey(key, transformHashCode(key.hashCode()), 0); - } catch (ClassCastException unused) { - return false; - } - } - - public boolean containsKeyEquivalent(final Object o, final Comparator cmp) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - return rootNode.containsKey(key, transformHashCode(key.hashCode()), 0, cmp); - } catch (ClassCastException unused) { - return false; - } - } - - public boolean containsValue(final Object o) { - for (Iterator iterator = valueIterator(); iterator.hasNext();) { - if (iterator.next().equals(o)) { - return true; - } - } - return false; - } - - public boolean containsValueEquivalent(final Object o, final Comparator cmp) { - for (Iterator iterator = valueIterator(); iterator.hasNext();) { - if (cmp.compare(iterator.next(), o) == 0) { - return true; - } - } - return false; - } - - public V get(final Object o) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - final Optional result = rootNode.findByKey(key, - transformHashCode(key.hashCode()), 0); - - if (result.isPresent()) { - return result.get(); - } else { - return null; - } - } catch (ClassCastException unused) { - return null; - } - } - - public V getEquivalent(final Object o, final Comparator cmp) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - final Optional result = rootNode.findByKey(key, - transformHashCode(key.hashCode()), 0, cmp); - - if (result.isPresent()) { - return result.get(); - } else { - return null; - } - } catch (ClassCastException unused) { - return null; - } - } - - public V __put(final K key, final V val) { - if (mutator.get() == null) { - throw new IllegalStateException("Transient already frozen."); - } - - final int keyHash = key.hashCode(); - final MapResult details = MapResult.unchanged(); - - final CompactMapNode newRootNode = rootNode.updated(mutator, key, val, - transformHashCode(keyHash), 0, details); - - if (details.isModified()) { - if (details.hasReplacedValue()) { - final V old = details.getReplacedValue(); - - final int valHashOld = old.hashCode(); - final int valHashNew = val.hashCode(); - - rootNode = newRootNode; - hashCode = hashCode + (keyHash ^ valHashNew) - (keyHash ^ valHashOld); - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return details.getReplacedValue(); - } else { - final int valHashNew = val.hashCode(); - rootNode = newRootNode; - hashCode += (keyHash ^ valHashNew); - cachedSize += 1; - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return null; - } - } - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return null; - } - - public V __putEquivalent(final K key, final V val, final Comparator cmp) { - if (mutator.get() == null) { - throw new IllegalStateException("Transient already frozen."); - } - - final int keyHash = key.hashCode(); - final MapResult details = MapResult.unchanged(); - - final CompactMapNode newRootNode = rootNode.updated(mutator, key, val, - transformHashCode(keyHash), 0, details, cmp); - - if (details.isModified()) { - if (details.hasReplacedValue()) { - final V old = details.getReplacedValue(); - - final int valHashOld = old.hashCode(); - final int valHashNew = val.hashCode(); - - rootNode = newRootNode; - hashCode = hashCode + (keyHash ^ valHashNew) - (keyHash ^ valHashOld); - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return details.getReplacedValue(); - } else { - final int valHashNew = val.hashCode(); - rootNode = newRootNode; - hashCode += (keyHash ^ valHashNew); - cachedSize += 1; - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return null; - } - } - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return null; - } - - public boolean __putAll(final Map map) { - boolean modified = false; - - for (Map.Entry entry : map.entrySet()) { - final boolean isPresent = this.containsKey(entry.getKey()); - final V replaced = this.__put(entry.getKey(), entry.getValue()); - - if (!isPresent || replaced != null) { - modified = true; - } - } - - return modified; - } - - public boolean __putAllEquivalent(final Map map, - final Comparator cmp) { - boolean modified = false; - - for (Map.Entry entry : map.entrySet()) { - final boolean isPresent = this.containsKeyEquivalent(entry.getKey(), cmp); - final V replaced = this.__putEquivalent(entry.getKey(), entry.getValue(), cmp); - - if (!isPresent || replaced != null) { - modified = true; - } - } - - return modified; - } - - public V __remove(final K key) { - if (mutator.get() == null) { - throw new IllegalStateException("Transient already frozen."); - } - - final int keyHash = key.hashCode(); - final MapResult details = MapResult.unchanged(); - - final CompactMapNode newRootNode = rootNode.removed(mutator, key, - transformHashCode(keyHash), 0, details); - - if (details.isModified()) { - assert details.hasReplacedValue(); - final int valHash = details.getReplacedValue().hashCode(); - - rootNode = newRootNode; - hashCode = hashCode - (keyHash ^ valHash); - cachedSize = cachedSize - 1; - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return details.getReplacedValue(); - } - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - - return null; - } - - public V __removeEquivalent(final K key, final Comparator cmp) { - if (mutator.get() == null) { - throw new IllegalStateException("Transient already frozen."); - } - - final int keyHash = key.hashCode(); - final MapResult details = MapResult.unchanged(); - - final CompactMapNode newRootNode = rootNode.removed(mutator, key, - transformHashCode(keyHash), 0, details, cmp); - - if (details.isModified()) { - assert details.hasReplacedValue(); - final int valHash = details.getReplacedValue().hashCode(); - - rootNode = newRootNode; - hashCode = hashCode - (keyHash ^ valHash); - cachedSize = cachedSize - 1; - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return details.getReplacedValue(); - } - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - - return null; - } - - public int size() { - return cachedSize; - } - - public boolean isEmpty() { - return cachedSize == 0; - } - - public Iterator keyIterator() { - return new TransientMapKeyIterator<>(this); - } - - public Iterator valueIterator() { - return new TransientMapValueIterator<>(this); - } - - public Iterator> entryIterator() { - return new TransientMapEntryIterator<>(this); - } - - public static class TransientMapKeyIterator extends MapKeyIterator { - final TransientTrieMap_5Bits collection; - K lastKey; - - public TransientMapKeyIterator(final TransientTrieMap_5Bits collection) { - super(collection.rootNode); - this.collection = collection; - } - - public K next() { - return lastKey = super.next(); - } - - public void remove() { - // TODO: test removal at iteration rigorously - collection.__remove(lastKey); - } - } - - public static class TransientMapValueIterator extends MapValueIterator { - final TransientTrieMap_5Bits collection; - - public TransientMapValueIterator(final TransientTrieMap_5Bits collection) { - super(collection.rootNode); - this.collection = collection; - } - - public V next() { - return super.next(); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - } - - public static class TransientMapEntryIterator extends MapEntryIterator { - final TransientTrieMap_5Bits collection; - - public TransientMapEntryIterator(final TransientTrieMap_5Bits collection) { - super(collection.rootNode); - this.collection = collection; - } - - public Map.Entry next() { - return super.next(); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - } - - @Override - public Set keySet() { - Set keySet = null; - - if (keySet == null) { - keySet = new AbstractSet() { - @Override - public Iterator iterator() { - return TransientTrieMap_5Bits.this.keyIterator(); - } - - @Override - public int size() { - return TransientTrieMap_5Bits.this.size(); - } - - @Override - public boolean isEmpty() { - return TransientTrieMap_5Bits.this.isEmpty(); - } - - @Override - public void clear() { - TransientTrieMap_5Bits.this.clear(); - } - - @Override - public boolean contains(Object k) { - return TransientTrieMap_5Bits.this.containsKey(k); - } - }; - } - - return keySet; - } - - @Override - public Collection values() { - Collection values = null; - - if (values == null) { - values = new AbstractCollection() { - @Override - public Iterator iterator() { - return TransientTrieMap_5Bits.this.valueIterator(); - } - - @Override - public int size() { - return TransientTrieMap_5Bits.this.size(); - } - - @Override - public boolean isEmpty() { - return TransientTrieMap_5Bits.this.isEmpty(); - } - - @Override - public void clear() { - TransientTrieMap_5Bits.this.clear(); - } - - @Override - public boolean contains(Object v) { - return TransientTrieMap_5Bits.this.containsValue(v); - } - }; - } - - return values; - } - - @Override - public Set> entrySet() { - Set> entrySet = null; - - if (entrySet == null) { - entrySet = new AbstractSet>() { - @Override - public Iterator> iterator() { - return new Iterator>() { - private final Iterator> i = entryIterator(); - - @Override - public boolean hasNext() { - return i.hasNext(); - } - - @Override - public Map.Entry next() { - return i.next(); - } - - @Override - public void remove() { - i.remove(); - } - }; - } - - @Override - public int size() { - return TransientTrieMap_5Bits.this.size(); - } - - @Override - public boolean isEmpty() { - return TransientTrieMap_5Bits.this.isEmpty(); - } - - @Override - public void clear() { - TransientTrieMap_5Bits.this.clear(); - } - - @Override - public boolean contains(Object k) { - return TransientTrieMap_5Bits.this.containsKey(k); - } - }; - } - - return entrySet; - } - - @Override - public boolean equals(final Object other) { - if (other == this) { - return true; - } - if (other == null) { - return false; - } - - if (other instanceof TransientTrieMap_5Bits) { - TransientTrieMap_5Bits that = (TransientTrieMap_5Bits) other; - - if (this.cachedSize != that.cachedSize) { - return false; - } - - if (this.hashCode != that.hashCode) { - return false; - } - - return rootNode.equals(that.rootNode); - } else if (other instanceof Map) { - Map that = (Map) other; - - if (this.size() != that.size()) - return false; - - for (@SuppressWarnings("unchecked") - Iterator it = that.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = it.next(); - - try { - @SuppressWarnings("unchecked") - final K key = (K) entry.getKey(); - final Optional result = rootNode.findByKey(key, - transformHashCode(key.hashCode()), 0); - - if (!result.isPresent()) { - return false; - } else { - @SuppressWarnings("unchecked") - final V val = (V) entry.getValue(); - - if (!result.get().equals(val)) { - return false; - } - } - } catch (ClassCastException unused) { - return false; - } - } - - return true; - } - - return false; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public ImmutableMap freeze() { - if (mutator.get() == null) { - throw new IllegalStateException("Transient already frozen."); - } - - mutator.set(null); - return new TrieMap_5Bits(rootNode, hashCode, cachedSize); - } - } - -} diff --git a/capsule/src/main/java/io/usethesource/capsule/TrieSet_5Bits.java b/capsule/src/main/java/io/usethesource/capsule/TrieSet_5Bits.java deleted file mode 100644 index d7757765e..000000000 --- a/capsule/src/main/java/io/usethesource/capsule/TrieSet_5Bits.java +++ /dev/null @@ -1,2314 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2015 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import java.text.DecimalFormat; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Deque; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; - -@SuppressWarnings("rawtypes") -public class TrieSet_5Bits implements ImmutableSet { - - @SuppressWarnings("unchecked") - private static final TrieSet_5Bits EMPTY_SET = new TrieSet_5Bits(CompactSetNode.EMPTY_NODE, 0, - 0); - - private static final boolean DEBUG = false; - - private final AbstractSetNode rootNode; - private final int hashCode; - private final int cachedSize; - - TrieSet_5Bits(AbstractSetNode rootNode, int hashCode, int cachedSize) { - this.rootNode = rootNode; - this.hashCode = hashCode; - this.cachedSize = cachedSize; - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - } - - @SuppressWarnings("unchecked") - public static final ImmutableSet of() { - return TrieSet_5Bits.EMPTY_SET; - } - - @SuppressWarnings("unchecked") - public static final ImmutableSet of(K... keys) { - ImmutableSet result = TrieSet_5Bits.EMPTY_SET; - - for (final K key : keys) { - result = result.__insert(key); - } - - return result; - } - - @SuppressWarnings("unchecked") - public static final TransientSet transientOf() { - return TrieSet_5Bits.EMPTY_SET.asTransient(); - } - - @SuppressWarnings("unchecked") - public static final TransientSet transientOf(K... keys) { - final TransientSet result = TrieSet_5Bits.EMPTY_SET.asTransient(); - - for (final K key : keys) { - result.__insert(key); - } - - return result; - } - - private boolean checkHashCodeAndSize(final int targetHash, final int targetSize) { - int hash = 0; - int size = 0; - - for (Iterator it = keyIterator(); it.hasNext();) { - final K key = it.next(); - - hash += key.hashCode(); - size += 1; - } - - return hash == targetHash && size == targetSize; - } - - public static final int transformHashCode(final int hash) { - return hash; - } - - public boolean contains(final Object o) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - return rootNode.contains(key, transformHashCode(key.hashCode()), 0); - } catch (ClassCastException unused) { - return false; - } - } - - public boolean containsEquivalent(final Object o, final Comparator cmp) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - return rootNode.contains(key, transformHashCode(key.hashCode()), 0, cmp); - } catch (ClassCastException unused) { - return false; - } - } - - public K get(final Object o) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - final Optional result = rootNode - .findByKey(key, transformHashCode(key.hashCode()), 0); - - if (result.isPresent()) { - return result.get(); - } else { - return null; - } - } catch (ClassCastException unused) { - return null; - } - } - - public K getEquivalent(final Object o, final Comparator cmp) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - final Optional result = rootNode.findByKey(key, transformHashCode(key.hashCode()), - 0, cmp); - - if (result.isPresent()) { - return result.get(); - } else { - return null; - } - } catch (ClassCastException unused) { - return null; - } - } - - public ImmutableSet __insert(final K key) { - final int keyHash = key.hashCode(); - final SetResult details = SetResult.unchanged(); - - final CompactSetNode newRootNode = rootNode.updated(null, key, - transformHashCode(keyHash), 0, details); - - if (details.isModified()) { - return new TrieSet_5Bits(newRootNode, hashCode + keyHash, cachedSize + 1); - } - - return this; - } - - public ImmutableSet __insertEquivalent(final K key, final Comparator cmp) { - final int keyHash = key.hashCode(); - final SetResult details = SetResult.unchanged(); - - final CompactSetNode newRootNode = rootNode.updated(null, key, - transformHashCode(keyHash), 0, details, cmp); - - if (details.isModified()) { - return new TrieSet_5Bits(newRootNode, hashCode + keyHash, cachedSize + 1); - } - - return this; - } - - public ImmutableSet __insertAll(final Set set) { - final TransientSet tmpTransient = this.asTransient(); - tmpTransient.__insertAll(set); - return tmpTransient.freeze(); - } - - public ImmutableSet __insertAllEquivalent(final Set set, - final Comparator cmp) { - final TransientSet tmpTransient = this.asTransient(); - tmpTransient.__insertAllEquivalent(set, cmp); - return tmpTransient.freeze(); - } - - public ImmutableSet __remove(final K key) { - final int keyHash = key.hashCode(); - final SetResult details = SetResult.unchanged(); - - final CompactSetNode newRootNode = rootNode.removed(null, key, - transformHashCode(keyHash), 0, details); - - if (details.isModified()) { - return new TrieSet_5Bits(newRootNode, hashCode - keyHash, cachedSize - 1); - } - - return this; - } - - public ImmutableSet __removeEquivalent(final K key, final Comparator cmp) { - final int keyHash = key.hashCode(); - final SetResult details = SetResult.unchanged(); - - final CompactSetNode newRootNode = rootNode.removed(null, key, - transformHashCode(keyHash), 0, details, cmp); - - if (details.isModified()) { - return new TrieSet_5Bits(newRootNode, hashCode - keyHash, cachedSize - 1); - } - - return this; - } - - public ImmutableSet __removeAll(final Set set) { - final TransientSet tmpTransient = this.asTransient(); - tmpTransient.__removeAll(set); - return tmpTransient.freeze(); - } - - public ImmutableSet __removeAllEquivalent(final Set set, - final Comparator cmp) { - final TransientSet tmpTransient = this.asTransient(); - tmpTransient.__removeAllEquivalent(set, cmp); - return tmpTransient.freeze(); - } - - public ImmutableSet __retainAll(final Set set) { - final TransientSet tmpTransient = this.asTransient(); - tmpTransient.__retainAll(set); - return tmpTransient.freeze(); - } - - public ImmutableSet __retainAllEquivalent(final TransientSet transientSet, - final Comparator cmp) { - final TransientSet tmpTransient = this.asTransient(); - tmpTransient.__retainAllEquivalent(transientSet, cmp); - return tmpTransient.freeze(); - } - - public boolean add(final K key) { - throw new UnsupportedOperationException(); - } - - public boolean addAll(final Collection c) { - throw new UnsupportedOperationException(); - } - - public void clear() { - throw new UnsupportedOperationException(); - } - - public boolean remove(final Object key) { - throw new UnsupportedOperationException(); - } - - public boolean removeAll(final Collection c) { - throw new UnsupportedOperationException(); - } - - public boolean retainAll(final Collection c) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean containsAll(final Collection c) { - for (Object item : c) { - if (!contains(item)) { - return false; - } - } - return true; - } - - @Override - public boolean containsAllEquivalent(final Collection c, final Comparator cmp) { - for (Object item : c) { - if (!containsEquivalent(item, cmp)) { - return false; - } - } - return true; - } - - public int size() { - return cachedSize; - } - - public boolean isEmpty() { - return cachedSize == 0; - } - - public Iterator iterator() { - return keyIterator(); - } - - public Iterator keyIterator() { - return new SetKeyIterator<>(rootNode); - } - - @Override - public Object[] toArray() { - Object[] array = new Object[cachedSize]; - - int idx = 0; - for (K key : this) { - array[idx++] = key; - } - - return array; - } - - @Override - public T[] toArray(final T[] a) { - List list = new ArrayList(cachedSize); - - for (K key : this) { - list.add(key); - } - - return list.toArray(a); - } - - @Override - public boolean equals(final Object other) { - if (other == this) { - return true; - } - if (other == null) { - return false; - } - - if (other instanceof TrieSet_5Bits) { - TrieSet_5Bits that = (TrieSet_5Bits) other; - - if (this.cachedSize != that.cachedSize) { - return false; - } - - if (this.hashCode != that.hashCode) { - return false; - } - - return rootNode.equals(that.rootNode); - } else if (other instanceof Set) { - Set that = (Set) other; - - if (this.size() != that.size()) - return false; - - return containsAll(that); - } - - return false; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean isTransientSupported() { - return true; - } - - @Override - public TransientSet asTransient() { - return new TransientTrieSet_5Bits(this); - } - - /* - * For analysis purposes only. - */ - protected AbstractSetNode getRootNode() { - return rootNode; - } - - /* - * For analysis purposes only. - */ - protected Iterator> nodeIterator() { - return new TrieSet_5BitsNodeIterator<>(rootNode); - } - - /* - * For analysis purposes only. - */ - protected int getNodeCount() { - final Iterator> it = nodeIterator(); - int sumNodes = 0; - - for (; it.hasNext(); it.next()) { - sumNodes += 1; - } - - return sumNodes; - } - - /* - * For analysis purposes only. Payload X Node - */ - protected int[][] arityCombinationsHistogram() { - final Iterator> it = nodeIterator(); - final int[][] sumArityCombinations = new int[33][33]; - - while (it.hasNext()) { - final AbstractSetNode node = it.next(); - sumArityCombinations[node.payloadArity()][node.nodeArity()] += 1; - } - - return sumArityCombinations; - } - - /* - * For analysis purposes only. - */ - protected int[] arityHistogram() { - final int[][] sumArityCombinations = arityCombinationsHistogram(); - final int[] sumArity = new int[33]; - - final int maxArity = 32; // TODO: factor out constant - - for (int j = 0; j <= maxArity; j++) { - for (int maxRestArity = maxArity - j, k = 0; k <= maxRestArity - j; k++) { - sumArity[j + k] += sumArityCombinations[j][k]; - } - } - - return sumArity; - } - - /* - * For analysis purposes only. - */ - public void printStatistics() { - final int[][] sumArityCombinations = arityCombinationsHistogram(); - final int[] sumArity = arityHistogram(); - final int sumNodes = getNodeCount(); - - final int[] cumsumArity = new int[33]; - for (int cumsum = 0, i = 0; i < 33; i++) { - cumsum += sumArity[i]; - cumsumArity[i] = cumsum; - } - - final float threshhold = 0.01f; // for printing results - for (int i = 0; i < 33; i++) { - float arityPercentage = (float) (sumArity[i]) / sumNodes; - float cumsumArityPercentage = (float) (cumsumArity[i]) / sumNodes; - - if (arityPercentage != 0 && arityPercentage >= threshhold) { - // details per level - StringBuilder bldr = new StringBuilder(); - int max = i; - for (int j = 0; j <= max; j++) { - for (int k = max - j; k <= max - j; k++) { - float arityCombinationsPercentage = (float) (sumArityCombinations[j][k]) - / sumNodes; - - if (arityCombinationsPercentage != 0 - && arityCombinationsPercentage >= threshhold) { - bldr.append(String.format("%d/%d: %s, ", j, k, new DecimalFormat( - "0.00%").format(arityCombinationsPercentage))); - } - } - } - final String detailPercentages = bldr.toString(); - - // overview - System.out.println(String.format("%2d: %s\t[cumsum = %s]\t%s", i, - new DecimalFormat("0.00%").format(arityPercentage), - new DecimalFormat("0.00%").format(cumsumArityPercentage), - detailPercentages)); - } - } - } - - abstract static class Optional { - private static final Optional EMPTY = new Optional() { - @Override - boolean isPresent() { - return false; - } - - @Override - Object get() { - return null; - } - }; - - @SuppressWarnings("unchecked") - static Optional empty() { - return EMPTY; - } - - static Optional of(T value) { - return new Value(value); - } - - abstract boolean isPresent(); - - abstract T get(); - - private static final class Value extends Optional { - private final T value; - - private Value(T value) { - this.value = value; - } - - @Override - boolean isPresent() { - return true; - } - - @Override - T get() { - return value; - } - } - } - - static final class SetResult { - private K replacedValue; - private boolean isModified; - private boolean isReplaced; - - // update: inserted/removed single element, element count changed - public void modified() { - this.isModified = true; - } - - public void updated(K replacedValue) { - this.replacedValue = replacedValue; - this.isModified = true; - this.isReplaced = true; - } - - // update: neither element, nor element count changed - public static SetResult unchanged() { - return new SetResult<>(); - } - - private SetResult() { - } - - public boolean isModified() { - return isModified; - } - - public boolean hasReplacedValue() { - return isReplaced; - } - - public K getReplacedValue() { - return replacedValue; - } - } - - protected static interface INode { - } - - protected static abstract class AbstractSetNode implements INode { - - static final int TUPLE_LENGTH = 1; - - abstract boolean contains(final K key, final int keyHash, final int shift); - - abstract boolean contains(final K key, final int keyHash, final int shift, - final Comparator cmp); - - abstract Optional findByKey(final K key, final int keyHash, final int shift); - - abstract Optional findByKey(final K key, final int keyHash, final int shift, - final Comparator cmp); - - abstract CompactSetNode updated(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details); - - abstract CompactSetNode updated(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details, - final Comparator cmp); - - abstract CompactSetNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details); - - abstract CompactSetNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details, - final Comparator cmp); - - static final boolean isAllowedToEdit(AtomicReference x, AtomicReference y) { - return x != null && y != null && (x == y || x.get() == y.get()); - } - - abstract boolean hasNodes(); - - abstract int nodeArity(); - - abstract AbstractSetNode getNode(final int index); - - @Deprecated - Iterator> nodeIterator() { - return new Iterator>() { - - int nextIndex = 0; - final int nodeArity = AbstractSetNode.this.nodeArity(); - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - @Override - public AbstractSetNode next() { - if (!hasNext()) - throw new NoSuchElementException(); - return AbstractSetNode.this.getNode(nextIndex++); - } - - @Override - public boolean hasNext() { - return nextIndex < nodeArity; - } - }; - } - - abstract boolean hasPayload(); - - abstract int payloadArity(); - - abstract K getKey(final int index); - - @Deprecated - abstract boolean hasSlots(); - - abstract int slotArity(); - - abstract Object getSlot(final int index); - - /** - * The arity of this trie node (i.e. number of values and nodes stored - * on this level). - * - * @return sum of nodes and values stored within - */ - - int arity() { - return payloadArity() + nodeArity(); - } - - int size() { - final Iterator it = new SetKeyIterator<>(this); - - int size = 0; - while (it.hasNext()) { - size += 1; - it.next(); - } - - return size; - } - } - - protected static abstract class CompactSetNode extends AbstractSetNode { - - static final int HASH_CODE_LENGTH = 32; - - static final int BIT_PARTITION_SIZE = 5; - static final int BIT_PARTITION_MASK = 0b11111; - - static final int mask(final int keyHash, final int shift) { - return (keyHash >>> shift) & BIT_PARTITION_MASK; - } - - static final int bitpos(final int mask) { - return (int) (1 << mask); - } - - abstract int nodeMap(); - - abstract int dataMap(); - - static final byte SIZE_EMPTY = 0b00; - static final byte SIZE_ONE = 0b01; - static final byte SIZE_MORE_THAN_ONE = 0b10; - - /** - * Abstract predicate over a node's size. Value can be either - * {@value #SIZE_EMPTY}, {@value #SIZE_ONE}, or - * {@value #SIZE_MORE_THAN_ONE}. - * - * @return size predicate - */ - abstract byte sizePredicate(); - - @Override - abstract CompactSetNode getNode(final int index); - - boolean nodeInvariant() { - boolean inv1 = (size() - payloadArity() >= 2 * (arity() - payloadArity())); - boolean inv2 = (this.arity() == 0) ? sizePredicate() == SIZE_EMPTY : true; - boolean inv3 = (this.arity() == 1 && payloadArity() == 1) ? sizePredicate() == SIZE_ONE - : true; - boolean inv4 = (this.arity() >= 2) ? sizePredicate() == SIZE_MORE_THAN_ONE : true; - - boolean inv5 = (this.nodeArity() >= 0) && (this.payloadArity() >= 0) - && ((this.payloadArity() + this.nodeArity()) == this.arity()); - - return inv1 && inv2 && inv3 && inv4 && inv5; - } - - abstract CompactSetNode copyAndInsertValue(final AtomicReference mutator, - final int bitpos, final K key); - - abstract CompactSetNode copyAndRemoveValue(final AtomicReference mutator, - final int bitpos); - - abstract CompactSetNode copyAndSetNode(final AtomicReference mutator, - final int bitpos, final CompactSetNode node); - - abstract CompactSetNode copyAndMigrateFromInlineToNode( - final AtomicReference mutator, final int bitpos, - final CompactSetNode node); - - abstract CompactSetNode copyAndMigrateFromNodeToInline( - final AtomicReference mutator, final int bitpos, - final CompactSetNode node); - - static final CompactSetNode mergeTwoKeyValPairs(final K key0, final int keyHash0, - final K key1, final int keyHash1, final int shift) { - assert !(key0.equals(key1)); - - if (shift >= HASH_CODE_LENGTH) { - // throw new - // IllegalStateException("Hash collision not yet fixed."); - return new HashCollisionSetNode_5Bits<>(keyHash0, (K[]) new Object[] { key0, key1 }); - } - - final int mask0 = mask(keyHash0, shift); - final int mask1 = mask(keyHash1, shift); - - if (mask0 != mask1) { - // both nodes fit on same level - final int dataMap = (int) (bitpos(mask0) | bitpos(mask1)); - - if (mask0 < mask1) { - return nodeOf(null, (int) (0), dataMap, new Object[] { key0, key1 }); - } else { - return nodeOf(null, (int) (0), dataMap, new Object[] { key1, key0 }); - } - } else { - final CompactSetNode node = mergeTwoKeyValPairs(key0, keyHash0, key1, keyHash1, - shift + BIT_PARTITION_SIZE); - // values fit on next level - - final int nodeMap = bitpos(mask0); - return nodeOf(null, nodeMap, (int) (0), new Object[] { node }); - } - } - - static final CompactSetNode EMPTY_NODE; - - static { - - EMPTY_NODE = new BitmapIndexedSetNode<>(null, (int) (0), (int) (0), new Object[] {}); - - }; - - static final CompactSetNode nodeOf(final AtomicReference mutator, - final int nodeMap, final int dataMap, final Object[] nodes) { - return new BitmapIndexedSetNode<>(mutator, nodeMap, dataMap, nodes); - } - - @SuppressWarnings("unchecked") - static final CompactSetNode nodeOf(AtomicReference mutator) { - return EMPTY_NODE; - } - - static final CompactSetNode nodeOf(AtomicReference mutator, - final int nodeMap, final int dataMap, final K key) { - assert nodeMap == 0; - return nodeOf(mutator, (int) (0), dataMap, new Object[] { key }); - } - - static final int index(final int bitmap, final int bitpos) { - return java.lang.Integer.bitCount(bitmap & (bitpos - 1)); - } - - static final int index(final int bitmap, final int mask, final int bitpos) { - return (bitmap == -1) ? mask : index(bitmap, bitpos); - } - - int dataIndex(final int bitpos) { - return java.lang.Integer.bitCount(dataMap() & (bitpos - 1)); - } - - int nodeIndex(final int bitpos) { - return java.lang.Integer.bitCount(nodeMap() & (bitpos - 1)); - } - - CompactSetNode nodeAt(final int bitpos) { - return getNode(nodeIndex(bitpos)); - } - - boolean contains(final K key, final int keyHash, final int shift) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - final int dataMap = dataMap(); - if ((dataMap & bitpos) != 0) { - final int index = index(dataMap, mask, bitpos); - return getKey(index).equals(key); - } - - final int nodeMap = nodeMap(); - if ((nodeMap & bitpos) != 0) { - final int index = index(nodeMap, mask, bitpos); - return getNode(index).contains(key, keyHash, shift + BIT_PARTITION_SIZE); - } - - return false; - } - - boolean contains(final K key, final int keyHash, final int shift, - final Comparator cmp) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - final int dataMap = dataMap(); - if ((dataMap & bitpos) != 0) { - final int index = index(dataMap, mask, bitpos); - return cmp.compare(getKey(index), key) == 0; - } - - final int nodeMap = nodeMap(); - if ((nodeMap & bitpos) != 0) { - final int index = index(nodeMap, mask, bitpos); - return getNode(index).contains(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); - } - - return false; - } - - Optional findByKey(final K key, final int keyHash, final int shift) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int index = dataIndex(bitpos); - if (getKey(index).equals(key)) { - return Optional.of(getKey(index)); - } - - return Optional.empty(); - } - - if ((nodeMap() & bitpos) != 0) { // node (not value) - final AbstractSetNode subNode = nodeAt(bitpos); - - return subNode.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE); - } - - return Optional.empty(); - } - - Optional findByKey(final K key, final int keyHash, final int shift, - final Comparator cmp) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int index = dataIndex(bitpos); - if (cmp.compare(getKey(index), key) == 0) { - return Optional.of(getKey(index)); - } - - return Optional.empty(); - } - - if ((nodeMap() & bitpos) != 0) { // node (not value) - final AbstractSetNode subNode = nodeAt(bitpos); - - return subNode.findByKey(key, keyHash, shift + BIT_PARTITION_SIZE, cmp); - } - - return Optional.empty(); - } - - CompactSetNode updated(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int dataIndex = dataIndex(bitpos); - final K currentKey = getKey(dataIndex); - - if (currentKey.equals(key)) { - return this; - } else { - final CompactSetNode subNodeNew = mergeTwoKeyValPairs(currentKey, - transformHashCode(currentKey.hashCode()), key, keyHash, shift - + BIT_PARTITION_SIZE); - - details.modified(); - return copyAndMigrateFromInlineToNode(mutator, bitpos, subNodeNew); - } - } else if ((nodeMap() & bitpos) != 0) { // node (not value) - final CompactSetNode subNode = nodeAt(bitpos); - final CompactSetNode subNodeNew = subNode.updated(mutator, key, keyHash, shift - + BIT_PARTITION_SIZE, details); - - if (details.isModified()) { - return copyAndSetNode(mutator, bitpos, subNodeNew); - } else { - return this; - } - } else { - // no value - details.modified(); - return copyAndInsertValue(mutator, bitpos, key); - } - } - - CompactSetNode updated(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details, - final Comparator cmp) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int dataIndex = dataIndex(bitpos); - final K currentKey = getKey(dataIndex); - - if (cmp.compare(currentKey, key) == 0) { - return this; - } else { - final CompactSetNode subNodeNew = mergeTwoKeyValPairs(currentKey, - transformHashCode(currentKey.hashCode()), key, keyHash, shift - + BIT_PARTITION_SIZE); - - details.modified(); - return copyAndMigrateFromInlineToNode(mutator, bitpos, subNodeNew); - } - } else if ((nodeMap() & bitpos) != 0) { // node (not value) - final CompactSetNode subNode = nodeAt(bitpos); - final CompactSetNode subNodeNew = subNode.updated(mutator, key, keyHash, shift - + BIT_PARTITION_SIZE, details, cmp); - - if (details.isModified()) { - return copyAndSetNode(mutator, bitpos, subNodeNew); - } else { - return this; - } - } else { - // no value - details.modified(); - return copyAndInsertValue(mutator, bitpos, key); - } - } - - CompactSetNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int dataIndex = dataIndex(bitpos); - - if (getKey(dataIndex).equals(key)) { - details.modified(); - - if (this.payloadArity() == 2 && this.nodeArity() == 0) { - /* - * Create new node with remaining pair. The new node - * will a) either become the new root returned, or b) - * unwrapped and inlined during returning. - */ - final int newDataMap = (shift == 0) ? (int) (dataMap() ^ bitpos) - : bitpos(mask(keyHash, 0)); - - if (dataIndex == 0) { - return CompactSetNode. nodeOf(mutator, (int) 0, newDataMap, - getKey(1)); - } else { - return CompactSetNode. nodeOf(mutator, (int) 0, newDataMap, - getKey(0)); - } - } else { - return copyAndRemoveValue(mutator, bitpos); - } - } else { - return this; - } - } else if ((nodeMap() & bitpos) != 0) { // node (not value) - final CompactSetNode subNode = nodeAt(bitpos); - final CompactSetNode subNodeNew = subNode.removed(mutator, key, keyHash, shift - + BIT_PARTITION_SIZE, details); - - if (!details.isModified()) { - return this; - } - - switch (subNodeNew.sizePredicate()) { - case 0: { - throw new IllegalStateException("Sub-node must have at least one element."); - } - case 1: { - if (this.payloadArity() == 0 && this.nodeArity() == 1) { - // escalate (singleton or empty) result - return subNodeNew; - } else { - // inline value (move to front) - return copyAndMigrateFromNodeToInline(mutator, bitpos, subNodeNew); - } - } - default: { - // modify current node (set replacement node) - return copyAndSetNode(mutator, bitpos, subNodeNew); - } - } - } - - return this; - } - - CompactSetNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details, - final Comparator cmp) { - final int mask = mask(keyHash, shift); - final int bitpos = bitpos(mask); - - if ((dataMap() & bitpos) != 0) { // inplace value - final int dataIndex = dataIndex(bitpos); - - if (cmp.compare(getKey(dataIndex), key) == 0) { - details.modified(); - - if (this.payloadArity() == 2 && this.nodeArity() == 0) { - /* - * Create new node with remaining pair. The new node - * will a) either become the new root returned, or b) - * unwrapped and inlined during returning. - */ - final int newDataMap = (shift == 0) ? (int) (dataMap() ^ bitpos) - : bitpos(mask(keyHash, 0)); - - if (dataIndex == 0) { - return CompactSetNode. nodeOf(mutator, (int) 0, newDataMap, - getKey(1)); - } else { - return CompactSetNode. nodeOf(mutator, (int) 0, newDataMap, - getKey(0)); - } - } else { - return copyAndRemoveValue(mutator, bitpos); - } - } else { - return this; - } - } else if ((nodeMap() & bitpos) != 0) { // node (not value) - final CompactSetNode subNode = nodeAt(bitpos); - final CompactSetNode subNodeNew = subNode.removed(mutator, key, keyHash, shift - + BIT_PARTITION_SIZE, details, cmp); - - if (!details.isModified()) { - return this; - } - - switch (subNodeNew.sizePredicate()) { - case 0: { - throw new IllegalStateException("Sub-node must have at least one element."); - } - case 1: { - if (this.payloadArity() == 0 && this.nodeArity() == 1) { - // escalate (singleton or empty) result - return subNodeNew; - } else { - // inline value (move to front) - return copyAndMigrateFromNodeToInline(mutator, bitpos, subNodeNew); - } - } - default: { - // modify current node (set replacement node) - return copyAndSetNode(mutator, bitpos, subNodeNew); - } - } - } - - return this; - } - - /** - * @return 0 <= mask <= 2^BIT_PARTITION_SIZE - 1 - */ - static byte recoverMask(int map, byte i_th) { - assert 1 <= i_th && i_th <= 32; - - byte cnt1 = 0; - byte mask = 0; - - while (mask < 32) { - if ((map & 0x01) == 0x01) { - cnt1 += 1; - - if (cnt1 == i_th) { - return mask; - } - } - - map = (int) (map >> 1); - mask += 1; - } - - assert cnt1 != i_th; - throw new RuntimeException("Called with invalid arguments."); - } - - @Override - public String toString() { - final StringBuilder bldr = new StringBuilder(); - bldr.append('['); - - for (byte i = 0; i < payloadArity(); i++) { - final byte pos = recoverMask(dataMap(), (byte) (i + 1)); - bldr.append(String.format("@%d<#%d>", pos, Objects.hashCode(getKey(i)))); - - if (!((i + 1) == payloadArity())) { - bldr.append(", "); - } - } - - if (payloadArity() > 0 && nodeArity() > 0) { - bldr.append(", "); - } - - for (byte i = 0; i < nodeArity(); i++) { - final byte pos = recoverMask(nodeMap(), (byte) (i + 1)); - bldr.append(String.format("@%d: %s", pos, getNode(i))); - - if (!((i + 1) == nodeArity())) { - bldr.append(", "); - } - } - - bldr.append(']'); - return bldr.toString(); - } - - } - - protected static abstract class CompactMixedSetNode extends CompactSetNode { - - private final int nodeMap; - private final int dataMap; - - CompactMixedSetNode(final AtomicReference mutator, final int nodeMap, - final int dataMap) { - this.nodeMap = nodeMap; - this.dataMap = dataMap; - } - - @Override - public int nodeMap() { - return nodeMap; - } - - @Override - public int dataMap() { - return dataMap; - } - - } - - private static final class BitmapIndexedSetNode extends CompactMixedSetNode { - - final AtomicReference mutator; - final Object[] nodes; - - private BitmapIndexedSetNode(final AtomicReference mutator, final int nodeMap, - final int dataMap, final Object[] nodes) { - super(mutator, nodeMap, dataMap); - - this.mutator = mutator; - this.nodes = nodes; - - if (DEBUG) { - - assert (TUPLE_LENGTH * java.lang.Integer.bitCount(dataMap) - + java.lang.Integer.bitCount(nodeMap) == nodes.length); - - for (int i = 0; i < TUPLE_LENGTH * payloadArity(); i++) { - assert ((nodes[i] instanceof CompactSetNode) == false); - } - for (int i = TUPLE_LENGTH * payloadArity(); i < nodes.length; i++) { - assert ((nodes[i] instanceof CompactSetNode) == true); - } - } - - assert nodeInvariant(); - } - - @SuppressWarnings("unchecked") - @Override - K getKey(final int index) { - return (K) nodes[TUPLE_LENGTH * index]; - } - - @SuppressWarnings("unchecked") - @Override - CompactSetNode getNode(final int index) { - return (CompactSetNode) nodes[nodes.length - 1 - index]; - } - - @Override - boolean hasPayload() { - return dataMap() != 0; - } - - @Override - int payloadArity() { - return java.lang.Integer.bitCount(dataMap()); - } - - @Override - boolean hasNodes() { - return nodeMap() != 0; - } - - @Override - int nodeArity() { - return java.lang.Integer.bitCount(nodeMap()); - } - - @Override - Object getSlot(final int index) { - return nodes[index]; - } - - @Override - boolean hasSlots() { - return nodes.length != 0; - } - - @Override - int slotArity() { - return nodes.length; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 0; - result = prime * result + ((int) dataMap()); - result = prime * result + ((int) dataMap()); - result = prime * result + Arrays.hashCode(nodes); - return result; - } - - @Override - public boolean equals(final Object other) { - if (null == other) { - return false; - } - if (this == other) { - return true; - } - if (getClass() != other.getClass()) { - return false; - } - BitmapIndexedSetNode that = (BitmapIndexedSetNode) other; - if (nodeMap() != that.nodeMap()) { - return false; - } - if (dataMap() != that.dataMap()) { - return false; - } - if (!ArrayUtils.equals(nodes, that.nodes)) { - return false; - } - return true; - } - - @Override - byte sizePredicate() { - if (this.nodeArity() == 0) { - switch (this.payloadArity()) { - case 0: - return SIZE_EMPTY; - case 1: - return SIZE_ONE; - default: - return SIZE_MORE_THAN_ONE; - } - } else { - return SIZE_MORE_THAN_ONE; - } - } - - @Override - CompactSetNode copyAndSetNode(final AtomicReference mutator, final int bitpos, - final CompactSetNode node) { - - final int idx = this.nodes.length - 1 - nodeIndex(bitpos); - - if (isAllowedToEdit(this.mutator, mutator)) { - // no copying if already editable - this.nodes[idx] = node; - return this; - } else { - final Object[] src = this.nodes; - final Object[] dst = (Object[]) new Object[src.length]; - - // copy 'src' and set 1 element(s) at position 'idx' - System.arraycopy(src, 0, dst, 0, src.length); - dst[idx + 0] = node; - - return nodeOf(mutator, nodeMap(), dataMap(), dst); - } - } - - @Override - CompactSetNode copyAndInsertValue(final AtomicReference mutator, - final int bitpos, final K key) { - final int idx = TUPLE_LENGTH * dataIndex(bitpos); - - final Object[] src = this.nodes; - final Object[] dst = (Object[]) new Object[src.length + 1]; - - // copy 'src' and insert 1 element(s) at position 'idx' - System.arraycopy(src, 0, dst, 0, idx); - dst[idx + 0] = key; - System.arraycopy(src, idx, dst, idx + 1, src.length - idx); - - return nodeOf(mutator, nodeMap(), (int) (dataMap() | bitpos), dst); - } - - @Override - CompactSetNode copyAndRemoveValue(final AtomicReference mutator, final int bitpos) { - final int idx = TUPLE_LENGTH * dataIndex(bitpos); - - final Object[] src = this.nodes; - final Object[] dst = (Object[]) new Object[src.length - 1]; - - // copy 'src' and remove 1 element(s) at position 'idx' - System.arraycopy(src, 0, dst, 0, idx); - System.arraycopy(src, idx + 1, dst, idx, src.length - idx - 1); - - return nodeOf(mutator, nodeMap(), (int) (dataMap() ^ bitpos), dst); - } - - @Override - CompactSetNode copyAndMigrateFromInlineToNode(final AtomicReference mutator, - final int bitpos, final CompactSetNode node) { - - final int idxOld = TUPLE_LENGTH * dataIndex(bitpos); - final int idxNew = this.nodes.length - TUPLE_LENGTH - nodeIndex(bitpos); - - final Object[] src = this.nodes; - final Object[] dst = new Object[src.length - 1 + 1]; - - // copy 'src' and remove 1 element(s) at position 'idxOld' and - // insert 1 element(s) at position 'idxNew' (TODO: carefully test) - assert idxOld <= idxNew; - System.arraycopy(src, 0, dst, 0, idxOld); - System.arraycopy(src, idxOld + 1, dst, idxOld, idxNew - idxOld); - dst[idxNew + 0] = node; - System.arraycopy(src, idxNew + 1, dst, idxNew + 1, src.length - idxNew - 1); - - return nodeOf(mutator, (int) (nodeMap() | bitpos), (int) (dataMap() ^ bitpos), dst); - } - - @Override - CompactSetNode copyAndMigrateFromNodeToInline(final AtomicReference mutator, - final int bitpos, final CompactSetNode node) { - - final int idxOld = this.nodes.length - 1 - nodeIndex(bitpos); - final int idxNew = TUPLE_LENGTH * dataIndex(bitpos); - - final Object[] src = this.nodes; - final Object[] dst = new Object[src.length - 1 + 1]; - - // copy 'src' and remove 1 element(s) at position 'idxOld' and - // insert 1 element(s) at position 'idxNew' (TODO: carefully test) - assert idxOld >= idxNew; - System.arraycopy(src, 0, dst, 0, idxNew); - dst[idxNew + 0] = node.getKey(0); - System.arraycopy(src, idxNew, dst, idxNew + 1, idxOld - idxNew); - System.arraycopy(src, idxOld + 1, dst, idxOld + 1, src.length - idxOld - 1); - - return nodeOf(mutator, (int) (nodeMap() ^ bitpos), (int) (dataMap() | bitpos), dst); - } - - } - - private static final class HashCollisionSetNode_5Bits extends CompactSetNode { - private final K[] keys; - - private final int hash; - - HashCollisionSetNode_5Bits(final int hash, final K[] keys) { - this.keys = keys; - - this.hash = hash; - - assert payloadArity() >= 2; - } - - boolean contains(final K key, final int keyHash, final int shift) { - if (this.hash == keyHash) { - for (K k : keys) { - if (k.equals(key)) { - return true; - } - } - } - return false; - } - - boolean contains(final K key, final int keyHash, final int shift, - final Comparator cmp) { - if (this.hash == keyHash) { - for (K k : keys) { - if (cmp.compare(k, key) == 0) { - return true; - } - } - } - return false; - } - - Optional findByKey(final K key, final int keyHash, final int shift) { - for (int i = 0; i < keys.length; i++) { - final K _key = keys[i]; - if (key.equals(_key)) { - return Optional.of(_key); - } - } - return Optional.empty(); - } - - Optional findByKey(final K key, final int keyHash, final int shift, - final Comparator cmp) { - for (int i = 0; i < keys.length; i++) { - final K _key = keys[i]; - if (cmp.compare(key, _key) == 0) { - return Optional.of(_key); - } - } - return Optional.empty(); - } - - CompactSetNode updated(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details) { - assert this.hash == keyHash; - - for (int idx = 0; idx < keys.length; idx++) { - if (keys[idx].equals(key)) { - return this; - } - } - - @SuppressWarnings("unchecked") - final K[] keysNew = (K[]) new Object[this.keys.length + 1]; - - // copy 'this.keys' and insert 1 element(s) at position - // 'keys.length' - System.arraycopy(this.keys, 0, keysNew, 0, keys.length); - keysNew[keys.length + 0] = key; - System.arraycopy(this.keys, keys.length, keysNew, keys.length + 1, this.keys.length - - keys.length); - - details.modified(); - return new HashCollisionSetNode_5Bits<>(keyHash, keysNew); - } - - CompactSetNode updated(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details, - final Comparator cmp) { - assert this.hash == keyHash; - - for (int idx = 0; idx < keys.length; idx++) { - if (cmp.compare(keys[idx], key) == 0) { - return this; - } - } - - @SuppressWarnings("unchecked") - final K[] keysNew = (K[]) new Object[this.keys.length + 1]; - - // copy 'this.keys' and insert 1 element(s) at position - // 'keys.length' - System.arraycopy(this.keys, 0, keysNew, 0, keys.length); - keysNew[keys.length + 0] = key; - System.arraycopy(this.keys, keys.length, keysNew, keys.length + 1, this.keys.length - - keys.length); - - details.modified(); - return new HashCollisionSetNode_5Bits<>(keyHash, keysNew); - } - - CompactSetNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details) { - for (int idx = 0; idx < keys.length; idx++) { - if (keys[idx].equals(key)) { - details.modified(); - - if (this.arity() == 1) { - return nodeOf(mutator); - } else if (this.arity() == 2) { - /* - * Create root node with singleton element. This node - * will be a) either be the new root returned, or b) - * unwrapped and inlined. - */ - final K theOtherKey = (idx == 0) ? keys[1] : keys[0]; - - return CompactSetNode. nodeOf(mutator).updated(mutator, theOtherKey, - keyHash, 0, details); - } else { - @SuppressWarnings("unchecked") - final K[] keysNew = (K[]) new Object[this.keys.length - 1]; - - // copy 'this.keys' and remove 1 element(s) at position - // 'idx' - System.arraycopy(this.keys, 0, keysNew, 0, idx); - System.arraycopy(this.keys, idx + 1, keysNew, idx, this.keys.length - idx - - 1); - - return new HashCollisionSetNode_5Bits<>(keyHash, keysNew); - } - } - } - return this; - } - - CompactSetNode removed(final AtomicReference mutator, final K key, - final int keyHash, final int shift, final SetResult details, - final Comparator cmp) { - for (int idx = 0; idx < keys.length; idx++) { - if (cmp.compare(keys[idx], key) == 0) { - details.modified(); - - if (this.arity() == 1) { - return nodeOf(mutator); - } else if (this.arity() == 2) { - /* - * Create root node with singleton element. This node - * will be a) either be the new root returned, or b) - * unwrapped and inlined. - */ - final K theOtherKey = (idx == 0) ? keys[1] : keys[0]; - - return CompactSetNode. nodeOf(mutator).updated(mutator, theOtherKey, - keyHash, 0, details, cmp); - } else { - @SuppressWarnings("unchecked") - final K[] keysNew = (K[]) new Object[this.keys.length - 1]; - - // copy 'this.keys' and remove 1 element(s) at position - // 'idx' - System.arraycopy(this.keys, 0, keysNew, 0, idx); - System.arraycopy(this.keys, idx + 1, keysNew, idx, this.keys.length - idx - - 1); - - return new HashCollisionSetNode_5Bits<>(keyHash, keysNew); - } - } - } - return this; - } - - @Override - boolean hasPayload() { - return true; - } - - @Override - int payloadArity() { - return keys.length; - } - - @Override - boolean hasNodes() { - return false; - } - - @Override - int nodeArity() { - return 0; - } - - @Override - int arity() { - return payloadArity(); - } - - @Override - byte sizePredicate() { - return SIZE_MORE_THAN_ONE; - } - - @Override - K getKey(final int index) { - return keys[index]; - } - - @Override - public CompactSetNode getNode(int index) { - throw new IllegalStateException("Is leaf node."); - } - - @Override - Object getSlot(final int index) { - throw new UnsupportedOperationException(); - } - - @Override - boolean hasSlots() { - throw new UnsupportedOperationException(); - } - - @Override - int slotArity() { - throw new UnsupportedOperationException(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 0; - result = prime * result + hash; - result = prime * result + Arrays.hashCode(keys); - return result; - } - - @Override - public boolean equals(Object other) { - if (null == other) { - return false; - } - if (this == other) { - return true; - } - if (getClass() != other.getClass()) { - return false; - } - - HashCollisionSetNode_5Bits that = (HashCollisionSetNode_5Bits) other; - - if (hash != that.hash) { - return false; - } - - if (arity() != that.arity()) { - return false; - } - - /* - * Linear scan for each key, because of arbitrary element order. - */ - outerLoop: for (int i = 0; i < that.payloadArity(); i++) { - final Object otherKey = that.getKey(i); - - for (int j = 0; j < keys.length; j++) { - final K key = keys[j]; - - if (key.equals(otherKey)) { - continue outerLoop; - } - } - return false; - - } - - return true; - } - - @Override - CompactSetNode copyAndInsertValue(final AtomicReference mutator, - final int bitpos, final K key) { - throw new UnsupportedOperationException(); - } - - @Override - CompactSetNode copyAndRemoveValue(final AtomicReference mutator, final int bitpos) { - throw new UnsupportedOperationException(); - } - - @Override - CompactSetNode copyAndSetNode(final AtomicReference mutator, final int bitpos, - final CompactSetNode node) { - throw new UnsupportedOperationException(); - } - - @Override - CompactSetNode copyAndMigrateFromInlineToNode(final AtomicReference mutator, - final int bitpos, final CompactSetNode node) { - throw new UnsupportedOperationException(); - } - - @Override - CompactSetNode copyAndMigrateFromNodeToInline(final AtomicReference mutator, - final int bitpos, final CompactSetNode node) { - throw new UnsupportedOperationException(); - } - - @Override - int nodeMap() { - throw new UnsupportedOperationException(); - } - - @Override - int dataMap() { - throw new UnsupportedOperationException(); - } - - } - - /** - * Iterator skeleton that uses a fixed stack in depth. - */ - private static abstract class AbstractSetIterator { - - private static final int MAX_DEPTH = 7; - - protected int currentValueCursor; - protected int currentValueLength; - protected AbstractSetNode currentValueNode; - - private int currentStackLevel = -1; - private final int[] nodeCursorsAndLengths = new int[MAX_DEPTH * 2]; - - @SuppressWarnings("unchecked") - AbstractSetNode[] nodes = new AbstractSetNode[MAX_DEPTH]; - - AbstractSetIterator(AbstractSetNode rootNode) { - if (rootNode.hasNodes()) { - currentStackLevel = 0; - - nodes[0] = rootNode; - nodeCursorsAndLengths[0] = 0; - nodeCursorsAndLengths[1] = rootNode.nodeArity(); - } - - if (rootNode.hasPayload()) { - currentValueNode = rootNode; - currentValueCursor = 0; - currentValueLength = rootNode.payloadArity(); - } - } - - /* - * search for next node that contains values - */ - private boolean searchNextValueNode() { - while (currentStackLevel >= 0) { - final int currentCursorIndex = currentStackLevel * 2; - final int currentLengthIndex = currentCursorIndex + 1; - - final int nodeCursor = nodeCursorsAndLengths[currentCursorIndex]; - final int nodeLength = nodeCursorsAndLengths[currentLengthIndex]; - - if (nodeCursor < nodeLength) { - final AbstractSetNode nextNode = nodes[currentStackLevel] - .getNode(nodeCursor); - nodeCursorsAndLengths[currentCursorIndex]++; - - if (nextNode.hasNodes()) { - /* - * put node on next stack level for depth-first - * traversal - */ - final int nextStackLevel = ++currentStackLevel; - final int nextCursorIndex = nextStackLevel * 2; - final int nextLengthIndex = nextCursorIndex + 1; - - nodes[nextStackLevel] = nextNode; - nodeCursorsAndLengths[nextCursorIndex] = 0; - nodeCursorsAndLengths[nextLengthIndex] = nextNode.nodeArity(); - } - - if (nextNode.hasPayload()) { - /* - * found next node that contains values - */ - currentValueNode = nextNode; - currentValueCursor = 0; - currentValueLength = nextNode.payloadArity(); - return true; - } - } else { - currentStackLevel--; - } - } - - return false; - } - - public boolean hasNext() { - if (currentValueCursor < currentValueLength) { - return true; - } else { - return searchNextValueNode(); - } - } - - public void remove() { - throw new UnsupportedOperationException(); - } - } - - protected static class SetKeyIterator extends AbstractSetIterator implements Iterator { - - SetKeyIterator(AbstractSetNode rootNode) { - super(rootNode); - } - - @Override - public K next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } else { - return currentValueNode.getKey(currentValueCursor++); - } - } - - } - - /** - * Iterator that first iterates over inlined-values and then continues depth - * first recursively. - */ - private static class TrieSet_5BitsNodeIterator implements Iterator> { - - final Deque>> nodeIteratorStack; - - TrieSet_5BitsNodeIterator(AbstractSetNode rootNode) { - nodeIteratorStack = new ArrayDeque<>(); - nodeIteratorStack.push(Collections.singleton(rootNode).iterator()); - } - - @Override - public boolean hasNext() { - while (true) { - if (nodeIteratorStack.isEmpty()) { - return false; - } else { - if (nodeIteratorStack.peek().hasNext()) { - return true; - } else { - nodeIteratorStack.pop(); - continue; - } - } - } - } - - @Override - public AbstractSetNode next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - - AbstractSetNode innerNode = nodeIteratorStack.peek().next(); - - if (innerNode.hasNodes()) { - nodeIteratorStack.push(innerNode.nodeIterator()); - } - - return innerNode; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } - - static final class TransientTrieSet_5Bits implements TransientSet { - final private AtomicReference mutator; - private AbstractSetNode rootNode; - private int hashCode; - private int cachedSize; - - TransientTrieSet_5Bits(TrieSet_5Bits trieSet_5Bits) { - this.mutator = new AtomicReference(Thread.currentThread()); - this.rootNode = trieSet_5Bits.rootNode; - this.hashCode = trieSet_5Bits.hashCode; - this.cachedSize = trieSet_5Bits.cachedSize; - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - } - - private boolean checkHashCodeAndSize(final int targetHash, final int targetSize) { - int hash = 0; - int size = 0; - - for (Iterator it = keyIterator(); it.hasNext();) { - final K key = it.next(); - - hash += key.hashCode(); - size += 1; - } - - return hash == targetHash && size == targetSize; - } - - public boolean add(final K key) { - throw new UnsupportedOperationException(); - } - - public boolean addAll(final Collection c) { - throw new UnsupportedOperationException(); - } - - public void clear() { - throw new UnsupportedOperationException(); - } - - public boolean remove(final Object key) { - throw new UnsupportedOperationException(); - } - - public boolean removeAll(final Collection c) { - throw new UnsupportedOperationException(); - } - - public boolean retainAll(final Collection c) { - throw new UnsupportedOperationException(); - } - - public boolean contains(final Object o) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - return rootNode.contains(key, transformHashCode(key.hashCode()), 0); - } catch (ClassCastException unused) { - return false; - } - } - - public boolean containsEquivalent(final Object o, final Comparator cmp) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - return rootNode.contains(key, transformHashCode(key.hashCode()), 0, cmp); - } catch (ClassCastException unused) { - return false; - } - } - - public K get(final Object o) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - final Optional result = rootNode.findByKey(key, - transformHashCode(key.hashCode()), 0); - - if (result.isPresent()) { - return result.get(); - } else { - return null; - } - } catch (ClassCastException unused) { - return null; - } - } - - public K getEquivalent(final Object o, final Comparator cmp) { - try { - @SuppressWarnings("unchecked") - final K key = (K) o; - final Optional result = rootNode.findByKey(key, - transformHashCode(key.hashCode()), 0, cmp); - - if (result.isPresent()) { - return result.get(); - } else { - return null; - } - } catch (ClassCastException unused) { - return null; - } - } - - public boolean __insert(final K key) { - if (mutator.get() == null) { - throw new IllegalStateException("Transient already frozen."); - } - - final int keyHash = key.hashCode(); - final SetResult details = SetResult.unchanged(); - - final CompactSetNode newRootNode = rootNode.updated(mutator, key, - transformHashCode(keyHash), 0, details); - - if (details.isModified()) { - - rootNode = newRootNode; - hashCode += keyHash; - cachedSize += 1; - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return true; - - } - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return false; - } - - public boolean __insertEquivalent(final K key, final Comparator cmp) { - if (mutator.get() == null) { - throw new IllegalStateException("Transient already frozen."); - } - - final int keyHash = key.hashCode(); - final SetResult details = SetResult.unchanged(); - - final CompactSetNode newRootNode = rootNode.updated(mutator, key, - transformHashCode(keyHash), 0, details, cmp); - - if (details.isModified()) { - - rootNode = newRootNode; - hashCode += keyHash; - cachedSize += 1; - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return true; - - } - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return false; - } - - public boolean __insertAll(final Set set) { - boolean modified = false; - - for (final K key : set) { - modified |= this.__insert(key); - } - - return modified; - } - - public boolean __insertAllEquivalent(final Set set, - final Comparator cmp) { - boolean modified = false; - - for (final K key : set) { - modified |= this.__insertEquivalent(key, cmp); - } - - return modified; - } - - public boolean __remove(final K key) { - if (mutator.get() == null) { - throw new IllegalStateException("Transient already frozen."); - } - - final int keyHash = key.hashCode(); - final SetResult details = SetResult.unchanged(); - - final CompactSetNode newRootNode = rootNode.removed(mutator, key, - transformHashCode(keyHash), 0, details); - - if (details.isModified()) { - rootNode = newRootNode; - hashCode = hashCode - keyHash; - cachedSize = cachedSize - 1; - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return true; - } - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - - return false; - } - - public boolean __removeEquivalent(final K key, final Comparator cmp) { - if (mutator.get() == null) { - throw new IllegalStateException("Transient already frozen."); - } - - final int keyHash = key.hashCode(); - final SetResult details = SetResult.unchanged(); - - final CompactSetNode newRootNode = rootNode.removed(mutator, key, - transformHashCode(keyHash), 0, details, cmp); - - if (details.isModified()) { - rootNode = newRootNode; - hashCode = hashCode - keyHash; - cachedSize = cachedSize - 1; - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - return true; - } - - if (DEBUG) { - assert checkHashCodeAndSize(hashCode, cachedSize); - } - - return false; - } - - public boolean __removeAll(final Set set) { - boolean modified = false; - - for (final K key : set) { - modified |= this.__remove(key); - } - - return modified; - } - - public boolean __removeAllEquivalent(final Set set, - final Comparator cmp) { - boolean modified = false; - - for (final K key : set) { - modified |= this.__removeEquivalent(key, cmp); - } - - return modified; - } - - public boolean __retainAll(final Set set) { - boolean modified = false; - - Iterator thisIterator = iterator(); - while (thisIterator.hasNext()) { - if (!set.contains(thisIterator.next())) { - thisIterator.remove(); - modified = true; - } - } - - return modified; - } - - public boolean __retainAllEquivalent(final TransientSet transientSet, - final Comparator cmp) { - boolean modified = false; - - Iterator thisIterator = iterator(); - while (thisIterator.hasNext()) { - if (!transientSet.containsEquivalent(thisIterator.next(), cmp)) { - thisIterator.remove(); - modified = true; - } - } - - return modified; - } - - @Override - public boolean containsAll(Collection c) { - for (Object item : c) { - if (!contains(item)) { - return false; - } - } - return true; - } - - @Override - public boolean containsAllEquivalent(Collection c, Comparator cmp) { - for (Object item : c) { - if (!containsEquivalent(item, cmp)) { - return false; - } - } - return true; - } - - public int size() { - return cachedSize; - } - - public boolean isEmpty() { - return cachedSize == 0; - } - - public Iterator iterator() { - return keyIterator(); - } - - public Iterator keyIterator() { - return new TransientSetKeyIterator<>(this); - } - - public static class TransientSetKeyIterator extends SetKeyIterator { - final TransientTrieSet_5Bits collection; - K lastKey; - - public TransientSetKeyIterator(final TransientTrieSet_5Bits collection) { - super(collection.rootNode); - this.collection = collection; - } - - public K next() { - return lastKey = super.next(); - } - - public void remove() { - // TODO: test removal at iteration rigorously - collection.__remove(lastKey); - } - } - - @Override - public Object[] toArray() { - Object[] array = new Object[cachedSize]; - - int idx = 0; - for (K key : this) { - array[idx++] = key; - } - - return array; - } - - @Override - public T[] toArray(final T[] a) { - List list = new ArrayList(cachedSize); - - for (K key : this) { - list.add(key); - } - - return list.toArray(a); - } - - @Override - public boolean equals(final Object other) { - if (other == this) { - return true; - } - if (other == null) { - return false; - } - - if (other instanceof TransientTrieSet_5Bits) { - TransientTrieSet_5Bits that = (TransientTrieSet_5Bits) other; - - if (this.cachedSize != that.cachedSize) { - return false; - } - - if (this.hashCode != that.hashCode) { - return false; - } - - return rootNode.equals(that.rootNode); - } else if (other instanceof Set) { - Set that = (Set) other; - - if (this.size() != that.size()) - return false; - - return containsAll(that); - } - - return false; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public ImmutableSet freeze() { - if (mutator.get() == null) { - throw new IllegalStateException("Transient already frozen."); - } - - mutator.set(null); - return new TrieSet_5Bits(rootNode, hashCode, cachedSize); - } - } - -} \ No newline at end of file diff --git a/capsule/src/test/java/io/usethesource/capsule/TrieMapTests.java b/capsule/src/test/java/io/usethesource/capsule/TrieMapTests.java deleted file mode 100644 index 3b285276a..000000000 --- a/capsule/src/test/java/io/usethesource/capsule/TrieMapTests.java +++ /dev/null @@ -1,438 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Random; - -import org.junit.Test; - -import io.usethesource.capsule.ImmutableMap; -import io.usethesource.capsule.TransientMap; -import io.usethesource.capsule.TrieMap_5Bits; - -public class TrieMapTests { - - /* - * UTILS - */ - @SuppressWarnings("rawtypes") - private static Class targetMapClass = TrieMap_5Bits.class; - - private static Method persistentMapOfEmpty; - private static Method persistentMapOfKeyValuePairs; - - private static Method transientMapOfEmpty; - private static Method transientMapOfKeyValuePairs; - - @SuppressWarnings("rawtypes") - public static Class getTargetMapClass() { - return targetMapClass; - } - - static { - try { - persistentMapOfEmpty = targetMapClass.getMethod("of"); - persistentMapOfKeyValuePairs = targetMapClass.getMethod("of", Object[].class); - - transientMapOfEmpty = targetMapClass.getMethod("transientOf"); - transientMapOfKeyValuePairs = targetMapClass.getMethod("transientOf", Object[].class); - } catch (NoSuchMethodException | SecurityException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final ImmutableMap mapOf() { - try { - return (ImmutableMap) persistentMapOfEmpty.invoke(null); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final ImmutableMap mapOf(Object... keyValuePairs) { - try { - return (ImmutableMap) persistentMapOfKeyValuePairs.invoke(null, - (Object) keyValuePairs); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final TransientMap transientMapOf() { - try { - return (TransientMap) transientMapOfEmpty.invoke(null); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public static final TransientMap transientMapOf(Object... keyValuePairs) { - try { - return (TransientMap) transientMapOfKeyValuePairs.invoke(null, - (Object) keyValuePairs); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - e.printStackTrace(); - throw new RuntimeException(e); - } - } - - /* - * TESTS - */ - - final static int size = (int) Math.pow(2, 10); - - @Test - public void testPrintStatsSequential() { - // int size = 128; - - ImmutableMap map = (ImmutableMap) mapOf(); - - for (int i = size; i > 0; i--) { - ImmutableMap res = (ImmutableMap) map.__put(i, i); - assert res.containsKey(i); - map = res; - } - - getTargetMapClass().cast(map).printStatistics(); - } - - @Test - public void testPrintStatsRandom() { - // int size = 128; - - ImmutableMap map = (ImmutableMap) mapOf(); - - Random rand = new Random(13); - - for (int i = size; i > 0; i--) { - final int j = rand.nextInt(); - - ImmutableMap res = (ImmutableMap) map.__put(j, j); - assert res.containsKey(j); - map = res; - } - - getTargetMapClass().cast(map).printStatistics(); - } - - @Test - public void testCheckPrefixConstruction() { - // int size = 128; - - ImmutableMap map = (ImmutableMap) mapOf(); - - ImmutableMap res1 = (ImmutableMap) map.__put(63, 63).__put(64, 64) - .__put(32768, 32768).__put(2147483647, 2147483647).__put(65536, 65536); - - assert res1.containsKey(63); - assert res1.containsKey(64); - assert res1.containsKey(32768); - assert res1.containsKey(65536); - assert res1.containsKey(2147483647); - - ImmutableMap res2 = (ImmutableMap) map.__put(2147483647, 2147483647) - .__put(32768, 32768).__put(63, 63).__put(64, 64).__put(65536, 65536); - - assert res2.containsKey(63); - assert res2.containsKey(64); - assert res2.containsKey(32768); - assert res2.containsKey(65536); - assert res2.containsKey(2147483647); - - assert res1.equals(res2); - - getTargetMapClass().cast(map).printStatistics(); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void testCheckCompactionFromBeginUponDelete() { - - ImmutableMap map = (ImmutableMap) mapOf(); - - ImmutableMap res1 = (ImmutableMap) map.__put(1, 1).__put(2, 2); - - ImmutableMap res2 = (ImmutableMap) res1.__put(32769, 32769).__remove(2); - - // what to test for? - assert !res1.equals(res2); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void testCheckCompactionFromMiddleUponDelete() { - - ImmutableMap map = (ImmutableMap) mapOf(); - - ImmutableMap res1 = (ImmutableMap) map.__put(1, 1).__put(2, 2) - .__put(65, 65).__put(66, 66); - - ImmutableMap res2 = (ImmutableMap) res1.__put(32769, 32769).__remove(66); - - // what to test for? - assert !res1.equals(res2); - } - - public static PureSeparateHashCodeInteger p(int value, int hash) { - return new PureSeparateHashCodeInteger(value, hash); - } - - public static PureSeparateHashCodeInteger p(int value) { - return new PureSeparateHashCodeInteger(value, value); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void testCheckCompactionFromBeginUponDelete_HashCollisionNode1() { - - ImmutableMap map = (ImmutableMap) mapOf(); - - ImmutableMap res1 = (ImmutableMap) map.__put(p(11, 1), p(11, 1)).__put(p(12, 1), p(12, 1)); - assertTrue(res1.containsKey(p(11, 1))); - assertTrue(res1.containsKey(p(12, 1))); - - ImmutableMap res2 = (ImmutableMap) res1.__remove(p(12, 1)); - assertTrue(res2.containsKey(p(11, 1))); - assertEquals(mapOf(p(11, 1), p(11, 1)), res2); - - ImmutableMap res3 = (ImmutableMap) res1.__remove(p(11, 1)); - assertTrue(res3.containsKey(p(12, 1))); - assertEquals(mapOf(p(12, 1), p(12, 1)), res3); - - ImmutableMap resX = (ImmutableMap) res1.__put(p(32769), p(32769)).__remove(p(12, 1)); - assertTrue(resX.containsKey(p(11, 1))); - assertTrue(resX.containsKey(p(32769))); - - // what to test for? - assert !res1.equals(resX); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void testCheckCompactionFromBeginUponDelete_HashCollisionNode2() { - - ImmutableMap map = (ImmutableMap) mapOf(); - - ImmutableMap res1 = (ImmutableMap) map.__put(p(32769_1, 32769), p(32769_1, 32769)).__put( - p(32769_2, 32769), p(32769_2, 32769)); - assertEquals(2, res1.size()); - assertTrue(res1.containsKey(p(32769_1, 32769))); - assertTrue(res1.containsKey(p(32769_2, 32769))); - - ImmutableMap res2 = (ImmutableMap) res1.__put(p(1, 1), p(1, 1)); - assertEquals(3, res2.size()); - assertTrue(res2.containsKey(p(1, 1))); - assertTrue(res2.containsKey(p(32769_1, 32769))); - assertTrue(res2.containsKey(p(32769_2, 32769))); - - ImmutableMap res3 = (ImmutableMap) res2.__remove(p(32769_2, 32769)); - assertEquals(2, res3.size()); - assertTrue(res3.containsKey(p(1, 1))); - assertTrue(res3.containsKey(p(32769_1, 32769))); - - ImmutableMap expected = (ImmutableMap) mapOf(p(1, 1), p(1, 1), p(32769_1, 32769), - p(32769_1, 32769)); - assertEquals(expected, res3); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void testCheckCompactionFromBeginUponDelete_HashCollisionNode3() { - - ImmutableMap map = (ImmutableMap) mapOf(); - - ImmutableMap res1 = (ImmutableMap) map.__put(p(32769_1, 32769), p(32769_1, 32769)).__put( - p(32769_2, 32769), p(32769_2, 32769)); - assertEquals(2, res1.size()); - assertTrue(res1.containsKey(p(32769_1, 32769))); - assertTrue(res1.containsKey(p(32769_2, 32769))); - - ImmutableMap res2 = (ImmutableMap) res1.__put(p(1, 1), p(1, 1)); - assertEquals(3, res2.size()); - assertTrue(res2.containsKey(p(1, 1))); - assertTrue(res2.containsKey(p(32769_1, 32769))); - assertTrue(res2.containsKey(p(32769_2, 32769))); - - ImmutableMap res3 = (ImmutableMap) res2.__remove(p(1, 1)); - assertEquals(2, res3.size()); - assertTrue(res3.containsKey(p(32769_1, 32769))); - assertTrue(res3.containsKey(p(32769_2, 32769))); - - assertEquals(res1, res3); - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Test - public void testCheckCompactionFromBeginUponDelete_HashCollisionNode4() { - - ImmutableMap map = (ImmutableMap) mapOf(); - - ImmutableMap res1 = (ImmutableMap) map.__put(p(32769_1, 32769), p(32769_1, 32769)).__put( - p(32769_2, 32769), p(32769_2, 32769)); - assertEquals(2, res1.size()); - assertTrue(res1.containsKey(p(32769_1, 32769))); - assertTrue(res1.containsKey(p(32769_2, 32769))); - - ImmutableMap res2 = (ImmutableMap) res1.__put(p(5), p(5)); - assertEquals(3, res2.size()); - assertTrue(res2.containsKey(p(5))); - assertTrue(res2.containsKey(p(32769_1, 32769))); - assertTrue(res2.containsKey(p(32769_2, 32769))); - - ImmutableMap res3 = (ImmutableMap) res2.__remove(p(5)); - assertEquals(2, res3.size()); - assertTrue(res3.containsKey(p(32769_1, 32769))); - assertTrue(res3.containsKey(p(32769_2, 32769))); - - assertEquals(res1, res3); - } - - @Test - public void testRecoverMask() { - byte mask = recoverMask(-2147483648, (byte) 1); - assertTrue(mask == 31); - } - - static byte recoverMask(int map, byte i_th) { - assert 1 <= i_th && i_th <= 32; - - byte cnt1 = 0; - byte mask = 0; - - while (mask < 32) { - if ((map & 0x01) == 0x01) { - cnt1 += 1; - - if (cnt1 == i_th) { - return mask; - } - } - - map = map >> 1; - mask += 1; - } - - throw new RuntimeException("Called with invalid arguments."); // cnt1 != - // i_th - } - -// @Test -// public void testPrintStatsRandomSmallAndBigIntegers() { -// TrieMap_Heterogeneous map = (TrieMap_Heterogeneous) TrieMap_Heterogeneous.of(); -// long smallCount = 0; -// long bigCount = 0; -// -// Random rand = new Random(13); -// -// for (int i = size; i > 0; i--) { -// final int j = rand.nextInt(); -// // System.out.println(j); -// -// final BigInteger bigJ = BigInteger.valueOf(j).multiply(BigInteger.valueOf(j)); -// // System.out.println(bigJ); -// -// if (i % 20 == 0) { // earlier: bigJ.bitLength() > 31 -// // System.out.println("BIG"); -// bigCount++; -// TrieMap_Heterogeneous res = (TrieMap_Heterogeneous) map.__put(bigJ, bigJ); -// assert res.containsKey(bigJ); -// map = res; -// } else { -// // System.out.println("SMALL"); -// smallCount++; -// TrieMap_Heterogeneous res = (TrieMap_Heterogeneous) map.__put(j, j); -// assert res.containsKey(j); -// map = res; -// } -// } -// -// // map.printStatistics(); -// // System.out.println(map); -// -// System.out.println(); -// System.out.println(String.format("PRIMITIVE: %10d (%.2f percent)", smallCount, 100. -// * smallCount / (smallCount + bigCount))); -// System.out.println(String.format("BIG_INTEGER: %10d (%.2f percent)", bigCount, 100. -// * bigCount / (smallCount + bigCount))); -// System.out.println(String.format("UNIQUE: %10d (%.2f percent)", map.size(), -// 100. * map.size() / (smallCount + bigCount))); -// System.out.println(); -// } - - @Test - public void testCreateSingletonWithFactoryMethod() { - ImmutableMap map = mapOf(63, 65); - assertTrue(map.containsKey(63)); - assertEquals(Integer.valueOf(65), map.get(63)); - } - - @Test - public void testRemoveFromSingleton() { - ImmutableMap map = mapOf(63, 65); - ImmutableMap res = map.__remove(63); - assertTrue(res.isEmpty()); - assertFalse(res.containsKey(63)); - assertEquals(mapOf(), res); - } - -} - -class PureSeparateHashCodeInteger { - - private final int value; - private final int hash; - - PureSeparateHashCodeInteger(int value, int hash) { - this.value = value; - this.hash = hash; - } - - @Override - public int hashCode() { - return hash; - } - - @Override - public boolean equals(Object other) { - if (other == null) { - return false; - } - if (other == this) { - return true; - } - - if (other instanceof PureSeparateHashCodeInteger) { - int otherValue = ((PureSeparateHashCodeInteger) other).value; - - return value == otherValue; - } - return false; - } - - @Override - public String toString() { - return String.format("%d [hash = %d]", value, hash); - } - -} \ No newline at end of file diff --git a/capsule/src/test/java/io/usethesource/capsule/TrieSetTests.java b/capsule/src/test/java/io/usethesource/capsule/TrieSetTests.java deleted file mode 100644 index 0afdb4685..000000000 --- a/capsule/src/test/java/io/usethesource/capsule/TrieSetTests.java +++ /dev/null @@ -1,401 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package io.usethesource.capsule; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Random; -import java.util.Set; - -import org.junit.BeforeClass; -import org.junit.Test; - -import io.usethesource.capsule.ImmutableSet; -import io.usethesource.capsule.TrieSet_5Bits; - -public class TrieSetTests { - - private class DummyValue { - public final int value; - public final int hashCode; - - DummyValue(int value, int hashCode) { - this.value = value; - this.hashCode = hashCode; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - DummyValue other = (DummyValue) obj; - if (hashCode != other.hashCode) - return false; - if (value != other.value) - return false; - return true; - } - - @Override - public String toString() { - return String.format("%d [hashCode=%d]", value, hashCode); - } - } - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } - - @Test - public void testNodeValNode() { - Map input = new LinkedHashMap<>(); - - input.put(1, 1); - input.put(2, 33); - input.put(3, 3); - input.put(4, 4); - input.put(5, 4); - input.put(6, 6); - input.put(7, 7); - input.put(8, 7); - - ImmutableSet set = TrieSet_5Bits.of(); - - for (Entry entry : input.entrySet()) { - set = set.__insert(new DummyValue(entry.getKey(), entry.getValue())); - } - - for (Entry entry : input.entrySet()) { - assertTrue(set.contains(new DummyValue(entry.getKey(), entry.getValue()))); - } - } - - @Test - public void testValNodeVal() { - Map input = new LinkedHashMap<>(); - - input.put(1, 1); - input.put(2, 2); - input.put(3, 2); - input.put(4, 4); - input.put(5, 5); - input.put(6, 5); - input.put(7, 7); - - ImmutableSet set = TrieSet_5Bits.of(); - - for (Entry entry : input.entrySet()) { - set = set.__insert(new DummyValue(entry.getKey(), entry.getValue())); - } - - for (Entry entry : input.entrySet()) { - assertTrue(set.contains(new DummyValue(entry.getKey(), entry.getValue()))); - } - } - - @Test - public void testIteration() { - Map input = new LinkedHashMap<>(); - - input.put(1, 1); - input.put(2, 2); - input.put(3, 2); - input.put(4, 4); - input.put(5, 5); - input.put(6, 5); - input.put(7, 7); - - ImmutableSet set = TrieSet_5Bits.of(); - - for (Entry entry : input.entrySet()) { - set = set.__insert(new DummyValue(entry.getKey(), entry.getValue())); - } - - Set keys = input.keySet(); - - for (DummyValue key : set) { - keys.remove(key.value); - } - - assertTrue (keys.isEmpty()); - } - -// @Test -// public void testExtendedIteration() { -// IValueFactory valueFactory = ValueFactory.getInstance(); -// int size = 10_000; -// -// ISetWriter writer = valueFactory.setWriter(); -// -// Random random = new Random(); -// for (int i = size; i > 0; i--) { -//// writer.insert(valueFactory.integer(i)); -// -// // Random -// writer.insert(valueFactory.integer(random.nextInt())); -// } -// -// ISet testSet = writer.done(); -// int realSize = testSet.size(); -// -// int countedSize = 0; -// for (Object key : testSet) { -// countedSize++; -// } -// -// System.out.println(String.format("realSize[%d] == countedSize[%d]", realSize, countedSize)); -// assertTrue (realSize == countedSize); -// } -// -// @Test -// public void testEqualityAfterInsertDelete() { -// IValueFactory valueFactory = ValueFactory.getInstance(); -// int size = 50; -// -// ISetWriter writer1 = valueFactory.setWriter(); -// ISetWriter writer2 = valueFactory.setWriter(); -// -// for (int i = size; i > 0; i--) { -// writer1.insert(valueFactory.integer(i)); -// writer2.insert(valueFactory.integer(i)); -// } -// -// ISet testSet = writer1.done(); -// ISet testSetDuplicate = writer2.done(); -// -//// IValue VALUE_EXISTING = valueFactory.integer(size - 1); -// IValue VALUE_NOT_EXISTING = valueFactory.integer(size + 1); -// -// testSetDuplicate = testSet.insert(VALUE_NOT_EXISTING); -// testSetDuplicate = testSetDuplicate.delete(VALUE_NOT_EXISTING); -// -// boolean equals = testSet.equals(testSetDuplicate); -// -// assertTrue (equals); -// } - - @Test - public void IterateWithLastBitsDifferent() { - DummyValue hash_n2147483648_obj1 = new DummyValue(1, -2147483648); - DummyValue hash_p1073741824_obj2 = new DummyValue(2, 1073741824); - - Set todo = new HashSet<>(); - todo.add(hash_n2147483648_obj1); - todo.add(hash_p1073741824_obj2); - - ImmutableSet xs = TrieSet_5Bits.of(hash_n2147483648_obj1, hash_p1073741824_obj2); - - for (DummyValue x : xs) { - todo.remove(x); - } - - assertEquals(Collections.EMPTY_SET, todo); - } - - @Test - public void TwoCollisionsEquals() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj2, hash98304_obj1); - - assertEquals(xs, ys); - } - - @Test - public void ThreeCollisionsEquals() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - DummyValue hash98304_obj3 = new DummyValue(3, 98304); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2, hash98304_obj3); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj3, hash98304_obj2, hash98304_obj1); - - assertEquals(xs, ys); - } - - @Test - public void RemovalFromCollisonNodeEqualsSingelton() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2).__remove(hash98304_obj2); - - assertEquals(xs, ys); - } - - @Test - public void CollisionIterate() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - Set todo = new HashSet<>(); - todo.add(hash98304_obj1); - todo.add(hash98304_obj2); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2); - - for (DummyValue x : xs) { - todo.remove(x); - } - - assertEquals(Collections.EMPTY_SET, todo); - } - - @Test - public void CollisionWithMergeInlineAbove1() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - DummyValue hash268435456_obj3 = new DummyValue(3, 268435456); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2, hash268435456_obj3).__remove(hash268435456_obj3); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2); - - assertEquals(xs, ys); - } - - @Test - public void CollisionWithMergeInlineAbove1_2() { - DummyValue hash8_obj1 = new DummyValue(1, 8); - DummyValue hash8_obj2 = new DummyValue(2, 8); - - DummyValue hash268435456_obj3 = new DummyValue(3, 268435456); - - ImmutableSet xs = TrieSet_5Bits.of(hash8_obj1, hash8_obj2, hash268435456_obj3).__remove(hash268435456_obj3); - ImmutableSet ys = TrieSet_5Bits.of(hash8_obj1, hash8_obj2); - - assertEquals(xs, ys); - } - - @Test - public void CollisionWithMergeInlineAbove2() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - DummyValue hash268435456_obj3 = new DummyValue(3, 268435456); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash268435456_obj3, hash98304_obj2).__remove(hash268435456_obj3); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2); - - assertEquals(xs, ys); - } - - @Test - public void CollisionWithMergeInlineAbove2_2() { - DummyValue hash8_obj1 = new DummyValue(1, 8); - DummyValue hash8_obj2 = new DummyValue(2, 8); - - DummyValue hash268435456_obj3 = new DummyValue(3, 268435456); - - ImmutableSet xs = TrieSet_5Bits.of(hash8_obj1, hash268435456_obj3, hash8_obj2).__remove(hash268435456_obj3); - ImmutableSet ys = TrieSet_5Bits.of(hash8_obj1, hash8_obj2); - - assertEquals(xs, ys); - } - - @Test - public void CollisionWithMergeInlineAbove1RemoveOneCollisonNode() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - DummyValue hash268435456_obj3 = new DummyValue(3, 268435456); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2, hash268435456_obj3).__remove(hash98304_obj2); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj1, hash268435456_obj3); - - assertEquals(xs, ys); - } - - @Test - public void CollisionWithMergeInlineAbove2RemoveOneCollisonNode() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - DummyValue hash268435456_obj3 = new DummyValue(3, 268435456); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash268435456_obj3, hash98304_obj2).__remove(hash98304_obj2); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj1, hash268435456_obj3); - - assertEquals(xs, ys); - } - - @Test - public void CollisionWithMergeInlineBelow1() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - DummyValue hash8_obj3 = new DummyValue(3, 8); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2, hash8_obj3).__remove(hash8_obj3); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2); - - assertEquals(xs, ys); - } - - @Test - public void CollisionWithMergeInlineBelow2() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - DummyValue hash8_obj3 = new DummyValue(3, 8); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash8_obj3, hash98304_obj2).__remove(hash8_obj3); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2); - - assertEquals(xs, ys); - } - - @Test - public void CollisionWithMergeInlineBelowRemoveOneCollisonNode1() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - DummyValue hash8_obj3 = new DummyValue(3, 8); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash98304_obj2, hash8_obj3).__remove(hash98304_obj2); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj1, hash8_obj3); - - assertEquals(xs, ys); - } - - @Test - public void CollisionWithMergeInlineBelowRemoveOneCollisonNode2() { - DummyValue hash98304_obj1 = new DummyValue(1, 98304); - DummyValue hash98304_obj2 = new DummyValue(2, 98304); - - DummyValue hash8_obj3 = new DummyValue(3, 8); - - ImmutableSet xs = TrieSet_5Bits.of(hash98304_obj1, hash8_obj3, hash98304_obj2).__remove(hash98304_obj2); - ImmutableSet ys = TrieSet_5Bits.of(hash98304_obj1, hash8_obj3); - - assertEquals(xs, ys); - } - -} diff --git a/value-core/doc/PBF-basic-spec.txt b/doc/PBF-basic-spec.txt similarity index 100% rename from value-core/doc/PBF-basic-spec.txt rename to doc/PBF-basic-spec.txt diff --git a/pom.xml b/pom.xml index dbf871404..4ef4e62d5 100644 --- a/pom.xml +++ b/pom.xml @@ -2,19 +2,13 @@ 4.0.0 - org.rascalmpl + org.rascalmpl value 0.5.0-SNAPSHOT - pom - - - value-api - value-core - capsule - + jar - scm:git:https://github.com/cwi-swat/pdb.values.git + scm:git:https://github.com/usethesource/rascal-value.git diff --git a/value-api/src/main/java/org/rascalmpl/value/IAnnotatable.java b/src/main/java/org/rascalmpl/value/IAnnotatable.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IAnnotatable.java rename to src/main/java/org/rascalmpl/value/IAnnotatable.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IBool.java b/src/main/java/org/rascalmpl/value/IBool.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IBool.java rename to src/main/java/org/rascalmpl/value/IBool.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IConstructor.java b/src/main/java/org/rascalmpl/value/IConstructor.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IConstructor.java rename to src/main/java/org/rascalmpl/value/IConstructor.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IDateTime.java b/src/main/java/org/rascalmpl/value/IDateTime.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IDateTime.java rename to src/main/java/org/rascalmpl/value/IDateTime.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IExternalValue.java b/src/main/java/org/rascalmpl/value/IExternalValue.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IExternalValue.java rename to src/main/java/org/rascalmpl/value/IExternalValue.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IInteger.java b/src/main/java/org/rascalmpl/value/IInteger.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IInteger.java rename to src/main/java/org/rascalmpl/value/IInteger.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IList.java b/src/main/java/org/rascalmpl/value/IList.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IList.java rename to src/main/java/org/rascalmpl/value/IList.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IListAlgebra.java b/src/main/java/org/rascalmpl/value/IListAlgebra.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IListAlgebra.java rename to src/main/java/org/rascalmpl/value/IListAlgebra.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IListRelation.java b/src/main/java/org/rascalmpl/value/IListRelation.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IListRelation.java rename to src/main/java/org/rascalmpl/value/IListRelation.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IListWriter.java b/src/main/java/org/rascalmpl/value/IListWriter.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IListWriter.java rename to src/main/java/org/rascalmpl/value/IListWriter.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IMap.java b/src/main/java/org/rascalmpl/value/IMap.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IMap.java rename to src/main/java/org/rascalmpl/value/IMap.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IMapWriter.java b/src/main/java/org/rascalmpl/value/IMapWriter.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IMapWriter.java rename to src/main/java/org/rascalmpl/value/IMapWriter.java diff --git a/value-api/src/main/java/org/rascalmpl/value/INode.java b/src/main/java/org/rascalmpl/value/INode.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/INode.java rename to src/main/java/org/rascalmpl/value/INode.java diff --git a/value-api/src/main/java/org/rascalmpl/value/INumber.java b/src/main/java/org/rascalmpl/value/INumber.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/INumber.java rename to src/main/java/org/rascalmpl/value/INumber.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IRational.java b/src/main/java/org/rascalmpl/value/IRational.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IRational.java rename to src/main/java/org/rascalmpl/value/IRational.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IReal.java b/src/main/java/org/rascalmpl/value/IReal.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IReal.java rename to src/main/java/org/rascalmpl/value/IReal.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IRelationalAlgebra.java b/src/main/java/org/rascalmpl/value/IRelationalAlgebra.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IRelationalAlgebra.java rename to src/main/java/org/rascalmpl/value/IRelationalAlgebra.java diff --git a/value-api/src/main/java/org/rascalmpl/value/ISet.java b/src/main/java/org/rascalmpl/value/ISet.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/ISet.java rename to src/main/java/org/rascalmpl/value/ISet.java diff --git a/value-api/src/main/java/org/rascalmpl/value/ISetAlgebra.java b/src/main/java/org/rascalmpl/value/ISetAlgebra.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/ISetAlgebra.java rename to src/main/java/org/rascalmpl/value/ISetAlgebra.java diff --git a/value-api/src/main/java/org/rascalmpl/value/ISetRelation.java b/src/main/java/org/rascalmpl/value/ISetRelation.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/ISetRelation.java rename to src/main/java/org/rascalmpl/value/ISetRelation.java diff --git a/value-api/src/main/java/org/rascalmpl/value/ISetWriter.java b/src/main/java/org/rascalmpl/value/ISetWriter.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/ISetWriter.java rename to src/main/java/org/rascalmpl/value/ISetWriter.java diff --git a/value-api/src/main/java/org/rascalmpl/value/ISourceLocation.java b/src/main/java/org/rascalmpl/value/ISourceLocation.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/ISourceLocation.java rename to src/main/java/org/rascalmpl/value/ISourceLocation.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IString.java b/src/main/java/org/rascalmpl/value/IString.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IString.java rename to src/main/java/org/rascalmpl/value/IString.java diff --git a/value-api/src/main/java/org/rascalmpl/value/ITuple.java b/src/main/java/org/rascalmpl/value/ITuple.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/ITuple.java rename to src/main/java/org/rascalmpl/value/ITuple.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IValue.java b/src/main/java/org/rascalmpl/value/IValue.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IValue.java rename to src/main/java/org/rascalmpl/value/IValue.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IValueFactory.java b/src/main/java/org/rascalmpl/value/IValueFactory.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IValueFactory.java rename to src/main/java/org/rascalmpl/value/IValueFactory.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IWithKeywordParameters.java b/src/main/java/org/rascalmpl/value/IWithKeywordParameters.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IWithKeywordParameters.java rename to src/main/java/org/rascalmpl/value/IWithKeywordParameters.java diff --git a/value-api/src/main/java/org/rascalmpl/value/IWriter.java b/src/main/java/org/rascalmpl/value/IWriter.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/IWriter.java rename to src/main/java/org/rascalmpl/value/IWriter.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/EmptyIdentifierException.java b/src/main/java/org/rascalmpl/value/exceptions/EmptyIdentifierException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/EmptyIdentifierException.java rename to src/main/java/org/rascalmpl/value/exceptions/EmptyIdentifierException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/FactParseError.java b/src/main/java/org/rascalmpl/value/exceptions/FactParseError.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/FactParseError.java rename to src/main/java/org/rascalmpl/value/exceptions/FactParseError.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/FactTypeDeclarationException.java b/src/main/java/org/rascalmpl/value/exceptions/FactTypeDeclarationException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/FactTypeDeclarationException.java rename to src/main/java/org/rascalmpl/value/exceptions/FactTypeDeclarationException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/FactTypeRedeclaredException.java b/src/main/java/org/rascalmpl/value/exceptions/FactTypeRedeclaredException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/FactTypeRedeclaredException.java rename to src/main/java/org/rascalmpl/value/exceptions/FactTypeRedeclaredException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/FactTypeUseException.java b/src/main/java/org/rascalmpl/value/exceptions/FactTypeUseException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/FactTypeUseException.java rename to src/main/java/org/rascalmpl/value/exceptions/FactTypeUseException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/FieldLabelMismatchException.java b/src/main/java/org/rascalmpl/value/exceptions/FieldLabelMismatchException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/FieldLabelMismatchException.java rename to src/main/java/org/rascalmpl/value/exceptions/FieldLabelMismatchException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalAnnotationDeclaration.java b/src/main/java/org/rascalmpl/value/exceptions/IllegalAnnotationDeclaration.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalAnnotationDeclaration.java rename to src/main/java/org/rascalmpl/value/exceptions/IllegalAnnotationDeclaration.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalConstructorApplicationException.java b/src/main/java/org/rascalmpl/value/exceptions/IllegalConstructorApplicationException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalConstructorApplicationException.java rename to src/main/java/org/rascalmpl/value/exceptions/IllegalConstructorApplicationException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalFieldNameException.java b/src/main/java/org/rascalmpl/value/exceptions/IllegalFieldNameException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalFieldNameException.java rename to src/main/java/org/rascalmpl/value/exceptions/IllegalFieldNameException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalFieldTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/IllegalFieldTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalFieldTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/IllegalFieldTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalIdentifierException.java b/src/main/java/org/rascalmpl/value/exceptions/IllegalIdentifierException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalIdentifierException.java rename to src/main/java/org/rascalmpl/value/exceptions/IllegalIdentifierException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalInstantiatedAbstractDataTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/IllegalInstantiatedAbstractDataTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalInstantiatedAbstractDataTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/IllegalInstantiatedAbstractDataTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalKeywordParameterDeclarationException.java b/src/main/java/org/rascalmpl/value/exceptions/IllegalKeywordParameterDeclarationException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalKeywordParameterDeclarationException.java rename to src/main/java/org/rascalmpl/value/exceptions/IllegalKeywordParameterDeclarationException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalOperationException.java b/src/main/java/org/rascalmpl/value/exceptions/IllegalOperationException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/IllegalOperationException.java rename to src/main/java/org/rascalmpl/value/exceptions/IllegalOperationException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/InvalidDateTimeException.java b/src/main/java/org/rascalmpl/value/exceptions/InvalidDateTimeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/InvalidDateTimeException.java rename to src/main/java/org/rascalmpl/value/exceptions/InvalidDateTimeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/NullTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/NullTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/NullTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/NullTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/OverloadingNotSupportedException.java b/src/main/java/org/rascalmpl/value/exceptions/OverloadingNotSupportedException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/OverloadingNotSupportedException.java rename to src/main/java/org/rascalmpl/value/exceptions/OverloadingNotSupportedException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/RedeclaredAnnotationException.java b/src/main/java/org/rascalmpl/value/exceptions/RedeclaredAnnotationException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/RedeclaredAnnotationException.java rename to src/main/java/org/rascalmpl/value/exceptions/RedeclaredAnnotationException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/RedeclaredConstructorException.java b/src/main/java/org/rascalmpl/value/exceptions/RedeclaredConstructorException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/RedeclaredConstructorException.java rename to src/main/java/org/rascalmpl/value/exceptions/RedeclaredConstructorException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/RedeclaredFieldNameException.java b/src/main/java/org/rascalmpl/value/exceptions/RedeclaredFieldNameException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/RedeclaredFieldNameException.java rename to src/main/java/org/rascalmpl/value/exceptions/RedeclaredFieldNameException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/RedeclaredKeywordParameterException.java b/src/main/java/org/rascalmpl/value/exceptions/RedeclaredKeywordParameterException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/RedeclaredKeywordParameterException.java rename to src/main/java/org/rascalmpl/value/exceptions/RedeclaredKeywordParameterException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UndeclaredAbstractDataTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/UndeclaredAbstractDataTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UndeclaredAbstractDataTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/UndeclaredAbstractDataTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UndeclaredAnnotationException.java b/src/main/java/org/rascalmpl/value/exceptions/UndeclaredAnnotationException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UndeclaredAnnotationException.java rename to src/main/java/org/rascalmpl/value/exceptions/UndeclaredAnnotationException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UndeclaredConstructorException.java b/src/main/java/org/rascalmpl/value/exceptions/UndeclaredConstructorException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UndeclaredConstructorException.java rename to src/main/java/org/rascalmpl/value/exceptions/UndeclaredConstructorException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UndeclaredFieldException.java b/src/main/java/org/rascalmpl/value/exceptions/UndeclaredFieldException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UndeclaredFieldException.java rename to src/main/java/org/rascalmpl/value/exceptions/UndeclaredFieldException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedAnnotationTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/UnexpectedAnnotationTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedAnnotationTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/UnexpectedAnnotationTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedChildTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/UnexpectedChildTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedChildTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/UnexpectedChildTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedConstructorTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/UnexpectedConstructorTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedConstructorTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/UnexpectedConstructorTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedElementTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/UnexpectedElementTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedElementTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/UnexpectedElementTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedMapKeyTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/UnexpectedMapKeyTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedMapKeyTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/UnexpectedMapKeyTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedMapValueTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/UnexpectedMapValueTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedMapValueTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/UnexpectedMapValueTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedResultTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/UnexpectedResultTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedResultTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/UnexpectedResultTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/UnexpectedTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UnexpectedTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/UnexpectedTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/exceptions/UnsupportedTypeException.java b/src/main/java/org/rascalmpl/value/exceptions/UnsupportedTypeException.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/exceptions/UnsupportedTypeException.java rename to src/main/java/org/rascalmpl/value/exceptions/UnsupportedTypeException.java diff --git a/value-api/src/main/java/org/rascalmpl/value/io/IValueBinaryReader.java b/src/main/java/org/rascalmpl/value/io/IValueBinaryReader.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/io/IValueBinaryReader.java rename to src/main/java/org/rascalmpl/value/io/IValueBinaryReader.java diff --git a/value-api/src/main/java/org/rascalmpl/value/io/IValueBinaryWriter.java b/src/main/java/org/rascalmpl/value/io/IValueBinaryWriter.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/io/IValueBinaryWriter.java rename to src/main/java/org/rascalmpl/value/io/IValueBinaryWriter.java diff --git a/value-api/src/main/java/org/rascalmpl/value/io/IValueTextReader.java b/src/main/java/org/rascalmpl/value/io/IValueTextReader.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/io/IValueTextReader.java rename to src/main/java/org/rascalmpl/value/io/IValueTextReader.java diff --git a/value-api/src/main/java/org/rascalmpl/value/io/IValueTextWriter.java b/src/main/java/org/rascalmpl/value/io/IValueTextWriter.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/io/IValueTextWriter.java rename to src/main/java/org/rascalmpl/value/io/IValueTextWriter.java diff --git a/value-api/src/main/java/org/rascalmpl/value/random/DataGenerator.java b/src/main/java/org/rascalmpl/value/random/DataGenerator.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/random/DataGenerator.java rename to src/main/java/org/rascalmpl/value/random/DataGenerator.java diff --git a/value-api/src/main/java/org/rascalmpl/value/random/RandomGenerator.java b/src/main/java/org/rascalmpl/value/random/RandomGenerator.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/random/RandomGenerator.java rename to src/main/java/org/rascalmpl/value/random/RandomGenerator.java diff --git a/value-api/src/main/java/org/rascalmpl/value/random/RandomIntegerGenerator.java b/src/main/java/org/rascalmpl/value/random/RandomIntegerGenerator.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/random/RandomIntegerGenerator.java rename to src/main/java/org/rascalmpl/value/random/RandomIntegerGenerator.java diff --git a/value-api/src/main/java/org/rascalmpl/value/random/RandomNumberGenerator.java b/src/main/java/org/rascalmpl/value/random/RandomNumberGenerator.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/random/RandomNumberGenerator.java rename to src/main/java/org/rascalmpl/value/random/RandomNumberGenerator.java diff --git a/value-api/src/main/java/org/rascalmpl/value/random/RandomRationalGenerator.java b/src/main/java/org/rascalmpl/value/random/RandomRationalGenerator.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/random/RandomRationalGenerator.java rename to src/main/java/org/rascalmpl/value/random/RandomRationalGenerator.java diff --git a/value-api/src/main/java/org/rascalmpl/value/random/RandomRealGenerator.java b/src/main/java/org/rascalmpl/value/random/RandomRealGenerator.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/random/RandomRealGenerator.java rename to src/main/java/org/rascalmpl/value/random/RandomRealGenerator.java diff --git a/value-api/src/main/java/org/rascalmpl/value/random/RandomTypeGenerator.java b/src/main/java/org/rascalmpl/value/random/RandomTypeGenerator.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/random/RandomTypeGenerator.java rename to src/main/java/org/rascalmpl/value/random/RandomTypeGenerator.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/AbstractDataType.java b/src/main/java/org/rascalmpl/value/type/AbstractDataType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/AbstractDataType.java rename to src/main/java/org/rascalmpl/value/type/AbstractDataType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/AliasType.java b/src/main/java/org/rascalmpl/value/type/AliasType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/AliasType.java rename to src/main/java/org/rascalmpl/value/type/AliasType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/BoolType.java b/src/main/java/org/rascalmpl/value/type/BoolType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/BoolType.java rename to src/main/java/org/rascalmpl/value/type/BoolType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/ConstructorType.java b/src/main/java/org/rascalmpl/value/type/ConstructorType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/ConstructorType.java rename to src/main/java/org/rascalmpl/value/type/ConstructorType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/DateTimeType.java b/src/main/java/org/rascalmpl/value/type/DateTimeType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/DateTimeType.java rename to src/main/java/org/rascalmpl/value/type/DateTimeType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/DefaultSubtypeOfValue.java b/src/main/java/org/rascalmpl/value/type/DefaultSubtypeOfValue.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/DefaultSubtypeOfValue.java rename to src/main/java/org/rascalmpl/value/type/DefaultSubtypeOfValue.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/DefaultTypeVisitor.java b/src/main/java/org/rascalmpl/value/type/DefaultTypeVisitor.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/DefaultTypeVisitor.java rename to src/main/java/org/rascalmpl/value/type/DefaultTypeVisitor.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/ExternalType.java b/src/main/java/org/rascalmpl/value/type/ExternalType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/ExternalType.java rename to src/main/java/org/rascalmpl/value/type/ExternalType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/ITypeVisitor.java b/src/main/java/org/rascalmpl/value/type/ITypeVisitor.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/ITypeVisitor.java rename to src/main/java/org/rascalmpl/value/type/ITypeVisitor.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/IntegerType.java b/src/main/java/org/rascalmpl/value/type/IntegerType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/IntegerType.java rename to src/main/java/org/rascalmpl/value/type/IntegerType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/ListType.java b/src/main/java/org/rascalmpl/value/type/ListType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/ListType.java rename to src/main/java/org/rascalmpl/value/type/ListType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/MapType.java b/src/main/java/org/rascalmpl/value/type/MapType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/MapType.java rename to src/main/java/org/rascalmpl/value/type/MapType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/NodeType.java b/src/main/java/org/rascalmpl/value/type/NodeType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/NodeType.java rename to src/main/java/org/rascalmpl/value/type/NodeType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/NumberType.java b/src/main/java/org/rascalmpl/value/type/NumberType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/NumberType.java rename to src/main/java/org/rascalmpl/value/type/NumberType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/ParameterType.java b/src/main/java/org/rascalmpl/value/type/ParameterType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/ParameterType.java rename to src/main/java/org/rascalmpl/value/type/ParameterType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/RationalType.java b/src/main/java/org/rascalmpl/value/type/RationalType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/RationalType.java rename to src/main/java/org/rascalmpl/value/type/RationalType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/RealType.java b/src/main/java/org/rascalmpl/value/type/RealType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/RealType.java rename to src/main/java/org/rascalmpl/value/type/RealType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/SetType.java b/src/main/java/org/rascalmpl/value/type/SetType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/SetType.java rename to src/main/java/org/rascalmpl/value/type/SetType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/SourceLocationType.java b/src/main/java/org/rascalmpl/value/type/SourceLocationType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/SourceLocationType.java rename to src/main/java/org/rascalmpl/value/type/SourceLocationType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/StringType.java b/src/main/java/org/rascalmpl/value/type/StringType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/StringType.java rename to src/main/java/org/rascalmpl/value/type/StringType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/TupleType.java b/src/main/java/org/rascalmpl/value/type/TupleType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/TupleType.java rename to src/main/java/org/rascalmpl/value/type/TupleType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/Type.java b/src/main/java/org/rascalmpl/value/type/Type.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/Type.java rename to src/main/java/org/rascalmpl/value/type/Type.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/TypeFactory.java b/src/main/java/org/rascalmpl/value/type/TypeFactory.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/TypeFactory.java rename to src/main/java/org/rascalmpl/value/type/TypeFactory.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/TypeStore.java b/src/main/java/org/rascalmpl/value/type/TypeStore.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/TypeStore.java rename to src/main/java/org/rascalmpl/value/type/TypeStore.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/ValueType.java b/src/main/java/org/rascalmpl/value/type/ValueType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/ValueType.java rename to src/main/java/org/rascalmpl/value/type/ValueType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/type/VoidType.java b/src/main/java/org/rascalmpl/value/type/VoidType.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/type/VoidType.java rename to src/main/java/org/rascalmpl/value/type/VoidType.java diff --git a/value-api/src/main/java/org/rascalmpl/value/visitors/IValueVisitor.java b/src/main/java/org/rascalmpl/value/visitors/IValueVisitor.java similarity index 100% rename from value-api/src/main/java/org/rascalmpl/value/visitors/IValueVisitor.java rename to src/main/java/org/rascalmpl/value/visitors/IValueVisitor.java diff --git a/value-api/LICENSE b/value-api/LICENSE deleted file mode 100644 index f735bee0e..000000000 --- a/value-api/LICENSE +++ /dev/null @@ -1,203 +0,0 @@ -Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC -LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM -CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - -a) in the case of the initial Contributor, the initial code and documentation - distributed under this Agreement, and -b) in the case of each subsequent Contributor: - i) changes to the Program, and - ii) additions to the Program; - - where such changes and/or additions to the Program originate from and are - distributed by that particular Contributor. A Contribution 'originates' - from a Contributor if it was added to the Program by such Contributor - itself or anyone acting on such Contributor's behalf. Contributions do not - include additions to the Program which: (i) are separate modules of - software distributed in conjunction with the Program under their own - license agreement, and (ii) are not derivative works of the Program. - -"Contributor" means any person or entity that distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which are -necessarily infringed by the use or sale of its Contribution alone or when -combined with the Program. - -"Program" means the Contributions distributed in accordance with this -Agreement. - -"Recipient" means anyone who receives the Program under this Agreement, -including all Contributors. - -2. GRANT OF RIGHTS - a) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free copyright license to - reproduce, prepare derivative works of, publicly display, publicly - perform, distribute and sublicense the Contribution of such Contributor, - if any, and such derivative works, in source code and object code form. - b) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free patent license under - Licensed Patents to make, use, sell, offer to sell, import and otherwise - transfer the Contribution of such Contributor, if any, in source code and - object code form. This patent license shall apply to the combination of - the Contribution and the Program if, at the time the Contribution is - added by the Contributor, such addition of the Contribution causes such - combination to be covered by the Licensed Patents. The patent license - shall not apply to any other combinations which include the Contribution. - No hardware per se is licensed hereunder. - c) Recipient understands that although each Contributor grants the licenses - to its Contributions set forth herein, no assurances are provided by any - Contributor that the Program does not infringe the patent or other - intellectual property rights of any other entity. Each Contributor - disclaims any liability to Recipient for claims brought by any other - entity based on infringement of intellectual property rights or - otherwise. As a condition to exercising the rights and licenses granted - hereunder, each Recipient hereby assumes sole responsibility to secure - any other intellectual property rights needed, if any. For example, if a - third party patent license is required to allow Recipient to distribute - the Program, it is Recipient's responsibility to acquire that license - before distributing the Program. - d) Each Contributor represents that to its knowledge it has sufficient - copyright rights in its Contribution, if any, to grant the copyright - license set forth in this Agreement. - -3. REQUIREMENTS - -A Contributor may choose to distribute the Program in object code form under -its own license agreement, provided that: - - a) it complies with the terms and conditions of this Agreement; and - b) its license agreement: - i) effectively disclaims on behalf of all Contributors all warranties - and conditions, express and implied, including warranties or - conditions of title and non-infringement, and implied warranties or - conditions of merchantability and fitness for a particular purpose; - ii) effectively excludes on behalf of all Contributors all liability for - damages, including direct, indirect, special, incidental and - consequential damages, such as lost profits; - iii) states that any provisions which differ from this Agreement are - offered by that Contributor alone and not by any other party; and - iv) states that source code for the Program is available from such - Contributor, and informs licensees how to obtain it in a reasonable - manner on or through a medium customarily used for software exchange. - -When the Program is made available in source code form: - - a) it must be made available under this Agreement; and - b) a copy of this Agreement must be included with each copy of the Program. - Contributors may not remove or alter any copyright notices contained - within the Program. - -Each Contributor must identify itself as the originator of its Contribution, -if -any, in a manner that reasonably allows subsequent Recipients to identify the -originator of the Contribution. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities with -respect to end users, business partners and the like. While this license is -intended to facilitate the commercial use of the Program, the Contributor who -includes the Program in a commercial product offering should do so in a manner -which does not create potential liability for other Contributors. Therefore, -if a Contributor includes the Program in a commercial product offering, such -Contributor ("Commercial Contributor") hereby agrees to defend and indemnify -every other Contributor ("Indemnified Contributor") against any losses, -damages and costs (collectively "Losses") arising from claims, lawsuits and -other legal actions brought by a third party against the Indemnified -Contributor to the extent caused by the acts or omissions of such Commercial -Contributor in connection with its distribution of the Program in a commercial -product offering. The obligations in this section do not apply to any claims -or Losses relating to any actual or alleged intellectual property -infringement. In order to qualify, an Indemnified Contributor must: -a) promptly notify the Commercial Contributor in writing of such claim, and -b) allow the Commercial Contributor to control, and cooperate with the -Commercial Contributor in, the defense and any related settlement -negotiations. The Indemnified Contributor may participate in any such claim at -its own expense. - -For example, a Contributor might include the Program in a commercial product -offering, Product X. That Contributor is then a Commercial Contributor. If -that Commercial Contributor then makes performance claims, or offers -warranties related to Product X, those performance claims and warranties are -such Commercial Contributor's responsibility alone. Under this section, the -Commercial Contributor would have to defend claims against the other -Contributors related to those performance claims and warranties, and if a -court requires any other Contributor to pay any damages as a result, the -Commercial Contributor must pay those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN -"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR -IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, -NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each -Recipient is solely responsible for determining the appropriateness of using -and distributing the Program and assumes all risks associated with its -exercise of rights under this Agreement , including but not limited to the -risks and costs of program errors, compliance with applicable laws, damage to -or loss of data, programs or equipment, and unavailability or interruption of -operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY -CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION -LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE -EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY -OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of the -remainder of the terms of this Agreement, and without further action by the -parties hereto, such provision shall be reformed to the minimum extent -necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Program itself -(excluding combinations of the Program with other software or hardware) -infringes such Recipient's patent(s), then such Recipient's rights granted -under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it fails to -comply with any of the material terms or conditions of this Agreement and does -not cure such failure in a reasonable period of time after becoming aware of -such noncompliance. If all Recipient's rights under this Agreement terminate, -Recipient agrees to cease use and distribution of the Program as soon as -reasonably practicable. However, Recipient's obligations under this Agreement -and any licenses granted by Recipient relating to the Program shall continue -and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, but in -order to avoid inconsistency the Agreement is copyrighted and may only be -modified in the following manner. The Agreement Steward reserves the right to -publish new versions (including revisions) of this Agreement from time to -time. No one other than the Agreement Steward has the right to modify this -Agreement. The Eclipse Foundation is the initial Agreement Steward. The -Eclipse Foundation may assign the responsibility to serve as the Agreement -Steward to a suitable separate entity. Each new version of the Agreement will -be given a distinguishing version number. The Program (including -Contributions) may always be distributed subject to the version of the -Agreement under which it was received. In addition, after a new version of the -Agreement is published, Contributor may elect to distribute the Program -(including its Contributions) under the new version. Except as expressly -stated in Sections 2(a) and 2(b) above, Recipient receives no rights or -licenses to the intellectual property of any Contributor under this Agreement, -whether expressly, by implication, estoppel or otherwise. All rights in the -Program not expressly granted under this Agreement are reserved. - -This Agreement is governed by the laws of the State of New York and the -intellectual property laws of the United States of America. No party to this -Agreement will bring a legal action under this Agreement more than one year -after the cause of action arose. Each party waives its rights to a jury trial in -any resulting litigation. diff --git a/value-api/pom.xml b/value-api/pom.xml deleted file mode 100644 index 4818bf7be..000000000 --- a/value-api/pom.xml +++ /dev/null @@ -1,16 +0,0 @@ - - 4.0.0 - - - org.rascalmpl - value - 0.5.0-SNAPSHOT - - - org.rascalmpl - value-api - 0.5.0-SNAPSHOT - jar - - diff --git a/value-core/LICENSE b/value-core/LICENSE deleted file mode 100644 index f735bee0e..000000000 --- a/value-core/LICENSE +++ /dev/null @@ -1,203 +0,0 @@ -Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC -LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM -CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - -a) in the case of the initial Contributor, the initial code and documentation - distributed under this Agreement, and -b) in the case of each subsequent Contributor: - i) changes to the Program, and - ii) additions to the Program; - - where such changes and/or additions to the Program originate from and are - distributed by that particular Contributor. A Contribution 'originates' - from a Contributor if it was added to the Program by such Contributor - itself or anyone acting on such Contributor's behalf. Contributions do not - include additions to the Program which: (i) are separate modules of - software distributed in conjunction with the Program under their own - license agreement, and (ii) are not derivative works of the Program. - -"Contributor" means any person or entity that distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which are -necessarily infringed by the use or sale of its Contribution alone or when -combined with the Program. - -"Program" means the Contributions distributed in accordance with this -Agreement. - -"Recipient" means anyone who receives the Program under this Agreement, -including all Contributors. - -2. GRANT OF RIGHTS - a) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free copyright license to - reproduce, prepare derivative works of, publicly display, publicly - perform, distribute and sublicense the Contribution of such Contributor, - if any, and such derivative works, in source code and object code form. - b) Subject to the terms of this Agreement, each Contributor hereby grants - Recipient a non-exclusive, worldwide, royalty-free patent license under - Licensed Patents to make, use, sell, offer to sell, import and otherwise - transfer the Contribution of such Contributor, if any, in source code and - object code form. This patent license shall apply to the combination of - the Contribution and the Program if, at the time the Contribution is - added by the Contributor, such addition of the Contribution causes such - combination to be covered by the Licensed Patents. The patent license - shall not apply to any other combinations which include the Contribution. - No hardware per se is licensed hereunder. - c) Recipient understands that although each Contributor grants the licenses - to its Contributions set forth herein, no assurances are provided by any - Contributor that the Program does not infringe the patent or other - intellectual property rights of any other entity. Each Contributor - disclaims any liability to Recipient for claims brought by any other - entity based on infringement of intellectual property rights or - otherwise. As a condition to exercising the rights and licenses granted - hereunder, each Recipient hereby assumes sole responsibility to secure - any other intellectual property rights needed, if any. For example, if a - third party patent license is required to allow Recipient to distribute - the Program, it is Recipient's responsibility to acquire that license - before distributing the Program. - d) Each Contributor represents that to its knowledge it has sufficient - copyright rights in its Contribution, if any, to grant the copyright - license set forth in this Agreement. - -3. REQUIREMENTS - -A Contributor may choose to distribute the Program in object code form under -its own license agreement, provided that: - - a) it complies with the terms and conditions of this Agreement; and - b) its license agreement: - i) effectively disclaims on behalf of all Contributors all warranties - and conditions, express and implied, including warranties or - conditions of title and non-infringement, and implied warranties or - conditions of merchantability and fitness for a particular purpose; - ii) effectively excludes on behalf of all Contributors all liability for - damages, including direct, indirect, special, incidental and - consequential damages, such as lost profits; - iii) states that any provisions which differ from this Agreement are - offered by that Contributor alone and not by any other party; and - iv) states that source code for the Program is available from such - Contributor, and informs licensees how to obtain it in a reasonable - manner on or through a medium customarily used for software exchange. - -When the Program is made available in source code form: - - a) it must be made available under this Agreement; and - b) a copy of this Agreement must be included with each copy of the Program. - Contributors may not remove or alter any copyright notices contained - within the Program. - -Each Contributor must identify itself as the originator of its Contribution, -if -any, in a manner that reasonably allows subsequent Recipients to identify the -originator of the Contribution. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities with -respect to end users, business partners and the like. While this license is -intended to facilitate the commercial use of the Program, the Contributor who -includes the Program in a commercial product offering should do so in a manner -which does not create potential liability for other Contributors. Therefore, -if a Contributor includes the Program in a commercial product offering, such -Contributor ("Commercial Contributor") hereby agrees to defend and indemnify -every other Contributor ("Indemnified Contributor") against any losses, -damages and costs (collectively "Losses") arising from claims, lawsuits and -other legal actions brought by a third party against the Indemnified -Contributor to the extent caused by the acts or omissions of such Commercial -Contributor in connection with its distribution of the Program in a commercial -product offering. The obligations in this section do not apply to any claims -or Losses relating to any actual or alleged intellectual property -infringement. In order to qualify, an Indemnified Contributor must: -a) promptly notify the Commercial Contributor in writing of such claim, and -b) allow the Commercial Contributor to control, and cooperate with the -Commercial Contributor in, the defense and any related settlement -negotiations. The Indemnified Contributor may participate in any such claim at -its own expense. - -For example, a Contributor might include the Program in a commercial product -offering, Product X. That Contributor is then a Commercial Contributor. If -that Commercial Contributor then makes performance claims, or offers -warranties related to Product X, those performance claims and warranties are -such Commercial Contributor's responsibility alone. Under this section, the -Commercial Contributor would have to defend claims against the other -Contributors related to those performance claims and warranties, and if a -court requires any other Contributor to pay any damages as a result, the -Commercial Contributor must pay those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN -"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR -IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, -NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each -Recipient is solely responsible for determining the appropriateness of using -and distributing the Program and assumes all risks associated with its -exercise of rights under this Agreement , including but not limited to the -risks and costs of program errors, compliance with applicable laws, damage to -or loss of data, programs or equipment, and unavailability or interruption of -operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY -CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION -LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE -EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY -OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under -applicable law, it shall not affect the validity or enforceability of the -remainder of the terms of this Agreement, and without further action by the -parties hereto, such provision shall be reformed to the minimum extent -necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity (including a -cross-claim or counterclaim in a lawsuit) alleging that the Program itself -(excluding combinations of the Program with other software or hardware) -infringes such Recipient's patent(s), then such Recipient's rights granted -under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it fails to -comply with any of the material terms or conditions of this Agreement and does -not cure such failure in a reasonable period of time after becoming aware of -such noncompliance. If all Recipient's rights under this Agreement terminate, -Recipient agrees to cease use and distribution of the Program as soon as -reasonably practicable. However, Recipient's obligations under this Agreement -and any licenses granted by Recipient relating to the Program shall continue -and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, but in -order to avoid inconsistency the Agreement is copyrighted and may only be -modified in the following manner. The Agreement Steward reserves the right to -publish new versions (including revisions) of this Agreement from time to -time. No one other than the Agreement Steward has the right to modify this -Agreement. The Eclipse Foundation is the initial Agreement Steward. The -Eclipse Foundation may assign the responsibility to serve as the Agreement -Steward to a suitable separate entity. Each new version of the Agreement will -be given a distinguishing version number. The Program (including -Contributions) may always be distributed subject to the version of the -Agreement under which it was received. In addition, after a new version of the -Agreement is published, Contributor may elect to distribute the Program -(including its Contributions) under the new version. Except as expressly -stated in Sections 2(a) and 2(b) above, Recipient receives no rights or -licenses to the intellectual property of any Contributor under this Agreement, -whether expressly, by implication, estoppel or otherwise. All rights in the -Program not expressly granted under this Agreement are reserved. - -This Agreement is governed by the laws of the State of New York and the -intellectual property laws of the United States of America. No party to this -Agreement will bring a legal action under this Agreement more than one year -after the cause of action arose. Each party waives its rights to a jury trial in -any resulting litigation. diff --git a/value-core/pom.xml b/value-core/pom.xml deleted file mode 100644 index 1ef8a5324..000000000 --- a/value-core/pom.xml +++ /dev/null @@ -1,110 +0,0 @@ - - 4.0.0 - - - org.rascalmpl - value - 0.5.0-SNAPSHOT - - - org.rascalmpl - value-core - 0.5.0-SNAPSHOT - jar - - - scm:git:https://github.com/cwi-swat/pdb.values.git - - - - UTF-8 - 1.8 - 1.8 - - - - - - org.apache.maven.wagon - wagon-http - 2.6 - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.5.1 - - - compile-tests - test-compile - - testCompile - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12.4 - - - test - test - - test - - - - - - - **/org/eclipse/imp/pdb/test/reference/**.java - - - - - - - - - - org.rascalmpl - value-api - 0.5.0-SNAPSHOT - - - io.usethesource - capsule - 0.1.0-SNAPSHOT - - - - diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractDefaultAnnotatable.java b/value-core/src/main/java/org/rascalmpl/value/impl/AbstractDefaultAnnotatable.java deleted file mode 100644 index 9959bac7a..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractDefaultAnnotatable.java +++ /dev/null @@ -1,137 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import java.util.Map; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.FactTypeUseException; - -import io.usethesource.capsule.AbstractSpecialisedImmutableMap; -import io.usethesource.capsule.ImmutableMap; - -/** - * A generic wrapper for an {@link IValue} that associates annotations to it. - * - * @param the interface over which this annotation wrapper closes - */ -public abstract class AbstractDefaultAnnotatable implements IAnnotatable { - - protected final T content; - protected final ImmutableMap annotations; - - /** - * Creates an {@link IAnnotatable} view on {@literal content} with empty - * annotations. - * - * @param content - * is the wrapped object that supports annotations - */ - public AbstractDefaultAnnotatable(T content) { - this.content = content; - this.annotations = AbstractSpecialisedImmutableMap.mapOf(); - } - - /** - * Creates an {@link IAnnotatable} view on {@link #content} with already - * provided {@link #annotations}. - * - * @param content - * is the wrapped object that supports annotations - * @param annotations - * is the map of annotations associated to {@link #content} - */ - public AbstractDefaultAnnotatable(T content, ImmutableMap annotations) { - this.content = content; - this.annotations = annotations; - } - - /** - * Wraps {@link #content} with other annotations. This methods is mandatory - * because of PDB's immutable value nature: Once annotations are modified, a - * new immutable view is returned. - * - * @param content - * is the wrapped object that supports annotations - * @param annotations - * is the map of annotations associated to {@link #content} - * @return a new representations of {@link #content} with associated - * {@link #annotations} - */ - protected abstract T wrap(final T content, final ImmutableMap annotations); - - @Override - public boolean hasAnnotations() { - return annotations.size() > 0; - } - - @Override - public Map getAnnotations() { - return annotations; - } - - @Override - public T removeAnnotations() { - return content; - } - - @Override - public boolean hasAnnotation(String label) throws FactTypeUseException { - return annotations.containsKey(label); - } - - @Override - public IValue getAnnotation(String label) throws FactTypeUseException { - return annotations.get(label); - } - - @Override - public T setAnnotation(String label, IValue newValue) - throws FactTypeUseException { - return wrap(content, annotations.__put(label, newValue)); - } - - @Override - public T removeAnnotation(String label) { - return wrap(content, annotations.__remove(label)); - } - - @Override - public T setAnnotations(Map otherAnnotations) { - if (otherAnnotations.isEmpty()) - return content; - - return wrap(content, AbstractSpecialisedImmutableMap.mapOf(otherAnnotations)); - } - - @Override - public T joinAnnotations(Map otherAnnotations) { - return wrap(content, annotations.__putAll(otherAnnotations)); - } - - @Override - public String toString() { - return content.toString(); - } - -// @Override -// public int hashCode() { -// // TODO -// } -// -// @Override -// public boolean equals(Object obj) { -// // TODO -// } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractDefaultWithKeywordParameters.java b/value-core/src/main/java/org/rascalmpl/value/impl/AbstractDefaultWithKeywordParameters.java deleted file mode 100644 index f295017e7..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractDefaultWithKeywordParameters.java +++ /dev/null @@ -1,169 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.FactTypeUseException; - -import io.usethesource.capsule.AbstractSpecialisedImmutableMap; -import io.usethesource.capsule.ImmutableMap; - - -/** - * A generic wrapper for an {@link IValue} that associates keyword parameters to it. - * - * @param the interface over which this parameter wrapper closes - */ -public abstract class AbstractDefaultWithKeywordParameters implements IWithKeywordParameters { - protected final T content; - protected final ImmutableMap parameters; - - /** - * Creates an {@link IWithKeywordParameters} view on {@link #content} with already - * provided {@link #parameters}. - * - * @param content - * is the wrapped object that supports annotations - * @param parameters - * is the map of annotations associated to {@link #content} - */ - public AbstractDefaultWithKeywordParameters(T content, ImmutableMap parameters) { - this.content = content; - this.parameters = parameters; - } - - /** - * Wraps {@link #content} with other parameters. This methods is mandatory - * because of PDB's immutable value nature: Once parameters are modified, a - * new immutable view is returned. - * - * @param content - * is the wrapped object that supports annotations - * @param annotations - * is the map of annotations associated to {@link #content} - * @return a new representations of {@link #content} with associated - * {@link #parameters} - */ - protected abstract T wrap(final T content, final ImmutableMap parameters); - - @Override - public String toString() { - return content.toString(); - } - - @Override - public IValue getParameter(String label) throws FactTypeUseException { - return parameters.get(label); - } - - @Override - public T setParameter(String label, IValue newValue) throws FactTypeUseException { - return wrap(content, parameters.__put(label, newValue)); - } - - @Override - public T unsetParameter(String label) { - ImmutableMap removed = parameters.__remove(label); - - if (removed.size() == 0) { - return content; - } else { - return wrap(content, removed); - } - } - - @Override - public T unsetAll() { - return content; - } - - @Override - public boolean hasParameter(String label) throws FactTypeUseException { - return parameters.containsKey(label); - } - - @Override - public boolean hasParameters() { - return parameters.size() > 0; - } - - @Override - public Set getParameterNames() { - return parameters.keySet(); - } - - @Override - public Map getParameters() { - return Collections.unmodifiableMap(parameters); - } - - @Override - public boolean equals(Object other) { - if (!getClass().equals(other.getClass())) { - return false; - } - - AbstractDefaultWithKeywordParameters o = (AbstractDefaultWithKeywordParameters) other; - - if (!content.isEqual(o.content)) { - return false; - } - - if (parameters.size() != o.parameters.size()) { - return false; - } - - for (String key : parameters.keySet()) { - if (!getParameter(key).equals(o.getParameter(key))) { - return false; - } - } - - return true; - } - - @Override - public > boolean equalParameters(U other) { - if (!(other instanceof AbstractDefaultWithKeywordParameters)) { - return false; - } - - AbstractDefaultWithKeywordParameters o = (AbstractDefaultWithKeywordParameters) other; - - if (parameters.size() != o.parameters.size()) { - return false; - } - - for (String key : parameters.keySet()) { - // TODO: isEqual should become equals when annotations have been removed. - IValue parameter = getParameter(key); - if (parameter == null && o.getParameter(key) != null) { - return false; - } - else if (parameter != null && !parameter.isEqual(o.getParameter(key))) { - return false; - } - } - - return true; - } - - @Override - public T setParameters(Map params) { - return wrap(content, AbstractSpecialisedImmutableMap.mapOf(params)); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractExternalValue.java b/value-core/src/main/java/org/rascalmpl/value/impl/AbstractExternalValue.java deleted file mode 100644 index fb8d9b7c7..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractExternalValue.java +++ /dev/null @@ -1,221 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2015 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Jurgen Vinju - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import java.util.Collections; -import java.util.Iterator; -import java.util.Map; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IExternalValue; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.type.ExternalType; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.AbstractSpecialisedImmutableMap; -import io.usethesource.capsule.ImmutableMap; - -/** - * IExternalValue, together with {@link ExternalType} offer a limited form of extensibility - * to the PDB's value and type system. The IExternalValue interface is used to tag extensions, - * such as 'function values' that are not part of the PDB fact exchange and manipulation - * interfaces but do need to integrate with them. - *
- * Note that implementations of IExternalValues are obliged to have a type that subclasses - * ExternalType and that they all implement encodeAsConstructor. - * If you do not do this, (de)serialization will not work. - *
- * Note that NORMAL USE OF THE PDB DOES NOT REQUIRE IMPLEMENTING THIS INTERFACE - */ -public abstract class AbstractExternalValue implements IExternalValue { - - @Override - public boolean isEqual(IValue other) { - return equals(other); - } - - public static IConstructor encodeAsConstructor(IExternalValue instance) { - return new IConstructor() { - @Override - public Type getConstructorType() { - return TypeFactory.getInstance().constructor(new TypeStore(), getType(), getName(), new Type[0]); - } - - @Override - public Type getType() { - return ((ExternalType) getType()).asAbstractDataType(); - } - - @Override - public String getName() { - return instance.getClass().getSimpleName().toLowerCase(); - } - - @Override - public Type getUninstantiatedConstructorType() { - return getConstructorType(); - } - - @Override - public IValue get(String label) { - return null; - } - - @Override - public IConstructor set(String label, IValue newChild) throws FactTypeUseException { - return this; - } - - @Override - public boolean has(String label) { - return false; - } - - @Override - public IConstructor set(int index, IValue newChild) { - return this; - } - - @Override - public Type getChildrenTypes() { - return TypeFactory.getInstance().voidType(); - } - - @Override - public boolean declaresAnnotation(TypeStore store, String label) { - return false; - } - - @Override - public T accept(IValueVisitor v) - throws E { - return v.visitConstructor(this); - } - - @Override - public boolean isEqual(IValue other) { - return equals(other); - } - - @Override - public boolean isAnnotatable() { - return true; - } - - @Override - public boolean mayHaveKeywordParameters() { - return true; - } - - @Override - public INode replace(int first, int second, int end, IList repl) - throws FactTypeUseException, IndexOutOfBoundsException { - return this; - } - - @Override - public int arity() { - return 0; - } - - @Override - public IValue get(int i) throws IndexOutOfBoundsException { - return null; - } - - @Override - public Iterable getChildren() { - return Collections.emptyList(); - } - - - @Override - public Iterator iterator() { - return Collections.emptyIterator(); - } - - - @Override - public IAnnotatable asAnnotatable() { - return new AbstractDefaultAnnotatable(this) { - @Override - protected IConstructor wrap(IConstructor content, - ImmutableMap annotations) { - return new AnnotatedConstructorFacade(content, annotations); - } - }; - } - - @Override - public IWithKeywordParameters asWithKeywordParameters() { - return new AbstractDefaultWithKeywordParameters(this, AbstractSpecialisedImmutableMap.mapOf()) { - @Override - protected IConstructor wrap(IConstructor content, ImmutableMap parameters) { - return new ConstructorWithKeywordParametersFacade(content, parameters); - } - - @Override - public boolean hasParameters() { - return false; - } - - @Override - public java.util.Set getParameterNames() { - return Collections.emptySet(); - } - - @Override - public Map getParameters() { - return Collections.unmodifiableMap(parameters); - } - }; - } - }; - } - - @Override - public IConstructor encodeAsConstructor() { - return encodeAsConstructor(this); - } - - @Override - public boolean isAnnotatable() { - return false; - } - - @Override - public IAnnotatable asAnnotatable() { - throw new UnsupportedOperationException(); - } - - @Override - public boolean mayHaveKeywordParameters() { - return false; - } - - @Override - public IWithKeywordParameters asWithKeywordParameters() { - throw new UnsupportedOperationException(); - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitExternal(this); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractList.java b/value-core/src/main/java/org/rascalmpl/value/impl/AbstractList.java deleted file mode 100644 index a227a326f..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractList.java +++ /dev/null @@ -1,170 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import java.util.Random; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListRelation; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.IllegalOperationException; -import org.rascalmpl.value.impl.func.ListFunctions; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -public abstract class AbstractList extends AbstractValue implements IList { - - public AbstractList() { - super(); - } - - protected static TypeFactory getTypeFactory() { - return TypeFactory.getInstance(); - } - - protected static Type inferListOrRelType(final Type elementType, final Iterable content) { - return inferListOrRelType(elementType, content.iterator().hasNext() == false); - } - - /* - * TODO: get rid of code duplication (@see AbstractSet.inferSetOrRelType) - */ - protected static Type inferListOrRelType(final Type elementType, final boolean isEmpty) { - final Type inferredElementType; - final Type inferredCollectionType; - - // is collection empty? - if (isEmpty) { - inferredElementType = getTypeFactory().voidType(); - } else { - inferredElementType = elementType; - } - - // consists collection out of tuples? - if (inferredElementType.isFixedWidth()) { - inferredCollectionType = getTypeFactory().lrelTypeFromTuple(inferredElementType); - } else { - inferredCollectionType = getTypeFactory().listType(inferredElementType); - } - - return inferredCollectionType; - } - - protected abstract IValueFactory getValueFactory(); - - @Override - public Type getElementType() { - return getType().getElementType(); - } - - @Override - public IList reverse() { - return ListFunctions.reverse(getValueFactory(), this); - } - - @Override - public IList shuffle(Random rand) { - return ListFunctions.shuffle(getValueFactory(), this, rand); - } - - @Override - public IList append(IValue e) { - return ListFunctions.append(getValueFactory(), this, e); - } - - @Override - public IList insert(IValue e) { - return ListFunctions.insert(getValueFactory(), this, e); - } - - @Override - public IList concat(IList that) { - return ListFunctions.concat(getValueFactory(), this, that); - } - - @Override - public IList put(int i, IValue e) { - return ListFunctions.put(getValueFactory(), this, i, e); - } - - @Override - public IList replace(int first, int second, int end, IList repl) { - return ListFunctions.replace(getValueFactory(), this, first, second, end, repl); - } - - @Override - public IList sublist(int offset, int length) { - return ListFunctions.sublist(getValueFactory(), this, offset, length); - } - - @Override - public boolean contains(IValue e) { - return ListFunctions.contains(getValueFactory(), this, e); - } - - @Override - public IList delete(IValue e) { - return ListFunctions.delete(getValueFactory(), this, e); - } - - @Override - public IList delete(int i) { - return ListFunctions.delete(getValueFactory(), this, i); - - } - - @Override - public IList product(IList that) { - return ListFunctions.product(getValueFactory(), this, that); - } - - @Override - public IList intersect(IList that) { - return ListFunctions.intersect(getValueFactory(), this, that); - } - - @Override - public IList subtract(IList that) { - return ListFunctions.subtract(getValueFactory(), this, that); - } - - @Override - public boolean isSubListOf(IList that) { - return ListFunctions.isSubListOf(getValueFactory(), this, that); - } - - @Override - public T accept(IValueVisitor v) throws E { - if (getElementType().isFixedWidth()) { - return v.visitListRelation(this); - } else { - return v.visitList(this); - } - } - - @Override - public boolean isRelation() { - return getType().isListRelation(); - } - - @Override - public IListRelation asRelation() { - if (!isRelation()) - throw new IllegalOperationException( - "Cannot be viewed as a relation.", getType()); - - return new DefaultRelationViewOnList(getValueFactory(), this); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractMap.java b/value-core/src/main/java/org/rascalmpl/value/impl/AbstractMap.java deleted file mode 100644 index a1b90aab3..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractMap.java +++ /dev/null @@ -1,118 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.func.MapFunctions; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -public abstract class AbstractMap extends AbstractValue implements IMap { - - public AbstractMap() { - super(); - } - - protected static TypeFactory getTypeFactory() { - return TypeFactory.getInstance(); - } - - protected static Type inferMapType(final Type candidateMapType, final java.util.Map content) { - return inferMapType(candidateMapType, content.isEmpty()); - } - - protected static Type inferMapType(final Type candidateMapType, final boolean isEmpty) { - if (!candidateMapType.isMap()) - throw new IllegalArgumentException("Type must be a map type: " - + candidateMapType); - - final Type inferredCollectionType; - - // is collection empty? - if (isEmpty) { - inferredCollectionType = getTypeFactory().mapType( - getTypeFactory().voidType(), candidateMapType.getKeyLabel(), - getTypeFactory().voidType(), candidateMapType.getValueLabel()); - - } else { - inferredCollectionType = candidateMapType; - } - - return inferredCollectionType; - } - - protected abstract IValueFactory getValueFactory(); - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitMap(this); - } - - @Override - public IMap put(IValue key, IValue value) { - return MapFunctions.put(getValueFactory(), this, key, value); - } - - @Override - public boolean containsKey(IValue key) { - return MapFunctions.containsKey(getValueFactory(), this, key); - } - - @Override - public boolean containsValue(IValue value) { - return MapFunctions.containsValue(getValueFactory(), this, value); - } - - @Override - public Type getKeyType() { - return getType().getKeyType(); - } - - @Override - public Type getValueType() { - return getType().getValueType(); - } - - @Override - public IMap join(IMap that) { - return MapFunctions.join(getValueFactory(), this, that); - } - - @Override - public IMap remove(IMap that) { - return MapFunctions.remove(getValueFactory(), this, that); - } - - @Override - public IMap compose(IMap that) { - return MapFunctions.compose(getValueFactory(), this, that); - } - - @Override - public IMap common(IMap that) { - return MapFunctions.common(getValueFactory(), this, that); - } - - @Override - public boolean isSubMap(IMap that) { - return MapFunctions.isSubMap(getValueFactory(), this, that); - } - - @Override - public IMap removeKey(IValue key) { - throw new UnsupportedOperationException(); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractNode.java b/value-core/src/main/java/org/rascalmpl/value/impl/AbstractNode.java deleted file mode 100644 index 5386a3194..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractNode.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - ******************************************************************************/ -package org.rascalmpl.value.impl; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.impl.func.NodeFunctions; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.AbstractSpecialisedImmutableMap; -import io.usethesource.capsule.ImmutableMap; - -public abstract class AbstractNode extends AbstractValue implements INode { - - protected static TypeFactory getTypeFactory() { - return TypeFactory.getInstance(); - } - - protected abstract IValueFactory getValueFactory(); - - - @Override - public INode replace(int first, int second, int end, IList repl) throws FactTypeUseException, IndexOutOfBoundsException { - return NodeFunctions.replace(getValueFactory(), this, first, second, end, repl); - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitNode(this); - } - - @Override - public boolean isAnnotatable() { - return true; - } - - @Override - public IAnnotatable asAnnotatable() { - return new AbstractDefaultAnnotatable(this) { - @Override - protected INode wrap(INode content, ImmutableMap annotations) { - return new AnnotatedNodeFacade(content, annotations); - } - }; - } - - @Override - public boolean mayHaveKeywordParameters() { - return true; - } - - @Override - public IWithKeywordParameters asWithKeywordParameters() { - return new AbstractDefaultWithKeywordParameters(this, AbstractSpecialisedImmutableMap.mapOf()) { - @Override - protected INode wrap(INode content, ImmutableMap parameters) { - return new NodeWithKeywordParametersFacade(content, parameters); - } - }; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractSet.java b/value-core/src/main/java/org/rascalmpl/value/impl/AbstractSet.java deleted file mode 100644 index 387d35426..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractSet.java +++ /dev/null @@ -1,123 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetRelation; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.IllegalOperationException; -import org.rascalmpl.value.impl.func.SetFunctions; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -public abstract class AbstractSet extends AbstractValue implements ISet { - - public AbstractSet() { - super(); - } - - protected static TypeFactory getTypeFactory() { - return TypeFactory.getInstance(); - } - - protected static Type inferSetOrRelType(final Type elementType, final Iterable content) { - return inferSetOrRelType(elementType, content.iterator().hasNext() == false); - } - - /* - * TODO: get rid of code duplication (@see AbstractList.inferListOrRelType) - */ - protected static Type inferSetOrRelType(final Type elementType, final boolean isEmpty) { - final Type inferredElementType; - final Type inferredCollectionType; - - // is collection empty? - if (isEmpty) { - inferredElementType = getTypeFactory().voidType(); - } else { - inferredElementType = elementType; - } - - // consists collection out of tuples? - if (inferredElementType.isFixedWidth()) { - inferredCollectionType = getTypeFactory().relTypeFromTuple(inferredElementType); - } else { - inferredCollectionType = getTypeFactory().setType(inferredElementType); - } - - return inferredCollectionType; - } - - protected abstract IValueFactory getValueFactory(); - - @Override - public Type getElementType() { - return getType().getElementType(); - } - - @Override - public ISet insert(IValue e) { - return SetFunctions.insert(getValueFactory(), this, e); - } - - @Override - public ISet union(ISet that) { - return SetFunctions.union(getValueFactory(), this, that); - } - - @Override - public ISet intersect(ISet that) { - return SetFunctions.intersect(getValueFactory(), this, that); - } - - @Override - public ISet subtract(ISet that) { - return SetFunctions.subtract(getValueFactory(), this, that); - } - - @Override - public ISet delete(IValue e) { - return SetFunctions.delete(getValueFactory(), this, e); - } - - @Override - public ISet product(ISet that) { - return SetFunctions.product(getValueFactory(), this, that); - } - - @Override - public boolean isSubsetOf(ISet that) { - return SetFunctions.isSubsetOf(getValueFactory(), this, that); - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitSet(this); - } - - @Override - public boolean isRelation() { - return getType().isRelation(); - } - - @Override - public ISetRelation asRelation() { - if (!isRelation()) - throw new IllegalOperationException( - "Cannot be viewed as a relation.", getType()); - - return new DefaultRelationViewOnSet(getValueFactory(), this); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractValue.java b/value-core/src/main/java/org/rascalmpl/value/impl/AbstractValue.java deleted file mode 100644 index b1fdc239d..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractValue.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Jurgen Vinju - interface and implementation - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.IllegalOperationException; -import org.rascalmpl.value.io.StandardTextWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.visitors.IValueVisitor; - -public abstract class AbstractValue implements IValue { - - protected AbstractValue() { - super(); - } - - @Override - public boolean isAnnotatable() { - return false; - } - - @Override - public IAnnotatable asAnnotatable() { - throw new IllegalOperationException("Cannot be viewed as annotatable.", getType()); - } - - @Override - public boolean mayHaveKeywordParameters() { - return false; - } - - @Override - public IWithKeywordParameters asWithKeywordParameters() { - throw new IllegalOperationException("Cannot be viewed as with keyword parameters.", - getType()); - } - - @Override - public Type getType() { - throw new UnsupportedOperationException(); - } - - @Override - public T accept(IValueVisitor v) throws E { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isEqual(IValue other) { - return equals(other); - } - - public String toString() { - return StandardTextWriter.valueToString(this); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractValueFactoryAdapter.java b/value-core/src/main/java/org/rascalmpl/value/impl/AbstractValueFactoryAdapter.java deleted file mode 100644 index 5deee7f8c..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractValueFactoryAdapter.java +++ /dev/null @@ -1,354 +0,0 @@ -package org.rascalmpl.value.impl; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.type.Type; - -/** - * This class provides a default way of easily reusing existing implementations of IValueFactory without having - * to extend them again and again using inheritance. Clients extend this class and override the methods that need - * special handling. - * - * Note: this class is intended to be sub-classed. It should not be abstract because we want the compiler to - * check that it provides a facade for the full IValueFactory interface. - */ -@SuppressWarnings("deprecation") -public /*abstract*/ class AbstractValueFactoryAdapter implements IValueFactory { - protected final IValueFactory adapted; - - public AbstractValueFactoryAdapter(IValueFactory adapted) { - this.adapted = adapted; - } - - public IBool bool(boolean value) { - return adapted.bool(value); - } - - - public IConstructor constructor(Type constructor) { - return adapted.constructor(constructor); - } - - public IConstructor constructor(Type constructor, IValue... children) - throws FactTypeUseException { - return adapted.constructor(constructor, children); - } - - public IDateTime date(int year, int month, int day) { - return adapted.date(year, month, day); - } - - public IDateTime datetime(int year, int month, int day, int hour, - int minute, int second, int millisecond) { - return adapted.datetime(year, month, day, hour, minute, second, millisecond); - } - - public IDateTime datetime(int year, int month, int day, int hour, - int minute, int second, int millisecond, int hourOffset, - int minuteOffset) { - return adapted.datetime(year, month, day, hour, minute, second, millisecond, hourOffset, minuteOffset); - } - - public IDateTime datetime(long instant) { - return adapted.datetime(instant); - } - - public IDateTime datetime(long instant, int timezoneHours, int timezoneMinutes) { - return adapted.datetime(instant, timezoneHours, timezoneMinutes); - } - - public IInteger integer(String i) throws NumberFormatException { - return adapted.integer(i); - } - - public IInteger integer(int i) { - return adapted.integer(i); - } - - public IInteger integer(long i) { - return adapted.integer(i); - } - - public IInteger integer(byte[] a) { - return adapted.integer(a); - } - - public IList list(Type eltType) { - return adapted.list(eltType); - } - - public IList list(IValue... elems) { - return adapted.list(elems); - } - - public IListWriter listWriter(Type eltType) { - return adapted.listWriter(eltType); - } - - public IListWriter listWriter() { - return adapted.listWriter(); - } - - public IMap map(Type key, Type value) { - return adapted.map(key, value); - } - - public IMapWriter mapWriter(Type key, Type value) { - return adapted.mapWriter(key, value); - } - - public IMapWriter mapWriter() { - return adapted.mapWriter(); - } - - public INode node(String name) { - return adapted.node(name); - } - - public INode node(String name, IValue... children) { - return adapted.node(name, children); - } - - public IReal real(String s) throws NumberFormatException { - return adapted.real(s); - } - - public IReal real(double d) { - return adapted.real(d); - } - - public ISet relation(Type tupleType) { - return adapted.relation(tupleType); - } - - public ISet relation(IValue... elems) { - return adapted.relation(elems); - } - - public ISetWriter relationWriter(Type type) { - return adapted.relationWriter(type); - } - - public ISetWriter relationWriter() { - return adapted.relationWriter(); - } - - public ISet set(Type eltType) { - return adapted.set(eltType); - } - - public ISet set(IValue... elems) { - return adapted.set(elems); - } - - public ISetWriter setWriter(Type eltType) { - return adapted.setWriter(eltType); - } - - public ISetWriter setWriter() { - return adapted.setWriter(); - } - - public ISourceLocation sourceLocation(URI uri, int offset, int length, - int beginLine, int endLine, int beginCol, int endCol) { - return adapted.sourceLocation(uri, offset, length, beginLine, endLine, beginCol, endCol); - } - - public ISourceLocation sourceLocation(String path, int offset, int length, - int beginLine, int endLine, int beginCol, int endCol) { - return adapted.sourceLocation(path, offset, length, beginLine, endLine, beginCol, endCol); - } - - public ISourceLocation sourceLocation(URI uri) { - return adapted.sourceLocation(uri); - } - - public ISourceLocation sourceLocation(String path) { - return adapted.sourceLocation(path); - } - - @Override - public ISourceLocation sourceLocation(ISourceLocation loc, int offset, int length, int beginLine, int endLine, int beginCol, int endCol) { - return adapted.sourceLocation(loc, offset, length, beginLine, endLine, beginCol, endCol); - } - - @Override - public ISourceLocation sourceLocation(ISourceLocation loc, int offset, int length) { - return adapted.sourceLocation(loc, offset, length); - } - - @Override - public ISourceLocation sourceLocation(String scheme, String authority, String path) throws URISyntaxException { - return adapted.sourceLocation(scheme, authority, path); - } - - @Override - public ISourceLocation sourceLocation(String scheme, String authority, String path, String query, String fragment) throws URISyntaxException { - return adapted.sourceLocation(scheme, authority, path, query, fragment); - } - - public IString string(String s) { - return adapted.string(s); - } - - public IDateTime time(int hour, int minute, int second, int millisecond) { - return adapted.time(hour, minute, second, millisecond); - } - - public IDateTime time(int hour, int minute, int second, int millisecond, - int hourOffset, int minuteOffset) { - return adapted.time(hour, minute, second, millisecond, hourOffset, minuteOffset); - } - - public ITuple tuple() { - return adapted.tuple(); - } - - public ITuple tuple(IValue... args) { - return adapted.tuple(args); - } - - @Override - public IRational rational(int a, int b) { - return adapted.rational(a,b); - } - - @Override - public IRational rational(long a, long b) { - return adapted.rational(a, b); - } - - @Override - public IRational rational(IInteger a, IInteger b) { - return adapted.rational(a, b); - } - - @Override - public IRational rational(String rat) throws NumberFormatException { - return adapted.rational(rat); - } - - @Override - public IReal real(String s, int p) throws NumberFormatException { - return adapted.real(s, p); - } - - @Override - public IReal real(double d, int p) { - return adapted.real(d, p); - } - - @Override - public int getPrecision() { - return adapted.getPrecision(); - } - - @Override - public int setPrecision(int p) { - return adapted.setPrecision(p); - } - - @Override - public IReal pi(int precision) { - return adapted.pi(precision); - } - - @Override - public IReal e(int precision) { - return adapted.e(precision); - } - - @Override - public IString string(int[] chars) throws IllegalArgumentException { - return adapted.string(chars); - } - - @Override - public IString string(int ch) throws IllegalArgumentException { - return adapted.string(ch); - } - - @Override - public ISourceLocation sourceLocation(URI uri, int offset, int length) { - return adapted.sourceLocation(uri, offset, length); - } - - @Override - public ITuple tuple(Type type, IValue... args) { - return adapted.tuple(type, args); - } - - @Override - public INode node(String name, Map annotations, IValue... children) throws FactTypeUseException { - return adapted.node(name, annotations, children); - } - - @Override - public INode node(String name, IValue[] children, Map keyArgValues) throws FactTypeUseException { - return adapted.node(name, children, keyArgValues); - } - - @Override - public IList listRelation(Type tupleType) { - return adapted.listRelation(tupleType); - } - - @Override - public IList listRelation(IValue... elems) { - return adapted.listRelation(elems); - } - - @Override - public IListWriter listRelationWriter(Type type) { - return adapted.listRelationWriter(type); - } - - @Override - public IListWriter listRelationWriter() { - return adapted.listRelationWriter(); - } - - @Override - public IMap map(Type mapType) { - return adapted.map(mapType); - } - - @Override - public IMapWriter mapWriter(Type mapType) { - return adapted.mapWriter(mapType); - } - - @Override - public IConstructor constructor(Type constructor, Map annotations, IValue... children) - throws FactTypeUseException { - return adapted.constructor(constructor, annotations, children); - } - - @Override - public IConstructor constructor(Type constructor, IValue[] children, Map kwParams) - throws FactTypeUseException { - return adapted.constructor(constructor, children, kwParams); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractWriter.java b/value-core/src/main/java/org/rascalmpl/value/impl/AbstractWriter.java deleted file mode 100644 index 014d62786..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AbstractWriter.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWriter; -import org.rascalmpl.value.exceptions.FactTypeUseException; - -public abstract class AbstractWriter implements IWriter { - public void insertAll(Iterable collection) throws FactTypeUseException { - for (IValue v : collection) { - insert(v); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AnnotatedConstructorFacade.java b/value-core/src/main/java/org/rascalmpl/value/impl/AnnotatedConstructorFacade.java deleted file mode 100644 index cb33e2d0c..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AnnotatedConstructorFacade.java +++ /dev/null @@ -1,162 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import java.util.Iterator; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.io.StandardTextWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeStore; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.ImmutableMap; - -public class AnnotatedConstructorFacade implements IConstructor { - - protected final IConstructor content; - protected final ImmutableMap annotations; - - public AnnotatedConstructorFacade(final IConstructor content, final ImmutableMap annotations) { - this.content = content; - this.annotations = annotations; - } - - public T accept(IValueVisitor v) throws E { - return v.visitConstructor(this); - } - - public Type getType() { - return content.getType(); - } - - public IValue get(int i) throws IndexOutOfBoundsException { - return content.get(i); - } - - public Type getConstructorType() { - return content.getConstructorType(); - } - - public Type getUninstantiatedConstructorType() { - return content.getUninstantiatedConstructorType(); - } - - public IValue get(String label) { - return content.get(label); - } - - public IConstructor set(String label, IValue newChild) - throws FactTypeUseException { - IConstructor newContent = content.set(label, newChild); - return new AnnotatedConstructorFacade(newContent, annotations); // TODO: introduce wrap() here as well - } - - public int arity() { - return content.arity(); - } - - public boolean has(String label) { - return content.has(label); - } - - public String toString() { - return StandardTextWriter.valueToString(this); - } - - public IConstructor set(int index, IValue newChild) - throws FactTypeUseException { - IConstructor newContent = content.set(index, newChild); - return new AnnotatedConstructorFacade(newContent, annotations); // TODO: introduce wrap() here as well - } - - public String getName() { - return content.getName(); - } - - public Iterable getChildren() { - return content.getChildren(); - } - - public Iterator iterator() { - return content.iterator(); - } - - public INode replace(int first, int second, int end, IList repl) - throws FactTypeUseException, IndexOutOfBoundsException { - return content.replace(first, second, end, repl); - } - - public Type getChildrenTypes() { - return content.getChildrenTypes(); - } - - public boolean declaresAnnotation(TypeStore store, String label) { - return content.declaresAnnotation(store, label); - } - - public boolean equals(Object o) { - if(o == this) return true; - if(o == null) return false; - - if(o.getClass() == getClass()){ - AnnotatedConstructorFacade other = (AnnotatedConstructorFacade) o; - - return content.equals(other.content) && - annotations.equals(other.annotations); - } - - return false; - } - - public boolean isEqual(IValue other) { - return content.isEqual(other); - } - - @Override - public int hashCode() { - return content.hashCode(); - } - - @Override - public boolean isAnnotatable() { - return true; - } - - @Override - public IAnnotatable asAnnotatable() { - return new AbstractDefaultAnnotatable(content, annotations) { - - @Override - protected IConstructor wrap(IConstructor content, - ImmutableMap annotations) { - return new AnnotatedConstructorFacade(content, annotations); - } - }; - } - - @Override - public boolean mayHaveKeywordParameters() { - return false; - } - - @Override - public IWithKeywordParameters asWithKeywordParameters() { - throw new UnsupportedOperationException("can not add keyword parameters to a node which already has annotations"); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/AnnotatedNodeFacade.java b/value-core/src/main/java/org/rascalmpl/value/impl/AnnotatedNodeFacade.java deleted file mode 100644 index 171d5fd43..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/AnnotatedNodeFacade.java +++ /dev/null @@ -1,130 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import java.util.Iterator; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.io.StandardTextWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.ImmutableMap; - -public class AnnotatedNodeFacade implements INode { - - protected final INode content; - protected final ImmutableMap annotations; - - public AnnotatedNodeFacade(final INode content, final ImmutableMap annotations) { - this.content = content; - this.annotations = annotations; - } - - public Type getType() { - return content.getType(); - } - - public T accept(IValueVisitor v) throws E { - return v.visitNode(this); - } - - public IValue get(int i) throws IndexOutOfBoundsException { - return content.get(i); - } - - public INode set(int i, IValue newChild) throws IndexOutOfBoundsException { - INode newContent = content.set(i, newChild); - return new AnnotatedNodeFacade(newContent, annotations); // TODO: introduce wrap() here as well - } - - public int arity() { - return content.arity(); - } - - public String toString() { - return StandardTextWriter.valueToString(this); - } - - public String getName() { - return content.getName(); - } - - public Iterable getChildren() { - return content.getChildren(); - } - - public Iterator iterator() { - return content.iterator(); - } - - public INode replace(int first, int second, int end, IList repl) - throws FactTypeUseException, IndexOutOfBoundsException { - INode newContent = content.replace(first, second, end, repl); - return new AnnotatedNodeFacade(newContent, annotations); // TODO: introduce wrap() here as well - } - - public boolean equals(Object o) { - if(o == this) return true; - if(o == null) return false; - - if(o.getClass() == getClass()){ - AnnotatedNodeFacade other = (AnnotatedNodeFacade) o; - - return content.equals(other.content) && - annotations.equals(other.annotations); - } - - return false; - } - - public boolean isEqual(IValue other) { - return content.isEqual(other); - } - - @Override - public int hashCode() { - return content.hashCode(); - } - - @Override - public boolean isAnnotatable() { - return true; - } - - @Override - public IAnnotatable asAnnotatable() { - return new AbstractDefaultAnnotatable(content, annotations) { - - @Override - protected INode wrap(INode content, - ImmutableMap annotations) { - return new AnnotatedNodeFacade(content, annotations); - } - }; - } - - @Override - public boolean mayHaveKeywordParameters() { - return false; - } - - @Override - public IWithKeywordParameters asWithKeywordParameters() { - throw new UnsupportedOperationException("can not add keyword parameters to a node which already has annotations"); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/ConstructorWithKeywordParametersFacade.java b/value-core/src/main/java/org/rascalmpl/value/impl/ConstructorWithKeywordParametersFacade.java deleted file mode 100644 index a528e6e45..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/ConstructorWithKeywordParametersFacade.java +++ /dev/null @@ -1,201 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import java.util.Collections; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.io.StandardTextWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeStore; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.ImmutableMap; - -public class ConstructorWithKeywordParametersFacade implements IConstructor { - protected final IConstructor content; - protected final ImmutableMap parameters; - - public ConstructorWithKeywordParametersFacade(final IConstructor content, final ImmutableMap parameters) { - this.content = content; - this.parameters = parameters; - } - - public Type getType() { - return content.getType(); - } - - public T accept(IValueVisitor v) throws E { - return v.visitConstructor(this); - } - - public IValue get(int i) throws IndexOutOfBoundsException { - return content.get(i); - } - - public IConstructor set(int i, IValue newChild) throws IndexOutOfBoundsException { - IConstructor newContent = content.set(i, newChild); - return new ConstructorWithKeywordParametersFacade(newContent, parameters); // TODO: introduce wrap() here as well - } - - public int arity() { - return content.arity(); - } - - public String toString() { - return StandardTextWriter.valueToString(this); - } - - public String getName() { - return content.getName(); - } - - public Iterable getChildren() { - return content.getChildren(); - } - - public Iterator iterator() { - return content.iterator(); - } - - public IConstructor replace(int first, int second, int end, IList repl) - throws FactTypeUseException, IndexOutOfBoundsException { - throw new UnsupportedOperationException("Replace not supported on constructor."); - } - - public boolean equals(Object o) { - if(o == this) return true; - if(o == null) return false; - - if(o.getClass() == getClass()){ - ConstructorWithKeywordParametersFacade other = (ConstructorWithKeywordParametersFacade) o; - - return content.equals(other.content) && - parameters.equals(other.parameters); - } - - return false; - } - - @Override - public boolean isEqual(IValue other) { - if (!(other instanceof ConstructorWithKeywordParametersFacade)) { - if (other instanceof IConstructor) { - IConstructor oc = ((IConstructor)other); - if (content.isEqual(oc) && oc.mayHaveKeywordParameters()) { - IWithKeywordParameters ocw = oc.asWithKeywordParameters(); - return ocw.getParameters().equals(parameters); - } - else { - return false; - } - } - else { - return false; - } - } - - // TODO: the equals here should be isEqual - ConstructorWithKeywordParametersFacade o = (ConstructorWithKeywordParametersFacade) other; - - return content.isEqual(o.content) && o.parameters.equals(parameters); - } - - @Override - public int hashCode() { - return 131 + 3 * content.hashCode() + 101 * parameters.hashCode(); - } - - @Override - public boolean isAnnotatable() { - return false; - } - - @Override - public IAnnotatable asAnnotatable() { - throw new UnsupportedOperationException("can not annotate a constructor which already has keyword parameters"); - } - - @Override - public boolean mayHaveKeywordParameters() { - return true; - } - - @Override - public IWithKeywordParameters asWithKeywordParameters() { - return new AbstractDefaultWithKeywordParameters(content, parameters) { - @Override - protected IConstructor wrap(IConstructor content, ImmutableMap parameters) { - return new ConstructorWithKeywordParametersFacade(content, parameters); - } - - @Override - public boolean hasParameters() { - return parameters != null && parameters.size() > 0; - } - - @Override - public Set getParameterNames() { - return parameters.keySet(); - } - - @Override - public Map getParameters() { - return Collections.unmodifiableMap(parameters); - } - }; - } - - @Override - public Type getConstructorType() { - return content.getConstructorType(); - } - - @Override - public Type getUninstantiatedConstructorType() { - return content.getUninstantiatedConstructorType(); - } - - @Override - public IValue get(String label) { - return content.get(label); - } - - @Override - public IConstructor set(String label, IValue newChild) throws FactTypeUseException { - return new ConstructorWithKeywordParametersFacade(content.set(label, newChild), parameters); - } - - @Override - public boolean has(String label) { - return content.has(label); - } - - - @Override - public Type getChildrenTypes() { - return content.getChildrenTypes(); - } - - @Override - public boolean declaresAnnotation(TypeStore store, String label) { - return content.declaresAnnotation(store, label); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/DefaultRelationViewOnList.java b/value-core/src/main/java/org/rascalmpl/value/impl/DefaultRelationViewOnList.java deleted file mode 100644 index 0ed6e47f4..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/DefaultRelationViewOnList.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.rascalmpl.value.impl; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListRelation; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.func.ListFunctions; - -public class DefaultRelationViewOnList implements IListRelation { - - protected final IValueFactory vf; - protected final IList rel1; - - public DefaultRelationViewOnList(final IValueFactory vf, final IList rel1) { - this.vf = vf; - this.rel1 = rel1; - } - - @Override - public IList compose(IListRelation rel2) { - return ListFunctions.compose(vf, rel1, rel2.asList()); - } - - @Override - public IList closure() { - return ListFunctions.closure(vf, rel1); - } - - @Override - public IList closureStar() { - return ListFunctions.closureStar(vf, rel1); - } - - @Override - public int arity() { - return rel1.getElementType().getArity(); - } - - @Override - public IList project(int... fieldIndexes) { - return ListFunctions.project(vf, rel1, fieldIndexes); - } - - @Override - public IList projectByFieldNames(String... fieldsNames) { - return ListFunctions.projectByFieldNames(vf, rel1, fieldsNames); - } - - @Override - public IList carrier() { - return ListFunctions.carrier(vf, rel1); - } - - @Override - public IList domain() { - return ListFunctions.domain(vf, rel1); - } - - @Override - public IList range() { - return ListFunctions.range(vf, rel1); - } - - @Override - public IList asList() { - return rel1; - } - - @Override - public String toString() { - return rel1.toString(); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/DefaultRelationViewOnSet.java b/value-core/src/main/java/org/rascalmpl/value/impl/DefaultRelationViewOnSet.java deleted file mode 100644 index 940c7210a..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/DefaultRelationViewOnSet.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.rascalmpl.value.impl; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetRelation; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.func.SetFunctions; - -public class DefaultRelationViewOnSet implements ISetRelation { - - protected final IValueFactory vf; - protected final ISet rel1; - - public DefaultRelationViewOnSet(final IValueFactory vf, final ISet rel1) { - this.vf = vf; - this.rel1 = rel1; - } - - @Override - public ISet compose(ISetRelation rel2) { - return SetFunctions.compose(vf, rel1, rel2.asSet()); - } - - @Override - public ISet closure() { - return SetFunctions.closure(vf, rel1); - } - - @Override - public ISet closureStar() { - return SetFunctions.closureStar(vf, rel1); - } - - @Override - public int arity() { - return rel1.getElementType().getArity(); - } - - @Override - public ISet project(int... fieldIndexes) { - return SetFunctions.project(vf, rel1, fieldIndexes); - } - - @Override - public ISet projectByFieldNames(String... fieldsNames) { - return SetFunctions.projectByFieldNames(vf, rel1, fieldsNames); - } - - @Override - public ISet carrier() { - return SetFunctions.carrier(vf, rel1); - } - - @Override - public ISet domain() { - return SetFunctions.domain(vf, rel1); - } - - @Override - public ISet range() { - return SetFunctions.range(vf, rel1); - } - - @Override - public ISet asSet() { - return rel1; - } - - @Override - public String toString() { - return rel1.toString(); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/NodeWithKeywordParametersFacade.java b/value-core/src/main/java/org/rascalmpl/value/impl/NodeWithKeywordParametersFacade.java deleted file mode 100644 index cd80e0481..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/NodeWithKeywordParametersFacade.java +++ /dev/null @@ -1,140 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl; - -import java.util.Iterator; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.io.StandardTextWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.ImmutableMap; - -public class NodeWithKeywordParametersFacade implements INode { - protected final INode content; - protected final ImmutableMap parameters; - - public NodeWithKeywordParametersFacade(final INode content, final ImmutableMap parameters) { - this.content = content; - this.parameters = parameters; - } - - public Type getType() { - return content.getType(); - } - - public T accept(IValueVisitor v) throws E { - return v.visitNode(this); - } - - public IValue get(int i) throws IndexOutOfBoundsException { - return content.get(i); - } - - public INode set(int i, IValue newChild) throws IndexOutOfBoundsException { - INode newContent = content.set(i, newChild); - return new NodeWithKeywordParametersFacade(newContent, parameters); // TODO: introduce wrap() here as well - } - - public int arity() { - return content.arity(); - } - - public String toString() { - return StandardTextWriter.valueToString(this); - } - - public String getName() { - return content.getName(); - } - - public Iterable getChildren() { - return content.getChildren(); - } - - public Iterator iterator() { - return content.iterator(); - } - - public INode replace(int first, int second, int end, IList repl) - throws FactTypeUseException, IndexOutOfBoundsException { - INode newContent = content.replace(first, second, end, repl); - return new NodeWithKeywordParametersFacade(newContent, parameters); // TODO: introduce wrap() here as well - } - - public boolean equals(Object o) { - if(o == this) return true; - if(o == null) return false; - - if(o.getClass() == getClass()){ - NodeWithKeywordParametersFacade other = (NodeWithKeywordParametersFacade) o; - - return content.equals(other.content) && - parameters.equals(other.parameters); - } - - return false; - } - - @Override - public boolean isEqual(IValue other) { - if (!other.mayHaveKeywordParameters()) { - return false; - } - - if (other instanceof NodeWithKeywordParametersFacade) { - NodeWithKeywordParametersFacade o = (NodeWithKeywordParametersFacade) other; - - // TODO: this equals is fishy - return content.isEqual(o.content) && o.parameters.equals(parameters); - } - - return false; - } - - @Override - public int hashCode() { - return 15551 + 7 * content.hashCode() + 11 * parameters.hashCode(); - } - - @Override - public boolean isAnnotatable() { - return false; - } - - @Override - public IAnnotatable asAnnotatable() { - throw new UnsupportedOperationException("can not annotate a constructor which already has keyword parameters"); - } - - @Override - public boolean mayHaveKeywordParameters() { - return true; - } - - @Override - public IWithKeywordParameters asWithKeywordParameters() { - return new AbstractDefaultWithKeywordParameters(content, parameters) { - @Override - protected INode wrap(INode content, ImmutableMap parameters) { - return new NodeWithKeywordParametersFacade(content, parameters); - } - }; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/Constructor.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/Constructor.java deleted file mode 100644 index 1695cdc8e..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/Constructor.java +++ /dev/null @@ -1,309 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.impl.AbstractDefaultAnnotatable; -import org.rascalmpl.value.impl.AbstractDefaultWithKeywordParameters; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.impl.AnnotatedConstructorFacade; -import org.rascalmpl.value.impl.ConstructorWithKeywordParametersFacade; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.AbstractSpecialisedImmutableMap; -import io.usethesource.capsule.ArrayIterator; -import io.usethesource.capsule.ImmutableMap; - -/** - * Implementation of IConstructor. - *

- * Constructors that are annotated will use the AnnotatedConstructor class instead. - * - * @author Arnold Lankamp - */ -/*package*/ class Constructor extends AbstractValue implements IConstructor { - protected final Type constructorType; - protected final IValue[] children; - private int hashCode = 0; - - /*package*/ static IConstructor newConstructor(Type constructorType, IValue[] children) { - return new Constructor(constructorType, children); - } - - /*package*/ static IConstructor newConstructor(Type constructorType, IValue[] children, Map kwParams) { - IConstructor r = new Constructor(constructorType, children); - - if (kwParams != null && !kwParams.isEmpty()) { - return r.asWithKeywordParameters().setParameters(kwParams); - } - - return r; - } - - private Constructor(Type constructorType, IValue[] children){ - super(); - - this.constructorType = constructorType; - this.children = children; - } - - @Override - public Type getUninstantiatedConstructorType() { - return constructorType; - } - - @Override - public Type getType(){ - return getConstructorType().getAbstractDataType(); - } - - @Override - public Type getConstructorType(){ - if (constructorType.getAbstractDataType().isParameterized()) { - // this assures we always have the most concrete type for constructors. - Type[] actualTypes = new Type[children.length]; - for (int i = 0; i < children.length; i++) { - actualTypes[i] = children[i].getType(); - } - - Map bindings = new HashMap(); - constructorType.getFieldTypes().match(TypeFactory.getInstance().tupleType(actualTypes), bindings); - - for (Type field : constructorType.getAbstractDataType().getTypeParameters()) { - if (!bindings.containsKey(field)) { - bindings.put(field, TypeFactory.getInstance().voidType()); - } - } - - return constructorType.instantiate(bindings); - } - - return constructorType; - } - - @Override - public Type getChildrenTypes(){ - return constructorType.getFieldTypes(); - } - - @Override - public String getName(){ - return constructorType.getName(); - } - - @Override - public int arity(){ - return children.length; - } - - @Override - public IValue get(int i){ - return children[i]; - } - - @Override - public IValue get(String label){ - return get(constructorType.getFieldIndex(label)); - } - - @Override - public Iterable getChildren(){ - return this; - } - - @Override - public Iterator iterator(){ - return ArrayIterator.of(children); - } - - @Override - public T accept(IValueVisitor v) throws E{ - return v.visitConstructor(this); - } - - @Override - public IConstructor set(int i, IValue newChild){ - IValue[] newChildren = children.clone(); - newChildren[i] = newChild; - - return newConstructor(constructorType, newChildren); - } - - @Override - public IConstructor set(String label, IValue newChild){ - IValue[] newChildren = children.clone(); - newChildren[constructorType.getFieldIndex(label)] = newChild; - - return newConstructor(constructorType, newChildren); - } - - @Override - public boolean declaresAnnotation(TypeStore store, String label) { - return (store.getAnnotationType(constructorType.getAbstractDataType(), label) != null); - } - - @Override - public int hashCode(){ - if (hashCode == 0) { - hashCode = constructorType.hashCode(); - - for(int i = children.length - 1; i >= 0; i--){ - hashCode = (hashCode << 23) + (hashCode >> 5); - hashCode ^= children[i].hashCode(); - } - } - return hashCode; - } - - @Override - public boolean equals(Object o){ - if(o == this) return true; - if(o == null) return false; - - if(o.getClass() == getClass()){ - Constructor otherTree = (Constructor) o; - - if(constructorType != otherTree.constructorType) return false; - - IValue[] otherChildren = otherTree.children; - int nrOfChildren = children.length; - if(otherChildren.length == nrOfChildren){ - for(int i = nrOfChildren - 1; i >= 0; i--){ - if(!otherChildren[i].equals(children[i])) return false; - } - return true; - } - } - - return false; - } - - @Override - public boolean isEqual(IValue value){ - if(value == this) return true; - if(value == null) return false; - - if(value instanceof IConstructor){ - IConstructor otherTree = (IConstructor) value; - - if(!constructorType.comparable(otherTree.getConstructorType())) { - return false; - } - - final Iterator it1 = this.iterator(); - final Iterator it2 = otherTree.iterator(); - - while (it1.hasNext() && it2.hasNext()) { - // call to IValue.isEqual(IValue) - if (it1.next().isEqual(it2.next()) == false) { - return false; - } - } - - // TODO: this can be optimized when annotations are removed - if (mayHaveKeywordParameters() && otherTree.mayHaveKeywordParameters()) { - return asWithKeywordParameters().equalParameters(otherTree.asWithKeywordParameters()); - } - - // TODO: this can be optimized when annotations are removed - if (mayHaveKeywordParameters() && asWithKeywordParameters().hasParameters()) { - return false; - } - - // TODO: this can be optimized when annotations are removed - if (otherTree.mayHaveKeywordParameters() && otherTree.asWithKeywordParameters().hasParameters()) { - return false; - } - - return true; - } - - return false; - } - - @Override - public boolean has(String label) { - return getConstructorType().hasField(label); - } - - @Override - public IConstructor replace(int first, int second, int end, IList repl) - throws FactTypeUseException, IndexOutOfBoundsException { - - throw new UnsupportedOperationException("Replace not supported on constructor."); - } - - /** - * TODO: Create and move to {@link AbstractConstructor}. - */ - @Override - public boolean isAnnotatable() { - return true; - } - - /** - * TODO: Create and move to {@link AbstractConstructor}. - */ - @Override - public IAnnotatable asAnnotatable() { - return new AbstractDefaultAnnotatable(this) { - @Override - protected IConstructor wrap(IConstructor content, - ImmutableMap annotations) { - return new AnnotatedConstructorFacade(content, annotations); - } - }; - } - - @Override - public boolean mayHaveKeywordParameters() { - return true; - } - - @Override - public IWithKeywordParameters asWithKeywordParameters() { - return new AbstractDefaultWithKeywordParameters(this, AbstractSpecialisedImmutableMap.mapOf()) { - @Override - protected IConstructor wrap(IConstructor content, ImmutableMap parameters) { - return new ConstructorWithKeywordParametersFacade(content, parameters); - } - - @Override - public boolean hasParameters() { - return false; - } - - @Override - public java.util.Set getParameterNames() { - return Collections.emptySet(); - } - - @Override - public Map getParameters() { - return Collections.unmodifiableMap(parameters); - } - }; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/List.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/List.java deleted file mode 100644 index ac9e96f1d..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/List.java +++ /dev/null @@ -1,376 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -* Paul Klint - added new methods -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Iterator; -import java.util.Random; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListRelation; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.IllegalOperationException; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.impl.func.ListFunctions; -import org.rascalmpl.value.impl.util.collections.ShareableValuesList; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * Implementation of IList. - * - * @author Arnold Lankamp - */ -/*package*/ class List extends AbstractValue implements IList{ - protected final static TypeFactory typeFactory = TypeFactory.getInstance(); - protected final static Type voidType = typeFactory.voidType(); - - protected final Type listType; - protected final Type elementType; - - protected final ShareableValuesList data; - - protected int hashCode = 0; - - /*package*/ static IList newList(Type elementType, ShareableValuesList data) { - return new List(elementType, data); - } - - private List(Type elementType, ShareableValuesList data){ - super(); - - if (data.isEmpty()) - this.elementType = voidType; - else - this.elementType = elementType; - - this.listType = typeFactory.listType(this.elementType); - - this.data = data; - - } - - /*package*/ static ListWriter createListWriter(Type eltType){ - return new ListWriter(eltType); - } - - /*package*/ static ListWriter createListWriter(){ - return new ListWriter(); - } - - public Type getType(){ - return listType; - } - - public Type getElementType(){ - return elementType; - } - - public int length(){ - return data.size(); - } - - public boolean isEmpty(){ - return length() == 0; - } - - public IValue get(int index){ - return data.get(index); - } - - public boolean contains(IValue element){ - return data.contains(element); - } - - public Iterator iterator(){ - return data.iterator(); - } - - public T accept(IValueVisitor v) throws E{ - return v.visitList(this); - } - - public IList append(IValue element){ - ShareableValuesList newData = new ShareableValuesList(data); - newData.append(element); - - Type newElementType = elementType.lub(element.getType()); - return new ListWriter(newElementType, newData).done(); - } - - public IList concat(IList other){ - ShareableValuesList newData = new ShareableValuesList(data); - Iterator otherIterator = other.iterator(); - while(otherIterator.hasNext()){ - newData.append(otherIterator.next()); - } - - Type newElementType = elementType.lub(other.getElementType()); - return new ListWriter(newElementType, newData).done(); - } - - public IList insert(IValue element){ - ShareableValuesList newData = new ShareableValuesList(data); - newData.insert(element); - - Type newElementType = elementType.lub(element.getType()); - return new ListWriter(newElementType, newData).done(); - } - - public IList put(int index, IValue element) throws IndexOutOfBoundsException{ - ShareableValuesList newData = new ShareableValuesList(data); - newData.set(index, element); - - Type newElementType = elementType.lub(element.getType()); - return new ListWriter(newElementType, newData).done(); - } - - public IList replace(int first, int second, int end, IList repl) - throws FactTypeUseException, IndexOutOfBoundsException { - ShareableValuesList newData = new ShareableValuesList(); - int rlen = repl.length(); - int increment = Math.abs(second - first); - if(first < end){ - int dataIndex = 0; - // Before begin - while(dataIndex < first){ - newData.append(data.get(dataIndex++)); - } - int replIndex = 0; - boolean wrapped = false; - // Between begin and end - while(dataIndex < end){ - newData.append(repl.get(replIndex++)); - if(replIndex == rlen){ - replIndex = 0; - wrapped = true; - } - dataIndex++; //skip the replaced element - for(int j = 1; j < increment && dataIndex < end; j++){ - newData.append(data.get(dataIndex++)); - } - } - if(!wrapped){ - while(replIndex < rlen){ - newData.append(repl.get(replIndex++)); - } - } - // After end - int dlen = data.size(); - while( dataIndex < dlen){ - newData.append(data.get(dataIndex++)); - } - } else { - // Before begin (from right to left) - int dataIndex = data.size() - 1; - while(dataIndex > first){ - newData.insert(data.get(dataIndex--)); - } - // Between begin (right) and end (left) - int replIndex = 0; - boolean wrapped = false; - while(dataIndex > end){ - newData.insert(repl.get(replIndex++)); - if(replIndex == repl.length()){ - replIndex = 0; - wrapped = true; - } - dataIndex--; //skip the replaced element - for(int j = 1; j < increment && dataIndex > end; j++){ - newData.insert(data.get(dataIndex--)); - } - } - if(!wrapped){ - while(replIndex < rlen){ - newData.insert(repl.get(replIndex++)); - } - } - // Left of end - while(dataIndex >= 0){ - newData.insert(data.get(dataIndex--)); - } - } - Type newElementType = elementType.lub(repl.getElementType()); - return new ListWriter(newElementType, newData).done(); - } - - public IList delete(int index){ - ShareableValuesList newData = new ShareableValuesList(data); - newData.remove(index); - - Type newElementType = TypeFactory.getInstance().voidType(); - for(IValue el : newData) - newElementType = newElementType.lub(el.getType()); - - return new ListWriter(newElementType, newData).done(); - } - - public IList delete(IValue element){ - ShareableValuesList newData = new ShareableValuesList(data); - - if (newData.remove(element)) { - Type newElementType = TypeFactory.getInstance().voidType(); - - for (IValue el : newData) { - newElementType = newElementType.lub(el.getType()); - } - - return new ListWriter(newElementType, newData).done(); - } - - return this; - } - - public IList reverse(){ - ShareableValuesList newData = new ShareableValuesList(data); - newData.reverse(); - - return new ListWriter(elementType, newData).done(); - } - - @Override - public IList shuffle(Random rand) { - ShareableValuesList newData = new ShareableValuesList(data); - // we use Fisher–Yates shuffle (or Knuth shuffle) - // unbiased and linear time, since set and get are O(1) - for (int i= newData.size() - 1; i >= 1; i--) { - // we use the stack as tmp variable :) - newData.set(i, newData.set(rand.nextInt(i + 1), newData.get(i))); - } - return new ListWriter(elementType, newData).done(); - } - - - public IList sublist(int offset, int length){ - ShareableValuesList newData = data.subList(offset, length); - - Type newElementType = TypeFactory.getInstance().voidType(); - for(IValue el : newData) - newElementType = newElementType.lub(el.getType()); - - return new ListWriter(newElementType, newData).done(); - } - - public int hashCode(){ - if (hashCode == 0) { - hashCode = data.hashCode(); - } - return hashCode; - } - - public boolean equals(Object o){ - if(o == this) return true; - if(o == null) return false; - - if(o instanceof List) { - List otherList = (List) o; - - if (getType() != otherList.getType()) return false; - - if (hashCode() != otherList.hashCode()) return false; - - if (listType != otherList.listType) return false; - - return data.equals(otherList.data); - } - - return false; - } - - public boolean isEqual(IValue value){ - if(value == this) return true; - if(value == null) return false; - - if(value instanceof List){ - List otherList = (List) value; - - return data.isEqual(otherList.data); - } - else if (value instanceof IList) { - return ListFunctions.isEqual(ValueFactory.getInstance(), this, value); - } - - return false; - } - - public IList product(IList lst){ - Type resultType = TypeFactory.getInstance().tupleType(getElementType(),lst.getElementType()); - ListWriter w = new ListWriter(resultType); - - for(IValue t1 : this){ - for(IValue t2 : lst){ - IValue vals[] = {t1, t2}; - ITuple t3 = Tuple.newTuple(resultType, vals); - w.insert(t3); - } - } - - return (IList) w.done(); - } - - public IList intersect(IList other) { - IListWriter w = ValueFactory.getInstance().listWriter(); - List o = (List) other; - - for(IValue v : data){ - if(o.data.contains(v)){ - w.append(v); - } - } - - return w.done(); - } - - public IList subtract(IList lst) { - IListWriter w = ValueFactory.getInstance().listWriter(); - for (IValue v: this.data) { - if (lst.contains(v)) { - lst = lst.delete(v); - } else - w.append(v); - } - return w.done(); - } - - public boolean isSubListOf(IList lst) { - int j = 0; - nextchar: - for(IValue elm : this.data){ - while(j < lst.length()){ - if(elm.isEqual(lst.get(j))){ - j++; - continue nextchar; - } else - j++; - } - return false; - } - return true; - } - - @Override - public boolean isRelation() { - return getType().isListRelation(); - } - - @Override - public IListRelation asRelation() { - if (!isRelation()) - throw new IllegalOperationException( - "Cannot be viewed as a relation.", getType()); - - return new RelationViewOnList(this); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/ListWriter.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/ListWriter.java deleted file mode 100644 index d10d792ac..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/ListWriter.java +++ /dev/null @@ -1,186 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Iterator; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.impl.util.collections.ShareableValuesList; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -// TODO Add checking. -/** - * Implementation of IListWriter. - * - * @author Arnold Lankamp - */ -/*package*/ class ListWriter implements IListWriter{ - protected Type elementType; - protected final boolean inferred; - - protected final ShareableValuesList data; - - protected IList constructedList; - - /*package*/ ListWriter(Type elementType){ - super(); - - this.elementType = elementType; - this.inferred = false; - - data = new ShareableValuesList(); - - constructedList = null; - } - - /*package*/ ListWriter(){ - super(); - - this.elementType = TypeFactory.getInstance().voidType(); - this.inferred = true; - data = new ShareableValuesList(); - - constructedList = null; - } - - /*package*/ ListWriter(Type elementType, ShareableValuesList data){ - super(); - - this.elementType = elementType; - this.inferred = false; - this.data = data; - - constructedList = null; - } - - public void append(IValue element){ - checkMutation(); - - updateType(element); - data.append(element); - } - - private void updateType(IValue element) { - if (inferred) { - elementType = elementType.lub(element.getType()); - } - } - - public void append(IValue... elems){ - checkMutation(); - - for(IValue elem : elems){ - updateType(elem); - data.append(elem); - } - } - - public void appendAll(Iterable collection){ - checkMutation(); - - Iterator collectionIterator = collection.iterator(); - while(collectionIterator.hasNext()){ - IValue next = collectionIterator.next(); - updateType(next); - data.append(next); - } - } - - public void insert(IValue elem){ - checkMutation(); - updateType(elem); - data.insert(elem); - } - - public void insert(IValue... elements){ - insert(elements, 0, elements.length); - } - - public void insert(IValue[] elements, int start, int length){ - checkMutation(); - checkBounds(elements, start, length); - - for(int i = start + length - 1; i >= start; i--){ - updateType(elements[i]); - data.insert(elements[i]); - } - } - - public void insertAll(Iterable collection){ - checkMutation(); - - Iterator collectionIterator = collection.iterator(); - while(collectionIterator.hasNext()){ - IValue next = collectionIterator.next(); - updateType(next); - data.insert(next); - } - } - - public void insertAt(int index, IValue element){ - checkMutation(); - - updateType(element); - data.insertAt(index, element); - } - - public void insertAt(int index, IValue... elements){ - insertAt(index, elements, 0, 0); - } - - public void insertAt(int index, IValue[] elements, int start, int length){ - checkMutation(); - checkBounds(elements, start, length); - - for(int i = start + length - 1; i >= start; i--){ - updateType(elements[i]); - data.insertAt(index, elements[i]); - } - } - - public IValue replaceAt(int index, IValue element){ - checkMutation(); - - updateType(element); - return data.set(index, element); - } - - @Override - public IValue get(int i) throws IndexOutOfBoundsException { - return data.get(i); - } - - @Override - public int length() { - return data.size(); - } - - protected void checkMutation(){ - if(constructedList != null) throw new UnsupportedOperationException("Mutation of a finalized list is not supported."); - } - - private void checkBounds(IValue[] elems, int start, int length){ - if(start < 0) throw new ArrayIndexOutOfBoundsException("start < 0"); - if((start + length) > elems.length) throw new ArrayIndexOutOfBoundsException("(start + length) > elems.length"); - } - - @Override - public IList done() { - if (constructedList == null) { - constructedList = List.newList(data.isEmpty() ? TypeFactory.getInstance().voidType() : elementType, data); - } - - return constructedList; - } -} \ No newline at end of file diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/Map.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/Map.java deleted file mode 100644 index 8a203dc70..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/Map.java +++ /dev/null @@ -1,318 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009, 2012 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -* Anya Helene Bagge - labels -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Iterator; -import java.util.Map.Entry; - -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.impl.util.collections.ShareableValuesHashMap; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * Implementation of IMap. - * - * @author Arnold Lankamp - */ -/*package*/ class Map extends AbstractValue implements IMap { - protected final static TypeFactory typeFactory = TypeFactory.getInstance(); - - protected final Type mapType; - - protected final ShareableValuesHashMap data; - - /*package*/ static IMap newMap(Type mapType, ShareableValuesHashMap data) { - return new Map(mapType, data); - } - - private Map(Type mapType, ShareableValuesHashMap data) { - super(); - - this.mapType = mapType; - - this.data = data; - } - - public Type getType(){ - return mapType; - } - - public Type getKeyType(){ - return mapType.getKeyType(); - } - - public Type getValueType(){ - return mapType.getValueType(); - } - - public int size(){ - return data.size(); - } - - public int arity(){ - return size(); - } - - public boolean isEmpty(){ - return data.isEmpty(); - } - - public IValue get(IValue key){ - return data.get(key); - } - - public Iterator iterator(){ - return data.keysIterator(); - } - - public Iterator> entryIterator(){ - return data.entryIterator(); - } - - public Iterator valueIterator(){ - return data.valuesIterator(); - } - - public T accept(IValueVisitor v) throws E{ - return v.visitMap(this); - } - - public boolean containsKey(IValue key){ - return data.contains(key); - } - - public boolean containsValue(IValue value){ - Iterator valuesIterator = data.valuesIterator(); - while(valuesIterator.hasNext()){ - if(valuesIterator.next().isEqual(value)) return true; - } - - return false; - } - - public boolean isSubMap(IMap other) { - Map otherMap = (Map) other; - - Iterator keysIterator = iterator(); - while (keysIterator.hasNext()) { - IValue key = keysIterator.next(); - if (!otherMap.data.contains(key)) { - return false; - } - if (!otherMap.data.get(key).isEqual(data.get(key))) { - return false; - } - } - - return true; - } - - public IMap put(IValue key, IValue value){ - ShareableValuesHashMap newData = new ShareableValuesHashMap(data); - IValue replaced = newData.put(key, value); - - if (replaced != null) { - /* - * we might have to narrow dynamic type of value range - */ - Type voidType = TypeFactory.getInstance().voidType(); - - Type newMapType = mapType; - Type newKeyType = voidType; - Type newValueType = voidType; - - for (Iterator> it = newData.entryIterator(); it.hasNext(); ) { - final Entry currentEntry = it.next(); - - newKeyType = newKeyType.lub(currentEntry.getKey().getType()); - newValueType = newValueType.lub(currentEntry.getValue().getType()); - - if(newKeyType != mapType.getKeyType() || newValueType != mapType.getValueType()) { - newMapType = TypeFactory.getInstance().mapType(newKeyType, mapType.getKeyLabel(), newValueType, mapType.getValueLabel()); - } - } - - return new MapWriter(newMapType, newData).done(); - } else { - Type newMapType = mapType; - Type newKeyType = mapType.getKeyType().lub(key.getType()); - Type newValueType = mapType.getValueType().lub(value.getType()); - - if(newKeyType != mapType.getKeyType() || newValueType != mapType.getValueType()) { - newMapType = TypeFactory.getInstance().mapType(newKeyType, mapType.getKeyLabel(), newValueType, mapType.getValueLabel()); - } - - return new MapWriter(newMapType, newData).done(); - } - } - - public IMap common(IMap other){ - ShareableValuesHashMap commonData = new ShareableValuesHashMap(); - Iterator> entryIterator; - - IMap theOtherMap; - - if(other.size() <= size()){ - entryIterator = other.entryIterator(); - theOtherMap = this; - }else{ - entryIterator = entryIterator(); - theOtherMap = other; - } - - Type newKeyType = TypeFactory.getInstance().voidType(); - Type newValueType = TypeFactory.getInstance().voidType(); - while(entryIterator.hasNext()){ - Entry entry = entryIterator.next(); - IValue key = entry.getKey(); - IValue value = entry.getValue(); - if(value.isEqual(theOtherMap.get(key))){ - newKeyType = newKeyType.lub(key.getType()); - newValueType = newValueType.lub(value.getType()); - commonData.put(key, value); - } - } - Type lub = mapType.lub(other.getType()); - return new MapWriter(TypeFactory.getInstance().mapType(newKeyType, lub.getKeyLabel(), newValueType, lub.getValueLabel()), commonData).done(); - } - - public IMap compose(IMap other){ - ShareableValuesHashMap newData = new ShareableValuesHashMap(); - - Map otherMap = (Map) other; - - Iterator> entryIterator = entryIterator(); - while(entryIterator.hasNext()){ - Entry entry = entryIterator.next(); - IValue value = otherMap.get(entry.getValue()); - if(value != null){ - newData.put(entry.getKey(), value); - } - } - - Type newMapType; - if(mapType.hasFieldNames() && otherMap.mapType.hasFieldNames()) { - newMapType = TypeFactory.getInstance().mapType(mapType.getKeyType(), mapType.getKeyLabel(), - otherMap.mapType.getValueType(), otherMap.mapType.getValueLabel()); - } - else { - newMapType = TypeFactory.getInstance().mapType(mapType.getKeyType(), otherMap.mapType.getValueType()); - } - return new MapWriter(newMapType, newData).done(); - } - - public IMap join(IMap other){ - ShareableValuesHashMap newData; - Iterator> entryIterator; - - Map otherMap = (Map) other; - newData = new ShareableValuesHashMap(data); - entryIterator = otherMap.entryIterator(); - - while(entryIterator.hasNext()){ - Entry entry = entryIterator.next(); - newData.put(entry.getKey(), entry.getValue()); - } - - return new MapWriter(mapType.lub(otherMap.mapType), newData).done(); - } - - public IMap remove(IMap other){ - ShareableValuesHashMap newData = new ShareableValuesHashMap(data); - - Iterator keysIterator = other.iterator(); - while(keysIterator.hasNext()){ - newData.remove(keysIterator.next()); - } - - Type newKeyType = TypeFactory.getInstance().voidType(); - Type newValueType = TypeFactory.getInstance().voidType(); - Iterator> entryIterator = newData.entryIterator(); - while(entryIterator.hasNext()) { - Entry el = entryIterator.next(); - newKeyType = newKeyType.lub(el.getKey().getType()); - newValueType = newValueType.lub(el.getValue().getType()); - } - - return new MapWriter(TypeFactory.getInstance().mapType(newKeyType, mapType.getKeyLabel(), newValueType, mapType.getValueLabel()), newData).done(); - } - - public int hashCode(){ - return data.hashCode(); - } - - public boolean equals(Object o){ - if(o == this) return true; - if(o == null) return false; - - if(o.getClass() == getClass()){ - Map otherMap = (Map) o; - - if (getType() != otherMap.getType()) return false; - - return data.equals(otherMap.data); - } - - return false; - } - - public boolean isEqual(IValue value){ - if(value == this) return true; - if(value == null) return false; - - if(value instanceof Map){ - Map otherMap = (Map) value; - - return data.isEqual(otherMap.data); - } - - return false; - } - - @Override - public IMap removeKey(IValue key) { - ShareableValuesHashMap newData = new ShareableValuesHashMap(data); - IValue replaced = newData.remove(key); - - if (replaced != null) { - /* - * we might have to narrow dynamic type of value range - */ - Type voidType = TypeFactory.getInstance().voidType(); - - Type newMapType = mapType; - Type newKeyType = voidType; - Type newValueType = voidType; - - for (Iterator> it = newData.entryIterator(); it.hasNext();) { - final Entry currentEntry = it.next(); - - newKeyType = newKeyType.lub(currentEntry.getKey().getType()); - newValueType = newValueType.lub(currentEntry.getValue().getType()); - - if (newKeyType != mapType.getKeyType() || newValueType != mapType.getValueType()) { - newMapType = TypeFactory.getInstance().mapType(newKeyType, - mapType.getKeyLabel(), newValueType, mapType.getValueLabel()); - } - } - - return new MapWriter(newMapType, newData).done(); - } else { - return this; - } - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/MapWriter.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/MapWriter.java deleted file mode 100644 index 5d727a7a2..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/MapWriter.java +++ /dev/null @@ -1,213 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009, 2012 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -* Anya Helene Bagge - labels -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Iterator; -import java.util.Map.Entry; - -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.impl.util.collections.ShareableValuesHashMap; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -// TODO Add checking. -/** - * Implementation of IMapWriter. - * - * @author Arnold Lankamp - */ -/*package*/ class MapWriter implements IMapWriter{ - protected Type keyType; - protected Type valueType; - protected Type mapType; - - protected final ShareableValuesHashMap data; - - protected IMap constructedMap; - protected final boolean inferred; - protected boolean inferredTypeinvalidated; - - /*package*/ MapWriter(){ - super(); - - this.mapType = null; - this.keyType = TypeFactory.getInstance().voidType(); - this.valueType = TypeFactory.getInstance().voidType(); - this.inferred = true; - - data = new ShareableValuesHashMap(); - - constructedMap = null; - } - - - /*package*/ MapWriter(Type mapType) { - super(); - - if(mapType.isFixedWidth() && mapType.getArity() >= 2) { - mapType = TypeFactory.getInstance().mapTypeFromTuple(mapType); - } - - this.mapType = mapType; - this.keyType = mapType.getKeyType(); - this.valueType = mapType.getValueType(); - this.inferred = false; - - data = new ShareableValuesHashMap(); - - constructedMap = null; - } - - /*package*/ MapWriter(Type mapType, ShareableValuesHashMap data){ - super(); - - this.mapType = mapType; - this.keyType = mapType.getKeyType(); - this.valueType = mapType.getValueType(); - this.data = data; - this.inferred = false; - - constructedMap = null; - } - - @Override - public void put(IValue key, IValue value){ - checkMutation(); - updateTypes(key,value); - - IValue replaced = data.put(key, value); - - if (replaced != null) { - inferredTypeinvalidated = true; - } - } - - private void updateTypes(IValue key, IValue value) { - if (inferred) { - keyType = keyType.lub(key.getType()); - valueType = valueType.lub(value.getType()); - } - } - - @Override - public void putAll(IMap map){ - checkMutation(); - - Iterator> entryIterator = map.entryIterator(); - while(entryIterator.hasNext()){ - Entry entry = entryIterator.next(); - IValue key = entry.getKey(); - IValue value = entry.getValue(); - updateTypes(key,value); - data.put(key, value); - } - } - - @Override - public void putAll(java.util.Map map){ - checkMutation(); - - Iterator> entryIterator = map.entrySet().iterator(); - while(entryIterator.hasNext()){ - Entry entry = entryIterator.next(); - IValue key = entry.getKey(); - IValue value = entry.getValue(); - updateTypes(key,value); - data.put(key,value); - } - } - - @Override - public void insert(IValue... values){ - checkMutation(); - - for(int i = values.length - 1; i >= 0; i--){ - IValue value = values[i]; - - if(!(value instanceof ITuple)) throw new IllegalArgumentException("Argument must be of ITuple type."); - - ITuple tuple = (ITuple) value; - - if(tuple.arity() != 2) throw new IllegalArgumentException("Tuple must have an arity of 2."); - - IValue key = tuple.get(0); - IValue value2 = tuple.get(1); - updateTypes(key,value2); - put(key, value2); - } - } - - @Override - public void insertAll(Iterable collection){ - checkMutation(); - - Iterator collectionIterator = collection.iterator(); - while(collectionIterator.hasNext()){ - IValue value = collectionIterator.next(); - - if(!(value instanceof ITuple)) throw new IllegalArgumentException("Argument must be of ITuple type."); - - ITuple tuple = (ITuple) value; - - if(tuple.arity() != 2) throw new IllegalArgumentException("Tuple must have an arity of 2."); - - IValue key = tuple.get(0); - IValue value2 = tuple.get(1); - updateTypes(key,value2); - put(key, value2); - } - } - - protected void checkMutation() { - if (constructedMap != null) - throw new UnsupportedOperationException( - "Mutation of a finalized map is not supported."); - } - - @Override - public IMap done(){ - if(constructedMap == null) { - if (mapType == null) { - mapType = TypeFactory.getInstance().mapType(keyType, valueType); - } - if (data.isEmpty()) { - Type voidType = TypeFactory.getInstance().voidType(); - Type voidMapType = TypeFactory.getInstance().mapType(voidType, mapType.getKeyLabel(), voidType, mapType.getValueLabel()); - - constructedMap = Map.newMap(voidMapType, data); - } else { - if (inferred && inferredTypeinvalidated) { - Type voidType = TypeFactory.getInstance().voidType(); - - keyType = voidType; - valueType = voidType; - - for (Iterator> it = data.entryIterator(); it.hasNext(); ) { - final Entry currentEntry = it.next(); - - keyType = keyType.lub(currentEntry.getKey().getType()); - valueType = valueType.lub(currentEntry.getValue().getType()); - - mapType = TypeFactory.getInstance().mapType(keyType, mapType.getKeyLabel(), valueType, mapType.getValueLabel()); - } - } - - constructedMap = Map.newMap(mapType, data); - } - } - - return constructedMap; - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/Node.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/Node.java deleted file mode 100644 index 46c469cf8..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/Node.java +++ /dev/null @@ -1,185 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -* Paul Klint - Implemented replace -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Iterator; -import java.util.Map; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.AbstractNode; -import org.rascalmpl.value.impl.func.NodeFunctions; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.ArrayIterator; - -/** - * Implementation of INode. - * - * @author Arnold Lankamp - */ -/*package*/ class Node extends AbstractNode implements INode { - protected final static Type NODE_TYPE = TypeFactory.getInstance().nodeType(); - protected final static Type VALUE_TYPE = TypeFactory.getInstance().valueType(); - - protected final String name; - protected final IValue[] children; - - /*package*/ static INode newNode(String name, IValue[] children) { - return new Node(name, children); - } - - private Node(String name, IValue[] children) { - super(); - - this.name = (name != null ? name.intern() : null); // Handle (weird) special case. - this.children = children; - } - - /*package*/ static INode newNode(String name, IList children) { - return new Node(name, children); - } - - private Node(String name, IList children) { - super(); - IValue[] childArray = new IValue[children.length()]; - this.name = (name != null ? name.intern() : null); // Handle (weird) special case. - for(int i = 0; i < childArray.length; i++){ - childArray[i] = children.get(i); - } - this.children = childArray; - } - - /*package*/ static INode newNode(String name, IValue[] children, Map keyArgValues) { - INode node = new Node(name, children, keyArgValues); - - if (keyArgValues != null && keyArgValues.size() > 0) { - return node.asWithKeywordParameters().setParameters(keyArgValues); - } - - return node; - } - - private Node(String name, IValue[] children, Map keyArgValues) { - super(); - this.name = (name != null ? name.intern() : null); // Handle (weird) special case. - this.children = children; - } - - @Override - public Type getType(){ - return NODE_TYPE; - } - - @Override - public int arity(){ - return children.length; - } - - @Override - protected IValueFactory getValueFactory() { - return ValueFactory.getInstance(); - } - - @Override - public IValue get(int i){ - return children[i]; - } - - @Override - public String getName(){ - return name; - } - - @Override - public Iterator iterator(){ - return ArrayIterator.of(children); - } - - @Override - public Iterable getChildren(){ - return this; - } - - @Override - public INode set(int i, IValue arg){ - IValue[] newChildren = children.clone(); - newChildren[i] = arg; - - return newNode(name, newChildren); - } - - @Override - public T accept(IValueVisitor v) throws E{ - return v.visitNode(this); - } - - @Override - public int hashCode(){ - int hash = name.hashCode(); - - for(int i = children.length - 1; i >= 0; i--){ - hash = (hash << 23) + (hash >> 5); - hash ^= children[i].hashCode(); - } - return hash; - } - - @Override - public boolean equals(Object o){ - if (o == this) { - return true; - } - if (o == null) { - return false; - } - - if (o.getClass() != getClass()) { - return false; - } - - Node other = (Node) o; - - // Yes '!=' works here, since it has been interned. - if (name != other.name) { - return false; - } - - IValue[] otherChildren = other.children; - int nrOfChildren = children.length; - - if (otherChildren.length != nrOfChildren) { - return false; - } - - for (int i = nrOfChildren - 1; i >= 0; i--) { - if (!otherChildren[i].equals(children[i])) { - return false; - } - } - - return true; - } - - /** - * TODO: Check if it is easily possible to cast annotatable's content to - * List and to reuse old isEqual. - */ - @Override - public boolean isEqual(IValue value){ - return NodeFunctions.isEqual(getValueFactory(), this, value); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationViewOnList.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationViewOnList.java deleted file mode 100644 index f61aee88f..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationViewOnList.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.rascalmpl.value.impl.fast; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListRelation; - -public class RelationViewOnList implements IListRelation { - - protected final IList rel1; - - public RelationViewOnList(IList rel1) { - this.rel1 = rel1; - } - - @Override - public IList compose(IListRelation rel2) { - return RelationalFunctionsOnList.compose(rel1, rel2.asList()); - } - - @Override - public IList closure() { - return RelationalFunctionsOnList.closure(rel1); - } - - @Override - public IList closureStar() { - return RelationalFunctionsOnList.closureStar(rel1); - } - - @Override - public int arity() { - return rel1.getElementType().getArity(); - } - - @Override - public IList project(int... fieldIndexes) { - return RelationalFunctionsOnList.project(rel1, fieldIndexes); - } - - @Override - public IList projectByFieldNames(String... fieldsNames) { - return RelationalFunctionsOnList.projectByFieldNames(rel1, fieldsNames); - } - - @Override - public IList carrier() { - return RelationalFunctionsOnList.carrier(rel1); - } - - @Override - public IList domain() { - return RelationalFunctionsOnList.domain(rel1); - } - - @Override - public IList range() { - return RelationalFunctionsOnList.range(rel1); - } - - @Override - public IList asList() { - return rel1; - } - - @Override - public String toString() { - return rel1.toString(); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationViewOnSet.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationViewOnSet.java deleted file mode 100644 index 1b481c617..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationViewOnSet.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.rascalmpl.value.impl.fast; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetRelation; - -public class RelationViewOnSet implements ISetRelation { - - protected final ISet rel1; - - public RelationViewOnSet(ISet rel1) { - this.rel1 = rel1; - } - - @Override - public ISet compose(ISetRelation rel2) { - return RelationalFunctionsOnSet.compose(rel1, rel2.asSet()); - } - - @Override - public ISet closure() { - return RelationalFunctionsOnSet.closure(rel1); - } - - @Override - public ISet closureStar() { - return RelationalFunctionsOnSet.closureStar(rel1); - } - - @Override - public int arity() { - return rel1.getElementType().getArity(); - } - - @Override - public ISet project(int... fieldIndexes) { - return RelationalFunctionsOnSet.project(rel1, fieldIndexes); - } - - @Override - public ISet projectByFieldNames(String... fieldsNames) { - return RelationalFunctionsOnSet.projectByFieldNames(rel1, fieldsNames); - } - - @Override - public ISet carrier() { - return RelationalFunctionsOnSet.carrier(rel1); - } - - @Override - public ISet domain() { - return RelationalFunctionsOnSet.domain(rel1); - } - - @Override - public ISet range() { - return RelationalFunctionsOnSet.range(rel1); - } - - @Override - public ISet asSet() { - return rel1; - } - - @Override - public String toString() { - return rel1.toString(); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationalFunctionsOnList.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationalFunctionsOnList.java deleted file mode 100644 index 164e85397..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationalFunctionsOnList.java +++ /dev/null @@ -1,179 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -* Michael Steindorfer - performance improvements -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.HashSet; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.IllegalOperationException; -import org.rascalmpl.value.impl.util.collections.ShareableValuesHashSet; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -public class RelationalFunctionsOnList { - - protected final static TypeFactory typeFactory = TypeFactory.getInstance(); - protected final static Type voidType = typeFactory.voidType(); - - public static int arity(IList rel) { - return rel.getElementType().getArity(); - } - - public static IList carrier(IList rel1) { - Type newType = rel1.getType().carrier(); - IListWriter w = List.createListWriter(newType.getElementType()); - HashSet cache = new HashSet<>(); - - for (IValue v : rel1) { - ITuple t = (ITuple) v; - for(IValue e : t){ - if(!cache.contains(e)){ - cache.add(e); - w.append(e); - } - } - } - - return w.done(); - } - - public static IList domain(IList rel1) { - Type lrelType = rel1.getType(); - IListWriter w = List.createListWriter(lrelType.getFieldType(0)); - HashSet cache = new HashSet<>(); - - for (IValue elem : rel1) { - ITuple tuple = (ITuple) elem; - IValue e = tuple.get(0); - if(!cache.contains(e)){ - cache.add(e); - w.append(e); - } - } - return w.done(); - } - - public static IList range(IList rel1) { - Type lrelType = rel1.getType(); - int last = lrelType.getArity() - 1; - IListWriter w = List.createListWriter(lrelType.getFieldType(last)); - HashSet cache = new HashSet<>(); - - for (IValue elem : rel1) { - ITuple tuple = (ITuple) elem; - IValue e = tuple.get(last); - if(!cache.contains(e)){ - cache.add(e); - w.append(e); - } - } - - return w.done(); - } - - public static IList compose(IList rel1, IList rel2) { - - Type otherTupleType = rel2.getType().getFieldTypes(); - - if(rel1.getElementType() == voidType) return rel1; - if(otherTupleType == voidType) return rel2; - - if(rel1.getElementType().getArity() != 2 || otherTupleType.getArity() != 2) throw new IllegalOperationException("compose", rel1.getElementType(), otherTupleType); - - // Relaxed type constraint: - if(!rel1.getElementType().getFieldType(1).comparable(otherTupleType.getFieldType(0))) throw new IllegalOperationException("compose", rel1.getElementType(), otherTupleType); - - Type[] newTupleFieldTypes = new Type[]{rel1.getElementType().getFieldType(0), otherTupleType.getFieldType(1)}; - Type tupleType = typeFactory.tupleType(newTupleFieldTypes); - - IListWriter w = new ListWriter(tupleType); - - for (IValue v1 : rel1) { - ITuple tuple1 = (ITuple) v1; - for (IValue t2 : rel2) { - ITuple tuple2 = (ITuple) t2; - - if (tuple1.get(1).isEqual(tuple2.get(0))) { - w.append(Tuple.newTuple(tuple1.get(0), tuple2.get(1))); - } - } - } - return w.done(); - } - - public static IList closure(IList rel1) { - Type resultType = rel1.getType().closure(); // will throw exception if not binary and reflexive - IList tmp = rel1; - - int prevCount = 0; - - ShareableValuesHashSet addedTuples = new ShareableValuesHashSet(); - while (prevCount != tmp.length()) { - prevCount = tmp.length(); - IList tcomp = compose(tmp, tmp); - IListWriter w = List.createListWriter(resultType.getElementType()); - for(IValue t1 : tcomp){ - if(!tmp.contains(t1)){ - if(!addedTuples.contains(t1)){ - addedTuples.add(t1); - w.append(t1); - } - } - } - tmp = tmp.concat(w.done()); - addedTuples.clear(); - } - return tmp; - } - - public static IList closureStar(IList rel1) { - Type resultType = rel1.getType().closure(); - // an exception will have been thrown if the type is not acceptable - - IListWriter reflex = List.createListWriter(resultType.getElementType()); - - for (IValue e: carrier(rel1)) { - reflex.insert(Tuple.newTuple(new IValue[] {e, e})); - } - - return closure(rel1).concat(reflex.done()); - } - - public static IList project(IList rel1, int... fields) { - IListWriter w = ValueFactory.getInstance().listWriter(); - - for (IValue v : rel1) { - w.append(((ITuple) v).select(fields)); - } - - return w.done(); - } - - public static IList projectByFieldNames(IList rel1, String... fields) { - int[] indexes = new int[fields.length]; - int i = 0; - - if (rel1.getType().getFieldTypes().hasFieldNames()) { - for (String field : fields) { - indexes[i++] = rel1.getType().getFieldTypes().getFieldIndex(field); - } - - return project(rel1, indexes); - } - - throw new IllegalOperationException("select with field names", rel1.getType()); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationalFunctionsOnSet.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationalFunctionsOnSet.java deleted file mode 100644 index 98f751ed4..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/RelationalFunctionsOnSet.java +++ /dev/null @@ -1,380 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -* Michael Steindorfer - performance improvements -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Iterator; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.IllegalOperationException; -import org.rascalmpl.value.impl.util.collections.ShareableValuesHashSet; -import org.rascalmpl.value.impl.util.collections.ShareableValuesList; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.util.RotatingQueue; -import org.rascalmpl.value.util.ShareableHashMap; -import org.rascalmpl.value.util.ValueIndexedHashMap; - -public class RelationalFunctionsOnSet { - - protected final static TypeFactory typeFactory = TypeFactory.getInstance(); - protected final static Type voidType = typeFactory.voidType(); - - public static int arity(ISet rel) { - return rel.getElementType().getArity(); - } - -// // TODO: Currently untested in PDB. -// public static ISet union(ISet rel1, ISet rel2){ -// ShareableValuesHashSet newData; -// Iterator setIterator; -// -// Set thisSet = (Set) rel1; -// Set otherSet = (Set) rel2; -// -// if(otherSet.size() <= rel1.size()){ -// newData = new ShareableValuesHashSet(thisSet.data); -// setIterator = otherSet.iterator(); -// }else{ -// newData = new ShareableValuesHashSet(otherSet.data); -// setIterator = rel1.iterator(); -// } -// -// while(setIterator.hasNext()){ -// newData.add(setIterator.next()); -// } -// -// Type newElementType = thisSet.elementType.lub(otherSet.elementType); -// return new SetWriter(newElementType, newData).done(); -// } - -// // TODO: Currently untested in PDB. -// public static ISet intersect(ISet rel1, ISet rel2){ -// ShareableValuesHashSet commonData = new ShareableValuesHashSet(); -// Iterator setIterator; -// -// ISet theOtherSet; -// -// if(rel2.size() <= rel1.size()){ -// setIterator = rel2.iterator(); -// theOtherSet = rel1; -// }else{ -// setIterator = rel1.iterator(); -// theOtherSet = rel2; -// } -// -// Type newElementType = TypeFactory.getInstance().voidType(); -// while(setIterator.hasNext()){ -// IValue value = setIterator.next(); -// if(theOtherSet.contains(value)){ -// newElementType = newElementType.lub(value.getType()); -// commonData.add(value); -// } -// } -// -// return new SetWriter(newElementType, commonData).done(); -// } - -// // TODO: Currently untested in PDB. -// public static ISet subtract(ISet rel1, ISet rel2){ -// ShareableValuesHashSet newData = new ShareableValuesHashSet(((Set)rel1).data); -// -// Iterator setIterator = rel2.iterator(); -// while(setIterator.hasNext()){ -// newData.remove(setIterator.next()); -// } -// -// Type newElementType = TypeFactory.getInstance().voidType(); -// for(IValue el : newData) -// newElementType = newElementType.lub(el.getType()); -// -// return new SetWriter(newElementType, newData).done(); -// } - - private static ShareableValuesHashSet computeCarrier(ISet rel1) { - ShareableValuesHashSet newData = new ShareableValuesHashSet(); - - Iterator relationIterator = ((Set)rel1).data.iterator(); - while(relationIterator.hasNext()){ - ITuple tuple = (ITuple) relationIterator.next(); - - Iterator tupleIterator = tuple.iterator(); - while(tupleIterator.hasNext()){ - newData.add(tupleIterator.next()); - } - } - - return newData; - } - - public static ISet carrier(ISet rel1) { - ShareableValuesHashSet newData = computeCarrier(rel1); - - Type type = determainMostGenericTypeInTuple(rel1); - return new SetWriter(type, newData).done(); - } - - // TODO: Currently untested in PDB. - public static ISet domain(ISet rel1){ - ShareableValuesHashSet newData = new ShareableValuesHashSet(); - - Iterator relationIterator = ((Set)rel1).data.iterator(); - while(relationIterator.hasNext()){ - ITuple tuple = (ITuple) relationIterator.next(); - - newData.add(tuple.get(0)); - } - - Type type = rel1.getElementType().getFieldType(0); - return new SetWriter(type, newData).done(); - } - - // TODO: Currently untested in PDB. - public static ISet range(ISet rel1){ - ShareableValuesHashSet newData = new ShareableValuesHashSet(); - - int last = rel1.getElementType().getArity() - 1; - - Iterator relationIterator = ((Set)rel1).data.iterator(); - while(relationIterator.hasNext()){ - ITuple tuple = (ITuple) relationIterator.next(); - - newData.add(tuple.get(last)); - } - - Type type = rel1.getElementType().getFieldType(last); - return new SetWriter(type, newData).done(); - } - - public static ISet compose(ISet rel1, ISet rel2){ - Type otherTupleType = rel2.getElementType(); - - if (rel1.getElementType() == voidType) { - return rel1; - } - if(otherTupleType == voidType) { - return rel2; - } - - if(rel1.getElementType().getArity() != 2 || otherTupleType.getArity() != 2) { - throw new IllegalOperationException("compose", rel1.getElementType(), otherTupleType); - } - if(!rel1.getElementType().getFieldType(1).comparable(otherTupleType.getFieldType(0))) { - return new SetWriter().done(); - } - - // Index - ShareableHashMap rightSides = new ShareableHashMap<>(); - - Iterator otherRelationIterator = rel2.iterator(); - while(otherRelationIterator.hasNext()){ - ITuple tuple = (ITuple) otherRelationIterator.next(); - - IValue key = tuple.get(0); - ShareableValuesList values = rightSides.get(key); - if(values == null){ - values = new ShareableValuesList(); - rightSides.put(key, values); - } - - values.append(tuple.get(1)); - } - - // Compute - ShareableValuesHashSet newData = new ShareableValuesHashSet(); - - Type[] newTupleFieldTypes = new Type[]{rel1.getElementType().getFieldType(0), otherTupleType.getFieldType(1)}; - Type tupleType = typeFactory.tupleType(newTupleFieldTypes); - - Iterator relationIterator = ((Set)rel1).data.iterator(); - while(relationIterator.hasNext()){ - ITuple thisTuple = (ITuple) relationIterator.next(); - - IValue key = thisTuple.get(1); - ShareableValuesList values = rightSides.get(key); - if(values != null){ - Iterator valuesIterator = values.iterator(); - do{ - IValue value = valuesIterator.next(); - IValue[] newTupleData = new IValue[]{thisTuple.get(0), value}; - newData.add(Tuple.newTuple(tupleType, newTupleData)); - }while(valuesIterator.hasNext()); - } - } - - return new SetWriter(tupleType, newData).done(); - } - - private static ShareableValuesHashSet computeClosure(ISet rel1, Type tupleType){ - ShareableValuesHashSet allData = new ShareableValuesHashSet(((Set)rel1).data); - - RotatingQueue iLeftKeys = new RotatingQueue<>(); - RotatingQueue> iLefts = new RotatingQueue<>(); - - ValueIndexedHashMap> interestingLeftSides = new ValueIndexedHashMap<>(); - ValueIndexedHashMap potentialRightSides = new ValueIndexedHashMap<>(); - - // Index - Iterator allDataIterator = allData.iterator(); - while(allDataIterator.hasNext()){ - ITuple tuple = (ITuple) allDataIterator.next(); - - IValue key = tuple.get(0); - IValue value = tuple.get(1); - RotatingQueue leftValues = interestingLeftSides.get(key); - ShareableValuesHashSet rightValues; - if(leftValues != null){ - rightValues = potentialRightSides.get(key); - }else{ - leftValues = new RotatingQueue<>(); - iLeftKeys.put(key); - iLefts.put(leftValues); - interestingLeftSides.put(key, leftValues); - - rightValues = new ShareableValuesHashSet(); - potentialRightSides.put(key, rightValues); - } - leftValues.put(value); - rightValues.add(value); - } - - int size = potentialRightSides.size(); - int nextSize = 0; - - // Compute - do{ - ValueIndexedHashMap rightSides = potentialRightSides; - potentialRightSides = new ValueIndexedHashMap<>(); - - for(; size > 0; size--){ - IValue leftKey = iLeftKeys.get(); - RotatingQueue leftValues = iLefts.get(); - - RotatingQueue interestingLeftValues = null; - - IValue rightKey; - while((rightKey = leftValues.get()) != null){ - ShareableValuesHashSet rightValues = rightSides.get(rightKey); - if(rightValues != null){ - Iterator rightValuesIterator = rightValues.iterator(); - while(rightValuesIterator.hasNext()){ - IValue rightValue = rightValuesIterator.next(); - if(allData.add(Tuple.newTuple(tupleType, new IValue[]{leftKey, rightValue}))){ - if(interestingLeftValues == null){ - nextSize++; - - iLeftKeys.put(leftKey); - interestingLeftValues = new RotatingQueue<>(); - iLefts.put(interestingLeftValues); - } - interestingLeftValues.put(rightValue); - - ShareableValuesHashSet potentialRightValues = potentialRightSides.get(rightKey); - if(potentialRightValues == null){ - potentialRightValues = new ShareableValuesHashSet(); - potentialRightSides.put(rightKey, potentialRightValues); - } - potentialRightValues.add(rightValue); - } - } - } - } - } - size = nextSize; - nextSize = 0; - }while(size > 0); - - return allData; - } - - public static ISet closure(ISet rel1) { - if(rel1.getElementType() == voidType) return rel1; - if(!isBinary(rel1)) { - throw new IllegalOperationException("closure", rel1.getType()); - } - - Type tupleElementType = rel1.getElementType().getFieldType(0).lub(rel1.getElementType().getFieldType(1)); - Type tupleType = typeFactory.tupleType(tupleElementType, tupleElementType); - - return new SetWriter(rel1.getElementType(), computeClosure(rel1, tupleType)).done(); - } - - // TODO: Currently untested in PDB. - public static ISet closureStar(ISet rel1) { - if (rel1.getElementType() == voidType) { - return rel1; - } - if (!isBinary(rel1)) { - throw new IllegalOperationException("closureStar", rel1.getType()); - } - - Type tupleElementType = rel1.getElementType().getFieldType(0).lub(rel1.getElementType().getFieldType(1)); - Type tupleType = typeFactory.tupleType(tupleElementType, tupleElementType); - - ShareableValuesHashSet closure = computeClosure(rel1, tupleType); - ShareableValuesHashSet carrier = computeCarrier(rel1); - - Iterator carrierIterator = carrier.iterator(); - while(carrierIterator.hasNext()){ - IValue element = carrierIterator.next(); - closure.add(Tuple.newTuple(tupleType, new IValue[]{element, element})); - } - - return new SetWriter(rel1.getElementType(), closure).done(); - } - - // TODO: Currently untested in PDB. - public static ISet project(ISet rel1, int... indexes){ - ShareableValuesHashSet newData = new ShareableValuesHashSet(); - - Iterator dataIterator = ((Set)rel1).data.iterator(); - while(dataIterator.hasNext()){ - ITuple tuple = (ITuple) dataIterator.next(); - - newData.add(tuple.select(indexes)); - } - - Type type = rel1.getElementType().select(indexes); - return new SetWriter(type, newData).done(); - } - - // TODO: Currently untested in PDB. - public static ISet projectByFieldNames(ISet rel1, String... fields){ - if(!rel1.getElementType().hasFieldNames()) throw new IllegalOperationException("select with field names", rel1.getType()); - - ShareableValuesHashSet newData = new ShareableValuesHashSet(); - - Iterator dataIterator = ((Set)rel1).data.iterator(); - while(dataIterator.hasNext()){ - ITuple tuple = (ITuple) dataIterator.next(); - - newData.add(tuple.selectByFieldNames(fields)); - } - - Type type = rel1.getElementType().select(fields); - return new SetWriter(type, newData).done(); - } - - private static Type determainMostGenericTypeInTuple(ISet rel1){ - Type result = rel1.getElementType().getFieldType(0); - for(int i = rel1.getElementType().getArity() - 1; i > 0; i--){ - result = result.lub(rel1.getElementType().getFieldType(i)); - } - - return result; - } - - private static boolean isBinary(ISet rel1){ - return rel1.getElementType().getArity() == 2; - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/Set.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/Set.java deleted file mode 100644 index b29833b7d..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/Set.java +++ /dev/null @@ -1,260 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009-2013 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -* Michael Steindorfer - performance improvements -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Iterator; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetRelation; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.IllegalOperationException; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.impl.func.SetFunctions; -import org.rascalmpl.value.impl.util.collections.ShareableValuesHashSet; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * Implementation of ISet. - * - * @author Arnold Lankamp - */ -/*package*/ class Set extends AbstractValue implements ISet { - protected final static TypeFactory typeFactory = TypeFactory.getInstance(); - protected final static Type voidType = typeFactory.voidType(); - - protected final Type setType; - protected final Type elementType; - - protected final ShareableValuesHashSet data; - - /*package*/ static ISet newSet(Type elementType, ShareableValuesHashSet data) { - return new Set(elementType, data); - } - - private Set(Type elementType, ShareableValuesHashSet data) { - super(); - - if (data.isEmpty()) - this.elementType = voidType; - else - this.elementType = elementType; - - this.setType = typeFactory.setType(this.elementType); - - this.data = data; - } - - public Type getType(){ - return setType; - } - - public Type getElementType(){ - return elementType; - } - - public int size(){ - return data.size(); - } - - public boolean isEmpty(){ - return data.isEmpty(); - } - - public Iterator iterator(){ - return data.iterator(); - } - - public T accept(IValueVisitor v) throws E{ - if (getElementType().isFixedWidth()) { - return v.visitRelation(this); - } else { - return v.visitSet(this); - } - } - - public boolean contains(IValue element){ - return data.contains(element); - } - - public boolean isSubsetOf(ISet other){ - Set otherSet = (Set) other; - - Iterator iterator = iterator(); - while(iterator.hasNext()){ - if(!otherSet.data.contains(iterator.next())) return false; - } - - return true; - } - - public ISet insert(IValue value){ - if(!contains(value)) { - ShareableValuesHashSet newData = new ShareableValuesHashSet(data); - newData.add(value); - - Type type = elementType.lub(value.getType()); - return new SetWriter(type, newData).done(); - } else { - return this; - } - } - - public ISet delete(IValue value){ - if (contains(value)) { - ShareableValuesHashSet newData = new ShareableValuesHashSet(data); - newData.remove(value); - - Type newElementType = TypeFactory.getInstance().voidType(); - for (IValue el : newData) { - newElementType = newElementType.lub(el.getType()); - } - return new SetWriter(newElementType, newData).done(); - } else { - return this; - } - } - - public ISet intersect(ISet other){ - ShareableValuesHashSet commonData = new ShareableValuesHashSet(); - Iterator setIterator; - - ISet theOtherSet; - - if(other.size() <= size()){ - setIterator = other.iterator(); - theOtherSet = this; - }else{ - setIterator = iterator(); - theOtherSet = other; - } - - Type newElementType = TypeFactory.getInstance().voidType(); - while(setIterator.hasNext()){ - IValue value = setIterator.next(); - if(theOtherSet.contains(value)){ - newElementType = newElementType.lub(value.getType()); - commonData.add(value); - } - } - - return new SetWriter(newElementType, commonData).done(); - } - - public ISet subtract(ISet other){ - ShareableValuesHashSet newData = new ShareableValuesHashSet(data); - - Iterator setIterator = other.iterator(); - while(setIterator.hasNext()){ - newData.remove(setIterator.next()); - } - Type newElementType = TypeFactory.getInstance().voidType(); - for(IValue el : newData) - newElementType = newElementType.lub(el.getType()); - return new SetWriter(newElementType, newData).done(); - } - - public ISet union(ISet other){ - ShareableValuesHashSet newData; - Iterator setIterator; - - Set otherSet = (Set) other; - - if(otherSet.size() <= size()){ - newData = new ShareableValuesHashSet(data); - setIterator = otherSet.iterator(); - }else{ - newData = new ShareableValuesHashSet(otherSet.data); - setIterator = iterator(); - } - - while(setIterator.hasNext()){ - newData.add(setIterator.next()); - } - - Type newElementType = elementType.lub(otherSet.elementType); - return new SetWriter(newElementType, newData).done(); - } - - public ISet product(ISet other){ - ShareableValuesHashSet newData = new ShareableValuesHashSet(); - - Type tupleType = typeFactory.tupleType(elementType, other.getElementType()); - - Iterator thisIterator = data.iterator(); - while(thisIterator.hasNext()){ - IValue left = thisIterator.next(); - - Iterator setIterator = other.iterator(); - while(setIterator.hasNext()){ - IValue right = setIterator.next(); - - IValue[] tuple = new IValue[]{left, right}; - newData.add(Tuple.newTuple(tupleType, tuple)); - } - } - - return new SetWriter(tupleType, newData).done(); - } - - public int hashCode(){ - return data.hashCode(); - } - - public boolean equals(Object o){ - if(o == this) return true; - if(o == null) return false; - - if(o.getClass() == getClass()){ - Set otherSet = (Set) o; - - if (getType() != otherSet.getType()) { - return false; - } - return data.equals(otherSet.data); - } - - return false; - } - - public boolean isEqual(IValue value){ - if(value == this) return true; - if(value == null) return false; - - if(value instanceof Set){ - Set otherSet = (Set) value; - - return data.isEqual(otherSet.data); - } - else if (value instanceof ISet) { - return SetFunctions.isEqual(ValueFactory.getInstance(), this, (ISet) value); - } - - return false; - } - - @Override - public boolean isRelation() { - return getType().isRelation(); - } - - @Override - public ISetRelation asRelation() { - if (!isRelation()) - throw new IllegalOperationException( - "Cannot be viewed as a relation.", getType()); - - return new RelationViewOnSet(this); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/SetWriter.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/SetWriter.java deleted file mode 100644 index 966bbabbb..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/SetWriter.java +++ /dev/null @@ -1,114 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Iterator; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.impl.util.collections.ShareableValuesHashSet; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -// TODO Add checking. -/** - * Implementation of ISetWriter. - * - * @author Arnold Lankamp - */ -/*package*/ class SetWriter implements ISetWriter{ - protected Type elementType; - protected final boolean inferred; - - protected final ShareableValuesHashSet data; - - protected ISet constructedSet; - - /*package*/ SetWriter(Type elementType){ - super(); - - this.elementType = elementType; - this.inferred = false; - - data = new ShareableValuesHashSet(); - - constructedSet = null; - } - - /*package*/ SetWriter(){ - super(); - - this.elementType = TypeFactory.getInstance().voidType(); - this.inferred = true; - - data = new ShareableValuesHashSet(); - - constructedSet = null; - } - - /*package*/ SetWriter(Type elementType, ShareableValuesHashSet data){ - super(); - - this.elementType = elementType; - this.inferred = false; - this.data = data; - - constructedSet = null; - } - - public void insert(IValue value){ - checkMutation(); - updateType(value); - data.add(value); - } - - private void updateType(IValue value) { - if (inferred) { - elementType = elementType.lub(value.getType()); - } - } - - @Override - public void insert(IValue... elements){ - checkMutation(); - - for(int i = elements.length - 1; i >= 0; i--){ - updateType(elements[i]); - data.add(elements[i]); - } - } - - @Override - public void insertAll(Iterable collection){ - checkMutation(); - - Iterator collectionIterator = collection.iterator(); - while(collectionIterator.hasNext()){ - IValue next = collectionIterator.next(); - updateType(next); - data.add(next); - } - } - - protected void checkMutation(){ - if(constructedSet != null) throw new UnsupportedOperationException("Mutation of a finalized map is not supported."); - } - - @Override - public ISet done(){ - if (constructedSet == null) { - constructedSet = Set.newSet(data.isEmpty() ? TypeFactory.getInstance().voidType() : elementType, data); - } - - return constructedSet; - } -} \ No newline at end of file diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/Tuple.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/Tuple.java deleted file mode 100644 index 299093f48..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/Tuple.java +++ /dev/null @@ -1,234 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * Implementation of ITuple. - * - * @author Arnold Lankamp - */ -/*package*/ class Tuple extends AbstractValue implements ITuple{ - - protected final static TypeFactory typeFactory = TypeFactory.getInstance(); - - private Type cachedTupleType; - protected final IValue[] elements; - - public static ITuple newTuple(Type tupleType, IValue[] elements) { - return new Tuple(tupleType, elements); - } - - private Tuple(Type tupleType, IValue[] elements) { - super(); - - this.cachedTupleType = tupleType; - this.elements = elements; - } - - /*package*/ static ITuple newTuple(IValue... elements) { - return new Tuple(elements); - } - - private Tuple(IValue... elements) { - super(); - - this.elements = elements; - } - - public Type getType() { - if (cachedTupleType == null) { - cachedTupleType = TypeFactory.getInstance().tupleType(elements); - } - - return cachedTupleType; - } - - public int arity() { - return elements.length; - } - - public IValue get(int i) { - return elements[i]; - } - - public IValue get(String label) { - return elements[getType().getFieldIndex(label)]; - } - - public Iterator iterator() { - return new TupleIterator(this); - } - - public T accept(IValueVisitor v) throws E { - return v.visitTuple(this); - } - - public ITuple set(int index, IValue arg) { - int nrOfElements = elements.length; - IValue[] newElements = new IValue[nrOfElements]; - Type[] elementTypes = new Type[nrOfElements]; - for (int i = nrOfElements - 1; i >= 0; i--) { - IValue element = elements[i]; - newElements[i] = element; - elementTypes[i] = element.getType(); - } - - newElements[index] = arg; - elementTypes[index] = arg.getType(); - - return new Tuple(typeFactory.tupleType(elementTypes), newElements); - } - - public ITuple set(String label, IValue arg) { - int nrOfElements = elements.length; - IValue[] newElements = new IValue[nrOfElements]; - Type[] elementTypes = new Type[nrOfElements]; - for (int i = nrOfElements - 1; i >= 0; i--) { - IValue element = elements[i]; - newElements[i] = element; - elementTypes[i] = element.getType(); - } - - newElements[getType().getFieldIndex(label)] = arg; - elementTypes[getType().getFieldIndex(label)] = arg.getType(); - - return new Tuple(typeFactory.tupleType(elementTypes), newElements); - } - - public IValue select(int... indexes) { - if (indexes.length == 1) - return get(indexes[0]); - - int nrOfElements = indexes.length; - IValue[] elements = new IValue[nrOfElements]; - Type[] elementTypes = new Type[nrOfElements]; - for (int i = nrOfElements - 1; i >= 0; i--) { - IValue element = get(indexes[i]); - elements[i] = element; - elementTypes[i] = element.getType(); - } - - return new Tuple(typeFactory.tupleType(elementTypes), elements); - } - - public IValue selectByFieldNames(String... fields) { - if (fields.length == 1) - return get(fields[0]); - - int nrOfElements = fields.length; - IValue[] elements = new IValue[nrOfElements]; - Type[] elementTypes = new Type[nrOfElements]; - for (int i = nrOfElements - 1; i >= 0; i--) { - IValue element = get(fields[i]); - elements[i] = element; - elementTypes[i] = element.getType(); - } - - return new Tuple(typeFactory.tupleType(elementTypes), elements); - } - - public int hashCode() { - int hash = 1331; - - for (int i = elements.length - 1; i >= 0; i--) { - hash -= (hash << 19) + (hash >>> 8); - hash ^= elements[i].hashCode(); - } - - return hash - (hash << 7); - } - - public boolean equals(Object o) { - if (o == this) - return true; - if (o == null) - return false; - - if (o.getClass() == getClass()) { - Tuple otherTuple = (Tuple) o; - - IValue[] otherElements = otherTuple.elements; - int nrOfElements = elements.length; - if (otherElements.length == nrOfElements) { - for (int i = nrOfElements - 1; i >= 0; i--) { - if (!otherElements[i].equals(elements[i])) - return false; - } - return true; - } - } - - return false; - } - - public boolean isEqual(IValue value) { - if (value == this) - return true; - if (value == null) - return false; - - if (value instanceof Tuple) { - Tuple otherTuple = (Tuple) value; - - if (!getType().comparable(otherTuple.getType())) - return false; - - IValue[] otherElements = otherTuple.elements; - int nrOfElements = elements.length; - if (otherElements.length == nrOfElements) { - for (int i = nrOfElements - 1; i >= 0; i--) { - if (!otherElements[i].isEqual(elements[i])) - return false; - } - return true; - } - } - - return false; - } - - private static class TupleIterator implements Iterator { - private final IValue[] elements; - private int index = 0; - - public TupleIterator(Tuple tuple) { - super(); - - elements = tuple.elements; - } - - public boolean hasNext() { - return index < elements.length; - } - - public IValue next() { - if (!hasNext()) - throw new NoSuchElementException("No more elements in this iteration."); - - return elements[index++]; - } - - public void remove() { - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/fast/ValueFactory.java b/value-core/src/main/java/org/rascalmpl/value/impl/fast/ValueFactory.java deleted file mode 100644 index 23e6660b4..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/fast/ValueFactory.java +++ /dev/null @@ -1,227 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009, 2012-2013 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Jurgen Vinju - interface and implementation -* Arnold Lankamp - implementation -* Anya Helene Bagge - rational support, labeled maps and tuples -* Davy Landman - added PI & E constants -* Michael Steindorfer - extracted factory for numeric data -*******************************************************************************/ -package org.rascalmpl.value.impl.fast; - -import java.util.Map; - -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.UnexpectedElementTypeException; -import org.rascalmpl.value.impl.primitive.AbstractPrimitiveValueFactory; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -/** - * Implementation of IValueFactory. - */ -public class ValueFactory extends AbstractPrimitiveValueFactory { - private final static TypeFactory tf = TypeFactory.getInstance(); - - private final static Type EMPTY_TUPLE_TYPE = TypeFactory.getInstance().tupleEmpty(); - - protected ValueFactory() { - super(); - } - - private static class InstanceKeeper{ - public final static ValueFactory instance = new ValueFactory(); - } - - public static ValueFactory getInstance(){ - return InstanceKeeper.instance; - } - - @Deprecated - public IListWriter listWriter(Type elementType){ - return new ListWriter(elementType); - } - - public IListWriter listWriter(){ - return new ListWriter(); - } - - @Deprecated - public IMapWriter mapWriter(Type keyType, Type valueType){ - return new MapWriter(TypeFactory.getInstance().mapType(keyType, valueType)); - } - - public IMapWriter mapWriter(Type mapType){ - return new MapWriter(mapType); - } - - public IMapWriter mapWriter(){ - return new MapWriter(); - } - - public ISetWriter setWriter(Type elementType){ - return new SetWriter(elementType); - } - - public ISetWriter setWriter(){ - return new SetWriter(); - } - - public ISetWriter relationWriter(Type tupleType){ - return new SetWriter(tupleType); - } - - public ISetWriter relationWriter(){ - return new SetWriter(); - } - - public IListWriter listRelationWriter(Type tupleType) { - return new ListWriter(tupleType); - } - - public IListWriter listRelationWriter() { - return new ListWriter(); - } - - public IList list(Type elementType){ - return listWriter(elementType).done(); - } - - public IList list(IValue... elements){ - IListWriter listWriter = listWriter(lub(elements)); - listWriter.append(elements); - - return listWriter.done(); - } - - public IMap map(Type mapType){ - return mapWriter(mapType).done(); - } - - public IMap map(Type keyType, Type valueType){ - return mapWriter(keyType, valueType).done(); - } - - public ISet set(Type elementType){ - return setWriter(TypeFactory.getInstance().voidType()).done(); - } - - public ISet set(IValue... elements){ - Type elementType = lub(elements); - - ISetWriter setWriter = setWriter(elementType); - setWriter.insert(elements); - return setWriter.done(); - } - - public ISet relation(Type tupleType){ - return relationWriter(tupleType).done(); - } - - public ISet relation(IValue... elements) { - Type elementType = lub(elements); - - if (!elementType.isFixedWidth()) throw new UnexpectedElementTypeException(tf.tupleType(tf.voidType()), elementType); - - ISetWriter relationWriter = relationWriter(elementType); - relationWriter.insert(elements); - return relationWriter.done(); - } - - public IList listRelation(Type tupleType) { - return listRelationWriter(tupleType).done(); - } - - public IList listRelation(IValue... elements) { - Type elementType = lub(elements); - - if (!elementType.isFixedWidth()) throw new UnexpectedElementTypeException(tf.tupleType(tf.voidType()), elementType); - - IListWriter listRelationWriter = listRelationWriter(elementType); - listRelationWriter.append(elements); - return listRelationWriter.done(); - } - - public INode node(String name) { - return Node.newNode(name, new IValue[0]); - } - - public INode node(String name, Map annos, IValue... children) { - return Node.newNode(name, children.clone()).asAnnotatable().setAnnotations(annos); - } - - public INode node(String name, IValue... children) { - return Node.newNode(name, children.clone()); - } - - @Override - public INode node(String name, IValue[] children, Map keyArgValues) - throws FactTypeUseException { - return Node.newNode(name, children.clone(), keyArgValues); - } - - @Override - public IConstructor constructor(Type constructorType) { - return Constructor.newConstructor(constructorType, new IValue[0]); - } - - @Override - public IConstructor constructor(Type constructorType, IValue... children){ - return Constructor.newConstructor(constructorType, children.clone()); - } - - @Override - public IConstructor constructor(Type constructorType, IValue[] children, Map kwParams){ - return Constructor.newConstructor(constructorType, children.clone(), kwParams); - } - - @Override - public IConstructor constructor(Type constructorType, - Map annotations, IValue... children) - throws FactTypeUseException { - return Constructor.newConstructor(constructorType, children.clone()).asAnnotatable().setAnnotations(annotations); - } - - public ITuple tuple() { - return Tuple.newTuple(EMPTY_TUPLE_TYPE, new IValue[0]); - } - - public ITuple tuple(IValue... args) { - return Tuple.newTuple(args.clone()); - } - - public ITuple tuple(Type type, IValue... args) { - return Tuple.newTuple(type, args.clone()); - } - - private static Type lub(IValue... elements) { - Type elementType = TypeFactory.getInstance().voidType(); - - for (int i = elements.length - 1; i >= 0; i--) { - elementType = elementType.lub(elements[i].getType()); - } - - return elementType; - } - - @Override - public String toString() { - return "VF_PDB_FAST"; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/func/ListFunctions.java b/value-core/src/main/java/org/rascalmpl/value/impl/func/ListFunctions.java deleted file mode 100644 index 08c9dc2b3..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/func/ListFunctions.java +++ /dev/null @@ -1,522 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI - * * Paul Klint - Paul.Klint@cwi.nl - CWI - * - * Based on code by: - * - * * Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.impl.func; - -import java.util.Iterator; -import java.util.Random; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.IllegalOperationException; -import org.rascalmpl.value.impl.util.collections.ShareableValuesHashSet; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -public final class ListFunctions { - - private final static TypeFactory TF = TypeFactory.getInstance(); - - public static IList sublist(IValueFactory vf, IList list1, int offset, int length) { - if (offset < 0 || length < 0 || offset + length > list1.length()) { - throw new IndexOutOfBoundsException(); - } - IListWriter w = vf.listWriter(); - for (int i = offset; i < offset + length; i++) { - w.append(list1.get(i)); - } - return w.done(); - } - - public static IList insert(IValueFactory vf, IList list1, IValue e) { - IListWriter w = vf.listWriter(); - w.appendAll(list1); - w.insert(e); - - return w.done(); - } - - public static IList put(IValueFactory vf, IList list1, int i, IValue e) - throws IndexOutOfBoundsException { - IListWriter w = vf.listWriter(); - w.appendAll(list1); - w.replaceAt(i, e); - return w.done(); - } - - // public static IList replace(IValueFactory vf, IList list1, int first, - // int second, int end, IList repl) { - // IListWriter w = vf.listWriter(); - // if (first < end) { - // for (int i = 0; i < first; i++) { - // w.append(list1.get(i)); - // } - // w.appendAll(repl); - // for (int i = end; i < list1.length(); i++) { - // w.append(list1.get(i)); - // } - // } else { - // for (int i = list1.length() - 1; i > first; i--) { - // w.insert(list1.get(i)); - // } - // for (IValue v : repl) { - // w.insert(v); - // } - // for (int i = end; i >= 0; i--) { - // w.insert(list1.get(i)); - // } - // } - // return w.done(); - // } - - public static IList replace(IValueFactory vf, IList list1, int first, - int second, int end, IList repl) throws FactTypeUseException, - IndexOutOfBoundsException { - IListWriter result = vf.listWriter(); - - int rlen = repl.length(); - int increment = Math.abs(second - first); - - if (first < end) { - int listIndex = 0; - // Before begin - while (listIndex < first) { - result.append(list1.get(listIndex++)); - } - int replIndex = 0; - boolean wrapped = false; - // Between begin and end - while (listIndex < end) { - result.append(repl.get(replIndex++)); - if (replIndex == rlen) { - replIndex = 0; - wrapped = true; - } - listIndex++; // skip the replaced element - for (int j = 1; j < increment && listIndex < end; j++) { - result.append(list1.get(listIndex++)); - } - } - if (!wrapped) { - while (replIndex < rlen) { - result.append(repl.get(replIndex++)); - } - } - // After end - int dlen = list1.length(); - while (listIndex < dlen) { - result.append(list1.get(listIndex++)); - } - } else { - // Before begin (from right to left) - int listIndex = list1.length() - 1; - while (listIndex > first) { - result.insert(list1.get(listIndex--)); - } - // Between begin (right) and end (left) - int replIndex = 0; - boolean wrapped = false; - while (listIndex > end) { - result.insert(repl.get(replIndex++)); - if (replIndex == repl.length()) { - replIndex = 0; - wrapped = true; - } - listIndex--; // skip the replaced element - for (int j = 1; j < increment && listIndex > end; j++) { - result.insert(list1.get(listIndex--)); - } - } - if (!wrapped) { - while (replIndex < rlen) { - result.insert(repl.get(replIndex++)); - } - } - // Left of end - while (listIndex >= 0) { - result.insert(list1.get(listIndex--)); - } - } - - return result.done(); - } - - public static IList append(IValueFactory vf, IList list1, IValue e) { - IListWriter w = vf.listWriter(); - w.appendAll(list1); - w.append(e); - - return w.done(); - } - - public static boolean contains(IValueFactory vf, IList list1, IValue e) { - for (IValue v : list1) { - if (v.isEqual(e)) { - return true; - } - } - return false; - } - - public static IList delete(IValueFactory vf, IList list1, IValue v) { - IListWriter w = vf.listWriter(); - - boolean deleted = false; - for (Iterator iterator = list1.iterator(); iterator.hasNext();) { - IValue e = iterator.next(); - - if (!deleted && e.isEqual(v)) { - deleted = true; // skip first occurrence - } else { - w.append(e); - } - } - return w.done(); - } - - public static IList delete(IValueFactory vf, IList list1, int index) { - IListWriter w = vf.listWriter(); - - int currentIndex = 0; - boolean deleted = false; - for (Iterator iterator = list1.iterator(); iterator.hasNext(); currentIndex++) { - IValue e = iterator.next(); - - if (!deleted && index == currentIndex) { - deleted = true; // skip first occurrence - } else { - w.append(e); - } - } - return w.done(); - } - - public static IList reverse(IValueFactory vf, IList list1) { - IListWriter w = vf.listWriter(); - for (IValue e : list1) { - w.insert(e); - } - return w.done(); - } - public static IList shuffle(IValueFactory vf, IList list1, Random rand) { - IListWriter w = vf.listWriter(); - w.appendAll(list1); // add everything - // we use Fisher–Yates shuffle (or Knuth shuffle) - // unbiased and linear time (incase of random access) - for (int i = list1.length() - 1; i >= 1; i--) { - w.replaceAt(i, w.replaceAt(rand.nextInt(i + 1), w.get(i))); - } - return w.done(); - } - - public static IList concat(IValueFactory vf, IList list1, IList list2) { - IListWriter w = vf.listWriter(); - w.appendAll(list1); - w.appendAll(list2); - return w.done(); - } - - public static int hashCode(IValueFactory vf, IList list1) { - int hash = 0; - - Iterator iterator = list1.iterator(); - while (iterator.hasNext()) { - IValue element = iterator.next(); - hash = (hash << 1) ^ element.hashCode(); - } - - return hash; - } - - public static boolean equals(IValueFactory vf, IList list1, Object other) { - if (other == list1) - return true; - if (other == null) - return false; - - if (other instanceof IList) { - IList list2 = (IList) other; - - if (list1.isEmpty() && list2.isEmpty()) { - return true; - } - - if (list1.getType() != list2.getType()) - return false; - - if (hashCode(vf, list1) != hashCode(vf, list2)) - return false; - - - - if (list1.length() == list2.length()) { - - final Iterator it1 = list1.iterator(); - final Iterator it2 = list2.iterator(); - - while (it1.hasNext() && it2.hasNext()) { - // call to Object.equals(Object) - if (it1.next().equals(it2.next()) == false) - return false; - } - - assert (!it1.hasNext() && !it2.hasNext()); - return true; - } - } - - return false; - } - - public static boolean isEqual(IValueFactory vf, IList list1, IValue other) { - // return equals(vf, list1, other); - if (other == list1) - return true; - if (other == null) - return false; - - if (other instanceof IList) { - IList list2 = (IList) other; - - if (list1.length() == list2.length()) { - - final Iterator it1 = list1.iterator(); - final Iterator it2 = list2.iterator(); - - while (it1.hasNext() && it2.hasNext()) { - // call to IValue.isEqual(IValue) - if (it1.next().isEqual(it2.next()) == false) - return false; - } - - assert (!it1.hasNext() && !it2.hasNext()); - return true; - } - } - - return false; - } - - public static IList product(IValueFactory vf, IList list1, IList list2) { - IListWriter w = vf.listWriter(); - - for (IValue t1 : list1) { - for (IValue t2 : list2) { - IValue values[] = { t1, t2 }; - ITuple t3 = vf.tuple(values); - w.insert(t3); - } - } - - return (IList) w.done(); - } - - public static IList intersect(IValueFactory vf, IList list1, IList list2) { - IListWriter w = vf.listWriter(); - - for (IValue v : list1) { - if (list2.contains(v)) { - w.append(v); - } - } - - return w.done(); - } - - public static IList subtract(IValueFactory vf, IList list1, IList list2) { - IListWriter w = vf.listWriter(); - for (IValue v : list1) { - if (list2.contains(v)) { - list2 = list2.delete(v); - } else - w.append(v); - } - return w.done(); - } - - public static boolean isSubListOf(IValueFactory vf, IList list1, IList list2) { - int j = 0; - nextValue: for (IValue elm : list1) { - while (j < list2.length()) { - if (elm.isEqual(list2.get(j))) { - j++; - continue nextValue; - } else - j++; - } - return false; - } - return true; - } - - public static IList closure(IValueFactory vf, IList list1) { - // will throw exception if not binary and reflexive - list1.getType().closure(); - - IList tmp = list1; - - int prevCount = 0; - - ShareableValuesHashSet addedTuples = new ShareableValuesHashSet(); - while (prevCount != tmp.length()) { - prevCount = tmp.length(); - IList tcomp = compose(vf, tmp, tmp); - IListWriter w = vf.listWriter(); - for (IValue t1 : tcomp) { - if (!tmp.contains(t1)) { - if (!addedTuples.contains(t1)) { - addedTuples.add(t1); - w.append(t1); - } - } - } - tmp = tmp.concat(w.done()); - addedTuples.clear(); - } - return tmp; - } - - public static IList closureStar(IValueFactory vf, IList list1) { - list1.getType().closure(); - // an exception will have been thrown if the type is not acceptable - - IListWriter reflex = vf.listWriter(); - - for (IValue e : carrier(vf, list1)) { - reflex.insert(vf.tuple(new IValue[] { e, e })); - } - - return closure(vf, list1).concat(reflex.done()); - } - - public static IList compose(IValueFactory vf, IList list1, IList list2) { - - Type otherTupleType = list2.getType().getFieldTypes(); - - if (list1.getElementType() == TF.voidType()) - return list1; - if (otherTupleType == TF.voidType()) - return list2; - - if (list1.getElementType().getArity() != 2 - || otherTupleType.getArity() != 2) - throw new IllegalOperationException("compose", - list1.getElementType(), otherTupleType); - - // Relaxed type constraint: - if (!list1.getElementType().getFieldType(1) - .comparable(otherTupleType.getFieldType(0))) - throw new IllegalOperationException("compose", - list1.getElementType(), otherTupleType); - - IListWriter w = vf.listWriter(); - - for (IValue v1 : list1) { - ITuple tuple1 = (ITuple) v1; - for (IValue t2 : list2) { - ITuple tuple2 = (ITuple) t2; - - if (tuple1.get(1).isEqual(tuple2.get(0))) { - w.append(vf.tuple(tuple1.get(0), tuple2.get(1))); - } - } - } - return w.done(); - } - - public static IList carrier(IValueFactory vf, IList rel1) { - IListWriter w = vf.listWriter(); - java.util.HashSet cache = new java.util.HashSet<>(); - - for (IValue v : rel1) { - ITuple t = (ITuple) v; - for (IValue e : t) { - if (!cache.contains(e)) { - cache.add(e); - w.append(e); - } - } - } - - return w.done(); - } - - public static IList domain(IValueFactory vf, IList rel1) { - int columnIndex = 0; - IListWriter w = vf.listWriter(); - java.util.HashSet cache = new java.util.HashSet<>(); - - for (IValue elem : rel1) { - ITuple tuple = (ITuple) elem; - IValue e = tuple.get(columnIndex); - if (!cache.contains(e)) { - cache.add(e); - w.append(e); - } - } - return w.done(); - } - - public static IList range(IValueFactory vf, IList rel1) { - int columnIndex = rel1.getType().getArity() - 1; - IListWriter w = vf.listWriter(); - java.util.HashSet cache = new java.util.HashSet<>(); - - for (IValue elem : rel1) { - ITuple tuple = (ITuple) elem; - IValue e = tuple.get(columnIndex); - if (!cache.contains(e)) { - cache.add(e); - w.append(e); - } - } - - return w.done(); - } - - public static IList project(IValueFactory vf, IList list1, int... fields) { - IListWriter w = vf.listWriter(); - - for (IValue v : list1) { - w.append(((ITuple) v).select(fields)); - } - - return w.done(); - } - - public static IList projectByFieldNames(IValueFactory vf, IList list1, String... fields) { - int[] indexes = new int[fields.length]; - int i = 0; - - if (list1.getType().getFieldTypes().hasFieldNames()) { - for (String field : fields) { - indexes[i++] = list1.getType().getFieldTypes() - .getFieldIndex(field); - } - - return project(vf, list1, indexes); - } - - throw new IllegalOperationException("select with field names", - list1.getType()); - } - -} \ No newline at end of file diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/func/MapFunctions.java b/value-core/src/main/java/org/rascalmpl/value/impl/func/MapFunctions.java deleted file mode 100644 index 48a7f2dd6..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/func/MapFunctions.java +++ /dev/null @@ -1,224 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse public static License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI - * * Paul Klint - Paul.Klint@cwi.nl - CWI - * * Anya Helene Bagge - anya@ii.uib.no - UiB - * - * Based on code by: - * - * * Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.impl.func; - -import java.util.Iterator; -import java.util.Map.Entry; - -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -public final class MapFunctions { - - @SuppressWarnings("unused") - private final static TypeFactory TF = TypeFactory.getInstance(); - - public static IMap compose(IValueFactory vf, IMap map1, IMap map2) { - Type newMapType; - - if (map1.getType().hasFieldNames() && map2.getType().hasFieldNames()) { - newMapType = TypeFactory.getInstance().mapType( - map1.getType().getKeyType(), map1.getType().getKeyLabel(), - map2.getType().getValueType(), - map2.getType().getValueLabel()); - } else { - newMapType = TypeFactory.getInstance().mapType(map1.getKeyType(), - map2.getValueType()); - } - - IMapWriter w = vf.mapWriter(newMapType); - - Iterator> iter = map1.entryIterator(); - while (iter.hasNext()) { - Entry e = iter.next(); - IValue value = map2.get(e.getValue()); - if (value != null) { - w.put(e.getKey(), value); - } - } - - return w.done(); - } - - public static IMap put(IValueFactory vf, IMap map1, IValue key, IValue value) { - IMapWriter sw = vf.mapWriter(map1.getType()); - sw.putAll(map1); - sw.put(key, value); - return sw.done(); - } - - public static IMap join(IValueFactory vf, IMap map1, IMap map2) { - IMapWriter sw = vf.mapWriter(map1.getType().lub(map2.getType())); - sw.putAll(map1); - sw.putAll(map2); - return sw.done(); - } - - public static IMap common(IValueFactory vf, IMap map1, IMap map2) { - IMapWriter sw = vf.mapWriter(map1.getType().lub(map2.getType())); - - for (IValue key : map1) { - IValue thisValue = map1.get(key); - IValue otherValue = map2.get(key); - if (otherValue != null && thisValue.isEqual(otherValue)) { - sw.put(key, thisValue); - } - } - return sw.done(); - } - - public static IMap remove(IValueFactory vf, IMap map1, IMap map2) { - IMapWriter sw = vf.mapWriter(map1.getType()); - for (IValue key : map1) { - if (!map2.containsKey(key)) { - sw.put(key, map1.get(key)); - } - } - return sw.done(); - } - - public static boolean isSubMap(IValueFactory vf, IMap map1, IMap map2) { - for (IValue key : map1) { - if (!map2.containsKey(key)) { - return false; - } - if (!map2.get(key).isEqual(map1.get(key))) { - return false; - } - } - return true; - } - - public static int hashCode(IValueFactory vf, IMap map1) { - int hash = 0; - - Iterator keyIterator = map1.iterator(); - while (keyIterator.hasNext()) { - IValue key = keyIterator.next(); - hash ^= key.hashCode(); - } - - return hash; - } - - public static boolean equals(IValueFactory vf, IMap map1, Object other){ - if (other == map1) return true; - if (other == null) return false; - - if (other instanceof IMap) { - IMap map2 = (IMap) other; - - if (map1.getType() != map2.getType()) return false; - - if (hashCode(vf, map1) != hashCode(vf, map2)) return false; - - if (map1.size() == map2.size()) { - - for (IValue k1 : map1) { - if (containsKeyWithEquals(vf, map2, k1) == false) { // call to Object.equals(Object) - return false; - } else if (map2.get(k1).equals(map1.get(k1)) == false) { // call to Object.equals(Object) - return false; - } - } - - return true; - } - } - - return false; - } - - public static boolean isEqual(IValueFactory vf, IMap map1, IValue other){ - if (other == map1) return true; - if (other == null) return false; - - if (other instanceof IMap) { - IMap map2 = (IMap) other; - - if (map1.size() == map2.size()) { - - for (IValue k1 : map1) { - if (containsKey(vf, map2, k1) == false) { // call to IValue.isEqual(IValue) - return false; - } else if (map2.get(k1).isEqual(map1.get(k1)) == false) { // call to IValue.isEqual(IValue) - return false; - } - } - - return true; - } - } - - return false; - - } - - public static IValue get(IValueFactory valueFactory, IMap map1, IValue key) { - for (Iterator> iterator = map1.entryIterator(); iterator.hasNext();) { - Entry entry = iterator.next(); - if (entry.getKey().isEqual(key)) { - return entry.getValue(); - } - } - return null; - } - - public static boolean containsKeyWithEquals(IValueFactory valueFactory, IMap map1, IValue key) { - for (Iterator iterator = map1.iterator(); iterator.hasNext();) { - if (iterator.next().equals(key)) { - return true; - } - } - return false; - } - - public static boolean containsKey(IValueFactory valueFactory, IMap map1, IValue key) { - for (Iterator iterator = map1.iterator(); iterator.hasNext();) { - if (iterator.next().isEqual(key)) { - return true; - } - } - return false; - } - - public static boolean containsValueWithEquals(IValueFactory valueFactory, IMap map1, - IValue value) { - for (Iterator iterator = map1.valueIterator(); iterator.hasNext();) { - if (iterator.next().equals(value)) { - return true; - } - } - return false; - } - - public static boolean containsValue(IValueFactory valueFactory, IMap map1, IValue value) { - for (Iterator iterator = map1.valueIterator(); iterator.hasNext();) { - if (iterator.next().isEqual(value)) { - return true; - } - } - return false; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/func/NodeFunctions.java b/value-core/src/main/java/org/rascalmpl/value/impl/func/NodeFunctions.java deleted file mode 100644 index 8111b360a..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/func/NodeFunctions.java +++ /dev/null @@ -1,148 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.func; - -import java.util.ArrayList; -import java.util.Iterator; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; - -public class NodeFunctions { - - /* - * TODO: merge with ListFunctions.replace(...). Algorithm is exactly the same, the only difference is - * that difference interfaces are used (IList, INode). - */ - public static INode replace(IValueFactory vf, INode node1, int first, int second, int end, IList repl) - throws FactTypeUseException, IndexOutOfBoundsException { - ArrayList newChildren = new ArrayList<>(); - int rlen = repl.length(); - int increment = Math.abs(second - first); - if (first < end) { - int childIndex = 0; - // Before begin - while (childIndex < first) { - newChildren.add(node1.get(childIndex++)); - } - int replIndex = 0; - boolean wrapped = false; - // Between begin and end - while (childIndex < end) { - newChildren.add(repl.get(replIndex++)); - if (replIndex == rlen) { - replIndex = 0; - wrapped = true; - } - childIndex++; //skip the replaced element - for (int j = 1; j < increment && childIndex < end; j++) { - newChildren.add(node1.get(childIndex++)); - } - } - if (!wrapped) { - while (replIndex < rlen) { - newChildren.add(repl.get(replIndex++)); - } - } - // After end - int dlen = node1.arity(); - while (childIndex < dlen) { - newChildren.add(node1.get(childIndex++)); - } - } else { - // Before begin (from right to left) - int childIndex = node1.arity() - 1; - while (childIndex > first) { - newChildren.add(0, node1.get(childIndex--)); - } - // Between begin (right) and end (left) - int replIndex = 0; - boolean wrapped = false; - while (childIndex > end) { - newChildren.add(0, repl.get(replIndex++)); - if (replIndex == repl.length()) { - replIndex = 0; - wrapped = true; - } - childIndex--; //skip the replaced element - for (int j = 1; j < increment && childIndex > end; j++) { - newChildren.add(0, node1.get(childIndex--)); - } - } - if (!wrapped) { - while (replIndex < rlen) { - newChildren.add(0, repl.get(replIndex++)); - } - } - // Left of end - while (childIndex >= 0) { - newChildren.add(0, node1.get(childIndex--)); - } - } - - IValue[] childArray = new IValue[newChildren.size()]; - newChildren.toArray(childArray); - return vf.node(node1.getName(), childArray); - } - - public static boolean isEqual(IValueFactory vf, INode node1, IValue value) { - if(value == node1) return true; - if(value == null) return false; - - if (node1.getType() != value.getType()) { - return false; - } - - if (value instanceof INode) { - INode node2 = (INode) value; - - // Object equality ('==') is not applicable here - // because value is cast to {@link INode}. - if (!node1.getName().equals(node2.getName())) { - return false; - } - - if (node1.arity() != node2.arity()) { - return false; - } - - Iterator it1 = node1.iterator(); - Iterator it2 = node2.iterator(); - - while (it1.hasNext()) { - if (!it1.next().isEqual(it2.next())) { - return false; - } - } - - if (node1.mayHaveKeywordParameters() && node2.mayHaveKeywordParameters()) { - return node1.asWithKeywordParameters().equalParameters(node2.asWithKeywordParameters()); - } - - if (node1.mayHaveKeywordParameters() && node1.asWithKeywordParameters().hasParameters()) { - return false; - } - - if (node2.mayHaveKeywordParameters() && node2.asWithKeywordParameters().hasParameters()) { - return false; - } - - return true; - } - - return false; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/func/SetFunctions.java b/value-core/src/main/java/org/rascalmpl/value/impl/func/SetFunctions.java deleted file mode 100644 index 647b114d1..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/func/SetFunctions.java +++ /dev/null @@ -1,523 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse public static License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI - * * Paul Klint - Paul.Klint@cwi.nl - CWI - * - * Based on code by: - * - * * Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.impl.func; - -import java.util.Iterator; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.IllegalOperationException; -import org.rascalmpl.value.impl.util.collections.ShareableValuesHashSet; -import org.rascalmpl.value.impl.util.collections.ShareableValuesList; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.util.RotatingQueue; -import org.rascalmpl.value.util.ShareableHashMap; -import org.rascalmpl.value.util.ValueIndexedHashMap; - -public final class SetFunctions { - - private final static TypeFactory TF = TypeFactory.getInstance(); - - public static boolean contains(IValueFactory vf, ISet set1, IValue e) { - for (IValue v : set1) { - if (v.isEqual(e)) { - return true; - } - } - return false; - } - - public static ISet insert(IValueFactory vf, ISet set1, IValue e) { - ISetWriter sw = vf.setWriter(); - sw.insertAll(set1); - sw.insert(e); - return sw.done(); - } - - public static ISet intersect(IValueFactory vf, ISet set1, ISet set2) { - if (set1 == set2) - return set1; - - ISetWriter w = vf.setWriter(); - - for (IValue v : set1) { - if (set2.contains(v)) { - w.insert(v); - } - } - - return w.done(); - } - - public static ISet union(IValueFactory vf, ISet set1, ISet set2) { - if (set1 == set2) - return set1; - - ISetWriter w = vf.setWriter(); - w.insertAll(set1); - w.insertAll(set2); - return w.done(); - } - - public static ISet subtract(IValueFactory vf, ISet set1, ISet set2) { - if (set1 == set2) - return vf.set(); - - ISetWriter sw = vf.setWriter(); - for (IValue a : set1) { - if (!set2.contains(a)) { - sw.insert(a); - } - } - return sw.done(); - } - - public static ISet delete(IValueFactory vf, ISet set1, IValue v) { - ISetWriter w = vf.setWriter(); - - boolean deleted = false; - for (Iterator iterator = set1.iterator(); iterator.hasNext();) { - IValue e = iterator.next(); - - if (!deleted && e.isEqual(v)) { - deleted = true; // skip first occurrence - } else { - w.insert(e); - } - } - return w.done(); - } - - public static boolean isSubsetOf(IValueFactory vf, ISet set1, ISet set2) { - for (IValue elem : set1) { - if (!set2.contains(elem)) { - return false; - } - } - return true; - } - - public static int hashCode(IValueFactory vf, ISet set1) { - int hash = 0; - - Iterator iterator = set1.iterator(); - while (iterator.hasNext()) { - IValue element = iterator.next(); - hash ^= element.hashCode(); - } - - return hash; - } - - public static boolean equals(IValueFactory vf, ISet set1, Object other) { - if (other == set1) - return true; - if (other == null) - return false; - - if (other instanceof ISet) { - ISet set2 = (ISet) other; - - if (set1.getType() != set2.getType()) - return false; - - if (hashCode(vf, set1) != hashCode(vf, set2)) - return false; - - if (set1.size() == set2.size()) { - - for (IValue v1 : set1) { - if (set2.contains(v1) == false) - return false; - } - - return true; - } - } - - return false; - } - - /* - * NOTE: it's actually difficult to support isEqual semantics for sets if - * it is not supported by the underlying container. - */ - public static boolean isEqual(IValueFactory vf, ISet set1, IValue other) { -// return equals(vf, set1, other); - if (other == set1) - return true; - if (other == null) - return false; - - if (other instanceof ISet) { - ISet set2 = (ISet) other; - - if (set1.size() == set2.size()) { - - for (IValue v1 : set1) { - // function contains() calls isEqual() but used O(n) time - if (contains(vf, set2, v1) == false) - return false; - } - - return true; - } - } - - return false; - } - - public static ISet product(IValueFactory vf, ISet set1, ISet set2) { - ISetWriter w = vf.setWriter(); - - for (IValue t1 : set1) { - for (IValue t2 : set2) { - ITuple t3 = vf.tuple(t1, t2); - w.insert(t3); - } - } - - return w.done(); - } - -// public static ISet compose(IValueFactory vf, ISet set1, ISet set2) -// throws FactTypeUseException { -// if (set1.getElementType() == TF.voidType()) -// return set1; -// if (set2.getElementType() == TF.voidType()) -// return set2; -// -// if (set1.getElementType().getArity() != 2 -// || set2.getElementType().getArity() != 2) { -// throw new IllegalOperationException( -// "Incompatible types for composition.", -// set1.getElementType(), set2.getElementType()); -// } -// -// if (!set1.getElementType().getFieldType(1) -// .comparable(set2.getElementType().getFieldType(0))) -// return vf.set(); -// -// ISetWriter w = vf.setWriter(); -// -// if (set1.getElementType().getFieldType(1) -// .comparable(set2.getElementType().getFieldType(0))) { -// for (IValue v1 : set1) { -// ITuple tuple1 = (ITuple) v1; -// for (IValue t2 : set2) { -// ITuple tuple2 = (ITuple) t2; -// -// if (tuple1.get(1).isEqual(tuple2.get(0))) { -// w.insert(vf.tuple(tuple1.get(0), tuple2.get(1))); -// } -// } -// } -// } -// return w.done(); -// } - - public static ISet compose(IValueFactory vf, ISet set1, ISet set2) throws FactTypeUseException { - if (set1.getElementType() == TF.voidType()) - return set1; - if (set2.getElementType() == TF.voidType()) - return set2; - - if (set1.getElementType().getArity() != 2 - || set2.getElementType().getArity() != 2) { - throw new IllegalOperationException( - "Incompatible types for composition.", - set1.getElementType(), set2.getElementType()); - } - - if (!set1.getElementType().getFieldType(1) - .comparable(set2.getElementType().getFieldType(0))) - return vf.set(); - - // Index - ShareableHashMap rightSides = new ShareableHashMap<>(); - - Iterator otherRelationIterator = set2.iterator(); - while(otherRelationIterator.hasNext()){ - ITuple tuple = (ITuple) otherRelationIterator.next(); - - IValue key = tuple.get(0); - ShareableValuesList values = rightSides.get(key); - if(values == null){ - values = new ShareableValuesList(); - rightSides.put(key, values); - } - - values.append(tuple.get(1)); - } - - // Compute - Type[] newTupleFieldTypes = new Type[]{set1.getElementType().getFieldType(0), set2.getElementType().getFieldType(1)}; - Type tupleType = TF.tupleType(newTupleFieldTypes); - - ISetWriter resultWriter = vf.setWriter(tupleType); - - Iterator relationIterator = set1.iterator(); - while(relationIterator.hasNext()){ - ITuple thisTuple = (ITuple) relationIterator.next(); - - IValue key = thisTuple.get(1); - ShareableValuesList values = rightSides.get(key); - if(values != null){ - Iterator valuesIterator = values.iterator(); - do{ - IValue value = valuesIterator.next(); - IValue[] newTupleData = new IValue[]{thisTuple.get(0), value}; - resultWriter.insert(vf.tuple(tupleType, newTupleData)); - }while(valuesIterator.hasNext()); - } - } - - return resultWriter.done(); - } - - public static ISet carrier(IValueFactory vf, ISet set1) { - ISetWriter w = vf.setWriter(); - - for (IValue t : set1) { - w.insertAll((ITuple) t); - } - - return w.done(); - } - - private static ShareableValuesHashSet computeClosureDelta(IValueFactory vf, ISet rel1, Type tupleType) { - RotatingQueue iLeftKeys = new RotatingQueue<>(); - RotatingQueue> iLefts = new RotatingQueue<>(); - - ValueIndexedHashMap> interestingLeftSides = new ValueIndexedHashMap<>(); - ValueIndexedHashMap potentialRightSides = new ValueIndexedHashMap<>(); - - // Index - Iterator allDataIterator = rel1.iterator(); - while(allDataIterator.hasNext()){ - ITuple tuple = (ITuple) allDataIterator.next(); - - IValue key = tuple.get(0); - IValue value = tuple.get(1); - RotatingQueue leftValues = interestingLeftSides.get(key); - ShareableValuesHashSet rightValues; - if(leftValues != null){ - rightValues = potentialRightSides.get(key); - }else{ - leftValues = new RotatingQueue<>(); - iLeftKeys.put(key); - iLefts.put(leftValues); - interestingLeftSides.put(key, leftValues); - - rightValues = new ShareableValuesHashSet(); - potentialRightSides.put(key, rightValues); - } - leftValues.put(value); - rightValues.add(value); - } - - int size = potentialRightSides.size(); - int nextSize = 0; - - // Compute - final ShareableValuesHashSet newTuples = new ShareableValuesHashSet(); - do{ - ValueIndexedHashMap rightSides = potentialRightSides; - potentialRightSides = new ValueIndexedHashMap<>(); - - for(; size > 0; size--){ - IValue leftKey = iLeftKeys.get(); - RotatingQueue leftValues = iLefts.get(); - - RotatingQueue interestingLeftValues = null; - - IValue rightKey; - while((rightKey = leftValues.get()) != null){ - ShareableValuesHashSet rightValues = rightSides.get(rightKey); - if(rightValues != null){ - Iterator rightValuesIterator = rightValues.iterator(); - while(rightValuesIterator.hasNext()){ - IValue rightValue = rightValuesIterator.next(); - if(newTuples.add(vf.tuple(tupleType, leftKey, rightValue))){ - if(interestingLeftValues == null){ - nextSize++; - - iLeftKeys.put(leftKey); - interestingLeftValues = new RotatingQueue<>(); - iLefts.put(interestingLeftValues); - } - interestingLeftValues.put(rightValue); - - ShareableValuesHashSet potentialRightValues = potentialRightSides.get(rightKey); - if(potentialRightValues == null){ - potentialRightValues = new ShareableValuesHashSet(); - potentialRightSides.put(rightKey, potentialRightValues); - } - potentialRightValues.add(rightValue); - } - } - } - } - } - size = nextSize; - nextSize = 0; - }while(size > 0); - - return newTuples; - } - -// public static ISet closure(IValueFactory vf, ISet set1) -// throws FactTypeUseException { -// // will throw exception if not binary and reflexive -// set1.getType().closure(); -// -// ISet tmp = set1; -// -// int prevCount = 0; -// -// while (prevCount != tmp.size()) { -// prevCount = tmp.size(); -// tmp = tmp.union(compose(vf, tmp, tmp)); -// } -// -// return tmp; -// } - - public static ISet closure(IValueFactory vf, ISet rel1) { - if (rel1.getElementType() == TF.voidType()) - return rel1; - if (!isBinary(rel1)) - throw new IllegalOperationException("closure", rel1.getType()); - - Type tupleElementType = rel1.getElementType().getFieldType(0).lub(rel1.getElementType().getFieldType(1)); - Type tupleType = TF.tupleType(tupleElementType, tupleElementType); - - java.util.Set closureDelta = computeClosureDelta(vf, rel1, tupleType); - - // NOTE: type is already known, thus, using a SetWriter degrades performance - ISetWriter resultWriter = vf.setWriter(tupleType); - resultWriter.insertAll(rel1); - resultWriter.insertAll(closureDelta); - - return resultWriter.done(); - } - -// public static ISet closureStar(IValueFactory vf, ISet set1) -// throws FactTypeUseException { -// set1.getType().closure(); -// // an exception will have been thrown if the type is not acceptable -// -// ISetWriter reflex = vf.setWriter(); -// -// for (IValue e : carrier(vf, set1)) { -// reflex.insert(vf.tuple(new IValue[] { e, e })); -// } -// -// return closure(vf, set1).union(reflex.done()); -// } - - // TODO: Currently untested in PDB. - public static ISet closureStar(IValueFactory vf, ISet rel1) { - if (rel1.getElementType() == TF.voidType()) - return rel1; - if (!isBinary(rel1)) - throw new IllegalOperationException("closureStar", rel1.getType()); - - Type tupleElementType = rel1.getElementType().getFieldType(0).lub(rel1.getElementType().getFieldType(1)); - Type tupleType = TF.tupleType(tupleElementType, tupleElementType); - - // calculate - ShareableValuesHashSet closureDelta = computeClosureDelta(vf, rel1, tupleType); - ISet carrier = carrier(vf, rel1); - - // aggregate result - // NOTE: type is already known, thus, using a SetWriter degrades performance - ISetWriter resultWriter = vf.setWriter(rel1.getElementType()); - resultWriter.insertAll(rel1); - resultWriter.insertAll(closureDelta); - - Iterator carrierIterator = carrier.iterator(); - while (carrierIterator.hasNext()) { - IValue element = carrierIterator.next(); - resultWriter.insert(vf.tuple(tupleType, element, element)); - } - - return resultWriter.done(); - } - - private static boolean isBinary(ISet rel1){ - return rel1.getElementType().getArity() == 2; - } - - public static ISet domain(IValueFactory vf, ISet set1) { - int columnIndex = 0; - ISetWriter w = vf.setWriter(); - - for (IValue elem : set1) { - ITuple tuple = (ITuple) elem; - w.insert(tuple.get(columnIndex)); - } - return w.done(); - } - - public static ISet range(IValueFactory vf, ISet set1) { - int columnIndex = set1.getType().getArity() - 1; - ISetWriter w = vf.setWriter(); - - for (IValue elem : set1) { - ITuple tuple = (ITuple) elem; - w.insert(tuple.get(columnIndex)); - } - - return w.done(); - } - - public static ISet project(IValueFactory vf, ISet set1, int... fields) { - ISetWriter w = vf.setWriter(); - - for (IValue v : set1) { - w.insert(((ITuple) v).select(fields)); - } - - return w.done(); - } - - public static ISet projectByFieldNames(IValueFactory vf, ISet set1, - String... fields) { - int[] indexes = new int[fields.length]; - int i = 0; - - if (set1.getType().getFieldTypes().hasFieldNames()) { - for (String field : fields) { - indexes[i++] = set1.getType().getFieldTypes() - .getFieldIndex(field); - } - - return project(vf, set1, indexes); - } - - throw new IllegalOperationException("select with field names", - set1.getType()); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/persistent/MapWriter.java b/value-core/src/main/java/org/rascalmpl/value/impl/persistent/MapWriter.java deleted file mode 100644 index e77c9a22f..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/persistent/MapWriter.java +++ /dev/null @@ -1,169 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.persistent; - -import java.util.Arrays; -import java.util.Comparator; -import java.util.Iterator; -import java.util.Map.Entry; - -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.UnexpectedElementTypeException; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.util.AbstractTypeBag; -import org.rascalmpl.value.util.EqualityUtils; - -import io.usethesource.capsule.DefaultTrieMap; -import io.usethesource.capsule.TransientMap; - -final class MapWriter implements IMapWriter { - - @SuppressWarnings("unchecked") - private static final Comparator equivalenceComparator = EqualityUtils - .getEquivalenceComparator(); - - protected AbstractTypeBag keyTypeBag; - protected AbstractTypeBag valTypeBag; - protected final TransientMap mapContent; - - protected final boolean checkUpperBound; - protected final Type upperBoundKeyType; - protected final Type upperBoundValType; - protected IMap constructedMap; - - MapWriter() { - super(); - - this.checkUpperBound = false; - this.upperBoundKeyType = null; - this.upperBoundValType = null; - - keyTypeBag = AbstractTypeBag.of(); - valTypeBag = AbstractTypeBag.of(); - mapContent = DefaultTrieMap.transientOf(); - constructedMap = null; - } - - MapWriter(Type prototypeType) { - super(); - - this.checkUpperBound = false; - this.upperBoundKeyType = prototypeType.getKeyType(); - this.upperBoundValType = prototypeType.getValueType(); - - if (prototypeType.hasFieldNames()) { - keyTypeBag = AbstractTypeBag.of(prototypeType.getKeyLabel()); - valTypeBag = AbstractTypeBag.of(prototypeType.getValueLabel()); - } else { - keyTypeBag = AbstractTypeBag.of(); - valTypeBag = AbstractTypeBag.of(); - } - - mapContent = DefaultTrieMap.transientOf(); - constructedMap = null; - } - - @Override - public void put(IValue key, IValue value) { - checkMutation(); - - final Type keyType = key.getType(); - final Type valType = value.getType(); - - if (checkUpperBound) { - if (!keyType.isSubtypeOf(upperBoundKeyType)) { - throw new UnexpectedElementTypeException(upperBoundKeyType, keyType); - } - - if (!valType.isSubtypeOf(upperBoundValType)) { - throw new UnexpectedElementTypeException(upperBoundValType, valType); - } - } - - final IValue replaced = mapContent.__putEquivalent(key, value, equivalenceComparator); - - keyTypeBag = keyTypeBag.increase(keyType); - valTypeBag = valTypeBag.increase(valType); - - if (replaced != null) { - final Type replacedType = replaced.getType(); - valTypeBag = valTypeBag.decrease(replacedType); - } - } - - @Override - public void putAll(IMap map) { - putAll(map.entryIterator()); - } - - @Override - public void putAll(java.util.Map map) { - putAll(map.entrySet().iterator()); - } - - private void putAll(Iterator> entryIterator) { - checkMutation(); - - while (entryIterator.hasNext()) { - Entry entry = entryIterator.next(); - IValue key = entry.getKey(); - IValue value = entry.getValue(); - - this.put(key, value); - } - } - - @Override - public void insert(IValue... values) { - insertAll(Arrays.asList(values)); - } - - @Override - public void insertAll(Iterable collection) { - checkMutation(); - - Iterator collectionIterator = collection.iterator(); - while (collectionIterator.hasNext()) { - final Object item = collectionIterator.next(); - - if (!(item instanceof ITuple)) { - throw new IllegalArgumentException("Argument must be of ITuple type."); - } - - final ITuple tuple = (ITuple) item; - - if (tuple.arity() != 2) { - throw new IllegalArgumentException("Tuple must have an arity of 2."); - } - - put(tuple.get(0), tuple.get(1)); - } - } - - protected void checkMutation() { - if (constructedMap != null) { - throw new UnsupportedOperationException("Mutation of a finalized map is not supported."); - } - } - - @Override - public IMap done() { - if (constructedMap == null) { - constructedMap = new PDBPersistentHashMap(keyTypeBag, valTypeBag, mapContent.freeze()); - } - - return constructedMap; - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/persistent/PDBPersistentHashMap.java b/value-core/src/main/java/org/rascalmpl/value/impl/persistent/PDBPersistentHashMap.java deleted file mode 100644 index 243a88db3..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/persistent/PDBPersistentHashMap.java +++ /dev/null @@ -1,310 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.persistent; - -import java.util.Comparator; -import java.util.Iterator; -import java.util.Map.Entry; - -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.AbstractMap; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.util.AbstractTypeBag; -import org.rascalmpl.value.util.EqualityUtils; - -import java.util.Objects; - -import io.usethesource.capsule.ImmutableMap; -import io.usethesource.capsule.TransientMap; - -public final class PDBPersistentHashMap extends AbstractMap { - - @SuppressWarnings("unchecked") - private static final Comparator equivalenceComparator = EqualityUtils.getEquivalenceComparator(); - - private Type cachedMapType; - private final AbstractTypeBag keyTypeBag; - private final AbstractTypeBag valTypeBag; - private final ImmutableMap content; - - /* - * Passing an pre-calulated map type is only allowed from inside this class. - */ - protected PDBPersistentHashMap(AbstractTypeBag keyTypeBag, - AbstractTypeBag valTypeBag, ImmutableMap content) { - Objects.requireNonNull(content); - this.cachedMapType = null; - this.keyTypeBag = keyTypeBag; - this.valTypeBag = valTypeBag; - this.content = content; - } - - @Override - protected IValueFactory getValueFactory() { - return ValueFactory.getInstance(); - } - - @Override - public Type getType() { - if (cachedMapType == null) { - final Type keyType = keyTypeBag.lub(); - final Type valType = valTypeBag.lub(); - - final String keyLabel = keyTypeBag.getLabel(); - final String valLabel = valTypeBag.getLabel(); - - if (keyLabel != null && valLabel != null) { - cachedMapType = getTypeFactory().mapType(keyType, keyLabel, valType, valLabel); - } else { - cachedMapType = getTypeFactory().mapType(keyType, valType); - } - } - return cachedMapType; - } - - @Override - public boolean isEmpty() { - return content.isEmpty(); - } - - @Override - public IMap put(IValue key, IValue value) { - final ImmutableMap contentNew = - content.__putEquivalent(key, value, equivalenceComparator); - - if (content == contentNew) - return this; - - final AbstractTypeBag keyBagNew; - final AbstractTypeBag valBagNew; - - if (content.size() == contentNew.size()) { - // value replaced - final IValue replaced = content.getEquivalent(key, equivalenceComparator); - keyBagNew = keyTypeBag; - valBagNew = valTypeBag.decrease(replaced.getType()).increase(value.getType()); - } else { - // pair added - keyBagNew = keyTypeBag.increase(key.getType()); - valBagNew = valTypeBag.increase(value.getType()); - } - - return new PDBPersistentHashMap(keyBagNew, valBagNew, contentNew); - } - - @Override - public int size() { - return content.size(); - } - - @Override - public boolean containsKey(IValue key) { - return content.containsKeyEquivalent(key, equivalenceComparator); - } - - @Override - public boolean containsValue(IValue value) { - return content.containsValueEquivalent(value, equivalenceComparator); - } - - @Override - public IValue get(IValue key) { - return content.getEquivalent(key, equivalenceComparator); - } - - @Override - public int hashCode() { - return content.hashCode(); - } - - @Override - public boolean equals(Object other) { - if (other == this) - return true; - if (other == null) - return false; - - if (other instanceof PDBPersistentHashMap) { - PDBPersistentHashMap that = (PDBPersistentHashMap) other; - - if (this.size() != that.size()) - return false; - - return content.equals(that.content); - } - - if (other instanceof IMap) { - IMap that = (IMap) other; - - if (this.getType() != that.getType()) - return false; - - if (this.size() != that.size()) - return false; - - for (IValue e : that) { - if (!content.containsKey(e)) { - return false; - } else if (!content.get(e).equals(that.get(e))) { - return false; - } - } - - return true; - } - - return false; - } - - @Override - public boolean isEqual(IValue other) { - if (other == this) - return true; - if (other == null) - return false; - - if (other instanceof IMap) { - IMap that = (IMap) other; - - if (this.size() != that.size()) - return false; - - for (IValue e : that) { - if (!containsKey(e)) { - return false; - } else if (!get(e).isEqual(that.get(e))) { - return false; - } - } - - return true; - } - - return false; - } - - @Override - public Iterator iterator() { - return content.keyIterator(); - } - - @Override - public Iterator valueIterator() { - return content.valueIterator(); - } - - @Override - public Iterator> entryIterator() { - return content.entryIterator(); - } - - @Deprecated - private static String mergeLabels(String one, String two) { - if (one != null && two != null && one.equals(two)) { - // both are the same - return one; - } else { - // only one is not null - return one != null ? one : two; - } - } - - @Override - public IMap join(IMap other) { - if (other instanceof PDBPersistentHashMap) { - PDBPersistentHashMap that = (PDBPersistentHashMap) other; - - final TransientMap transientContent = content.asTransient(); - - boolean isModified = false; - int previousSize = size(); - - AbstractTypeBag keyBagNew = null; - if (that.keyTypeBag.getLabel() != null) { - keyBagNew = keyTypeBag.setLabel(mergeLabels(keyTypeBag.getLabel(), - that.keyTypeBag.getLabel())); - - isModified |= (keyBagNew.getLabel() != keyTypeBag.getLabel()); - } else { - keyBagNew = keyTypeBag; - } - - AbstractTypeBag valBagNew = null; - if (that.valTypeBag.getLabel() != null) { - valBagNew = valTypeBag.setLabel(mergeLabels(valTypeBag.getLabel(), - that.valTypeBag.getLabel())); - - isModified |= (valBagNew.getLabel() != valTypeBag.getLabel()); - } else { - valBagNew = valTypeBag; - } - - for (Iterator> it = that.entryIterator(); it.hasNext();) { - Entry tuple = it.next(); - IValue key = tuple.getKey(); - IValue value = tuple.getValue(); - - final IValue replaced = transientContent.__putEquivalent(key, value, - equivalenceComparator); - - if (replaced != null) { - // value replaced - valBagNew = valBagNew.decrease(replaced.getType()).increase(value.getType()); - - isModified = true; - } else if (previousSize != transientContent.size()) { - // pair added - keyBagNew = keyBagNew.increase(key.getType()); - valBagNew = valBagNew.increase(value.getType()); - - isModified = true; - previousSize++; - } - } - - if (isModified) { - return new PDBPersistentHashMap(keyBagNew, valBagNew, transientContent.freeze()); - } else { - return this; - } - } else { - return super.join(other); - } - } - - @Override - public IMap remove(IMap that) { - // TODO Auto-generated method stub - return super.remove(that); - } - - @Override - public IMap compose(IMap that) { - // TODO Auto-generated method stub - return super.compose(that); - } - - @Override - public IMap common(IMap that) { - // TODO Auto-generated method stub - return super.common(that); - } - - @Override - public boolean isSubMap(IMap that) { - // TODO Auto-generated method stub - return super.isSubMap(that); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/persistent/PDBPersistentHashSet.java b/value-core/src/main/java/org/rascalmpl/value/impl/persistent/PDBPersistentHashSet.java deleted file mode 100644 index ed60a9d94..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/persistent/PDBPersistentHashSet.java +++ /dev/null @@ -1,328 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.persistent; - -import java.util.Comparator; -import java.util.Iterator; -import java.util.Objects; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.AbstractSet; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.util.AbstractTypeBag; -import org.rascalmpl.value.util.EqualityUtils; - -import io.usethesource.capsule.DefaultTrieSet; -import io.usethesource.capsule.ImmutableSet; -import io.usethesource.capsule.TransientSet; - -public final class PDBPersistentHashSet extends AbstractSet { - - private static final PDBPersistentHashSet EMPTY = new PDBPersistentHashSet(); - - @SuppressWarnings("unchecked") - private static final Comparator equivalenceComparator = EqualityUtils.getEquivalenceComparator(); - - private Type cachedSetType; - private final AbstractTypeBag elementTypeBag; - private final ImmutableSet content; - - private PDBPersistentHashSet() { - this.elementTypeBag = AbstractTypeBag.of(); - this.content = DefaultTrieSet.of(); - } - - public PDBPersistentHashSet(AbstractTypeBag elementTypeBag, ImmutableSet content) { - Objects.requireNonNull(elementTypeBag); - Objects.requireNonNull(content); - this.elementTypeBag = elementTypeBag; - this.content = content; - } - - @Override - protected IValueFactory getValueFactory() { - return ValueFactory.getInstance(); - } - - @Override - public Type getType() { - if (cachedSetType == null) { - final Type elementType = elementTypeBag.lub(); - - // consists collection out of tuples? - if (elementType.isFixedWidth()) { - cachedSetType = getTypeFactory().relTypeFromTuple(elementType); - } else { - cachedSetType = getTypeFactory().setType(elementType); - } - } - return cachedSetType; - } - - @Override - public boolean isEmpty() { - return content.isEmpty(); - } - - @Override - public ISet insert(IValue value) { - final ImmutableSet contentNew = content.__insertEquivalent(value, equivalenceComparator); - - if (content == contentNew) - return this; - - final AbstractTypeBag bagNew = elementTypeBag.increase(value.getType()); - - return new PDBPersistentHashSet(bagNew, contentNew); - } - - @Override - public ISet delete(IValue value) { - final ImmutableSet contentNew = content.__removeEquivalent(value, equivalenceComparator); - - if (content == contentNew) - return this; - - final AbstractTypeBag bagNew = elementTypeBag.decrease(value.getType()); - - return new PDBPersistentHashSet(bagNew, contentNew); - } - - @Override - public int size() { - return content.size(); - } - - @Override - public boolean contains(IValue value) { - return content.containsEquivalent(value, equivalenceComparator); - } - - @Override - public Iterator iterator() { - return content.iterator(); - } - - @Override - public int hashCode() { - return content.hashCode(); - } - - @Override - public boolean equals(Object other) { - if (other == this) - return true; - if (other == null) - return false; - - if (other instanceof PDBPersistentHashSet) { - PDBPersistentHashSet that = (PDBPersistentHashSet) other; - - if (this.getType() != that.getType()) - return false; - - if (this.size() != that.size()) - return false; - - return content.equals(that.content); - } - - if (other instanceof ISet) { - ISet that = (ISet) other; - - if (this.getType() != that.getType()) - return false; - - if (this.size() != that.size()) - return false; - - for (IValue e : that) - if (!content.contains(e)) - return false; - - return true; - } - - return false; - } - - @Override - public boolean isEqual(IValue other) { - if (other == this) - return true; - if (other == null) - return false; - - if (other instanceof ISet) { - ISet that = (ISet) other; - - if (this.size() != that.size()) - return false; - - for (IValue e : that) - if (!content.containsEquivalent(e, equivalenceComparator)) - return false; - - return true; - } - - return false; - } - - @Override - public ISet union(ISet other) { - if (other == this) - return this; - if (other == null) - return this; - - if (other instanceof PDBPersistentHashSet) { - PDBPersistentHashSet that = (PDBPersistentHashSet) other; - - final ImmutableSet one; - final ImmutableSet two; - AbstractTypeBag bag; - final ISet def; - - if (that.size() >= this.size()) { - def = that; - one = that.content; - bag = that.elementTypeBag; - two = this.content; - } else { - def = this; - one = this.content; - bag = this.elementTypeBag; - two = that.content; - } - - final TransientSet tmp = one.asTransient(); - boolean modified = false; - - for (IValue key : two) { - if (tmp.__insertEquivalent(key, equivalenceComparator)) { - modified = true; - bag = bag.increase(key.getType()); - } - } - - if (modified) { - return new PDBPersistentHashSet(bag, tmp.freeze()); - } - return def; - } else { - return super.union(other); - } - } - - @Override - public ISet intersect(ISet other) { - if (other == this) - return this; - if (other == null) - return EMPTY; - - if (other instanceof PDBPersistentHashSet) { - PDBPersistentHashSet that = (PDBPersistentHashSet) other; - - final ImmutableSet one; - final ImmutableSet two; - AbstractTypeBag bag; - final ISet def; - - if (that.size() >= this.size()) { - def = this; - one = this.content; - bag = this.elementTypeBag; - two = that.content; - } else { - def = that; - one = that.content; - bag = that.elementTypeBag; - two = this.content; - } - - final TransientSet tmp = one.asTransient(); - boolean modified = false; - - for (Iterator it = tmp.iterator(); it.hasNext();) { - final IValue key = it.next(); - if (!two.containsEquivalent(key, equivalenceComparator)) { - it.remove(); - modified = true; - bag = bag.decrease(key.getType()); - } - } - - if (modified) { - return new PDBPersistentHashSet(bag, tmp.freeze()); - } - return def; - } else { - return super.intersect(other); - } - } - - @Override - public ISet subtract(ISet other) { - if (other == this) - return EMPTY; - if (other == null) - return this; - - if (other instanceof PDBPersistentHashSet) { - PDBPersistentHashSet that = (PDBPersistentHashSet) other; - - final ImmutableSet one; - final ImmutableSet two; - AbstractTypeBag bag; - final ISet def; - - def = this; - one = this.content; - bag = this.elementTypeBag; - two = that.content; - - final TransientSet tmp = one.asTransient(); - boolean modified = false; - - for (IValue key : two) { - if (tmp.__removeEquivalent(key, equivalenceComparator)) { - modified = true; - bag = bag.decrease(key.getType()); - } - } - - if (modified) { - return new PDBPersistentHashSet(bag, tmp.freeze()); - } - return def; - } else { - return super.subtract(other); - } - } - - @Override - public ISet product(ISet that) { - // TODO Auto-generated method stub - return super.product(that); - } - - @Override - public boolean isSubsetOf(ISet that) { - // TODO Auto-generated method stub - return super.isSubsetOf(that); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/persistent/SetWriter.java b/value-core/src/main/java/org/rascalmpl/value/impl/persistent/SetWriter.java deleted file mode 100644 index efae0dbb9..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/persistent/SetWriter.java +++ /dev/null @@ -1,114 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.persistent; - -import java.util.Comparator; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.UnexpectedElementTypeException; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.util.AbstractTypeBag; -import org.rascalmpl.value.util.EqualityUtils; - -import io.usethesource.capsule.DefaultTrieSet; -import io.usethesource.capsule.TransientSet; - -class SetWriter implements ISetWriter { - - @SuppressWarnings("unchecked") - private static final Comparator equivalenceComparator = EqualityUtils - .getEquivalenceComparator(); - - protected AbstractTypeBag elementTypeBag; - protected final TransientSet setContent; - - protected final boolean checkUpperBound; - protected final Type upperBoundType; - protected ISet constructedSet; - - SetWriter(Type upperBoundType) { - super(); - - this.checkUpperBound = true; - this.upperBoundType = upperBoundType; - - elementTypeBag = AbstractTypeBag.of(); - setContent = DefaultTrieSet.transientOf(); - constructedSet = null; - } - - SetWriter() { - super(); - - this.checkUpperBound = false; - this.upperBoundType = null; - - elementTypeBag = AbstractTypeBag.of(); - setContent = DefaultTrieSet.transientOf(); - constructedSet = null; - } - - private void put(IValue element) { - final Type elementType = element.getType(); - - if (checkUpperBound && !elementType.isSubtypeOf(upperBoundType)) { - throw new UnexpectedElementTypeException(upperBoundType, elementType); - } - - boolean result = setContent.__insertEquivalent(element, equivalenceComparator); - if (result) { - elementTypeBag = elementTypeBag.increase(elementType); - } - } - - @Override - public void insert(IValue... values) throws FactTypeUseException { - checkMutation(); - - for (IValue item : values) { - put(item); - } - } - - @Override - public void insertAll(Iterable collection) throws FactTypeUseException { - checkMutation(); - - for (IValue item : collection) { - put(item); - } - } - - @Override - public ISet done() { - if (constructedSet == null) { - constructedSet = new PDBPersistentHashSet(elementTypeBag, setContent.freeze()); - } - - return constructedSet; - } - - private void checkMutation() { - if (constructedSet != null) { - throw new UnsupportedOperationException("Mutation of a finalized set is not supported."); - } - } - - @Override - public String toString() { - return setContent.toString(); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/persistent/ValueFactory.java b/value-core/src/main/java/org/rascalmpl/value/impl/persistent/ValueFactory.java deleted file mode 100644 index 0ade87ed4..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/persistent/ValueFactory.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.persistent; - -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -public class ValueFactory extends org.rascalmpl.value.impl.fast.ValueFactory { - - protected ValueFactory() { - super(); - } - - private static class InstanceKeeper { - public final static ValueFactory instance = new ValueFactory(); - } - - public static ValueFactory getInstance() { - return InstanceKeeper.instance; - } - - public ISetWriter setWriter(Type upperBoundType) { - return new SetWriter(upperBoundType); - } - - public ISetWriter setWriter() { - return new SetWriter(); - } - - public ISetWriter relationWriter(Type upperBoundType) { - return setWriter(upperBoundType); - } - - public ISetWriter relationWriter() { - return new SetWriter(); - } - - public ISet set(Type elementType) { - return setWriter().done(); - } - - public ISet set(IValue... elements) { - ISetWriter setWriter = setWriter(); - setWriter.insert(elements); - return setWriter.done(); - } - - public ISet relation(Type tupleType) { - return relationWriter(tupleType).done(); - } - - public ISet relation(IValue... elements) { - return set(elements); - } - - @Override - public IMapWriter mapWriter(Type keyType, Type valueType) { - return mapWriter(TypeFactory.getInstance().mapType(keyType, valueType)); - } - - @Override - public IMapWriter mapWriter(Type mapType) { - return new MapWriter(mapType); - } - - @Override - public IMapWriter mapWriter() { - return new MapWriter(); - } - - @Override - public IMap map(Type mapType) { - return mapWriter(mapType).done(); - } - - @Override - public IMap map(Type keyType, Type valueType) { - return mapWriter(keyType, valueType).done(); - } - - @Override - public String toString() { - return "VF_PDB_PERSISTENT"; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/AbstractNumberValue.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/AbstractNumberValue.java deleted file mode 100644 index 239daccbc..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/AbstractNumberValue.java +++ /dev/null @@ -1,167 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.INumber; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.exceptions.UnexpectedTypeException; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.type.TypeFactory; - -/*package*/ abstract class AbstractNumberValue extends AbstractValue implements INumber{ - private final static TypeFactory typeFactory = TypeFactory.getInstance(); - - /*package*/ AbstractNumberValue(){ - super(); - } - - @Override - public INumber add(INumber other){ - if(isIntegerType(other)){ - return add(other.toInteger()); - } - if(isRealType(other)){ - return add(other.toReal(((IReal) other).precision())); - } - if(isRationalType(other)){ - return add(other.toRational()); - } - - throw new UnexpectedTypeException(typeFactory.numberType(), other.getType()); - } - - @Override - public INumber divide(INumber other, int precision){ - if(isIntegerType(other)){ - return divide(other.toInteger(), precision); - } - if(isRealType(other)){ - return divide(other.toReal(precision), precision); - } - if(isRationalType(other)){ - return divide(other.toRational(), precision); - } - throw new UnexpectedTypeException(typeFactory.numberType(), other.getType()); - } - - @Override - public IBool greater(INumber other){ - if(isIntegerType(other)){ - return greater(other.toInteger()); - } - if(isRealType(other)){ - return greater(other.toReal(((IReal) other).precision())); - } - if(isRationalType(other)){ - return greater(other.toRational()); - } - throw new UnexpectedTypeException(typeFactory.numberType(), other.getType()); - } - - - @Override - public IBool equal(INumber other){ - if(isIntegerType(other)){ - return equal(other.toInteger()); - } - if(isRealType(other)){ - return equal(other.toReal(((IReal) other).precision())); - } - if(isRationalType(other)){ - return equal(other.toRational()); - } - throw new UnexpectedTypeException(typeFactory.numberType(), other.getType()); - } - - @Override - public IBool greaterEqual(INumber other){ - if(isIntegerType(other)){ - return greaterEqual(other.toInteger()); - } - if(isRealType(other)){ - return greaterEqual(other.toReal(((IReal) other).precision())); - } - if(isRationalType(other)){ - return greaterEqual(other.toRational()); - } - throw new UnexpectedTypeException(typeFactory.numberType(), other.getType()); - } - - @Override - public IBool less(INumber other){ - if(isIntegerType(other)){ - return less(other.toInteger()); - } - if(isRealType(other)){ - return less(other.toReal(((IReal) other).precision())); - } - if(isRationalType(other)){ - return less(other.toRational()); - } - throw new UnexpectedTypeException(typeFactory.numberType(), other.getType()); - } - - @Override - public IBool lessEqual(INumber other){ - if(isIntegerType(other)){ - return lessEqual(other.toInteger()); - } - if(isRealType(other)){ - return lessEqual(other.toReal(((IReal) other).precision())); - } - if(isRationalType(other)){ - return lessEqual(other.toRational()); - } - throw new UnexpectedTypeException(typeFactory.numberType(), other.getType()); - } - - @Override - public INumber multiply(INumber other){ - if(isIntegerType(other)){ - return multiply(other.toInteger()); - } - if(isRealType(other)){ - return multiply(other.toReal(((IReal) other).precision())); - } - if(isRationalType(other)){ - return multiply(other.toRational()); - } - throw new UnexpectedTypeException(typeFactory.numberType(), other.getType()); - } - - @Override - public INumber subtract(INumber other){ - if(isIntegerType(other)){ - return subtract(other.toInteger()); - } - if(isRealType(other)){ - return subtract(other.toReal(((IReal) other).precision())); - } - if(isRationalType(other)){ - return subtract(other.toRational()); - } - throw new UnexpectedTypeException(typeFactory.numberType(), other.getType()); - } - - protected boolean isRationalType(INumber other) { - return other.getType().equivalent(TypeFactory.getInstance().rationalType()); - } - - protected boolean isRealType(INumber other) { - return other.getType().equivalent(TypeFactory.getInstance().realType()); - } - - protected boolean isIntegerType(INumber other) { - return other.getType().equivalent(TypeFactory.getInstance().integerType()); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/AbstractPrimitiveValueFactory.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/AbstractPrimitiveValueFactory.java deleted file mode 100644 index 3eef0b76d..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/AbstractPrimitiveValueFactory.java +++ /dev/null @@ -1,273 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009, 2012-2013 Centrum Wiskunde en Informatica (CWI) - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Jurgen Vinju - interface and implementation - * Arnold Lankamp - implementation - * Anya Helene Bagge - rational support, labeled maps and tuples - * Davy Landman - added PI & E constants - * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.concurrent.atomic.AtomicInteger; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.util.ShareableHashMap; - -/** - * Base value factory with optimized representations of primitive values. - */ -public abstract class AbstractPrimitiveValueFactory implements IValueFactory { - - private final static int DEFAULT_PRECISION = 10; - private final AtomicInteger currentPrecision = new AtomicInteger(DEFAULT_PRECISION); - - protected Type inferInstantiatedTypeOfConstructor(final Type constructorType, final IValue... children) { - Type instantiatedType; - if (!constructorType.getAbstractDataType().isParameterized()) { - instantiatedType = constructorType; - } else { - ShareableHashMap bindings = new ShareableHashMap<>(); - TypeFactory tf = TypeFactory.getInstance(); - Type params = constructorType.getAbstractDataType().getTypeParameters(); - for (Type p : params) { - if (p.isOpen()) { - bindings.put(p, tf.voidType()); - } - } - constructorType.getFieldTypes().match(tf.tupleType(children), bindings); - instantiatedType = constructorType.instantiate(bindings); - } - - return instantiatedType; - } - - @Override - public IInteger integer(String integerValue) { - return IntegerValue.newInteger(integerValue); - } - - @Override - public IInteger integer(int value) { - return IntegerValue.newInteger(value); - } - - @Override - public IInteger integer(long value) { - return IntegerValue.newInteger(value); - } - - @Override - public IInteger integer(byte[] integerData) { - return IntegerValue.newInteger(integerData); - } - - @Override - public IRational rational(int a, int b) { - return rational(integer(a), integer(b)); - } - - @Override - public IRational rational(long a, long b) { - return rational(integer(a), integer(b)); - } - - @Override - public IRational rational(IInteger a, IInteger b) { - return RationalValue.newRational(a, b); - } - - @Override - public IRational rational(String rat) throws NumberFormatException { - if (rat.contains("r")) { - String[] parts = rat.split("r"); - if (parts.length == 2) { - return rational(integer(parts[0]), integer(parts[1])); - } - if (parts.length == 1) { - return rational(integer(parts[0]), integer(1)); - } - throw new NumberFormatException(rat); - } else { - return rational(integer(rat), integer(1)); - } - } - - @Override - public IReal real(String value) { - return BigDecimalValue.newReal(value); - } - - @Override - public IReal real(String value, int precision) throws NumberFormatException { - return BigDecimalValue.newReal(value, precision); - } - - @Override - public IReal real(double value) { - return BigDecimalValue.newReal(value); - } - - @Override - public IReal real(double value, int precision) { - return BigDecimalValue.newReal(value, precision); - } - - @Override - public int getPrecision() { - return currentPrecision.get(); - } - - @Override - public int setPrecision(int p) { - return currentPrecision.getAndSet(p); - } - - @Override - public IReal pi(int precision) { - return BigDecimalValue.pi(precision); - } - - @Override - public IReal e(int precision) { - return BigDecimalValue.e(precision); - } - - @Override - public IString string(String value) { - return StringValue.newString(value); - } - - @Override - public IString string(int[] chars) { - StringBuilder b = new StringBuilder(chars.length); - for (int ch : chars) { - b.appendCodePoint(ch); - } - return string(b.toString()); - } - - @Override - public IString string(int ch) { - StringBuilder b = new StringBuilder(1); - b.appendCodePoint(ch); - return string(b.toString()); - } - - @Override - public IBool bool(boolean value) { - return BoolValue.getBoolValue(value); - } - - @Override - public IDateTime date(int year, int month, int day) { - return DateTimeValues.newDate(year, month, day); - } - - @Override - public IDateTime time(int hour, int minute, int second, int millisecond) { - return DateTimeValues.newTime(hour, minute, second, millisecond); - } - - @Override - public IDateTime time(int hour, int minute, int second, int millisecond, - int hourOffset, int minuteOffset) { - return DateTimeValues.newTime(hour, minute, second, millisecond, hourOffset, minuteOffset); - } - - @Override - public IDateTime datetime(int year, int month, int day, int hour, - int minute, int second, int millisecond) { - return DateTimeValues.newDateTime(year, month, day, hour, minute, second, millisecond); - } - - @Override - public IDateTime datetime(int year, int month, int day, int hour, - int minute, int second, int millisecond, int hourOffset, - int minuteOffset) { - return DateTimeValues.newDateTime(year, month, day, hour, minute, second, millisecond, hourOffset, minuteOffset); - } - - @Override - public IDateTime datetime(long instant) { - return DateTimeValues.newDateTime(instant); - } - - @Override - public IDateTime datetime(long instant, int timezoneHours, int timezoneMinutes) { - return DateTimeValues.newDateTime(instant, timezoneHours, timezoneMinutes); - } - - @Override - public ISourceLocation sourceLocation(URI uri, int offset, int length) { - return sourceLocation(sourceLocation(uri), offset, length); - } - - @Override - public ISourceLocation sourceLocation(ISourceLocation loc, int offset, int length) { - return SourceLocationValues.newSourceLocation(loc, offset, length); - } - - @Override - public ISourceLocation sourceLocation(URI uri, int offset, int length, int beginLine, int endLine, int beginCol, int endCol) { - return sourceLocation(sourceLocation(uri), offset, length, beginLine, endLine, beginCol, endCol); - } - @Override - public ISourceLocation sourceLocation(ISourceLocation loc, int offset, int length, int beginLine, int endLine, int beginCol, int endCol) { - return SourceLocationValues.newSourceLocation(loc, offset, length, beginLine, endLine, beginCol, endCol); - } - - @Override - public ISourceLocation sourceLocation(String path, int offset, int length, int beginLine, int endLine, int beginCol, int endCol) { - return sourceLocation(sourceLocation(path), offset, length, beginLine, endLine, beginCol, endCol); - } - - @Override - public ISourceLocation sourceLocation(URI uri) { - try { - return SourceLocationValues.newSourceLocation(uri); - } catch (URISyntaxException e) { - throw new RuntimeException("An URI should always be a correct URI", e); - } - } - - @Override - public ISourceLocation sourceLocation(String path) { - if (!path.startsWith("/")) - path = "/" + path; - try { - return sourceLocation("file", "", path); - } catch (URISyntaxException e) { - throw new RuntimeException("Paths should not cause a incorrect syntax exception", e); - } - } - - @Override - public ISourceLocation sourceLocation(String scheme, String authority, String path) throws URISyntaxException { - return sourceLocation(scheme, authority, path, null, null); - } - - @Override - public ISourceLocation sourceLocation(String scheme, String authority, - String path, String query, String fragment) throws URISyntaxException { - return SourceLocationValues.newSourceLocation(scheme, authority, path, query, fragment); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/BigDecimalValue.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/BigDecimalValue.java deleted file mode 100644 index 5118fce6f..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/BigDecimalValue.java +++ /dev/null @@ -1,434 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Arnold Lankamp - interfaces and implementation - * * Jurgen Vinju - extensions and fixes - * * Davy Landman - added mathematical functions - * * Paul Klint - Precision handling - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.math.MathContext; -import java.math.RoundingMode; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.INumber; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.impl.util.BigDecimalCalculations; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/* - * TODO: provide specializations for smaller values, similar to IntegerValue / BigIntegerValue. - */ -/*package*/ class BigDecimalValue extends AbstractNumberValue implements IReal { - private final static Type DOUBLE_TYPE = TypeFactory.getInstance().realType(); - - protected final BigDecimal value; - - /*package*/ static IReal newReal(BigDecimal value) { - return new BigDecimalValue(value); - } - - /*package*/ static IReal newReal(String value) { - return new BigDecimalValue(new BigDecimal(value)); - } - - /*package*/ static IReal newReal(String value, int precision) throws NumberFormatException { - return new BigDecimalValue(new BigDecimal(value, new MathContext(precision))); - } - - /*package*/ static IReal newReal(double value) { - checkNanAndInfinity(value); - return new BigDecimalValue(BigDecimal.valueOf(value)); - } - - public static void checkNanAndInfinity(double value) { - if (Double.isNaN(value)) { - throw new NumberFormatException("no support for NaN"); - } - if (Double.isInfinite(value)) { - throw new NumberFormatException("no support for infinity"); - } - } - - /*package*/ static IReal newReal(double value, int precision) { - checkNanAndInfinity(value); - return new BigDecimalValue(new BigDecimal(value, new MathContext(precision))); - } - - private BigDecimalValue(BigDecimal value){ - super(); - - this.value = value; - } - - private BigDecimalValue(BigDecimal value, int precision){ - super(); - - this.value = new BigDecimal(value.toEngineeringString(), new MathContext(precision)); - } - - @Override - public IReal abs() { - return newReal(value.abs()); - } - - @Override - public IReal toReal(int precision) { - return this; - } - - @Override - public Type getType(){ - return DOUBLE_TYPE; - } - - @Override - public float floatValue(){ - return value.floatValue(); - } - - @Override - public double doubleValue(){ - return value.doubleValue(); - } - - @Override - public IInteger toInteger(){ - return IntegerValue.newInteger(value.toBigInteger()); - } - - @Override - public IRational toRational(){ - throw new UnsupportedOperationException(); - } - - @Override - public IReal floor(){ - return BigDecimalValue.newReal(value.setScale(0, RoundingMode.FLOOR)); - } - - @Override - public IReal round(){ - return BigDecimalValue.newReal(value.setScale(0, RoundingMode.HALF_UP)); - } - - @Override - public IReal add(IReal other){ - return BigDecimalValue.newReal(value.add(((BigDecimalValue) other).value)); - } - - @Override - public INumber add(IInteger other) { - return add(other.toReal(value.precision())); - } - - @Override - public INumber add(IRational other) { - return add(other.toReal(value.precision())); - } - - @Override - public IReal subtract(IReal other){ - return BigDecimalValue.newReal(value.subtract(((BigDecimalValue) other).value)); - } - - @Override - public INumber subtract(IInteger other) { - return subtract(other.toReal(value.precision())); - } - - @Override - public INumber subtract(IRational other) { - return subtract(other.toReal(value.precision())); - } - - @Override - public IReal multiply(IReal other){ - //int precision = Math.min(Math.max(value.precision(), other.precision()), BaseValueFactory.PRECISION); - //MathContext mc = new MathContext(precision, RoundingMode.HALF_UP); - return BigDecimalValue.newReal(value.multiply(((BigDecimalValue) other).value)); - } - - @Override - public INumber multiply(IInteger other) { - return multiply(other.toReal(value.precision())); - } - - @Override - public INumber multiply(IRational other) { - return multiply(other.toReal(value.precision())); - } - - @Override - public IReal divide(IReal other, int precision){ - // make sure the precision is *at least* the same as that of the arguments - precision = Math.max(Math.max(value.precision(), other.precision()), precision); - MathContext mc = new MathContext(precision, RoundingMode.HALF_UP); - return BigDecimalValue.newReal(value.divide(((BigDecimalValue) other).value, mc)); - } - - @Override - public IReal divide(IInteger other, int precision) { - return divide(other.toReal(precision), precision); - } - - @Override - public IReal divide(IRational other, int precision) { - return divide(other.toReal(precision), precision); - } - - @Override - public IReal negate(){ - return BigDecimalValue.newReal(value.negate()); - } - - @Override - public int precision(){ - return value.precision(); - } - - @Override - public int scale(){ - return value.scale(); - } - - @Override - public IInteger unscaled(){ - return IntegerValue.newInteger(value.unscaledValue()); - } - - @Override - public IBool equal(IReal other){ - return BoolValue.getBoolValue(compare(other) == 0); - } - - @Override - public IBool equal(IInteger other) { - return equal(other.toReal(value.precision())); - } - - @Override - public IBool equal(IRational other) { - return equal(other.toReal(value.precision())); - } - - @Override - public IBool greater(IReal other){ - return BoolValue.getBoolValue(compare(other) > 0); - } - - @Override - public IBool greater(IInteger other) { - return greater(other.toReal(value.precision())); - } - - @Override - public IBool greater(IRational other) { - return greater(other.toReal(value.precision())); - } - - @Override - public IBool greaterEqual(IReal other){ - return BoolValue.getBoolValue(compare(other) >= 0); - } - - @Override - public IBool greaterEqual(IInteger other) { - return greaterEqual(other.toReal(value.precision())); - } - - @Override - public IBool greaterEqual(IRational other) { - return greaterEqual(other.toReal(value.precision())); - } - - - @Override - public IBool less(IReal other){ - return BoolValue.getBoolValue(compare(other) < 0); - } - - @Override - public IBool less(IInteger other) { - return less(other.toReal(value.precision())); - } - - @Override - public IBool less(IRational other) { - return less(other.toReal(value.precision())); - } - - @Override - public IBool lessEqual(IReal other){ - return BoolValue.getBoolValue(compare(other) <= 0); - } - - @Override - public IBool lessEqual(IInteger other) { - return lessEqual(other.toReal(value.precision())); - } - - @Override - public IBool lessEqual(IRational other) { - return lessEqual(other.toReal(value.precision())); - } - - @Override - public int compare(IReal other){ - return value.compareTo(((BigDecimalValue) other).value); - } - - @Override - public int compare(INumber other) { - return compare(other.toReal(value.precision())); - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitReal(this); - } - - /* - * Description and implementation from the (now removed) reference implementation: - * - * // Java BigDecimals have a bug, their even though 3.0 and 3.00 are equal, - * // their hashCode() is not, which is against the equals/hashCode() contract. - * // To work around this, we use this simple trick here which is correct but - * // might lead to many collisions. - * // return Double.valueOf(value.doubleValue()).hashCode(); - */ - public int hashCode(){ - // BigDecimals don't generate consistent hashcodes for things that are actually 'equal'. - // This code rectifies this problem. - long bits = Double.doubleToLongBits(value.doubleValue()); - return (int) (bits ^ (bits >>> 32)); - } - - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - BigDecimalValue otherDouble = (BigDecimalValue) o; - return (value.equals(otherDouble.value)); - } - - return false; - } - - @Override - public boolean isEqual(IValue o){ - return equals(o); - } - - @Override - public String getStringRepresentation(){ - StringBuilder sb = new StringBuilder(); - String decimalString = value.toString(); - sb.append(decimalString); - if (!decimalString.matches(".*[\\.Ee].*")) { - sb.append("."); - } - return sb.toString(); - } - - @Override - public int signum() { - return value.signum(); - } - - @Override - public IReal log(IInteger base, int precision) { - return log(base.toReal(precision), precision); - } - - @Override - public IReal log(IReal base, int precision) { - IReal lnBase = base.ln(precision + 1); - IReal lnThis = this.ln(precision + 1); - return lnThis.divide(lnBase, precision); - } - - @Override - public IReal ln(int precision) { - return newReal(BigDecimalCalculations.ln(value, precision)); - } - - @Override - public IReal sqrt(int precision) { - return newReal(BigDecimalCalculations.sqrt(value, precision)); - } - - @Override - public IReal nroot(IInteger n, int precision) { - return newReal(BigDecimalCalculations.intRoot(value, new BigInteger(n.getTwosComplementRepresentation()), precision)); - } - - @Override - public IReal exp(int precision) { - return newReal(BigDecimalCalculations.exp(value, precision)); - } - - @Override - public IReal pow(IInteger power) { - if (power.signum() < 0) { - // negative power is 1/(this^-power) - return newReal( - BigDecimal.ONE.divide(value.pow(power.negate().intValue()), value.precision(), RoundingMode.HALF_EVEN) - ); - } - return newReal(value.pow(power.intValue())); - } - @Override - public IReal pow(IReal power, int precision) { - BigDecimal actualPower = null; - if (power instanceof BigDecimalValue) { - actualPower = ((BigDecimalValue)power).value; - } - else { - actualPower = new BigDecimal(power.getStringRepresentation()); - } - return newReal(BigDecimalCalculations.pow(value, actualPower, precision)); - } - - @Override - public IReal tan(int precision) { - return newReal(BigDecimalCalculations.tan(value, precision)); - } - - @Override - public IReal sin(int precision) { - return newReal(BigDecimalCalculations.sin(value, precision)); - } - - @Override - public IReal cos(int precision) { - return newReal(BigDecimalCalculations.cos(value, precision)); - } - - public static IReal pi(int precision) { - if (precision < 0 || precision > 1000) - throw new IllegalArgumentException("PI max precision is 1000"); - return newReal(BigDecimalCalculations.PI.setScale(precision, BigDecimal.ROUND_HALF_EVEN)); - } - - public static IReal e(int precision) { - if (precision < 0 || precision > 1000) - throw new IllegalArgumentException("E max precision is 1000"); - return newReal(BigDecimalCalculations.E.setScale(precision, BigDecimal.ROUND_HALF_EVEN)); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/BigIntegerValue.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/BigIntegerValue.java deleted file mode 100644 index cd4e08f0e..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/BigIntegerValue.java +++ /dev/null @@ -1,362 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Arnold Lankamp - interfaces and implementation - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.INumber; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * Specialized implementation for integer values that fall outside the 32-bit range. - * - * @author Arnold Lankamp - */ -/*package*/ class BigIntegerValue extends AbstractNumberValue implements IInteger, ICanBecomeABigInteger{ - private final static Type INTEGER_TYPE = TypeFactory.getInstance().integerType(); - - protected final BigInteger value; - - /*package*/ BigIntegerValue(BigInteger value){ - super(); - if(value.equals(BigInteger.ZERO)) - value = BigInteger.ZERO; - if(value.equals(BigInteger.ONE)) - value = BigInteger.ONE; - - this.value = value; - } - - @Override - public IInteger toInteger() { - return this; - } - - @Override - public Type getType(){ - return INTEGER_TYPE; - } - - @Override - public int intValue(){ - return value.intValue(); - } - - @Override - public long longValue(){ - return value.longValue(); - } - - @Override - public double doubleValue(){ - return value.doubleValue(); - } - - @Override - public IReal toReal(int precision){ - // precision is ignored intentionally - return BigDecimalValue.newReal(new BigDecimal(value)); - } - - @Override - public IRational toRational(){ - return RationalValue.newRational(this, IntegerValue.INTEGER_ONE); - } - @Override - public byte[] getTwosComplementRepresentation(){ - return value.toByteArray(); - } - - @Override - public BigInteger toBigInteger(){ - return value; - } - - @Override - public IInteger add(IInteger other){ - BigInteger o = ((ICanBecomeABigInteger) other).toBigInteger(); - BigInteger result = value.add(o); - if(result == value) - return this; - else if(result == o) - return other; - int length = result.bitLength(); - if(length <= 31){ - return IntegerValue.newInteger(result.intValue()); - } - - return IntegerValue.newInteger(result); - } - - @Override - public IReal add(IReal other) { - return (IReal) other.add(this); - } - - @Override - public IRational add(IRational other) { - return (IRational) other.add(this); - } - - @Override - public IInteger subtract(IInteger other){ - BigInteger result = value.subtract(((ICanBecomeABigInteger) other).toBigInteger()); - if(result == value) - return this; - - int length = result.bitLength(); - if(length <= 31){ - return IntegerValue.newInteger(result.intValue()); - } - - return IntegerValue.newInteger(result); - } - - @Override - public INumber subtract(IReal other) { - return toReal(other.precision()).subtract(other); - } - - @Override - public INumber subtract(IRational other) { - return toRational().subtract(other); - } - - @Override - public IInteger multiply(IInteger other){ - BigInteger o = ((ICanBecomeABigInteger) other).toBigInteger(); - BigInteger result = value.multiply(o); - if(result == value) - return this; - else if(result == o) - return other; - // The result of this operation can never fit in a 32-bit integer, so no need to check. - return IntegerValue.newInteger(result); - } - - @Override - public IReal multiply(IReal other) { - return (IReal) other.multiply(this); - } - - @Override - public IRational multiply(IRational other) { - return (IRational) other.multiply(this); - } - @Override - public IInteger divide(IInteger other){ - BigInteger result = value.divide(((ICanBecomeABigInteger) other).toBigInteger()); - if(result == value) - return this; - - int length = result.bitLength(); - if(length <= 31){ - return IntegerValue.newInteger(result.intValue()); - } - - return IntegerValue.newInteger(result); - } - - @Override - public IRational divide(IRational other) { - return toRational().divide(other); - } - - @Override - public INumber divide(IInteger other, int precision) { - return toReal(precision).divide(other, precision); - } - - @Override - public INumber divide(IRational other, int precision) { - return toReal(precision).divide(other, precision); - } - - @Override - public IReal divide(IReal other, int precision) { - return toReal(precision).divide(other, precision); - } - - @Override - public IInteger mod(IInteger other){ - BigInteger result = value.mod(((ICanBecomeABigInteger) other).toBigInteger()); - - if(other instanceof IntegerValue){ - int integerResult = result.intValue(); - return IntegerValue.newInteger(integerResult); - } - - return IntegerValue.newInteger(result); - } - - @Override - public IInteger remainder(IInteger other){ - BigInteger result = value.remainder(((ICanBecomeABigInteger) other).toBigInteger()); - - if(other instanceof IntegerValue){ - int integerResult = result.intValue(); - return IntegerValue.newInteger(integerResult); - } - - return IntegerValue.newInteger(result); - } - - @Override - public IInteger negate(){ - return IntegerValue.newInteger(value.negate()); - } - - @Override - public IBool equal(IInteger other){ - return BoolValue.getBoolValue(compare(other) == 0); - } - - @Override - public IBool equal(IReal other) { - return other.equal(this); - } - - @Override - public IBool equal(IRational other) { - return other.equal(this); - } - - @Override - public IBool greater(IInteger other){ - return BoolValue.getBoolValue(compare(other) > 0); - } - - @Override - public IBool greater(IReal other) { - return other.less(this); - } - - @Override - public IBool greater(IRational other) { - return other.less(this); - } - - @Override - public IBool greaterEqual(IInteger other){ - return BoolValue.getBoolValue(compare(other) >= 0); - } - - @Override - public IBool greaterEqual(IReal other) { - return other.lessEqual(this); - } - - @Override - public IBool greaterEqual(IRational other) { - return other.lessEqual(this); - } - - @Override - public IBool less(IInteger other){ - return BoolValue.getBoolValue(compare(other) < 0); - } - - @Override - public IBool less(IReal other) { - return other.greater(this); - } - - @Override - public IBool less(IRational other) { - return other.greater(this); - } - - @Override - public IBool lessEqual(IInteger other){ - return BoolValue.getBoolValue(compare(other) <= 0); - } - - @Override - public IBool lessEqual(IReal other) { - return other.greaterEqual(this); - } - - @Override - public IBool lessEqual(IRational other) { - return other.greaterEqual(this); - } - - @Override - public int compare(IInteger other){ - return value.compareTo(((ICanBecomeABigInteger) other).toBigInteger()); - } - - @Override - public int compare(INumber other) { - if (isIntegerType(other)) { - return compare(other.toInteger()); - } - else if (isRationalType(other)) { - return toRational().compare(other); - } - else { - assert other instanceof IReal; - return toReal(((IReal) other).precision()).compare(other); - } - } - - @Override - public T accept(IValueVisitor v) throws E{ - return v.visitInteger(this); - } - - public int hashCode(){ - return value.hashCode(); - } - - public boolean equals(Object o){ - if(o == null) return false; - else if(o == this) return true; - - if(o.getClass() == getClass()){ - BigIntegerValue otherInteger = (BigIntegerValue) o; - return value.equals(otherInteger.value); - } - - return false; - } - - @Override - public boolean isEqual(IValue other){ - return equals(other); - } - - @Override - public String getStringRepresentation(){ - return value.toString(); - } - - @Override - public int signum() { - return value.signum(); - } - - @Override - public IInteger abs() { - return IntegerValue.newInteger(value.abs()); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/BoolValue.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/BoolValue.java deleted file mode 100644 index 9c914f308..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/BoolValue.java +++ /dev/null @@ -1,134 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012-2013 Centrum Wiskunde en Informatica (CWI) - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * * Arnold Lankamp - interfaces and implementation - * * Jurgen Vinju - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/*package*/ abstract class BoolValue extends AbstractValue implements IBool { - /*package*/ final static BoolValue TRUE = new BoolValue() { - @Override - public boolean getValue() { - return true; - } - - public int hashCode() { - return 1; - } - - @Override - public IBool not() { - return FALSE; - } - - @Override - public IBool and(IBool other) { - return other; - } - - @Override - public IBool or(IBool other) { - return this; - } - - @Override - public IBool xor(IBool other) { - return other == this ? FALSE : TRUE; - } - - @Override - public IBool implies(IBool other) { - return other; - } - }; - /*package*/ final static BoolValue FALSE = new BoolValue() { - @Override - public boolean getValue() { - return false; - } - - @Override - public IBool not() { - return TRUE; - } - - @Override - public IBool and(IBool other) { - return this; - } - - @Override - public IBool or(IBool other) { - return other; - } - - @Override - public IBool xor(IBool other) { - return other; - } - - @Override - public IBool implies(IBool other) { - return TRUE; - } - - public int hashCode() { - return 2; - } - }; - private final static Type BOOL_TYPE = TypeFactory.getInstance().boolType(); - - private BoolValue() { - super(); - } - - /*package*/ static BoolValue getBoolValue(boolean bool) { - return bool ? TRUE : FALSE; - } - - public abstract int hashCode(); - - public boolean equals(Object o) { - return this == o; - } - - @Override - public Type getType() { - return BOOL_TYPE; - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitBoolean(this); - } - - @Override - public boolean isEqual(IValue value) { - return this == value; - } - - @Override - public IBool equivalent(IBool other) { - return other == this ? TRUE : this; - } - - @Override - public String getStringRepresentation() { - return toString(); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/DateTimeValues.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/DateTimeValues.java deleted file mode 100644 index 135a78425..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/DateTimeValues.java +++ /dev/null @@ -1,877 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Mark Hills (Mark.Hills@cwi.nl) - initial API and implementation - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; -import java.util.TimeZone; - -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.InvalidDateTimeException; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - - -/** A concrete instance of IDateTime, representing either a date, - * a time, or a date with time. - * - * NOTE: We currently do not support partial dates and times; i.e., - * it is not possible to represent "July 2009" or "15" (hours). - * - */ -/*package*/ class DateTimeValues { - - private final static Type DATE_TIME_TYPE = TypeFactory.getInstance().dateTimeType(); - - /*package*/ static IDateTime newDate(int year, int month, int day) { - return new DateTimeValues.DateValue(year, month, day); - } - - private static class DateValue extends AbstractValue implements IDateTime { - - private int year; - private int month; - private int day; - - /** - * Construct a DateTime object representing a date. - * - * @param year The year of the date - * @param month The month of the date - * @param day The day of the date - */ - private DateValue(int year, int month, int day) { - super(); - - this.year = year; - this.month = month; - this.day = day; - - // Check to make sure the provided value are valid. - // TODO: Failure here should throw a PDB exception. - Calendar cal = Calendar.getInstance(TimeZone.getDefault(),Locale.getDefault()); - cal.setLenient(false); - cal.set(year, month-1, day); - try { - cal.get(Calendar.YEAR); - } catch (IllegalArgumentException iae) { - throw new InvalidDateTimeException("Cannot create date with provided values."); - } - } - - @Override - public Type getType() { - return DATE_TIME_TYPE; - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitDateTime(this); - } - - @Override - public int compareTo(IDateTime arg0) { - if (arg0.isDate()) { - long m1 = this.getInstant(); - long m2 = arg0.getInstant(); - if (m1 == m2) - return 0; - else if (m1 < m2) - return -1; - else - return 1; - } else { - throw new UnsupportedOperationException("Date and non-Date values are not comparable"); - } - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getInstant() - */ - @Override - public long getInstant() { - Calendar cal = Calendar.getInstance(TimeZone.getDefault(),Locale.getDefault()); - cal.setTime(new Date(0)); - cal.set(this.year, this.month-1, this.day); - return cal.getTimeInMillis(); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getCentury() - */ - @Override - public int getCentury() { - return (year - (year % 100)) / 100; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getYear() - */ - @Override - public int getYear() { - return this.year; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getMonthOfYear() - */ - @Override - public int getMonthOfYear() { - return this.month; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getDayOfMonth() - */ - @Override - public int getDayOfMonth() { - return this.day; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getHourOfDay() - */ - @Override - public int getHourOfDay() { - throw new UnsupportedOperationException("Cannot get hours on a date value"); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getMinuteOfHour() - */ - @Override - public int getMinuteOfHour() { - throw new UnsupportedOperationException("Cannot get minutes on a date value"); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getSecondOfMinute() - */ - @Override - public int getSecondOfMinute() { - throw new UnsupportedOperationException("Cannot get seconds on a date value"); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getMillisecondsOfSecond() - */ - @Override - public int getMillisecondsOfSecond() { - throw new UnsupportedOperationException("Cannot get milliseconds on a date value"); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getTimezoneOffsetHours() - */ - @Override - public int getTimezoneOffsetHours() { - throw new UnsupportedOperationException("Cannot get timezone offset hours on a date value"); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getTimezoneOffsetMinutes() - */ - @Override - public int getTimezoneOffsetMinutes() { - throw new UnsupportedOperationException("Cannot get timezone offset minutes on a date value"); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#isDate() - */ - @Override - public boolean isDate() { - return true; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#isTime() - */ - @Override - public boolean isTime() { - return false; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#isDateTime() - */ - @Override - public boolean isDateTime() { - return false; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + day; - result = prime * result + month; - result = prime * result + year; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - DateValue other = (DateValue) obj; - if (day != other.day) - return false; - if (month != other.month) - return false; - if (year != other.year) - return false; - return true; - } - - @Override - public boolean isEqual(IValue other) { - return equals(other); - } - } - - /*package*/ static IDateTime newTime(int hour, int minute, int second, int millisecond) { - return new DateTimeValues.TimeValue(hour, minute, second, millisecond); - } - - /*package*/ static IDateTime newTime(int hour, int minute, int second, int millisecond, - int hourOffset, int minuteOffset) { - return new DateTimeValues.TimeValue(hour, minute, second, millisecond, hourOffset, minuteOffset); - } - - private static class TimeValue extends AbstractValue implements IDateTime { - - private int hour; - private int minute; - private int second; - private int millisecond; - private int timezoneHours; - private int timezoneMinutes; - - private final static int millisInAMinute = 1000 * 60; - private final static int millisInAnHour = TimeValue.millisInAMinute * 60; - - /** - * Given the hour and minute offset, generate the appropriate Java - * timezone string - * - * @param hourOffset The hour offset for the timezone. - * @param minuteOffset The minute offset for the timezone. - * - * @return A string with the proper timezone. - */ - private static String getTZString(int hourOffset, int minuteOffset) { - String tzString = "GMT" + - ((hourOffset < 0 || (0 == hourOffset && minuteOffset < 0)) ? "-" : "+") + - String.format("%02d",hourOffset >= 0 ? hourOffset : hourOffset * -1) + - String.format("%02d",minuteOffset >= 0 ? minuteOffset : minuteOffset * -1); - return tzString; - } - - /** - * Construct a DateTime object representing a time. - * - * @param hour The hour of the time - * @param minute The minute of the time - * @param second The second of the time - * @param millisecond The millisecond of the time - */ - private TimeValue(int hour, int minute, int second, int millisecond) { - super(); - - this.hour = hour; - this.minute = minute; - this.second = second; - this.millisecond = millisecond; - - // Check to make sure the provided values are valid. - // TODO: Failure here should throw a PDB exception. - Calendar cal = Calendar.getInstance(TimeZone.getDefault(),Locale.getDefault()); - cal.setLenient(false); - cal.set(Calendar.HOUR_OF_DAY, hour); - cal.set(Calendar.MINUTE, minute); - cal.set(Calendar.SECOND, second); - cal.set(Calendar.MILLISECOND, millisecond); - - try { - cal.get(Calendar.HOUR_OF_DAY); - } catch (IllegalArgumentException iae) { - throw new InvalidDateTimeException("Cannot create time with provided values."); - } - - // Get back the time zone information so we can store it with - // the rest of the date information. This is based on the - // current default time zone, since none was provided. - this.timezoneHours = cal.get(Calendar.ZONE_OFFSET) / TimeValue.millisInAnHour; - this.timezoneMinutes = cal.get(Calendar.ZONE_OFFSET) % TimeValue.millisInAnHour / TimeValue.millisInAMinute; - } - - /** - * Construct a DateTime object representing a time with an explicit timezone offset. - * - * @param hour The hour of the time - * @param minute The minute of the time - * @param second The second of the time - * @param millisecond The millisecond of the time - * @param hourOffset The timezone offset of the time, in hours - * @param minuteOffset The timezone offset of the time, in minutes - */ - private TimeValue(int hour, int minute, int second, int millisecond, int hourOffset, int minuteOffset) { - super(); - - this.hour = hour; - this.minute = minute; - this.second = second; - this.millisecond = millisecond; - this.timezoneHours = hourOffset; - this.timezoneMinutes = minuteOffset; - - // Check to make sure the provided values are valid. - // TODO: Failure here should throw a PDB exception. - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(getTZString(hourOffset,minuteOffset)),Locale.getDefault()); - cal.setLenient(false); - cal.set(Calendar.HOUR_OF_DAY, hour); - cal.set(Calendar.MINUTE, minute); - cal.set(Calendar.SECOND, second); - cal.set(Calendar.MILLISECOND, millisecond); - - try { - cal.get(Calendar.HOUR_OF_DAY); - } catch (IllegalArgumentException iae) { - throw new InvalidDateTimeException("Cannot create time with provided values."); - } - } - - @Override - public Type getType() { - return DATE_TIME_TYPE; - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitDateTime(this); - } - - @Override - public int compareTo(IDateTime arg0) { - if (arg0.isTime()) { - long m1 = this.getInstant(); - long m2 = arg0.getInstant(); - if (m1 == m2) - return 0; - else if (m1 < m2) - return -1; - else - return 1; - } else { - throw new UnsupportedOperationException("Time and non-Time values are not comparable"); - } - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getInstant() - */ - @Override - public long getInstant() { - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(getTZString(this.timezoneHours,this.timezoneMinutes)),Locale.getDefault()); - cal.set(1970, 0, 1, this.hour, this.minute, this.second); - cal.set(Calendar.MILLISECOND, this.millisecond); - return cal.getTimeInMillis(); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getCentury() - */ - @Override - public int getCentury() { - throw new UnsupportedOperationException("Cannot get century on a time value"); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getYear() - */ - @Override - public int getYear() { - throw new UnsupportedOperationException("Cannot get year on a time value"); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getMonthOfYear() - */ - @Override - public int getMonthOfYear() { - throw new UnsupportedOperationException("Cannot get month on a time value"); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getDayOfMonth() - */ - @Override - public int getDayOfMonth() { - throw new UnsupportedOperationException("Cannot get day on a time value"); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getHourOfDay() - */ - @Override - public int getHourOfDay() { - return this.hour; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getMinuteOfHour() - */ - @Override - public int getMinuteOfHour() { - return this.minute; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getSecondOfMinute() - */ - @Override - public int getSecondOfMinute() { - return this.second; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getMillisecondsOfSecond() - */ - @Override - public int getMillisecondsOfSecond() { - return this.millisecond; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getTimezoneOffsetHours() - */ - @Override - public int getTimezoneOffsetHours() { - return this.timezoneHours; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getTimezoneOffsetMinutes() - */ - @Override - public int getTimezoneOffsetMinutes() { - return this.timezoneMinutes; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#isDate() - */ - @Override - public boolean isDate() { - return false; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#isTime() - */ - @Override - public boolean isTime() { - return true; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#isDateTime() - */ - @Override - public boolean isDateTime() { - return false; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + hour; - result = prime * result + millisecond; - result = prime * result + minute; - result = prime * result + second; - result = prime * result + timezoneHours; - result = prime * result + timezoneMinutes; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - TimeValue other = (TimeValue) obj; - if (hour != other.hour) - return false; - if (millisecond != other.millisecond) - return false; - if (minute != other.minute) - return false; - if (second != other.second) - return false; - if (timezoneHours != other.timezoneHours) - return false; - if (timezoneMinutes != other.timezoneMinutes) - return false; - return true; - } - - @Override - public boolean isEqual(IValue other) { - return equals(other); - } - } - - /*package*/ static IDateTime newDateTime(int year, int month, int day, int hour, - int minute, int second, int millisecond) { - return new DateTimeValues.DateTimeValue(year, month, day, hour, minute, second, millisecond); - } - - /*package*/ static IDateTime newDateTime(int year, int month, int day, int hour, - int minute, int second, int millisecond, int hourOffset, - int minuteOffset) { - return new DateTimeValues.DateTimeValue(year, month, day, hour, minute, second, millisecond, hourOffset, minuteOffset); - } - - /*package*/ static IDateTime newDateTime(long instant) { - return new DateTimeValues.DateTimeValue(instant, 0, 0); - } - - /*package*/ static IDateTime newDateTime(long instant, int timezoneHours, int timezoneMinutes) { - return new DateTimeValues.DateTimeValue(instant, timezoneHours, timezoneMinutes); - } - - private static class DateTimeValue extends AbstractValue implements IDateTime { - - private int year; - private int month; - private int day; - private int hour; - private int minute; - private int second; - private int millisecond; - private int timezoneHours; - private int timezoneMinutes; - - /** - * Construct a DateTime object representing a date and time. - * - * @param year The year of the datetime - * @param month The month of the datetime - * @param day The day of the datetime - * @param hour The hour of the datetime - * @param minute The minute of the datetime - * @param second The second of the datetime - * @param millisecond The millisecond of the datetime - */ - private DateTimeValue(int year, int month, int day, int hour, int minute, int second, int millisecond) { - super(); - - this.year = year; - this.month = month; - this.day = day; - this.hour = hour; - this.minute = minute; - this.second = second; - this.millisecond = millisecond; - - // Check to make sure the provided values are valid. - // TODO: Failure here should throw a PDB exception. - Calendar cal = Calendar.getInstance(TimeZone.getDefault(),Locale.getDefault()); - cal.setLenient(false); - cal.set(year, month-1, day, hour, minute, second); - cal.set(Calendar.MILLISECOND, millisecond); - - try { - cal.get(Calendar.HOUR_OF_DAY); - } catch (IllegalArgumentException iae) { - throw new InvalidDateTimeException("Cannot create datetime with provided values."); - } - - // Get back the time zone information so we can store it with - // the rest of the date information. This is based on the - // current default time zone, since none was provided. - this.timezoneHours = cal.get(Calendar.ZONE_OFFSET) / TimeValue.millisInAnHour; - this.timezoneMinutes = cal.get(Calendar.ZONE_OFFSET) % TimeValue.millisInAnHour / TimeValue.millisInAMinute; - } - - /** - * Construct a DateTime object representing a date and time, with an explicit timezone. - * - * @param year The year of the datetime - * @param month The month of the datetime - * @param day The day of the datetime - * @param hour The hour of the datetime - * @param minute The minute of the datetime - * @param second The second of the datetime - * @param millisecond The millisecond of the datetime - * @param hourOffset The timezone offset of the time, in hours - * @param minuteOffset The timezone offset of the time, in minutes - */ - private DateTimeValue(int year, int month, int day, int hour, int minute, int second, int millisecond, int hourOffset, int minuteOffset) { - super(); - this.year = year; - this.month = month; - this.day = day; - this.hour = hour; - this.minute = minute; - this.second = second; - this.millisecond = millisecond; - this.timezoneHours = hourOffset; - this.timezoneMinutes = minuteOffset; - - // Check to make sure the provided values are valid. - // TODO: Failure here should throw a PDB exception. - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TimeValue.getTZString(hourOffset,minuteOffset)),Locale.getDefault()); - cal.setLenient(false); - cal.set(year, month-1, day, hour, minute, second); - cal.set(Calendar.MILLISECOND, millisecond); - - try { - cal.get(Calendar.HOUR_OF_DAY); - } catch (IllegalArgumentException iae) { - throw new InvalidDateTimeException("Cannot create datetime with provided values."); - } - } - - /** - * Construct a DateTime object representing the current instant on the date/time - * scale (in milliseconds, based on the Java epoch). - * - * @param instant The millisecond instant. - * @param timezoneHours The hour offset for the new object's timezone - * @param timezoneMinutes The minute offset for the new object's timezone - */ - private DateTimeValue(long instant, int timezoneHours, int timezoneMinutes) { - super(); - - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TimeValue.getTZString(timezoneHours, timezoneMinutes)),Locale.getDefault()); - cal.setLenient(false); - cal.setTime(new Date(instant)); - - this.year = cal.get(Calendar.YEAR); - this.month = cal.get(Calendar.MONTH) + 1; - this.day = cal.get(Calendar.DAY_OF_MONTH); - this.hour = cal.get(Calendar.HOUR_OF_DAY); - this.minute = cal.get(Calendar.MINUTE); - this.second = cal.get(Calendar.SECOND); - this.millisecond = cal.get(Calendar.MILLISECOND); - this.timezoneHours = timezoneHours; - this.timezoneMinutes = timezoneMinutes; - } - - @Override - public Type getType() { - return DATE_TIME_TYPE; - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitDateTime(this); - } - - @Override - public int compareTo(IDateTime arg0) { - if (arg0.isDateTime()) { - long m1 = this.getInstant(); - long m2 = arg0.getInstant(); - if (m1 == m2) - return 0; - else if (m1 < m2) - return -1; - else - return 1; - } else { - throw new UnsupportedOperationException("DateTime and non-DateTime values are not comparable"); - } - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getInstant() - */ - @Override - public long getInstant() { - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TimeValue.getTZString(this.timezoneHours,this.timezoneMinutes)),Locale.getDefault()); - cal.set(this.year, this.month-1, this.day, this.hour, this.minute, this.second); - cal.set(Calendar.MILLISECOND, this.millisecond); - return cal.getTimeInMillis(); - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getCentury() - */ - @Override - public int getCentury() { - return (year - (year % 100)) / 100; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getYear() - */ - @Override - public int getYear() { - return this.year; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getMonthOfYear() - */ - @Override - public int getMonthOfYear() { - return this.month; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getDayOfMonth() - */ - @Override - public int getDayOfMonth() { - return this.day; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getHourOfDay() - */ - @Override - public int getHourOfDay() { - return this.hour; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getMinuteOfHour() - */ - @Override - public int getMinuteOfHour() { - return this.minute; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getSecondOfMinute() - */ - @Override - public int getSecondOfMinute() { - return this.second; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getMillisecondsOfSecond() - */ - @Override - public int getMillisecondsOfSecond() { - return this.millisecond; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getTimezoneOffsetHours() - */ - @Override - public int getTimezoneOffsetHours() { - return this.timezoneHours; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#getTimezoneOffsetMinutes() - */ - @Override - public int getTimezoneOffsetMinutes() { - return this.timezoneMinutes; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#isDate() - */ - @Override - public boolean isDate() { - return false; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#isTime() - */ - @Override - public boolean isTime() { - return false; - } - - /* (non-Javadoc) - * @see org.rascalmpl.value.IDateTime#isDateTime() - */ - @Override - public boolean isDateTime() { - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + day; - result = prime * result + hour; - result = prime * result + millisecond; - result = prime * result + minute; - result = prime * result + month; - result = prime * result + second; - result = prime * result + timezoneHours; - result = prime * result + timezoneMinutes; - result = prime * result + year; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - DateTimeValue other = (DateTimeValue) obj; - if (day != other.day) - return false; - if (hour != other.hour) - return false; - if (millisecond != other.millisecond) - return false; - if (minute != other.minute) - return false; - if (month != other.month) - return false; - if (second != other.second) - return false; - if (timezoneHours != other.timezoneHours) - return false; - if (timezoneMinutes != other.timezoneMinutes) - return false; - if (year != other.year) - return false; - return true; - } - - @Override - public boolean isEqual(IValue other) { - return equals(other); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/ExternalValue.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/ExternalValue.java deleted file mode 100644 index a7668c633..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/ExternalValue.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Jurgen Vinju - initial API and implementation - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import java.util.Collections; -import java.util.Iterator; -import java.util.Map; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IExternalValue; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.impl.AbstractDefaultAnnotatable; -import org.rascalmpl.value.impl.AbstractDefaultWithKeywordParameters; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.impl.AnnotatedConstructorFacade; -import org.rascalmpl.value.impl.ConstructorWithKeywordParametersFacade; -import org.rascalmpl.value.type.ExternalType; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.AbstractSpecialisedImmutableMap; -import io.usethesource.capsule.ImmutableMap; - -/** - * See {@link IExternalValue} - *
- * Note that NORMAL USE OF THE PDB DOES NOT REQUIRE EXTENDING THIS CLASS. - */ -public abstract class ExternalValue implements IExternalValue { - - private final ExternalType type; - - @Override - public boolean isEqual(IValue other) { - return equals(other); - } - - - protected ExternalValue(ExternalType type) { - this.type = type; - } - - @Override - public ExternalType getType() { - return type; - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitExternal(this); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/ICanBecomeABigInteger.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/ICanBecomeABigInteger.java deleted file mode 100644 index 2ea3995e9..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/ICanBecomeABigInteger.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Arnold Lankamp - interfaces and implementation - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import java.math.BigInteger; - -/** - * Strangely named class, which defines that the implementor can convert something to a big integer. - * - * @author Arnold Lankamp - */ -public interface ICanBecomeABigInteger{ - - /** - * Returns the big integer. - * - * @return The big integer. - */ - BigInteger toBigInteger(); -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/IURI.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/IURI.java deleted file mode 100644 index e9911d68d..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/IURI.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.rascalmpl.value.impl.primitive; - -import java.net.URI; - -public interface IURI { - String getScheme(); - String getAuthority(); - String getPath(); - String getFragment(); - String getQuery(); - Boolean hasAuthority(); - Boolean hasPath(); - Boolean hasFragment(); - Boolean hasQuery(); - URI getURI(); -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/IntegerValue.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/IntegerValue.java deleted file mode 100644 index 33aba25cf..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/IntegerValue.java +++ /dev/null @@ -1,543 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Arnold Lankamp - interfaces and implementation - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.INumber; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * Implementation for IInteger. - *

- * Integer values that fall outside the 32-bit range will be store in BigIntegerValue instead. - * - * @author Arnold Lankamp - */ -/*package*/ class IntegerValue extends AbstractNumberValue implements IInteger, ICanBecomeABigInteger{ - private final static Type INTEGER_TYPE = TypeFactory.getInstance().integerType(); - - private final static String INTEGER_MAX_STRING = "2147483647"; - private final static String NEGATIVE_INTEGER_MAX_STRING = "-2147483648"; - - private final static int SEVEN_BITS_MASK = 0x0000007f; - private final static int FIFTEEN_BITS_MASK = 0x00007fff; - private final static int TWENTYTHREE_BITS_MASK = 0x007fffff; - public final static IInteger INTEGER_ONE = newInteger(1); - protected final int value; - - /* - * TODO: Unify IntegerValue and BigIntegerValue in same java class file. - */ - /*package*/ static IInteger newInteger(BigInteger value) { - if (value.bitLength() > 31) { - return new BigIntegerValue(value); - } - return new IntegerValue(value.intValue()); - } - - /*package*/ static IInteger newInteger(int value) { - return new IntegerValue(value); - } - - /*package*/ static IInteger newInteger(String integerValue) { - if (integerValue.startsWith("-")) { - if (integerValue.length() < 11 || (integerValue.length() == 11 && integerValue.compareTo(NEGATIVE_INTEGER_MAX_STRING) <= 0)) { - return new IntegerValue(Integer.parseInt(integerValue)); - } - return new BigIntegerValue(new BigInteger(integerValue)); - } - - if (integerValue.length() < 10 || (integerValue.length() == 10 && integerValue.compareTo(INTEGER_MAX_STRING) <= 0)) { - return new IntegerValue(Integer.parseInt(integerValue)); - } - return new BigIntegerValue(new BigInteger(integerValue)); - } - - /*package*/ static IInteger newInteger(long value) { - if (((value & 0x000000007fffffffL) == value) || ((value & 0xffffffff80000000L) == 0xffffffff80000000L)) { - return newInteger((int) value); - } else { - byte[] valueData = new byte[8]; - valueData[0] = (byte) ((value >>> 56) & 0xff); - valueData[1] = (byte) ((value >>> 48) & 0xff); - valueData[2] = (byte) ((value >>> 40) & 0xff); - valueData[3] = (byte) ((value >>> 32) & 0xff); - valueData[4] = (byte) ((value >>> 24) & 0xff); - valueData[5] = (byte) ((value >>> 16) & 0xff); - valueData[6] = (byte) ((value >>> 8) & 0xff); - valueData[7] = (byte) (value & 0xff); - return newInteger(valueData); - } - } - - /*package*/ static IInteger newInteger(byte[] integerData) { - if (integerData.length <= 4) { - int value = 0; - for (int i = integerData.length - 1, j = 0; i >= 0; i--, j++) { - value |= ((integerData[i] & 0xff) << (j * 8)); - } - - return new IntegerValue(value); - } - return new BigIntegerValue(new BigInteger(integerData)); - } - - private IntegerValue(int value){ - super(); - this.value = value; - } - - @Override - public IInteger toInteger() { - return this; - } - - @Override - public Type getType(){ - return INTEGER_TYPE; - } - - @Override - public int intValue(){ - return value; - } - - @Override - public long longValue(){ - return value; - } - - @Override - public double doubleValue(){ - return value; - } - - @Override - public IReal toReal(int precision){ - return BigDecimalValue.newReal(BigDecimal.valueOf(value)); - } - - @Override - public byte[] getTwosComplementRepresentation(){ - if((value & SEVEN_BITS_MASK) == value){ - byte[] data = new byte[1]; - data[0] = (byte) (value & 0x7f); - return data; - }else if((value & FIFTEEN_BITS_MASK) == value){ - byte[] data = new byte[2]; - data[0] = (byte) ((value >> 8) & 0x7f); - data[1] = (byte) (value & 0xff); - return data; - }else if((value & TWENTYTHREE_BITS_MASK) == value){ - byte[] data = new byte[3]; - data[0] = (byte) ((value >> 16) & 0x7f); - data[1] = (byte) ((value >> 8) & 0xff); - data[2] = (byte) (value & 0xff); - return data; - } - - byte[] data = new byte[4]; - data[0] = (byte) ((value >> 24) & 0xff); - data[1] = (byte) ((value >> 16) & 0xff); - data[2] = (byte) ((value >> 8) & 0xff); - data[3] = (byte) (value & 0xff); - return data; - } - - @Override - public BigInteger toBigInteger(){ - return new BigInteger(getTwosComplementRepresentation()); - } - - @Override - public boolean isEqual(IValue other) { - return equals(other); - } - - @Override - public IInteger add(IInteger other){ - if(value == 0) - return other; - - if(other instanceof BigIntegerValue){ - return other.add(this); - } - - int otherIntValue = other.intValue(); - - if(otherIntValue == 0) - return this; - - int result = value + otherIntValue; - if((value < 0) && (otherIntValue < 0) && (result >= 0)){// Overflow -> positive. - byte[] intValueData = new byte[5]; - intValueData[0] = (byte) 0xff; - intValueData[1] = (byte)((result >>> 24) & 0xff); - intValueData[2] = (byte)((result >>> 16) & 0xff); - intValueData[3] = (byte)((result >>> 8) & 0xff); - intValueData[4] = (byte)(result & 0xff); - - return IntegerValue.newInteger(new BigInteger(intValueData)); - }else if((value > 0) && (otherIntValue > 0) && (result < 0)){// Overflow -> negative. - byte[] intValueData = new byte[5]; - intValueData[0] = 0; - intValueData[1] = (byte)((result >>> 24) & 0xff); - intValueData[2] = (byte)((result >>> 16) & 0xff); - intValueData[3] = (byte)((result >>> 8) & 0xff); - intValueData[4] = (byte)(result & 0xff); - - return IntegerValue.newInteger(new BigInteger(intValueData)); - } - - return IntegerValue.newInteger(result); - } - - @Override - public IRational add(IRational other) { - return (IRational ) other.add(this); - } - - @Override - public IReal add(IReal other) { - return (IReal) other.add(this); - } - - @Override - public INumber subtract(IReal other) { - return toReal(other.precision()).subtract(other); - } - - @Override - public IInteger subtract(IInteger other){ - if(value == 0) - return other.negate(); - - if(other instanceof BigIntegerValue){ - return other.negate().subtract(this.negate()); - } - - int otherIntValue = other.intValue(); - - if(otherIntValue == 0) - return this; - - int result = value - otherIntValue; - if((value < 0) && (otherIntValue > 0) && (result > 0)){// Overflow -> positive. - byte[] intValueData = new byte[5]; - intValueData[0] = (byte) 0xff; - intValueData[1] = (byte)((result >>> 24) & 0xff); - intValueData[2] = (byte)((result >>> 16) & 0xff); - intValueData[3] = (byte)((result >>> 8) & 0xff); - intValueData[4] = (byte)(result & 0xff); - - return IntegerValue.newInteger(new BigInteger(intValueData)); - }else if((value > 0) && (otherIntValue < 0) && (result < 0)){// Overflow -> negative. - byte[] intValueData = new byte[5]; - intValueData[0] = 0; - intValueData[1] = (byte)((result >>> 24) & 0xff); - intValueData[2] = (byte)((result >>> 16) & 0xff); - intValueData[3] = (byte)((result >>> 8) & 0xff); - intValueData[4] = (byte)(result & 0xff); - - return IntegerValue.newInteger(new BigInteger(intValueData)); - } - - return IntegerValue.newInteger(result); - } - - @Override - public IRational subtract(IRational other) { - return toRational().subtract(other); - } - - @Override - public IInteger multiply(IInteger other){ - if(value == 0) - return this; - if(value == 1) - return other; - - if(other instanceof BigIntegerValue){ - return other.multiply(this); - } - - int otherIntValue = other.intValue(); - if(otherIntValue == 0) return other; - if(otherIntValue == 1) return this; - - boolean resultIsPositive = ((((value ^ otherIntValue) ^ 0x80000000) & 0x80000000) == 0x80000000); - if(resultIsPositive){ - int div = Integer.MAX_VALUE / otherIntValue; - if((value > 0)){ - if(value <= div){ - return IntegerValue.newInteger(value * other.intValue()); - } - }else{ - if(value >= div){ - return IntegerValue.newInteger(value * other.intValue()); - } - } - }else{ - int div = Integer.MIN_VALUE / otherIntValue; - if((value > 0)){ - if(value <= div){ - return IntegerValue.newInteger(value * other.intValue()); - } - }else{ - if(value >= div){ - return IntegerValue.newInteger(value * other.intValue()); - } - } - } - - return IntegerValue.newInteger(toBigInteger().multiply(((ICanBecomeABigInteger) other).toBigInteger())); - } - - @Override - public IRational multiply(IRational other) { - return (IRational) other.multiply(this); - } - - @Override - public IReal multiply(IReal other) { - return (IReal) other.multiply(this); - } - - @Override - public IInteger divide(IInteger other){ - if(value == 0) - return this; - if(other instanceof BigIntegerValue){ - return IntegerValue.newInteger(toBigInteger().divide(((ICanBecomeABigInteger) other).toBigInteger())); - } - - int otherIntValue = other.intValue(); - if(otherIntValue == 1) - return this; - return IntegerValue.newInteger(value / otherIntValue); - } - - - @Override - public IRational divide(IRational other) { - return toRational().divide(other); - } - - @Override - public INumber divide(IInteger other, int precision) { - return toReal(precision).divide(other, precision); - } - - @Override - public INumber divide(IRational other, int precision) { - return toReal(precision).divide(other, precision); - } - - @Override - public IReal divide(IReal other, int precision) { - return toReal(precision).divide(other, precision); - } - - @Override - public IInteger mod(IInteger other){ - if(other instanceof BigIntegerValue){ - if(value < 0){ - BigInteger m = ((BigIntegerValue)other).toBigInteger(); - // i.e. -1 % m = m + (-1) - BigInteger res = m.add(toBigInteger()); - return IntegerValue.newInteger(res); - } - return this; - } - int otherVal = other.intValue(); - int newValue = value % other.intValue(); - newValue = newValue >= 0 ? newValue : newValue + otherVal; - return IntegerValue.newInteger(newValue); - } - - @Override - public IInteger remainder(IInteger other){ - if(other instanceof BigIntegerValue){ - return this; - } - - return IntegerValue.newInteger(value % other.intValue()); - } - - @Override - public IInteger negate(){ - if(value == 0) - return this; - else - return IntegerValue.newInteger((~((long) value)) + 1); - } - - @Override - public IBool equal(IInteger other){ - return BoolValue.getBoolValue(compare(other) == 0); - } - - @Override - public IBool equal(IRational other) { - return other.equal(this); - } - - @Override - public IBool equal(IReal other) { - return other.equal(this); - } - - @Override - public IBool greater(IInteger other){ - return BoolValue.getBoolValue(compare(other) > 0); - } - - @Override - public IBool greater(IRational other) { - return other.less(this); - } - - @Override - public IBool greater(IReal other) { - return other.less(this); - } - - @Override - public IBool greaterEqual(IInteger other){ - return BoolValue.getBoolValue(compare(other) >= 0); - } - - @Override - public IBool greaterEqual(IRational other) { - return other.lessEqual(this); - } - - @Override - public IBool greaterEqual(IReal other) { - return BoolValue.getBoolValue(compare(other) >= 0); - } - - @Override - public IBool less(IInteger other){ - return BoolValue.getBoolValue(compare(other) < 0); - } - - @Override - public IBool less(IRational other) { - return other.greater(this); - } - - @Override - public IBool less(IReal other) { - return other.greater(this); - } - - @Override - public IBool lessEqual(IInteger other){ - return BoolValue.getBoolValue(compare(other) <= 0); - } - - @Override - public IBool lessEqual(IRational other) { - return other.greaterEqual(this); - } - - @Override - public IBool lessEqual(IReal other) { - return other.greaterEqual(this); - } - - @Override - public int compare(IInteger other){ - if(other instanceof BigIntegerValue){ - return ((~other.compare(this)) + 1); - } - - if(value > other.intValue()) return 1; - if(value < other.intValue()) return -1; - - return 0; - } - - @Override - public int compare(INumber other) { - if (isIntegerType(other)) { - return compare(other.toInteger()); - } - else if (isRationalType(other)) { - return toRational().compare(other); - } - else { - assert other instanceof IReal; - return toReal(((IReal) other).precision()).compare(other); - } - } - - @Override - public T accept(IValueVisitor v) throws E{ - return v.visitInteger(this); - } - - public int hashCode(){ - int h = value ^ 0x85ebca6b; - // based on the final Avalanching phase of MurmurHash2 - // providing a nice mix of bits even for small numbers. - h ^= h >>> 13; - h *= 0x5bd1e995; - h ^= h >>> 15; - - return h; - } - - public boolean equals(Object o){ - if(o == null) return false; - else if(o == this) return true; - - if(o.getClass() == getClass()){ - IntegerValue otherInteger = (IntegerValue) o; - return (value == otherInteger.value); - } - - return false; - } - - @Override - public String getStringRepresentation(){ - return Integer.toString(value); - } - - @Override - public int signum() { - return value < 0 ? -1 : (value == 0 ? 0 : 1); - } - - @Override - public IInteger abs() { - return newInteger(Math.abs(value)); - } - - @Override - public IRational toRational() { - return RationalValue.newRational(this, INTEGER_ONE); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/RationalValue.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/RationalValue.java deleted file mode 100644 index 317af9a0b..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/RationalValue.java +++ /dev/null @@ -1,378 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Anya Helene Bagge - initial implementation - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.INumber; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/*package*/ class RationalValue extends AbstractNumberValue implements IRational { - public static final Type RATIONAL_TYPE = TypeFactory.getInstance().rationalType(); - - protected final IInteger num; - protected final IInteger denom; - - /*package*/ static IRational newRational(IInteger a, IInteger b) { - return new RationalValue(a, b); - } - - private RationalValue(IInteger num, IInteger denom) { - if(denom.signum() < 0) { - num = num.negate(); - denom = denom.negate(); - } - // normalize infinites - if(denom.signum() == 0) { - if(num.signum() > 0) - num = intOne(); - else if(num.signum() < 0) - num = intOne().negate(); - else - throw new ArithmeticException("Illegal fraction 0/0"); - - } - else if(num.signum() == 0) { - denom = intOne(); - } - else { - IInteger gcd = gcd(num, denom); - while(gcd.compare(intOne()) != 0) { - num = num.divide(gcd); - denom = denom.divide(gcd); - gcd = gcd(num, denom); - } - } - this.num = num; - this.denom = denom; - } - - @Override - public IRational add(IRational other) { - // (num*other.denom + denom*other.num) / denom*other.denom - return toRational( - num.multiply(other.denominator()).add(denom.multiply(other.numerator())), - denom.multiply(other.denominator())); - } - - @Override - public IReal add(IReal other) { - return toReal(other.precision()).add(other); - } - - @Override - public INumber add(IInteger other) { - return toRational(num.add(other.multiply(denom)), denom); - } - - @Override - public IRational subtract(IRational other) { - // (num*other.denom - denom*other.num) / denom*other.denom - return toRational( - num.multiply(other.denominator()).subtract(denom.multiply(other.numerator())), - denom.multiply(other.denominator())); - } - - @Override - public INumber subtract(IReal other) { - return toReal(other.precision()).subtract(other); - } - - @Override - public INumber subtract(IInteger other) { - return toRational(num.subtract(other.multiply(denom)), denom); - } - - @Override - public IRational multiply(IRational other) { - return toRational(num.multiply(other.numerator()), - denom.multiply(other.denominator())); - } - - @Override - public IReal multiply(IReal other) { - return toReal(other.precision()).multiply(other); - } - - @Override - public INumber multiply(IInteger other) { - return toRational(num.multiply(other), denom); - } - - // TODO: should we perhaps drop this and only have the other divide? - // or vice-versa? - @Override - public IRational divide(IRational other) { - return toRational(num.multiply(other.denominator()), - denom.multiply(other.numerator())); - } - - @Override - public IReal divide(IReal other, int precision) { - return toReal(precision).divide(other, precision); - } - - @Override - public IRational divide(IInteger other, int precision) { - return divide(other); // forget precision - } - - @Override - public IRational divide(IInteger other) { - return toRational(num, denom.multiply(other)); - } - - - @Override - public INumber divide(IRational other, int precision) { - return toRational(num.multiply(other.denominator()), - denom.multiply(other.numerator())); - } - - @Override - public IBool less(IRational other) { - return BoolValue.getBoolValue(compare(other) < 0); - } - - @Override - public IBool less(IReal other) { - return other.greater(this); - } - - @Override - public IBool less(IInteger other) { - return less(other.toRational()); - } - - @Override - public IBool greater(IRational other) { - return BoolValue.getBoolValue(compare(other) > 0); - } - - @Override - public IBool greater(IReal other) { - return other.less(this); - } - - @Override - public IBool greater(IInteger other) { - return greater(other.toRational()); - } - - @Override - public IBool equal(IRational other) { - return BoolValue.getBoolValue(compare(other) == 0); - } - - @Override - public IBool equal(IReal other) { - return other.equal(this); - } - - @Override - public IBool equal(IInteger other) { - return equal(other.toRational()); - } - - @Override - public IBool lessEqual(IRational other) { - return BoolValue.getBoolValue(compare(other) <= 0); - } - - @Override - public IBool lessEqual(IReal other) { - return other.greaterEqual(this); - } - - @Override - public IBool lessEqual(IInteger other) { - return lessEqual(other.toRational()); - } - - @Override - public IBool greaterEqual(IRational other) { - return BoolValue.getBoolValue(compare(other) >= 0); - } - - @Override - public IBool greaterEqual(IReal other) { - return other.lessEqual(this); - } - - @Override - public IBool greaterEqual(IInteger other) { - return greaterEqual(other.toRational()); - } - - @Override - public boolean isEqual(IValue other) { - return equals(other); - } - - public boolean equals(Object o) { - if(o == null) return false; - if(o == this) return true; - - if(o.getClass() == getClass()){ - RationalValue other = (RationalValue) o; - return num.equals(other.num) && denom.equals(other.denom); - } - - return false; - } - - @Override - public int compare(INumber other) { - if(isIntegerType(other)) { - IInteger div = num.divide(denom); - IInteger rem = num.remainder(denom); - if(div.compare(other) != 0) - return div.compare(other); - else - return rem.signum(); - } - else if(isRationalType(other)){ - IRational diff = subtract((IRational)other); - return diff.signum(); - } - else { - assert other instanceof IReal; - return toReal(((IReal) other).precision()).compare(other); - } - } - - @Override - public Type getType() { - return RATIONAL_TYPE; - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitRational(this); - } - - @Override - public IRational negate() { - return toRational(num.negate(), denom); - } - - @Override - public IReal toReal(int precision) { - IReal r1 = num.toReal(precision); - IReal r2 = denom.toReal(precision); - r1 = r1.divide(r2, precision); - return r1; - } - - @Override - public IInteger toInteger() { - return num.divide(denom); - } - - @Override - public String getStringRepresentation() { - return num.getStringRepresentation() + "r" + (denom.equals(intOne()) ? "" : denom.getStringRepresentation()); - } - - @Override - public int compare(IRational other) { - IRational diff = subtract(other); - return diff.signum(); - } - - @Override - public int signum() { - return num.signum(); - } - - @Override - public IRational abs() { - return toRational(num.abs(), denom); - } - - @Override - public IInteger floor() { - return num.divide(denom); - } - - @Override - public IInteger round() { - return toReal(2).round().toInteger(); - } - - @Override - public IRational toRational() { - return this; - } - - public IRational toRational(IInteger n, IInteger d) { - return newRational(n, d); - } - - @Override - public IRational remainder(IRational other) { - throw new UnsupportedOperationException(); - } - - @Override - public int hashCode() { - if(denom.equals(intOne())) - return num.hashCode(); - else { - final int prime = 31; - int result = 1; - result = prime * result + num.hashCode(); - result = prime * result + denom.hashCode(); - return result; - } - } - - @Override - public IInteger numerator() { - return num; - } - - @Override - public IInteger denominator() { - return denom; - } - - @Override - public IInteger remainder() { - return num.remainder(denom); - } - - protected IInteger gcd(IInteger n, IInteger d) { - n = n.abs(); - d = d.abs(); - while(d.signum() > 0) { - IInteger tmp = d; - d = n.mod(d); - n = tmp; - } - return n; - } - protected IInteger intOne() { - return IntegerValue.INTEGER_ONE; - } - - @Override - public double doubleValue() { - return num.doubleValue() / denom.doubleValue(); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/SourceLocationURIValues.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/SourceLocationURIValues.java deleted file mode 100644 index 878494442..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/SourceLocationURIValues.java +++ /dev/null @@ -1,851 +0,0 @@ -package org.rascalmpl.value.impl.primitive; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.regex.Pattern; - -/* - * Not supported: in URI class, scheme is case insensitive, but this is already kinda broken, since on windows & osx, so should path's be. - */ -/*package*/ class SourceLocationURIValues { - static IURI newURI(URI base) throws URISyntaxException { - return newURI(base.getScheme(), base.getAuthority(),base.getPath(), base.getQuery(), base.getFragment()); - } - - private static final Pattern schemePattern = Pattern.compile("[A-Za-z][A-Za-z0-9+\\-.]*"); - private static final Pattern doubleSlashes = Pattern.compile("//+"); - static IURI newURI(String scheme, String authority, String path, String query, String fragment) throws URISyntaxException { - if (path != null) { - if (path.isEmpty()) { - path = null; - } - else if (!path.startsWith("/")) { - path = "/" + path; - } - if (path != null) { - // normalize double or longer slashes - path = doubleSlashes.matcher(path).replaceAll("/"); - } - } - if (scheme == null || scheme.equals("")) { - throw new URISyntaxException(scheme, "scheme cannot be empty or null"); - } - if (!schemePattern.matcher(scheme).matches()) { - throw new URISyntaxException(scheme, "Scheme is not a valid scheme"); - } - if (authority == null || authority.equals("")) { - if (path == null || path.equals("/")) { - if (query == null) { - if (fragment == null) { - return new SourceLocationURIValues.BaseURI(scheme); - } - return new SourceLocationURIValues.FragmentURI(scheme, fragment); - } - if (fragment == null) { - return new SourceLocationURIValues.QueryURI(scheme, query); - } - return new SourceLocationURIValues.FragmentQueryURI(scheme, query, fragment); - } - if (query == null) { - if (fragment == null) { - return new SourceLocationURIValues.PathURI(scheme, path); - } - return new SourceLocationURIValues.FragmentPathURI(scheme, path, fragment); - } - if (fragment == null) { - return new SourceLocationURIValues.QueryPathURI(scheme, path, query); - } - return new SourceLocationURIValues.FragmentQueryPathURI(scheme, path, query, fragment); - } - if (path == null) { - if (query == null) { - if (fragment == null) { - return new SourceLocationURIValues.AuthorityURI(scheme, authority); - } - return new SourceLocationURIValues.FragmentAuthorityURI(scheme, authority, fragment); - } - if (fragment == null) { - return new SourceLocationURIValues.QueryAuthorityURI(scheme, authority, query); - } - return new SourceLocationURIValues.FragmentQueryAuthorityURI(scheme, authority, query, fragment); - } - if (query == null) { - if (fragment == null) { - return new SourceLocationURIValues.PathAuthorityURI(scheme, authority, path); - } - return new SourceLocationURIValues.FragmentPathAuthorityURI(scheme, authority, path, fragment); - } - if (fragment == null) { - return new SourceLocationURIValues.QueryPathAuthorityURI(scheme, authority, path, query); - } - return new SourceLocationURIValues.FragmentQueryPathAuthorityURI(scheme, authority, path, query, fragment); - } - - - private static class BaseURI implements IURI { - protected final String scheme; - - - public BaseURI(String scheme) { - this.scheme = scheme.intern(); - } - - - public URI getURI() { - try { - return new URI(scheme,"","/",null,null); - } catch (URISyntaxException e) { - throw new RuntimeException("Internal state corrupted?", e); - } - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - return scheme == ((BaseURI)obj).scheme; - } - return false; - } - @Override - public int hashCode() { - return scheme.hashCode(); - } - - @Override - public String getScheme() { - return scheme; - } - - @Override - public String getAuthority() { - return ""; - } - - @Override - public String getPath() { - return "/"; - } - - @Override - public String getFragment() { - return ""; - } - - @Override - public String getQuery() { - return ""; - } - - @Override - public Boolean hasAuthority() { - return false; - } - - @Override - public Boolean hasPath() { - return true; - } - - @Override - public Boolean hasFragment() { - return false; - } - - @Override - public Boolean hasQuery() { - return false; - } - - } - - private static final Pattern squareBrackets = Pattern.compile("(\\[|\\])"); - - private static URI buildURIWithAuthority(String scheme, String authority, - String path, String query, String fragment) { - try { - return new URI(scheme, authority, path, query, fragment); - } catch (URISyntaxException e) { - if (authority != null && squareBrackets.matcher(authority).find()) { - // Java URI do not correctly quote the brackets inside the authority - // even though RFC2732 specifies this. - // it has to do with the fact that the encoding/quotation is a single pass - // and that authority is actually ambigious, so it requires backtracking to - // decide which alternative of the authority part is used, and the quoting rules are - // slightly different. - // so if it fails to parse, we put some placeholder chars, which get encoded, - // we then replace the encoded values with the correct encoded values - // and create a new URI out of this. (to avoid double encoding) - authority = hideBrackets(authority); - URI temp = buildURIWithAuthority(scheme, authority, path, query, fragment); - return unhideBrackets(temp); - } - throw new RuntimeException("Internal state corrupted?", e); - } - - } - - private static final Pattern squareBracketOpenPlaceholder = Pattern.compile("%00%00%EF%BF%B0%00%00"); - private static final Pattern squareBracketClosePlaceholder = Pattern.compile("%00%00%EF%BF%B1%00%00"); - private static URI unhideBrackets(URI temp) { - String newURI = temp.toASCIIString(); - newURI = squareBracketOpenPlaceholder.matcher(newURI).replaceAll("%5B"); - newURI = squareBracketClosePlaceholder.matcher(newURI).replaceAll("%5D"); - try { - return new URI(newURI); - } catch (URISyntaxException e) { - throw new RuntimeException("Internal state corrupted?", e); - } - } - - private static final Pattern squareBracketOpen = Pattern.compile("\\["); - private static final Pattern squareBracketClose = Pattern.compile("\\]"); - private static String hideBrackets(String authority) { - authority = squareBracketOpen.matcher(authority).replaceAll("\0\0\uFFF0\0\0"); - return squareBracketClose.matcher(authority).replaceAll("\0\0\uFFF1\0\0"); - } - - - - - private static class AuthorityURI extends BaseURI { - protected final String authority; - - public AuthorityURI(String scheme, String authority) { - super(scheme); - this.authority = authority.intern(); - } - - @Override - public URI getURI() { - return buildURIWithAuthority(scheme, authority, null,null,null); - } - - - @Override - public Boolean hasPath() { - return false; - } - - @Override - public Boolean hasAuthority() { - return true; - } - @Override - public String getAuthority() { - return authority; - } - @Override - public int hashCode() { - return scheme.hashCode() + authority.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - AuthorityURI u = (AuthorityURI)obj; - return scheme == u.scheme - && authority == u.authority - ; - } - return false; - } - } - - private static class PathURI extends BaseURI { - protected final String path; - private int hash = 0; // we can cache the hash code since the 8-byte alignment leaves room for one - - public PathURI(String scheme, String path) { - super(scheme); - this.path = path; - } - - @Override - public URI getURI() { - try { - return new URI(scheme, "", path, null, null); - } catch (URISyntaxException e) { - throw new RuntimeException("Internal state corrupted?", e); - } - } - - @Override - public Boolean hasPath() { - return true; - } - @Override - public String getPath() { - return path; - } - @Override - public int hashCode() { - if (hash == 0) { - hash = scheme.hashCode() + path.hashCode(); - } - return hash; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - PathURI u = (PathURI)obj; - if (hash != 0 && u.hash != 0 && hash != u.hash) - return false; - return scheme == u.scheme - && path.equals(u.path); - } - return false; - } - } - - private static class PathAuthorityURI extends AuthorityURI { - protected final String path; - - public PathAuthorityURI(String scheme, String authority, String path) { - super(scheme, authority); - this.path = path; - } - - @Override - public URI getURI() { - return buildURIWithAuthority(scheme, authority, path,null,null); - } - - @Override - public Boolean hasPath() { - return true; - } - @Override - public String getPath() { - return path; - } - @Override - public int hashCode() { - return scheme.hashCode() + authority.hashCode() + path.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - PathAuthorityURI u = (PathAuthorityURI)obj; - return scheme == u.scheme - && authority == u.authority - && path.equals(u.path); - } - return false; - } - } - - private static class QueryURI extends BaseURI { - protected final String query; - - public QueryURI(String scheme, String query) { - super(scheme); - this.query = query; - } - - @Override - public URI getURI() { - try { - return new URI(scheme, "", "/", query, null); - } catch (URISyntaxException e) { - throw new RuntimeException("Internal state corrupted?", e); - } - } - - @Override - public Boolean hasQuery() { - return true; - } - @Override - public String getQuery() { - return query; - } - @Override - public int hashCode() { - return scheme.hashCode() + query.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - QueryURI u = (QueryURI)obj; - return scheme == u.scheme - && query.equals(u.query) - ; - } - return false; - } - } - - private static class QueryAuthorityURI extends AuthorityURI { - protected final String query; - - public QueryAuthorityURI(String scheme, String authority, String query) { - super(scheme, authority); - this.query = query; - } - - @Override - public URI getURI() { - return buildURIWithAuthority(scheme, authority, null, query, null); - } - - @Override - public Boolean hasQuery() { - return true; - } - @Override - public String getQuery() { - return query; - } - @Override - public int hashCode() { - return scheme.hashCode() + authority.hashCode() + query.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - QueryAuthorityURI u = (QueryAuthorityURI)obj; - return scheme == u.scheme - && authority == u.authority - && query.equals(u.query) - ; - } - return false; - } - } - - private static class QueryPathURI extends PathURI { - protected final String query; - - public QueryPathURI(String scheme, String path, String query) { - super(scheme, path); - this.query = query; - } - - @Override - public URI getURI() { - try { - return new URI(scheme, "", path, query, null); - } catch (URISyntaxException e) { - throw new RuntimeException("Internal state corrupted?", e); - } - } - - @Override - public Boolean hasQuery() { - return true; - } - @Override - public String getQuery() { - return query; - } - @Override - public int hashCode() { - return scheme.hashCode() + path.hashCode() + query.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - QueryPathURI u = (QueryPathURI)obj; - return scheme == u.scheme - && path.equals(u.path) - && query.equals(u.query) - ; - } - return false; - } - } - - private static class QueryPathAuthorityURI extends PathAuthorityURI { - protected final String query; - - public QueryPathAuthorityURI(String scheme, String authority, String path, String query) { - super(scheme, authority, path); - this.query = query; - } - - @Override - public URI getURI() { - return buildURIWithAuthority(scheme, authority, path,query,null); - } - - @Override - public Boolean hasQuery() { - return true; - } - @Override - public String getQuery() { - return query; - } - @Override - public int hashCode() { - return scheme.hashCode() + authority.hashCode() + path.hashCode() + query.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - QueryPathAuthorityURI u = (QueryPathAuthorityURI)obj; - return scheme == u.scheme - && authority == u.authority - && path.equals(u.path) - && query.equals(u.query) - ; - } - return false; - } - } - - private static class FragmentURI extends BaseURI { - protected final String fragment; - - public FragmentURI(String scheme, String fragment) { - super(scheme); - this.fragment = fragment; - } - - @Override - public URI getURI() { - try { - return new URI(scheme, "", "/", null, fragment); - } catch (URISyntaxException e) { - throw new RuntimeException("Internal state corrupted?", e); - } - } - - @Override - public Boolean hasFragment() { - return true; - } - @Override - public String getFragment() { - return fragment; - } - @Override - public int hashCode() { - return scheme.hashCode() + fragment.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - FragmentURI u = (FragmentURI)obj; - return scheme == u.scheme - && fragment.equals(u.fragment) - ; - } - return false; - } - } - - private static class FragmentAuthorityURI extends AuthorityURI { - protected final String fragment; - - public FragmentAuthorityURI(String scheme, String authority, String fragment) { - super(scheme, authority); - this.fragment = fragment; - } - - @Override - public URI getURI() { - return buildURIWithAuthority(scheme, authority, null, null, fragment); - } - - @Override - public Boolean hasFragment() { - return true; - } - @Override - public String getFragment() { - return fragment; - } - @Override - public int hashCode() { - return scheme.hashCode() + authority.hashCode() + fragment.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - FragmentAuthorityURI u = (FragmentAuthorityURI)obj; - return scheme == u.scheme - && authority == u.authority - && fragment.equals(u.fragment) - ; - } - return false; - } - } - - private static class FragmentPathURI extends PathURI { - protected final String fragment; - - public FragmentPathURI(String scheme, String path, String fragment) { - super(scheme, path); - this.fragment = fragment; - } - - @Override - public URI getURI() { - try { - return new URI(scheme, "", path, null, fragment); - } catch (URISyntaxException e) { - throw new RuntimeException("Internal state corrupted?", e); - } - } - - @Override - public Boolean hasFragment() { - return true; - } - @Override - public String getFragment() { - return fragment; - } - @Override - public int hashCode() { - return scheme.hashCode() + path.hashCode() + fragment.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - FragmentPathURI u = (FragmentPathURI)obj; - return scheme == u.scheme - && path.equals(u.path) - && fragment.equals(u.fragment) - ; - } - return false; - } - } - - private static class FragmentPathAuthorityURI extends PathAuthorityURI { - protected final String fragment; - - public FragmentPathAuthorityURI(String scheme, String authority, String path, String fragment) { - super(scheme, authority, path); - this.fragment = fragment; - } - - @Override - public URI getURI() { - return buildURIWithAuthority(scheme, authority, path, null, fragment); - } - - @Override - public Boolean hasFragment() { - return true; - } - @Override - public String getFragment() { - return fragment; - } - @Override - public int hashCode() { - return scheme.hashCode() + authority.hashCode() + path.hashCode() + fragment.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - FragmentPathAuthorityURI u = (FragmentPathAuthorityURI)obj; - return scheme == u.scheme - && authority == u.authority - && path.equals(u.path) - && fragment.equals(u.fragment) - ; - } - return false; - } - } - private static class FragmentQueryURI extends QueryURI { - protected final String fragment; - - public FragmentQueryURI(String scheme, String query, String fragment) { - super(scheme, query); - this.fragment = fragment; - } - - @Override - public URI getURI() { - try { - return new URI(scheme, "", "/", query, fragment); - } catch (URISyntaxException e) { - throw new RuntimeException("Internal state corrupted?", e); - } - } - - @Override - public Boolean hasFragment() { - return true; - } - @Override - public String getFragment() { - return fragment; - } - @Override - public int hashCode() { - return scheme.hashCode() + query.hashCode() + fragment.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - FragmentQueryURI u = (FragmentQueryURI)obj; - return scheme == u.scheme - && query.equals(u.query) - && fragment.equals(u.fragment) - ; - } - return false; - } - } - - private static class FragmentQueryAuthorityURI extends QueryAuthorityURI { - protected final String fragment; - - public FragmentQueryAuthorityURI(String scheme, String authority, String query, String fragment) { - super(scheme, authority, query); - this.fragment = fragment; - } - - @Override - public URI getURI() { - return buildURIWithAuthority(scheme, authority, null, query, fragment); - } - - @Override - public Boolean hasFragment() { - return true; - } - @Override - public String getFragment() { - return fragment; - } - @Override - public int hashCode() { - return scheme.hashCode() + authority.hashCode() + query.hashCode() + fragment.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - FragmentQueryAuthorityURI u = (FragmentQueryAuthorityURI)obj; - return scheme == u.scheme - && authority == u.authority - && query.equals(u.query) - && fragment.equals(u.fragment) - ; - } - return false; - } - } - - private static class FragmentQueryPathURI extends QueryPathURI { - protected final String fragment; - - public FragmentQueryPathURI(String scheme, String path, String query, String fragment) { - super(scheme, path, query); - this.fragment = fragment; - } - - @Override - public URI getURI() { - try { - return new URI(scheme, "", path, query, fragment); - } catch (URISyntaxException e) { - throw new RuntimeException("Internal state corrupted?", e); - } - } - - @Override - public Boolean hasFragment() { - return true; - } - @Override - public String getFragment() { - return fragment; - } - @Override - public int hashCode() { - return scheme.hashCode() + path.hashCode() + query.hashCode() + fragment.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - FragmentQueryPathURI u = (FragmentQueryPathURI)obj; - return scheme == u.scheme - && path.equals(u.path) - && query.equals(u.query) - && fragment.equals(u.fragment) - ; - } - return false; - } - } - - private static class FragmentQueryPathAuthorityURI extends QueryPathAuthorityURI { - protected final String fragment; - - public FragmentQueryPathAuthorityURI(String scheme, String authority, String path, String query, String fragment) { - super(scheme, authority, path, query); - this.fragment = fragment; - } - - @Override - public URI getURI() { - return buildURIWithAuthority(scheme, authority, path, query, fragment); - } - - @Override - public Boolean hasFragment() { - return true; - } - @Override - public String getFragment() { - return fragment; - } - @Override - public int hashCode() { - return scheme.hashCode() + authority.hashCode() + path.hashCode() + query.hashCode() + fragment.hashCode(); - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if(obj.getClass() == getClass()){ - FragmentQueryPathAuthorityURI u = (FragmentQueryPathAuthorityURI)obj; - return scheme == u.scheme - && authority == u.authority - && path.equals(u.path) - && query.equals(u.query) - && fragment.equals(u.fragment) - ; - } - return false; - } - } - -} \ No newline at end of file diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/SourceLocationValues.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/SourceLocationValues.java deleted file mode 100644 index 12c9b1955..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/SourceLocationValues.java +++ /dev/null @@ -1,909 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Arnold Lankamp - implementation - * * Jurgen Vinju - implementation - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * This is a container class for a number of implementations of ISourceLocation. Each implementation is extremely similar to the others. - * except that different native types are used to store offsets, lengths, line and column indices. The goal is to use a minimum amount - * of heap for each source location object, since at run-time there will be so many of them. We measured the effect of this on some real - * applications and showed more than 50% improvement in memory usage. - */ -/*package*/ class SourceLocationValues { - - - - /*package*/ static ISourceLocation newSourceLocation(ISourceLocation loc, int offset, int length) { - IURI uri = ((Incomplete)loc).uri; - if (offset < 0) throw new IllegalArgumentException("offset should be positive"); - if (length < 0) throw new IllegalArgumentException("length should be positive"); - - if (offset < Byte.MAX_VALUE && length < Byte.MAX_VALUE) { - return new SourceLocationValues.ByteByte(uri, (byte) offset, (byte) length); - } - - if (offset < Character.MAX_VALUE && length < Character.MAX_VALUE) { - return new SourceLocationValues.CharChar(uri, (char) offset, (char) length); - } - - return new SourceLocationValues.IntInt(uri, offset, length); - } - - /*package*/ static ISourceLocation newSourceLocation(ISourceLocation loc, int offset, int length, int beginLine, int endLine, int beginCol, int endCol) { - IURI uri = ((Incomplete)loc).uri; - if (offset < 0) throw new IllegalArgumentException("offset should be positive"); - if (length < 0) throw new IllegalArgumentException("length should be positive"); - if (beginLine < 0) throw new IllegalArgumentException("beginLine should be positive"); - if (beginCol < 0) throw new IllegalArgumentException("beginCol should be positive"); - if (endCol < 0) throw new IllegalArgumentException("endCol should be positive"); - if (endLine < beginLine) - throw new IllegalArgumentException("endLine should be larger than or equal to beginLine"); - if (endLine == beginLine && endCol < beginCol) - throw new IllegalArgumentException("endCol should be larger than or equal to beginCol, if on the same line"); - - if (offset < Character.MAX_VALUE - && length < Character.MAX_VALUE - && beginLine < Byte.MAX_VALUE - && endLine < Byte.MAX_VALUE - && beginCol < Byte.MAX_VALUE - && endCol < Byte.MAX_VALUE) { - return new SourceLocationValues.CharCharByteByteByteByte(uri, (char) offset, (char) length, (byte) beginLine, (byte) endLine, (byte) beginCol, (byte) endCol); - } else if (offset < Character.MAX_VALUE - && length < Character.MAX_VALUE - && beginLine < Character.MAX_VALUE - && endLine < Character.MAX_VALUE - && beginCol < Character.MAX_VALUE - && endCol < Character.MAX_VALUE) { - return new SourceLocationValues.CharCharCharCharCharChar(uri, (char) offset, (char) length, (char) beginLine, (char) endLine, (char) beginCol, (char) endCol); - } else if (beginLine < Character.MAX_VALUE - && endLine < Character.MAX_VALUE - && beginCol < Byte.MAX_VALUE - && endCol < Byte.MAX_VALUE) { - return new SourceLocationValues.IntIntCharCharByteByte(uri, offset, length, (char) beginLine, (char) endLine, (byte) beginCol, (byte) endCol); - } else if (beginCol < Byte.MAX_VALUE - && endCol < Byte.MAX_VALUE) { - return new SourceLocationValues.IntIntIntIntByteByte(uri, offset, length, beginLine, endLine, (byte) beginCol, (byte) endCol); - } - - return new SourceLocationValues.IntIntIntIntIntInt(uri, offset, length, beginLine, endLine, beginCol, endCol); - } - - private final static Lock locationCacheLock = new ReentrantLock(true); - @SuppressWarnings("serial") - private final static LinkedHashMap locationCache = new LinkedHashMap(400*4/3, 0.75f, true) { - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > 400; - } - }; - - private final static Lock reverseLocationCacheLock = new ReentrantLock(true); - @SuppressWarnings("serial") - private final static LinkedHashMap reverseLocationCache = new LinkedHashMap(400*4/3, 0.75f, true) { - @Override - protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > 400; - } - }; - - /*package*/ static ISourceLocation newSourceLocation(URI uri) throws URISyntaxException { - try { - // lock around the location cache, except if it takes to long to lock, then just skip the cache - if (locationCacheLock.tryLock(10, TimeUnit.MILLISECONDS)) { - try { - ISourceLocation result = locationCache.get(uri); - if (result == null) { - result = newSourceLocation(uri.getScheme(), uri.getAuthority(), uri.getPath(), uri.getQuery(), uri.getFragment()); - locationCache.put(uri, result); - } - return result; - } - finally { - locationCacheLock.unlock(); - } - } - } catch (InterruptedException e) { - } - // we couldn't get the lock, lets continue without cache - return newSourceLocation(uri.getScheme(), uri.getAuthority(), uri.getPath(), uri.getQuery(), uri.getFragment()); - } - - /*package*/ static ISourceLocation newSourceLocation(String scheme, String authority, - String path, String query, String fragment) throws URISyntaxException { - IURI u = SourceLocationURIValues.newURI(scheme, authority, path, query, fragment); - return new SourceLocationValues.OnlyURI(u); - } - - - private abstract static class Complete extends Incomplete { - private Complete(IURI uri) { - super(uri); - } - - @Override - public boolean hasOffsetLength() { - return true; - } - - @Override - public boolean hasLineColumn() { - return true; - } - } - - - private abstract static class Incomplete extends AbstractValue implements ISourceLocation { - protected IURI uri; - - public Incomplete(IURI uri) { - this.uri = uri; - } - - @Override - public Boolean hasAuthority() { - return uri.hasAuthority(); - } - - @Override - public Boolean hasFragment() { - return uri.hasFragment(); - } - - @Override - public Boolean hasPath() { - return uri.hasPath(); - } - - @Override - public Boolean hasQuery() { - return uri.hasQuery(); - } - - @Override - public String getAuthority() { - return uri.getAuthority(); - } - - @Override - public String getFragment() { - return uri.getFragment(); - } - - @Override - public String getPath() { - return uri.getPath(); - } - - @Override - public String getQuery() { - return uri.getQuery(); - } - - @Override - public String getScheme() { - return uri.getScheme(); - } - - @Override - public ISourceLocation top() { - return new OnlyURI(uri); - } - - @Override - public URI getURI() { - try { - if (reverseLocationCacheLock.tryLock(10, TimeUnit.MILLISECONDS)) { - try { - URI result = reverseLocationCache.get(uri); - if (result == null) { - result = uri.getURI(); - try { - // assure correct encoding, side effect of JRE's implementation of URIs - result = new URI(result.toASCIIString()); - } catch (URISyntaxException e) { - } - reverseLocationCache.put(uri, result); - } - return result; - } - finally { - reverseLocationCacheLock.unlock(); - } - } - } catch (InterruptedException e) { - } - // we could not get the lock, the cache was to busy, lets continue - URI result = uri.getURI(); - try { - // assure correct encoding, side effect of JRE's implementation of URIs - result = new URI(result.toASCIIString()); - } catch (URISyntaxException e) { - } - return result; - } - - @Override - public Type getType(){ - return TypeFactory.getInstance().sourceLocationType(); - } - - @Override - public boolean hasLineColumn() { - return false; - } - - @Override - public boolean hasOffsetLength() { - return false; - } - - @Override - public int getBeginColumn() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public int getBeginLine() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public int getEndColumn() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public int getEndLine() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public int getLength() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public int getOffset() throws UnsupportedOperationException { - throw new UnsupportedOperationException(); - } - - @Override - public T accept(IValueVisitor v) throws E{ - return v.visitSourceLocation(this); - } - - @Override - public boolean isEqual(IValue value){ - return equals(value); - } - } - - private static class IntIntIntIntIntInt extends Complete { - protected final int offset; - protected final int length; - protected final int beginLine; - protected final int endLine; - protected final int beginCol; - protected final int endCol; - - private IntIntIntIntIntInt(IURI uri, int offset, int length, int beginLine, int endLine, int beginCol, int endCol){ - super(uri); - - this.offset = offset; - this.length = length; - this.beginLine = beginLine; - this.endLine = endLine; - this.beginCol = beginCol; - this.endCol = endCol; - } - @Override - public Type getType(){ - return TypeFactory.getInstance().sourceLocationType(); - } - - @Override - public int getBeginLine(){ - return beginLine; - } - - @Override - public int getEndLine(){ - return endLine; - } - - @Override - public int getBeginColumn(){ - return beginCol; - } - - @Override - public int getEndColumn(){ - return endCol; - } - - @Override - public int getOffset(){ - return offset; - } - - @Override - public int getLength(){ - return length; - } - - @Override - public int hashCode(){ - int hash = uri.hashCode(); - hash ^= beginLine << 3; - hash ^= (endLine << 23); - hash ^= (beginCol << 13); - hash ^= (endCol << 18); - hash ^= (offset << 8); - hash ^= (length << 29); - - return hash; - } - - @Override - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - IntIntIntIntIntInt otherSourceLocation = (IntIntIntIntIntInt) o; - return (uri.equals(otherSourceLocation.uri) - && (beginLine == otherSourceLocation.beginLine) - && (endLine == otherSourceLocation.endLine) - && (beginCol == otherSourceLocation.beginCol) - && (endCol == otherSourceLocation.endCol) - && (offset == otherSourceLocation.offset) - && (length == otherSourceLocation.length)); - } - - return false; - } - } - - private static class CharCharByteByteByteByte extends Complete { - protected final char offset; - protected final char length; - protected final byte beginLine; - protected final byte endLine; - protected final byte beginCol; - protected final byte endCol; - - private CharCharByteByteByteByte(IURI uri, char offset, char length, byte beginLine, byte endLine, byte beginCol, byte endCol){ - super(uri); - - this.offset = offset; - this.length = length; - this.beginLine = beginLine; - this.endLine = endLine; - this.beginCol = beginCol; - this.endCol = endCol; - } - @Override - public Type getType(){ - return TypeFactory.getInstance().sourceLocationType(); - } - - @Override - public int getBeginLine(){ - return beginLine; - } - - @Override - public int getEndLine(){ - return endLine; - } - - @Override - public int getBeginColumn(){ - return beginCol; - } - - @Override - public int getEndColumn(){ - return endCol; - } - - @Override - public int getOffset(){ - return offset; - } - - @Override - public int getLength(){ - return length; - } - - @Override - public int hashCode(){ - int hash = uri.hashCode(); - hash ^= beginLine << 3; - hash ^= (endLine << 23); - hash ^= (beginCol << 13); - hash ^= (endCol << 18); - hash ^= (offset << 8); - hash ^= (length << 29); - - return hash; - } - - @Override - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - CharCharByteByteByteByte otherSourceLocation = (CharCharByteByteByteByte) o; - return (uri.equals(otherSourceLocation.uri) - && (beginLine == otherSourceLocation.beginLine) - && (endLine == otherSourceLocation.endLine) - && (beginCol == otherSourceLocation.beginCol) - && (endCol == otherSourceLocation.endCol) - && (offset == otherSourceLocation.offset) - && (length == otherSourceLocation.length)); - } - - return false; - } - } - - private static class CharCharCharCharCharChar extends Complete { - protected final char offset; - protected final char length; - protected final char beginLine; - protected final char endLine; - protected final char beginCol; - protected final char endCol; - - private CharCharCharCharCharChar(IURI uri, char offset, char length, char beginLine, char endLine, char beginCol, char endCol){ - super(uri); - - this.offset = offset; - this.length = length; - this.beginLine = beginLine; - this.endLine = endLine; - this.beginCol = beginCol; - this.endCol = endCol; - } - @Override - public Type getType(){ - return TypeFactory.getInstance().sourceLocationType(); - } - - @Override - public int getBeginLine(){ - return beginLine; - } - - @Override - public int getEndLine(){ - return endLine; - } - - @Override - public int getBeginColumn(){ - return beginCol; - } - - @Override - public int getEndColumn(){ - return endCol; - } - - @Override - public int getOffset(){ - return offset; - } - - @Override - public int getLength(){ - return length; - } - - @Override - public int hashCode(){ - int hash = uri.hashCode(); - hash ^= beginLine << 3; - hash ^= (endLine << 23); - hash ^= (beginCol << 13); - hash ^= (endCol << 18); - hash ^= (offset << 8); - hash ^= (length << 29); - - return hash; - } - - @Override - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - CharCharCharCharCharChar otherSourceLocation = (CharCharCharCharCharChar) o; - return (uri.equals(otherSourceLocation.uri) - && (beginLine == otherSourceLocation.beginLine) - && (endLine == otherSourceLocation.endLine) - && (beginCol == otherSourceLocation.beginCol) - && (endCol == otherSourceLocation.endCol) - && (offset == otherSourceLocation.offset) - && (length == otherSourceLocation.length)); - } - - return false; - } - } - - private final static class OnlyURI extends Incomplete { - - private OnlyURI(IURI uri){ - super(uri); - } - - @Override - public int hashCode(){ - return uri.hashCode(); - } - - @Override - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - OnlyURI otherSourceLocation = (OnlyURI) o; - return uri.equals(otherSourceLocation.uri); - } - - return false; - } - - @Override - public ISourceLocation top() { - // this is why the class is final - return this; - } - } - - private static class IntIntIntIntByteByte extends Complete { - protected final int offset; - protected final int length; - protected final int beginLine; - protected final int endLine; - protected final byte beginCol; - protected final byte endCol; - - private IntIntIntIntByteByte(IURI uri, int offset, int length, int beginLine, int endLine, byte beginCol, byte endCol){ - super(uri); - - this.offset = offset; - this.length = length; - this.beginLine = beginLine; - this.endLine = endLine; - this.beginCol = beginCol; - this.endCol = endCol; - } - - @Override - public int getBeginLine(){ - return beginLine; - } - - @Override - public int getEndLine(){ - return endLine; - } - - @Override - public int getBeginColumn(){ - return beginCol; - } - - @Override - public int getEndColumn(){ - return endCol; - } - - @Override - public int getOffset(){ - return offset; - } - - @Override - public int getLength(){ - return length; - } - - @Override - public int hashCode(){ - int hash = uri.hashCode(); - hash ^= beginLine << 3; - hash ^= (endLine << 23); - hash ^= (beginCol << 13); - hash ^= (endCol << 18); - hash ^= (offset << 8); - hash ^= (length << 29); - - return hash; - } - - @Override - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - IntIntIntIntByteByte otherSourceLocation = (IntIntIntIntByteByte) o; - return (uri.equals(otherSourceLocation.uri) - && (beginLine == otherSourceLocation.beginLine) - && (endLine == otherSourceLocation.endLine) - && (beginCol == otherSourceLocation.beginCol) - && (endCol == otherSourceLocation.endCol) - && (offset == otherSourceLocation.offset) - && (length == otherSourceLocation.length)); - } - - return false; - } - } - - private static class IntIntCharCharByteByte extends Complete { - protected final int offset; - protected final int length; - protected final char beginLine; - protected final char endLine; - protected final byte beginCol; - protected final byte endCol; - - private IntIntCharCharByteByte(IURI uri, int offset, int length, char beginLine, char endLine, byte beginCol, byte endCol){ - super(uri); - - this.offset = offset; - this.length = length; - this.beginLine = beginLine; - this.endLine = endLine; - this.beginCol = beginCol; - this.endCol = endCol; - } - - @Override - public int getBeginLine(){ - return beginLine; - } - - @Override - public int getEndLine(){ - return endLine; - } - - @Override - public int getBeginColumn(){ - return beginCol; - } - - @Override - public int getEndColumn(){ - return endCol; - } - - @Override - public int getOffset(){ - return offset; - } - - @Override - public int getLength(){ - return length; - } - - @Override - public int hashCode(){ - int hash = uri.hashCode(); - hash ^= beginLine << 3; - hash ^= (endLine << 23); - hash ^= (beginCol << 13); - hash ^= (endCol << 18); - hash ^= (offset << 8); - hash ^= (length << 29); - - return hash; - } - - @Override - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - IntIntCharCharByteByte otherSourceLocation = (IntIntCharCharByteByte) o; - return (uri.equals(otherSourceLocation.uri) - && (beginLine == otherSourceLocation.beginLine) - && (endLine == otherSourceLocation.endLine) - && (beginCol == otherSourceLocation.beginCol) - && (endCol == otherSourceLocation.endCol) - && (offset == otherSourceLocation.offset) - && (length == otherSourceLocation.length)); - } - - return false; - } - } - - private static class ByteByte extends Incomplete { - protected final byte offset; - protected final byte length; - - private ByteByte(IURI uri, byte offset, byte length){ - super(uri); - - this.offset = offset; - this.length = length; - } - - @Override - public boolean hasOffsetLength() { - return true; - } - - @Override - public int getOffset(){ - return offset; - } - - @Override - public int getLength(){ - return length; - } - - @Override - public int hashCode(){ - int hash = uri.hashCode(); - hash ^= (offset << 8); - hash ^= (length << 29); - - return hash; - } - - @Override - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - ByteByte otherSourceLocation = (ByteByte) o; - return (uri.equals(otherSourceLocation.uri) - && (offset == otherSourceLocation.offset) - && (length == otherSourceLocation.length)); - } - - return false; - } - } - - private static class CharChar extends Incomplete { - protected final char offset; - protected final char length; - - private CharChar(IURI uri, char offset, char length){ - super(uri); - - this.offset = offset; - this.length = length; - } - - @Override - public boolean hasOffsetLength() { - return true; - } - - @Override - public int getOffset(){ - return offset; - } - - @Override - public int getLength(){ - return length; - } - - @Override - public int hashCode(){ - int hash = uri.hashCode(); - hash ^= (offset << 8); - hash ^= (length << 29); - - return hash; - } - - @Override - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - CharChar otherSourceLocation = (CharChar) o; - return (uri.equals(otherSourceLocation.uri) - && (offset == otherSourceLocation.offset) - && (length == otherSourceLocation.length)); - } - - return false; - } - } - - private static class IntInt extends Incomplete { - protected final int offset; - protected final int length; - - private IntInt(IURI uri, int offset, int length){ - super(uri); - - this.offset = offset; - this.length = length; - } - - @Override - public boolean hasOffsetLength() { - return true; - } - - @Override - public boolean hasLineColumn() { - return false; - } - - @Override - public int getOffset(){ - return offset; - } - - @Override - public int getLength(){ - return length; - } - - @Override - public int hashCode(){ - int hash = uri.hashCode(); - hash ^= (offset << 8); - hash ^= (length << 29); - - return hash; - } - - @Override - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - IntInt otherSourceLocation = (IntInt) o; - return (uri.equals(otherSourceLocation.uri) - && (offset == otherSourceLocation.offset) - && (length == otherSourceLocation.length)); - } - - return false; - } - } - - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/StringValue.java b/value-core/src/main/java/org/rascalmpl/value/impl/primitive/StringValue.java deleted file mode 100644 index 46a7873a9..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/primitive/StringValue.java +++ /dev/null @@ -1,301 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2009-2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Arnold Lankamp - interfaces and implementation - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.primitive; - -import java.nio.CharBuffer; - -import org.rascalmpl.value.IString; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * Implementation of IString. - * - * @author Arnold Lankamp - */ -/*package*/ class StringValue { - private final static Type STRING_TYPE = TypeFactory.getInstance().stringType(); - - /*package*/ static IString newString(String value) { - if (value ==null) value = ""; - return newString(value, containsSurrogatePairs(value)); - } - /*package*/ static IString newString(String value, boolean fullUnicode) { - if (value ==null) value = ""; - if (fullUnicode) { - return new FullUnicodeString(value); - } - return new SimpleUnicodeString(value); - } - - private static boolean containsSurrogatePairs(String str) { - if (str == null) { - return false; - } - int len = str.length(); - for (int i = 1; i < len; i++) { - if (Character.isSurrogatePair(str.charAt(i - 1), str.charAt(i))) { - return true; - } - } - return false; - } - - private static class FullUnicodeString extends AbstractValue implements IString { - protected final String value; - - - private FullUnicodeString(String value){ - super(); - - this.value = value; - } - - @Override - public Type getType(){ - return STRING_TYPE; - } - - @Override - public String getValue(){ - return value; - } - - @Override - public IString concat(IString other){ - StringBuilder buffer = new StringBuilder(); - buffer.append(value); - buffer.append(other.getValue()); - - return StringValue.newString(buffer.toString(), true); - } - - @Override - public int compare(IString other){ - int result = value.compareTo(other.getValue()); - - if(result > 0) return 1; - if(result < 0) return -1; - - return 0; - } - - @Override - public T accept(IValueVisitor v) throws E{ - return v.visitString(this); - } - - public int hashCode(){ - return value.hashCode(); - } - - public boolean equals(Object o){ - if(o == null) return false; - if(this == o) return true; - if(o.getClass() == getClass()){ - FullUnicodeString otherString = (FullUnicodeString) o; - return value.equals(otherString.value); - } - - return false; - } - - @Override - public boolean isEqual(IValue value){ - return equals(value); - } - - @Override - public IString reverse() { - StringBuilder b = new StringBuilder(value); - return newString(b.reverse().toString(), true); - } - - @Override - public int length() { - return value.codePointCount(0, value.length()); - } - - private int codePointAt(java.lang.String str, int i) { - return str.codePointAt(str.offsetByCodePoints(0,i)); - } - - @Override - public IString substring(int start, int end) { - return newString(value.substring(value.offsetByCodePoints(0, start),value.offsetByCodePoints(0, end))); - } - - @Override - public IString substring(int start) { - return newString(value.substring(value.offsetByCodePoints(0, start))); - } - - @Override - public int charAt(int index) { - return codePointAt(value, index); - } - - private int nextCP(CharBuffer cbuf){ - int cp = Character.codePointAt(cbuf, 0); - if(cbuf.position() < cbuf.capacity()){ - cbuf.position(cbuf.position() + Character.charCount(cp)); - } - return cp; - } - - private void skipCP(CharBuffer cbuf){ - if(cbuf.hasRemaining()){ - int cp = Character.codePointAt(cbuf, 0); - cbuf.position(cbuf.position() + Character.charCount(cp)); - } - } - - @Override - public IString replace(int first, int second, int end, IString repl) { - StringBuilder buffer = new StringBuilder(); - - int valueLen = value.codePointCount(0, value.length()); - CharBuffer valueBuf; - - int replLen = repl.length(); - CharBuffer replBuf = CharBuffer.wrap(repl.getValue()); - - int increment = Math.abs(second - first); - if(first <= end){ - valueBuf = CharBuffer.wrap(value); - int valueIndex = 0; - // Before begin (from left to right) - while(valueIndex < first){ - buffer.appendCodePoint(nextCP(valueBuf)); valueIndex++; - } - int replIndex = 0; - boolean wrapped = false; - // Between begin and end - while(valueIndex < end){ - buffer.appendCodePoint(nextCP(replBuf)); replIndex++; - if(replIndex == replLen){ - replBuf.position(0); replIndex = 0; - wrapped = true; - } - skipCP(valueBuf); valueIndex++; //skip the replaced element - for(int j = 1; j < increment && valueIndex < end; j++){ - buffer.appendCodePoint(nextCP(valueBuf)); valueIndex++; - } - } - if(!wrapped){ - while(replIndex < replLen){ - buffer.appendCodePoint(nextCP(replBuf)); replIndex++; - } - } - // After end - - while( valueIndex < valueLen){ - buffer.appendCodePoint(nextCP(valueBuf)); valueIndex++; - } - } else { - // Before begin (from right to left) - - // Place reversed value of fValue in valueBuffer for better sequential code point access - // Also add code points to buffer in reverse order and reverse again at the end - valueBuf = CharBuffer.wrap(new StringBuilder(value).reverse().toString()); - - int valueIndex = valueLen - 1; - while(valueIndex > first){ - buffer.appendCodePoint(nextCP(valueBuf)); - valueIndex--; - } - // Between begin (right) and end (left) - int replIndex = 0; - boolean wrapped = false; - while(valueIndex > end){ - buffer.appendCodePoint(nextCP(replBuf)); replIndex++; - if(replIndex == repl.length()){ - replBuf.position(0); replIndex = 0; - wrapped = true; - } - skipCP(valueBuf); valueIndex--; //skip the replaced element - for(int j = 1; j < increment && valueIndex > end; j++){ - buffer.appendCodePoint(nextCP(valueBuf)); valueIndex--; - } - } - if(!wrapped){ - while(replIndex < replLen){ - buffer.appendCodePoint(nextCP(replBuf)); replIndex++; - } - } - // Left of end - while(valueIndex >= 0){ - buffer.appendCodePoint(nextCP(valueBuf)); valueIndex--; - } - buffer.reverse(); - } - - String res = buffer.toString(); - return StringValue.newString(res); - } - } - - private static class SimpleUnicodeString extends FullUnicodeString { - public SimpleUnicodeString(String value) { - super(value); - } - @Override - public boolean equals(Object o) { - if(o == null) return false; - if(this == o) return true; - if(o.getClass() == getClass()){ - SimpleUnicodeString otherString = (SimpleUnicodeString) o; - return value.equals(otherString.value); - } - - return false; - } - - // Common operations which do not need to be slow - @Override - public int length() { - return value.length(); - } - @Override - public int charAt(int index) { - return value.charAt(index); - } - - @Override - public IString substring(int start) { - return newString(value.substring(start), false); - } - - @Override - public IString substring(int start, int end) { - return newString(value.substring(start, end), false); - } - - @Override - public IString reverse() { - return newString(new StringBuilder(value).reverse().toString(), false); - } - - @Override - public IString concat(IString other) { - StringBuilder buffer = new StringBuilder(); - buffer.append(value); - buffer.append(other.getValue()); - - return StringValue.newString(buffer.toString(), other.getClass() != getClass()); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/reference/Constructor.java b/value-core/src/main/java/org/rascalmpl/value/impl/reference/Constructor.java deleted file mode 100644 index 6d25b2d3d..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/reference/Constructor.java +++ /dev/null @@ -1,212 +0,0 @@ -package org.rascalmpl.value.impl.reference; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.UnexpectedChildTypeException; -import org.rascalmpl.value.impl.AbstractDefaultAnnotatable; -import org.rascalmpl.value.impl.AbstractDefaultWithKeywordParameters; -import org.rascalmpl.value.impl.AnnotatedConstructorFacade; -import org.rascalmpl.value.impl.ConstructorWithKeywordParametersFacade; -import org.rascalmpl.value.impl.func.NodeFunctions; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.AbstractSpecialisedImmutableMap; -import io.usethesource.capsule.ImmutableMap; - -/** - * Implementation of a typed tree node with access to children via labels - */ -public class Constructor extends Node implements IConstructor { - /*package*/ Constructor(Type type, IValue[] children) { - super(type.getName(), type, children); - - } - - /*package*/ Constructor(Type type) { - this(type, new IValue[0]); - } - - /*package*/ Constructor(Type type, IValue[] children, Map kwParams) { - this(type, getAllChildren(type, children, kwParams)); - } - - private static IValue[] getAllChildren(Type type, IValue[] children, Map kwParams) { - IValue[] allChildren = new IValue[children.length + kwParams.size()]; - System.arraycopy(children, 0, allChildren, 0, children.length); - - for (Entry entry : kwParams.entrySet()) { - allChildren[type.getFieldIndex(entry.getKey())] = entry.getValue(); - } - - return allChildren; - } - - private Constructor(Constructor other, int childIndex, IValue newChild) { - super(other, childIndex, newChild); - } - - @Override - public Type getType() { - return getConstructorType().getAbstractDataType(); - } - - @Override - public Type getUninstantiatedConstructorType() { - return fType; - } - - public Type getConstructorType() { - if (fType.getAbstractDataType().isParameterized()) { - assert fType.getAbstractDataType().isOpen(); - - // this assures we always have the most concrete type for constructors. - Type[] actualTypes = new Type[fChildren.length]; - for (int i = 0; i < fChildren.length; i++) { - actualTypes[i] = fChildren[i].getType(); - } - - Map bindings = new HashMap(); - fType.getFieldTypes().match(TypeFactory.getInstance().tupleType(actualTypes), bindings); - - for (Type field : fType.getAbstractDataType().getTypeParameters()) { - if (!bindings.containsKey(field)) { - bindings.put(field, TypeFactory.getInstance().voidType()); - } - } - - return fType.instantiate(bindings); - } - - return fType; - } - - public IValue get(String label) { - return super.get(fType.getFieldIndex(label)); - } - - public Type getChildrenTypes() { - return fType.getFieldTypes(); - } - - @Override - public IConstructor set(int i, IValue newChild) throws IndexOutOfBoundsException { - checkChildType(i, newChild); - return new Constructor(this, i, newChild); - } - - - public IConstructor set(String label, IValue newChild) throws FactTypeUseException { - int childIndex = fType.getFieldIndex(label); - checkChildType(childIndex, newChild); - return new Constructor(this, childIndex, newChild); - } - - private void checkChildType(int i, IValue newChild) { - Type type = newChild.getType(); - Type expectedType = getConstructorType().getFieldType(i); - if (!type.isSubtypeOf(expectedType)) { - throw new UnexpectedChildTypeException(expectedType, type); - } - } - - @Override - public boolean equals(Object obj) { - if(this == obj) { - return true; - } - else if(obj == null) { - return false; - } - else if (getClass() == obj.getClass()) { - Constructor other = (Constructor) obj; - return fType.comparable(other.fType) && super.equals(obj); - } - return false; - } - - @Override - public boolean isEqual(IValue value) { - return NodeFunctions.isEqual(getValueFactory(), this, value); - } - - @Override - public int hashCode() { - return 17 + ~super.hashCode(); - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitConstructor(this); - } - - public boolean declaresAnnotation(TypeStore store, String label) { - return store.getAnnotationType(getType(), label) != null; - } - - public boolean has(String label) { - return getConstructorType().hasField(label); - } - - /** - * TODO: Create and move to {@link AbstractConstructor}. - */ - @Override - public boolean isAnnotatable() { - return true; - } - - /** - * TODO: Create and move to {@link AbstractConstructor}. - */ - @Override - public IAnnotatable asAnnotatable() { - return new AbstractDefaultAnnotatable(this) { - @Override - protected IConstructor wrap(IConstructor content, - ImmutableMap annotations) { - return new AnnotatedConstructorFacade(content, annotations); - } - }; - } - - @Override - public boolean mayHaveKeywordParameters() { - return true; - } - - @Override - public IWithKeywordParameters asWithKeywordParameters() { - return new AbstractDefaultWithKeywordParameters(this, AbstractSpecialisedImmutableMap.mapOf()) { - @Override - protected IConstructor wrap(IConstructor content, ImmutableMap parameters) { - return new ConstructorWithKeywordParametersFacade(content, parameters); - } - - @Override - public boolean hasParameters() { - return parameters != null && parameters.size() > 0; - } - - @Override - public java.util.Set getParameterNames() { - return parameters.keySet(); - } - - @Override - public Map getParameters() { - return Collections.unmodifiableMap(parameters); - } - }; - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/reference/List.java b/value-core/src/main/java/org/rascalmpl/value/impl/reference/List.java deleted file mode 100644 index 3ea02b5a8..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/reference/List.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.reference; - -import java.util.Iterator; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.AbstractList; -import org.rascalmpl.value.impl.func.ListFunctions; -import org.rascalmpl.value.type.Type; - -/*package*/ class List extends AbstractList { - - private final Type type; - private final java.util.List content; - - /*package*/ List(Type elementType, java.util.List content) { - super(); - this.type = inferListOrRelType(elementType, content); - this.content = content; - } - - @Override - public Type getType() { - return type; - } - - @Override - protected IValueFactory getValueFactory() { - return ValueFactory.getInstance(); - } - - @Override - public Iterator iterator() { - return content.iterator(); - } - - @Override - public int length() { - return content.size(); - } - - @Override - public IValue get(int i) { - return content.get(i); - } - - @Override - public boolean isEmpty() { - return content.isEmpty(); - } - - @Override - public int hashCode() { - return content.hashCode(); - } - - @Override - public boolean equals(Object that) { - return ListFunctions.equals(getValueFactory(), this, that); - } - - @Override - public boolean isEqual(IValue that) { - return ListFunctions.isEqual(getValueFactory(), this, that); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/reference/ListWriter.java b/value-core/src/main/java/org/rascalmpl/value/impl/reference/ListWriter.java deleted file mode 100644 index de2a11348..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/reference/ListWriter.java +++ /dev/null @@ -1,191 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI - * * Paul Klint - Paul.Klint@cwi.nl - CWI - * - * Based on code by: - * - * * Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.impl.reference; - -import java.util.LinkedList; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.UnexpectedElementTypeException; -import org.rascalmpl.value.impl.AbstractWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -/** - * This class does not guarantee thread-safety. Users must lock the writer object for thread safety. - * It is thread-friendly however. - */ -/*package*/ class ListWriter extends AbstractWriter implements IListWriter { - protected Type eltType; - protected final java.util.List listContent; - - protected IList constructedList; - private final boolean inferred; - - /*package*/ ListWriter(Type eltType){ - super(); - - this.eltType = eltType; - this.inferred = false; - listContent = new LinkedList<>(); - - constructedList = null; - } - - /*package*/ ListWriter(){ - super(); - - this.eltType = TypeFactory.getInstance().voidType(); - inferred = true; - listContent = new LinkedList<>(); - - constructedList = null; - } - - private void checkMutation(){ - if(constructedList != null) throw new UnsupportedOperationException("Mutation of a finalized list is not supported."); - } - - private static void checkInsert(IValue elem, Type eltType) throws FactTypeUseException{ - Type type = elem.getType(); - if(!type.isSubtypeOf(eltType)){ - throw new UnexpectedElementTypeException(eltType, type); - } - } - - private void put(int index, IValue elem){ - if (inferred) { - eltType = eltType.lub(elem.getType()); - } - else { - checkInsert(elem, eltType); - } - listContent.add(index, elem); - } - - public void insert(IValue elem) throws FactTypeUseException { - checkMutation(); - put(0, elem); - } - - @Override - public void insert(IValue[] elems, int start, int length) throws FactTypeUseException{ - checkMutation(); - checkBounds(elems, start, length); - - for(int i = start + length - 1; i >= start; i--){ - updateType(elems[i]); - put(0, elems[i]); - } - } - - @Override - public IValue replaceAt(int index, IValue elem) throws FactTypeUseException, IndexOutOfBoundsException { - checkMutation(); - updateType(elem); - checkInsert(elem, eltType); - return listContent.set(index, elem); - } - - @Override - public void insert(IValue... elems) throws FactTypeUseException{ - insert(elems, 0, elems.length); - } - - @Override - public void insertAt(int index, IValue[] elems, int start, int length) throws FactTypeUseException{ - checkMutation(); - checkBounds(elems, start, length); - - for(int i = start + length - 1; i >= start; i--) { - if (inferred) { - eltType = eltType.lub(elems[i].getType()); - } - put(index, elems[i]); - } - } - - @Override - public void insertAt(int index, IValue... elems) throws FactTypeUseException{ - insertAt(index, elems, 0, 0); - } - - public void append(IValue elem) throws FactTypeUseException{ - checkMutation(); - updateType(elem); - put(listContent.size(), elem); - } - - @Override - public void append(IValue... elems) throws FactTypeUseException{ - checkMutation(); - - for(IValue elem : elems){ - updateType(elem); - put(listContent.size(), elem); - } - } - - @Override - public void appendAll(Iterable collection) throws FactTypeUseException{ - checkMutation(); - - for(IValue v : collection){ - updateType(v); - put(listContent.size(), v); - } - } - - private void updateType(IValue v) { - if (inferred) { - eltType = eltType.lub(v.getType()); - } - } - - @Override - public IList done() { - // Temporary fix of the static vs dynamic type issue - eltType = TypeFactory.getInstance().voidType(); - for(IValue el : listContent) - eltType = eltType.lub(el.getType()); - // --- - if (constructedList == null) { - constructedList = new List(eltType, listContent); - } - - return constructedList; - } - - private void checkBounds(IValue[] elems, int start, int length) { - if(start < 0) throw new ArrayIndexOutOfBoundsException("start < 0"); - if((start + length) > elems.length) throw new ArrayIndexOutOfBoundsException("(start + length) > elems.length"); - } - - @Override - public IValue get(int i) throws IndexOutOfBoundsException { - return listContent.get(i); - } - - @Override - public int length() { - return listContent.size(); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/reference/Map.java b/value-core/src/main/java/org/rascalmpl/value/impl/reference/Map.java deleted file mode 100644 index 72cc75ed8..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/reference/Map.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI - * * Paul Klint - Paul.Klint@cwi.nl - CWI - * - * Based on code by: - * - * * Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.impl.reference; - -import java.util.Iterator; -import java.util.Map.Entry; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.AbstractMap; -import org.rascalmpl.value.impl.func.MapFunctions; -import org.rascalmpl.value.type.Type; - -/*package*/ class Map extends AbstractMap { - - final Type type; - final java.util.Map content; - - /*package*/ Map(Type candidateMapType, java.util.Map content) { - super(); - this.type = inferMapType(candidateMapType, content); - this.content = content; - } - - @Override - public Type getType() { - return type; - } - - @Override - protected IValueFactory getValueFactory() { - return ValueFactory.getInstance(); - } - - @Override - public int size() { - return content.size(); - } - - @Override - public boolean isEmpty() { - return content.isEmpty(); - } - - @Override - public IValue get(IValue key) { - return MapFunctions.get(getValueFactory(), this, key); - } - - @Override - public Iterator iterator() { - return content.keySet().iterator(); - } - - @Override - public Iterator valueIterator() { - return content.values().iterator(); - } - - @Override - public Iterator> entryIterator() { - return content.entrySet().iterator(); - } - - @Override - public boolean equals(Object other) { - return MapFunctions.equals(getValueFactory(), this, other); - } - - @Override - public boolean isEqual(IValue other) { - return MapFunctions.isEqual(getValueFactory(), this, other); - } - - @Override - public int hashCode() { - return MapFunctions.hashCode(getValueFactory(), this); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/reference/MapWriter.java b/value-core/src/main/java/org/rascalmpl/value/impl/reference/MapWriter.java deleted file mode 100644 index 5ff762823..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/reference/MapWriter.java +++ /dev/null @@ -1,156 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI - * * Paul Klint - Paul.Klint@cwi.nl - CWI - * * Anya Helene Bagge - anya@ii.uib.no - UiB - * - * Based on code by: - * - * * Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.impl.reference; - -import java.util.Map.Entry; - -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.UnexpectedMapKeyTypeException; -import org.rascalmpl.value.exceptions.UnexpectedMapValueTypeException; -import org.rascalmpl.value.impl.AbstractWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -/*package*/ class MapWriter extends AbstractWriter implements IMapWriter { - private Type staticMapType; - private Type staticKeyType; - private Type staticValueType; - private final boolean inferred; - private final java.util.HashMap mapContent; - private Map constructedMap; - - /*package*/ MapWriter(){ - super(); - - this.staticMapType = TypeFactory.getInstance().mapType( - TypeFactory.getInstance().voidType(), - TypeFactory.getInstance().voidType()); - this.staticKeyType = TypeFactory.getInstance().voidType(); - this.staticValueType = TypeFactory.getInstance().voidType(); - this.inferred = true; - - mapContent = new java.util.HashMap<>(); - } - - /*package*/ MapWriter(Type mapType){ - super(); - - if(mapType.isFixedWidth() && mapType.getArity() >= 2) { - mapType = TypeFactory.getInstance().mapTypeFromTuple(mapType); - } - - this.staticMapType = mapType; - this.staticKeyType = mapType.getKeyType(); - this.staticValueType = mapType.getValueType(); - this.inferred = false; - - mapContent = new java.util.HashMap<>(); - } - - private static void check(Type key, Type value, Type keyType, Type valueType) - throws FactTypeUseException { - if (!key.isSubtypeOf(keyType)) { - throw new UnexpectedMapKeyTypeException(keyType, key); - } - if (!value.isSubtypeOf(valueType)) { - throw new UnexpectedMapValueTypeException(valueType, value); - } - } - - private void checkMutation() { - if (constructedMap != null) - throw new UnsupportedOperationException( - "Mutation of a finalized list is not supported."); - } - - @Override - public void putAll(IMap map) throws FactTypeUseException{ - checkMutation(); - - for(IValue key : map){ - IValue value = map.get(key); - updateTypes(key, value); - mapContent.put(key, value); - } - } - - private void updateTypes(IValue key, IValue value) { - if (inferred) { - staticKeyType = staticKeyType.lub(key.getType()); - staticValueType = staticValueType.lub(value.getType()); - } - - } - - @Override - public void putAll(java.util.Map map) throws FactTypeUseException{ - checkMutation(); - for(Entry entry : map.entrySet()){ - IValue value = entry.getValue(); - updateTypes(entry.getKey(), value); - check(entry.getKey().getType(), value.getType(), staticKeyType, staticValueType); - mapContent.put(entry.getKey(), value); - } - } - - @Override - public void put(IValue key, IValue value) throws FactTypeUseException{ - checkMutation(); - updateTypes(key,value); - mapContent.put(key, value); - } - - @Override - public void insert(IValue... value) throws FactTypeUseException { - for(IValue tuple : value){ - ITuple t = (ITuple) tuple; - IValue key = t.get(0); - IValue value2 = t.get(1); - updateTypes(key,value2); - put(key, value2); - } - } - - @Override - public IMap done(){ - // Temporary fix of the static vs dynamic type issue - Type dynamicKeyType = TypeFactory.getInstance().voidType(); - Type dynamicValueType = TypeFactory.getInstance().voidType(); - for (java.util.Map.Entry entry : mapContent.entrySet()) { - dynamicKeyType = dynamicKeyType.lub(entry.getKey().getType()); - dynamicValueType = dynamicValueType.lub(entry.getValue().getType()); - } - // --- - - if (constructedMap == null) { - Type dynamicMapType = TypeFactory.getInstance().mapType( - dynamicKeyType, staticMapType.getKeyLabel(), - dynamicValueType, staticMapType.getValueLabel()); - - constructedMap = new Map(dynamicMapType, mapContent); - } - - return constructedMap; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/reference/Node.java b/value-core/src/main/java/org/rascalmpl/value/impl/reference/Node.java deleted file mode 100644 index a63c23d02..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/reference/Node.java +++ /dev/null @@ -1,212 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007-2013 IBM Corporation & CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.reference; - -import java.util.Iterator; -import java.util.Map; - -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.AbstractNode; -import org.rascalmpl.value.impl.func.NodeFunctions; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -import io.usethesource.capsule.ArrayIterator; - -/** - * Naive implementation of an untyped tree node, using array of children. - */ -/*package*/ class Node extends AbstractNode implements INode { - protected final static Type VALUE_TYPE = TypeFactory.getInstance().valueType(); - - @Override - public Type getType() { - return fType; - } - - protected final Type fType; - protected final IValue[] fChildren; - protected final String fName; - protected int fHash = 0; - protected final String[] keyArgNames; - - /*package*/ Node(String name, IValue[] children) { - super(); - fType = TypeFactory.getInstance().nodeType(); - fName = name; - fChildren = children.clone(); - keyArgNames = null; - } - - protected Node(String name, Type type, IValue[] children) { - super(); - fType = type; - fName = name; - fChildren = children.clone(); - keyArgNames = null; - } - - /*package*/ Node(String name, IValue[] children, Map keyArgValues){ - super(); - fType = TypeFactory.getInstance().nodeType(); - fName = (name != null ? name.intern() : null); // Handle (weird) special case. - if(keyArgValues != null){ - int nkw = keyArgValues.size(); - IValue[] extendedChildren = new IValue[children.length + nkw]; - for(int i = 0; i < children.length;i++){ - extendedChildren[i] = children[i]; - } - - String keyArgNames[]= new String[nkw]; - int k = 0; - for(String kw : keyArgValues.keySet()){ - keyArgNames[k++] = kw; - } - for(int i = 0; i < nkw; i++){ - extendedChildren[children.length + i] = keyArgValues.get(keyArgNames[i]); - } - this.fChildren = extendedChildren; - this.keyArgNames = keyArgNames; - } else { - this.fChildren = children; - this.keyArgNames = null; - } - } - - /*package*/ Node(String name) { - this(name, new IValue[0]); - } - - /** - * Replaces a child - * @param other - * @param index - * @param newChild - */ - protected Node(Node other, int index, IValue newChild) { - super(); - fType = other.fType; - fName = other.fName; - fChildren = other.fChildren.clone(); - fChildren[index] = newChild; - keyArgNames = null; - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitNode(this); - } - - @Override - public int arity() { - return fChildren.length; - } - - @Override - protected IValueFactory getValueFactory() { - return ValueFactory.getInstance(); - } - - @Override - public IValue get(int i) throws IndexOutOfBoundsException { - try { - return fChildren[i]; - } - catch (ArrayIndexOutOfBoundsException e) { - throw new IndexOutOfBoundsException("Node node does not have child at pos " + i); - } - } - - @Override - public Iterable getChildren() { - return this; - } - - @Override - public String getName() { - return fName; - } - - @Override - public INode set(int i, IValue newChild) throws IndexOutOfBoundsException { - try { - return new Node(this, i, newChild); - } catch (ArrayIndexOutOfBoundsException e) { - throw new IndexOutOfBoundsException("Node node does not have child at pos " + i); - } - } - - @Override - public Iterator iterator() { - return ArrayIterator.of(fChildren); - } - - @Override - public boolean equals(Object obj) { - if(this == obj) { - return true; - } - else if(obj == null) { - return false; - } - else if (getClass() == obj.getClass()) { - Node other = (Node) obj; - - if (!fType.comparable(other.fType)) { - return false; - } - - if (fChildren.length != other.fChildren.length) { - return false; - } - - if (fName == other.fName || (fName != null && fName.equals(other.fName))) { - for (int i = 0; i < fChildren.length; i++) { - if (!fChildren[i].equals(other.fChildren[i])) { - return false; - } - } - - return true; - } - } - - return false; - } - - @Override - public boolean isEqual(IValue value){ - return NodeFunctions.isEqual(getValueFactory(), this, value); - } - - public int computeHashCode() { - int hash = fName != null ? fName.hashCode() : 0; - - for (int i = 0; i < fChildren.length; i++) { - hash = (hash << 1) ^ (hash >> 1) ^ fChildren[i].hashCode(); - } - return hash; - } - - @Override - public int hashCode() { - if (fHash == 0) { - fHash = computeHashCode(); - } - return fHash; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/reference/Set.java b/value-core/src/main/java/org/rascalmpl/value/impl/reference/Set.java deleted file mode 100644 index 37b5a880f..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/reference/Set.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI - * * Paul Klint - Paul.Klint@cwi.nl - CWI - * - * Based on code by: - * - * * Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.impl.reference; - -import java.util.Iterator; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.AbstractSet; -import org.rascalmpl.value.impl.func.SetFunctions; -import org.rascalmpl.value.type.Type; - -/*package*/ class Set extends AbstractSet { - - final Type type; - final java.util.Set content; - - /*package*/ Set(Type elementType, java.util.Set content) { - super(); - this.type = inferSetOrRelType(elementType, content); - this.content = content; - } - - @Override - public Type getType() { - return type; - } - - @Override - public boolean isEmpty() { - return content.isEmpty(); - } - - @Override - public int size() { - return content.size(); - } - - @Override - public boolean contains(IValue e) { - return content.contains(e); - } - - @Override - public int hashCode() { - return content.hashCode(); - } - - @Override - public boolean equals(Object other) { - return SetFunctions.equals(getValueFactory(), this, other); - } - - @Override - public boolean isEqual(IValue other) { - return SetFunctions.isEqual(getValueFactory(), this, other); - } - - @Override - protected IValueFactory getValueFactory() { - return ValueFactory.getInstance(); - } - - @Override - public Iterator iterator() { - return content.iterator(); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/reference/SetWriter.java b/value-core/src/main/java/org/rascalmpl/value/impl/reference/SetWriter.java deleted file mode 100644 index 27c6c4097..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/reference/SetWriter.java +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - * * Jurgen J. Vinju - Jurgen.Vinju@cwi.nl - CWI - * * Paul Klint - Paul.Klint@cwi.nl - CWI - * - * Based on code by: - * - * * Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.impl.reference; - -import java.util.HashSet; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.UnexpectedElementTypeException; -import org.rascalmpl.value.impl.AbstractWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -/*package*/ class SetWriter extends AbstractWriter implements ISetWriter { - protected final HashSet setContent; - protected final boolean inferred; - protected Type eltType; - protected Set constructedSet; - - /*package*/ SetWriter(Type eltType) { - super(); - - this.eltType = eltType; - this.inferred = false; - setContent = new HashSet<>(); - } - - /*package*/ SetWriter() { - super(); - this.eltType = TypeFactory.getInstance().voidType(); - this.inferred = true; - setContent = new HashSet<>(); - } - - private static void checkInsert(IValue elem, Type eltType) throws FactTypeUseException { - Type type = elem.getType(); - if (!type.isSubtypeOf(eltType)) { - throw new UnexpectedElementTypeException(eltType, type); - } - } - - private void put(IValue elem) { - updateType(elem); - checkInsert(elem, eltType); - setContent.add(elem); - } - - private void updateType(IValue elem) { - if (inferred) { - eltType = eltType.lub(elem.getType()); - } - } - - @Override - public void insert(IValue... elems) throws FactTypeUseException { - checkMutation(); - - for (IValue elem : elems) { - put(elem); - } - } - - @Override - public void insertAll(Iterable collection) throws FactTypeUseException { - checkMutation(); - - for (IValue v : collection) { - put(v); - } - } - - @Override - public ISet done() { - // Temporary fix of the static vs dynamic type issue - eltType = TypeFactory.getInstance().voidType(); - for(IValue el : setContent) - eltType = eltType.lub(el.getType()); - // --- - if (constructedSet == null) { - constructedSet = new Set(eltType, setContent); - } - - return constructedSet; - } - - private void checkMutation() { - if (constructedSet != null) - throw new UnsupportedOperationException("Mutation of a finalized set is not supported."); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/reference/Tuple.java b/value-core/src/main/java/org/rascalmpl/value/impl/reference/Tuple.java deleted file mode 100644 index 4a9796caf..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/reference/Tuple.java +++ /dev/null @@ -1,191 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007-2013 IBM Corporation & CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.impl.reference; - -import java.util.Iterator; - -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.impl.AbstractValue; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -class Tuple extends AbstractValue implements ITuple { - - protected final Type fType; - protected final IValue[] fElements; - - /*package*/ Tuple(IValue... elements) { - super(); - this.fType = TypeFactory.getInstance().tupleType(elements); - this.fElements = elements; - } - - private Tuple(Tuple other, int i, IValue elem) { - this.fType = other.getType(); - fElements = other.fElements.clone(); - fElements[i] = elem; - } - - @Override - public Type getType() { - return fType; - } - - @Override - public T accept(IValueVisitor v) throws E { - return v.visitTuple(this); - } - - @Override - public boolean isEqual(IValue other) { - return equals(other); - } - - /*package*/ Tuple(Type tupleType, IValue[] elems) { - super(); - this.fType = tupleType; - this.fElements = elems; - } - - @Override - public Iterator iterator() { - return new Iterator() { - private int count = 0; - - @Override - public boolean hasNext() { - return count < arity(); - } - - @Override - public IValue next() { - return get(count++); - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Can not remove elements from a tuple"); - } - }; - } - - @Override - public int hashCode() { - int hash = 0; - - for (int i = 0; i < fElements.length; i++) { - hash = (hash << 1) ^ (hash >> 1) ^ fElements[i].hashCode(); - } - return hash; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } else if (o == null) { - return false; - } else if (getClass() == o.getClass()) { - Tuple peer = (Tuple) o; - - if (!fType.comparable(peer.fType)) { - return false; - } - - int arity = arity(); - if (arity != peer.arity()) { - return false; - } - for (int i = 0; i < arity; i++) { - if (!get(i).equals(peer.get(i))) { - return false; - } - } - return true; - } - return false; - } - - @Override - public IValue get(int i) throws IndexOutOfBoundsException { - try { - return fElements[i]; - } catch (ArrayIndexOutOfBoundsException e) { - throw new IndexOutOfBoundsException("Tuple index " + i + " is larger than tuple width " + arity()); - } - } - - @Override - public IValue get(String label) throws FactTypeUseException { - return fElements[fType.getFieldIndex(label)]; - } - - @Override - public ITuple set(int i, IValue arg) throws IndexOutOfBoundsException { - return new Tuple(this, i, arg); - } - - @Override - public ITuple set(String label, IValue arg) throws FactTypeUseException { - int i = fType.getFieldIndex(label); - return new Tuple(this, i, arg); - } - - @Override - public int arity() { - return fElements.length; - } - - @Override - public IValue select(int... fields) throws IndexOutOfBoundsException { - Type type = fType.select(fields); - - if (type.isFixedWidth()) { - return doSelect(type, fields); - } - - return get(fields[0]); - } - - @Override - public IValue selectByFieldNames(String... fields) throws FactTypeUseException { - Type type = fType.select(fields); - - if (type.isFixedWidth()) { - int[] indexes = new int[fields.length]; - int i = 0; - for (String name : fields) { - indexes[i] = type.getFieldIndex(name); - } - - return doSelect(type, indexes); - } - - return get(fields[0]); - } - - private IValue doSelect(Type type, int... fields) throws IndexOutOfBoundsException { - if (fields.length == 1) - return get(fields[0]); - IValue[] elems = new IValue[fields.length]; - Type[] elemTypes = new Type[fields.length]; - for (int i = 0; i < fields.length; i++) { - elems[i] = get(fields[i]); - elemTypes[i] = elems[i].getType(); - } - return new Tuple(TypeFactory.getInstance().tupleType(elemTypes), elems); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/reference/ValueFactory.java b/value-core/src/main/java/org/rascalmpl/value/impl/reference/ValueFactory.java deleted file mode 100644 index 3dcc63668..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/reference/ValueFactory.java +++ /dev/null @@ -1,308 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007, 2008, 2012 IBM Corporation & CWI -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation -* Jurgen Vinju (jurgen@vinju.org) -* Anya Helene Bagge - rational support, labeled maps and tuples -*******************************************************************************/ - -package org.rascalmpl.value.impl.reference; - -import java.util.Objects; - -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.UnexpectedElementTypeException; -import org.rascalmpl.value.impl.primitive.AbstractPrimitiveValueFactory; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -/** - * This is a reference implementation for an @{link IValueFactory}. It uses - * the Java standard library to implement it in a most straightforward but - * not necessarily very efficient manner. - */ -public class ValueFactory extends AbstractPrimitiveValueFactory { - private static final ValueFactory sInstance = new ValueFactory(); - public static ValueFactory getInstance() { - return sInstance; - } - - protected ValueFactory() { - super(); - } - - protected static void checkNull(Object... args) { - for (Object a : args) { - Objects.requireNonNull(a); - } - } - - protected static void checkNull(java.util.Map args) { - for (java.util.Map.Entry entry : args.entrySet()) { - if (entry == null || entry.getKey() == null || entry.getValue() == null) { - throw new NullPointerException(); - } - } - } - - @Override - public ISet relation(Type tupleType) { - checkNull(tupleType); - return relationWriter(tupleType).done(); - } - - @Override - public ISet relation(IValue... tuples) { - checkNull((Object[]) tuples); - Type elementType = lub(tuples); - - if (!elementType.isFixedWidth()) { - TypeFactory tf = TypeFactory.getInstance(); - throw new UnexpectedElementTypeException(tf.tupleType(tf.voidType()), elementType); - } - - ISetWriter rw = setWriter(elementType); - rw.insert(tuples); - return rw.done(); - } - - @Override - public ISetWriter relationWriter(Type tupleType) { - checkNull(tupleType); - return new SetWriter(tupleType); - } - - @Override - public ISetWriter relationWriter() { - return new SetWriter(); - } - - @Override - public ISet set(Type eltType){ - checkNull(eltType); - return setWriter(eltType).done(); - } - - @Override - public ISetWriter setWriter(Type eltType) { - checkNull(eltType); - return new SetWriter(eltType); - } - - @Override - public ISetWriter setWriter() { - return new SetWriter(); - } - - @Override - public ISet set(IValue... elems) throws FactTypeUseException { - checkNull((Object[]) elems); - Type elementType = lub(elems); - - ISetWriter sw = setWriter(elementType); - sw.insert(elems); - return sw.done(); - } - - @Override - public IList list(Type eltType) { - checkNull(eltType); - return listWriter(eltType).done(); - } - - @Override - public IListWriter listWriter(Type eltType) { - checkNull(eltType); - return new ListWriter(eltType); - } - - @Override - public IListWriter listWriter() { - return new ListWriter(); - } - - @Override - public IList list(IValue... rest) { - checkNull((Object[]) rest); - Type eltType = lub(rest); - IListWriter lw = listWriter(eltType); - lw.append(rest); - return lw.done(); - } - - private Type lub(IValue... elems) { - checkNull((Object[]) elems); - Type elementType = TypeFactory.getInstance().voidType(); - for (IValue elem : elems) { - elementType = elementType.lub(elem.getType()); - } - return elementType; - } - - @Override - public ITuple tuple() { - return new Tuple(new IValue[0]); - } - - @Override - public ITuple tuple(IValue... args) { - checkNull((Object[]) args); - - return new Tuple(args.clone()); - } - - @Override - public ITuple tuple(Type type, IValue... args) { - checkNull((Object[]) args); - - return new Tuple(type, args.clone()); - } - - @Override - public INode node(String name) { - checkNull(name); - return new Node(name); - } - - @Override - public INode node(String name, java.util.Map annotations, IValue... children) { - checkNull(name); - checkNull(annotations); - checkNull((Object[]) children); - - return new Node(name, children).asAnnotatable().setAnnotations(annotations); - } - - @Override - public INode node(String name, IValue... children) { - checkNull(name); - checkNull((Object[]) children); - return new Node(name, children); - } - - @Override - public INode node(String name, IValue[] children, java.util.Map keyArgValues) - throws FactTypeUseException { - checkNull(name); - checkNull((Object[]) children); -// checkNull(keyArgValues); // fails; are null values allowed? - - return new Node(name, children.clone(), keyArgValues); - } - - @Override - public IConstructor constructor(Type constructorType, IValue... children) { - checkNull(constructorType); - checkNull((Object[]) children); - Type instantiatedType = inferInstantiatedTypeOfConstructor(constructorType, children); - return new Constructor(instantiatedType, children); - } - - @Override - public IConstructor constructor(Type constructorType, java.util.Map annotations, IValue... children) { - checkNull(constructorType); - checkNull(annotations); - checkNull((Object[]) children); - - return new Constructor(constructorType, children).asAnnotatable().setAnnotations(annotations); - } - - @Override - public IConstructor constructor(Type constructorType, IValue[] children, java.util.Map kwParams) { - checkNull(constructorType); - checkNull(kwParams); - checkNull((Object[]) children); - - return new Constructor(constructorType, children, kwParams); - } - - @Override - public IConstructor constructor(Type constructorType) { - checkNull(constructorType); - Type instantiatedType = inferInstantiatedTypeOfConstructor(constructorType, new IValue[0]); - return new Constructor(instantiatedType); - } - - @Override - public IMap map(Type keyType, Type valueType) { - checkNull(keyType); - checkNull(valueType); - return mapWriter(keyType, valueType).done(); - } - - @Override - public IMap map(Type mapType) { - checkNull(mapType); - return mapWriter(mapType).done(); - } - @Override - public IMapWriter mapWriter(Type keyType, Type valueType) { - checkNull(keyType); - checkNull(valueType); - return new MapWriter(TypeFactory.getInstance().mapType(keyType, valueType)); - } - - @Override - public IMapWriter mapWriter(Type mapType) { - checkNull(mapType); - return new MapWriter(mapType); - } - - @Override - public IMapWriter mapWriter() { - return new MapWriter(); - } - - @Override - public IListWriter listRelationWriter(Type tupleType) { - checkNull(tupleType); - return new ListWriter(tupleType); - } - - @Override - public IListWriter listRelationWriter() { - return new ListWriter(); - } - - @Override - public IList listRelation(Type tupleType) { - checkNull(tupleType); - return listWriter(tupleType).done(); - } - - @Override - public IList listRelation(IValue... tuples) { - checkNull((Object[]) tuples); - Type elementType = lub(tuples); - - if (!elementType.isFixedWidth()) { - TypeFactory tf = TypeFactory.getInstance(); - throw new UnexpectedElementTypeException(tf.tupleType(tf.voidType()), elementType); - } - - IListWriter rw = listRelationWriter(elementType); - rw.append(tuples); - return rw.done(); - } - - @Override - public String toString() { - return "VF_PDB_REFERENCE"; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/util/BigDecimalCalculations.java b/value-core/src/main/java/org/rascalmpl/value/impl/util/BigDecimalCalculations.java deleted file mode 100644 index 2685475f1..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/util/BigDecimalCalculations.java +++ /dev/null @@ -1,539 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2011 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Davy Landman - wrote and imported functions for calculating various math operations -*******************************************************************************/ - -package org.rascalmpl.value.impl.util; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.math.MathContext; -import java.math.RoundingMode; - - - -public class BigDecimalCalculations { - /** - * pi in 1000 decimals places - */ - public static final BigDecimal PI = new BigDecimal( - "3.141592653589793238462643383279502884197169399375105820974944592307" + - "81640628620899862803482534211706798214808651328230664709384460955058" + - "22317253594081284811174502841027019385211055596446229489549303819644" + - "28810975665933446128475648233786783165271201909145648566923460348610" + - "45432664821339360726024914127372458700660631558817488152092096282925" + - "40917153643678925903600113305305488204665213841469519415116094330572" + - "70365759591953092186117381932611793105118548074462379962749567351885" + - "75272489122793818301194912983367336244065664308602139494639522473719" + - "07021798609437027705392171762931767523846748184676694051320005681271" + - "45263560827785771342757789609173637178721468440901224953430146549585" + - "37105079227968925892354201995611212902196086403441815981362977477130" + - "99605187072113499999983729780499510597317328160963185950244594553469" + - "08302642522308253344685035261931188171010003137838752886587533208381" + - "42061717766914730359825349042875546873115956286388235378759375195778" + - "18577805321712268066130019278766111959092164201988") ; - - public static final BigDecimal halfPI = PI.divide(new BigDecimal(2)); - public static final BigDecimal twoPI = PI.multiply(new BigDecimal(2)); - - /** - * e in 1000 decimals places - */ - public static final BigDecimal E = new BigDecimal( - "2.718281828459045235360287471352662497757247093699959574966967627724" + - "07663035354759457138217852516642742746639193200305992181741359662904" + - "35729003342952605956307381323286279434907632338298807531952510190115" + - "73834187930702154089149934884167509244761460668082264800168477411853" + - "74234544243710753907774499206955170276183860626133138458300075204493" + - "38265602976067371132007093287091274437470472306969772093101416928368" + - "19025515108657463772111252389784425056953696770785449969967946864454" + - "90598793163688923009879312773617821542499922957635148220826989519366" + - "80331825288693984964651058209392398294887933203625094431173012381970" + - "68416140397019837679320683282376464804295311802328782509819455815301" + - "75671736133206981125099618188159304169035159888851934580727386673858" + - "94228792284998920868058257492796104841984443634632449684875602336248" + - "27041978623209002160990235304369941849146314093431738143640546253152" + - "09618369088870701676839642437814059271456354906130310720851038375051" + - "011574770417189861068739696552126715468895703503540"); - - /** - * above 500 (/below -500) the approximation slows down more than the normalisation costs. - * So we normalize first - */ - private static final BigDecimal sincosNormalizePoint = BigDecimal.valueOf(500); - - private static BigInteger maxBigDecimalPowExp = BigInteger.valueOf(999999999); // maximum exponent for BigDecimal.pow - - - /** - * Compute the sine of x to a given scale - * @param x - * the value of x - * @param - * scale the desired scale of the result - * @return the result value - */ - public static BigDecimal sin(BigDecimal x, int scale) - { - if (x.signum() == 0) - return BigDecimal.ZERO; - if (x.abs().compareTo(sincosNormalizePoint) >= 0 ) { - x = x.remainder(twoPI, new MathContext(scale + 1)); - } - if (x.signum() == -1) - return sinTaylor(x.negate(), scale).negate(); - else - return sinTaylor(x, scale); - } - - - private static BigDecimal calculateConvergenceTolerance(int scale) { - return BigDecimal.valueOf(5).movePointLeft(scale + 1); - } - - // code based on arctanTaylor by Ronald Mak - private static BigDecimal sinTaylor(BigDecimal x, int scale) - { - int sp1 = scale + 1; - int i = 3; - boolean addFlag = false; - - BigDecimal power = x; - BigDecimal result = x; - BigDecimal fac = new BigDecimal(2*3); - BigDecimal term; - - BigDecimal tolerance = calculateConvergenceTolerance(scale); - - // Loop until the approximations converge - // (two successive approximations are within the tolerance). - do { - // x^i - power = power.multiply(x).multiply(x).setScale(sp1, BigDecimal.ROUND_HALF_EVEN); - // (x^i)/(i!) - term = power.divide(fac, sp1,BigDecimal.ROUND_HALF_EVEN); - // result = result +- (x^i)/(i!) - result = addFlag ? result.add(term) : result.subtract(term); - - // state for next round - i += 2; - fac = fac.multiply(BigDecimal.valueOf(i - 1)).multiply(BigDecimal.valueOf(i)); - addFlag = !addFlag; - - } while (term.compareTo(tolerance) > 0); - - return result; - } - - /** - * Compute the cosine of x to a given scale - * @param x the value of x - * @param scale the desired scale of the result - * @return the result value - */ - public static BigDecimal cos(BigDecimal x, int scale) - { - if (x.signum() == 0) - return BigDecimal.ONE; - if (x.abs().compareTo(sincosNormalizePoint) >= 0 ) { - x = x.remainder(twoPI, new MathContext(scale + 1)); - } - if (x.signum() == -1) - return cosTaylor(x.negate(), scale); - else - return cosTaylor(x, scale); - } - - // code based on arctanTaylor by Ronald Mak - // same as sin but without the x starting point and +1 in faculty - private static BigDecimal cosTaylor(BigDecimal x, int scale) - { - int sp1 = scale + 1; - int i = 2; - boolean addFlag = false; - - BigDecimal power = BigDecimal.ONE; - BigDecimal result = BigDecimal.ONE; - BigDecimal fac = new BigDecimal(2); - BigDecimal term; - - BigDecimal tolerance = calculateConvergenceTolerance(scale); - - // Loop until the approximations converge - // (two successive approximations are within the tolerance). - do { - // x^i - power = power.multiply(x).multiply(x).setScale(sp1, BigDecimal.ROUND_HALF_EVEN); - // (x^i)/(i!) - term = power.divide(fac, sp1, BigDecimal.ROUND_HALF_EVEN); - // result = result +- (x^i)/(i!) - result = addFlag ? result.add(term) : result.subtract(term); - - // prepare state for next loop - i += 2; - fac = fac.multiply(BigDecimal.valueOf(i -1)).multiply(BigDecimal.valueOf(i)); - addFlag = !addFlag; - - } while (term.compareTo(tolerance) > 0); - return result; - } - - - /** - * Compute the tangent of x to a given scale, |x| < pi/2 - * - * @param x - * the value of x - * @param scale - * the desired scale of the result - * @return the result value - */ - public static BigDecimal tan(BigDecimal x, int scale) { - if (x.signum() == 0) - return BigDecimal.ZERO; - if (x.abs().compareTo(halfPI) > 0) - throw new ArithmeticException("x should be between -(pi/2) and (pi/2)"); - // easiest implementation of tan (no need for Bernoulli numbers) but this is slower than the other 2 - return sin(x, scale + 1).divide(cos(x, scale + 1), scale, RoundingMode.HALF_UP); - } - - - /** - * Compute x^exponent to a given scale. - * - * @param x - * the value x - * @param exponent - * the exponent value - * @param scale - * the desired scale of the result - * @return the result value - */ - private static BigDecimal intPower(BigDecimal x, BigInteger exponent, int scale) { - boolean negativeExponent = exponent.signum() == -1; - - if (negativeExponent) { - exponent = exponent.negate(); - } - - if (exponent.equals(BigInteger.ZERO)) { - return BigDecimal.ONE.setScale(scale); - } - - MathContext mc = new MathContext(scale, RoundingMode.HALF_EVEN); - - if (exponent.equals(BigInteger.ONE)) { - if (negativeExponent) { - return BigDecimal.ONE.divide(x, mc); - } - return x.setScale(scale, BigDecimal.ROUND_HALF_EVEN); - } - - BigDecimal result = BigDecimal.valueOf(1); - - if (exponent.compareTo(maxBigDecimalPowExp) >= 0) { - BigDecimal maxExpPow = x.pow(maxBigDecimalPowExp.intValue(), mc); - while (exponent.compareTo(maxBigDecimalPowExp) >= 0) { - result = result.multiply(maxExpPow); - exponent = exponent.subtract(maxBigDecimalPowExp); - } - } - - result = result.multiply(x.pow(exponent.intValue(), mc)); - - if (negativeExponent) { - return BigDecimal.ONE.divide(result, mc); - } - - return result.setScale(scale, RoundingMode.HALF_EVEN); - } - - /** - * The functions below this line are based on the Numerical implementations of - * Java Number Cruncher: The Java Programmer's Guide - * to Numerical Computing - * by Ronald Mak - * - * He has shared the code in the book at the following page: - * http://authors.phptr.com/mak/downloads.html - * - * And has put the source in the public domain: - * "I wrote all these programs strictly as - * illustrative examples for my book. - * You're free to use the source code any - * way you like, but bear in mind that this is - * NOT fully tested, commercial-quality code. - * Neither Prentice Hall PTR nor I can be - * responsible for anything bad that may happen - * if you use these programs." - * - * The only changes were the removal of call to Thread.yield(), switching to - * and formatting improvements - */ - - /** - * Compute the integral root of x to a given scale, x >= 0. Use Newton's - * algorithm. - * - * @param x - * the value of x - * @param index - * the integral root value - * @param scale - * the desired scale of the result - * @return the result value - */ - public static BigDecimal intRoot(BigDecimal x, BigInteger index, int scale) { - // Check that x >= 0. - if (x.signum() < 0) { - throw new ArithmeticException("x < 0"); - } - - int sp1 = scale + 1; - BigDecimal n = x; - BigDecimal i = new BigDecimal(index); - BigDecimal im1 = i.subtract(BigDecimal.ONE); - BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1); - BigDecimal xPrev; - BigInteger indexm1 = index.subtract(BigInteger.ONE); - - // The initial approximation is x/index. - x = x.divide(i, scale, BigDecimal.ROUND_HALF_EVEN); - - // Loop until the approximations converge - // (two successive approximations are equal after rounding). - do { - // x^(index-1) - BigDecimal xToIm1 = intPower(x, indexm1, sp1 + 1); - // x^index - BigDecimal xToI = x.multiply(xToIm1); - // n + (index-1)*(x^index) - BigDecimal numerator = n.add(im1.multiply(xToI)); - // (index*(x^(index-1)) - BigDecimal denominator = i.multiply(xToIm1); - // x = (n + (index-1)*(x^index)) / (index*(x^(index-1))) - xPrev = x; - if (denominator.compareTo(BigDecimal.ZERO) == 0) { - x = BigDecimal.ZERO.setScale(sp1); - } - else { - x = numerator.divide(denominator, sp1, BigDecimal.ROUND_DOWN); - } - - } while (x.subtract(xPrev).abs().compareTo(tolerance) > 0); - - return x.setScale(scale, RoundingMode.HALF_EVEN); - } - - /** - * Compute e^x to a given scale. Break x into its whole and fraction parts - * and compute (e^(1 + fraction/whole))^whole using Taylor's formula. - * - * @param x - * the value of x - * @param scale - * the desired scale of the result - * @return the result value - */ - public static BigDecimal exp(BigDecimal x, int scale) { - // e^0 = 1 - if (x.signum() == 0) { - return BigDecimal.valueOf(1); - } - - boolean isNegative = x.signum() == -1; - - if (isNegative) { - x = x.negate(); - } - - // Compute the whole part of x. - BigDecimal xWhole = x.setScale(0, BigDecimal.ROUND_DOWN); - - BigDecimal result; - - // If there isn't a whole part, compute and return e^x. - if (xWhole.signum() == 0) { - result = expTaylor(x, scale); - } - else { - // Compute the fraction part of x. - BigDecimal xFraction = x.subtract(xWhole); - - // z = 1 + fraction/whole - BigDecimal z = BigDecimal.valueOf(1).add( - xFraction.divide(xWhole, scale, BigDecimal.ROUND_HALF_EVEN)); - - // t = e^z - BigDecimal t = expTaylor(z, scale); - - result = intPower(t, xWhole.toBigInteger(), scale); - } - - if (isNegative) { - return BigDecimal.ONE.divide(result, new MathContext(scale, RoundingMode.HALF_EVEN)); - } - - return result; - } - - /** - * Compute e^x to a given scale by the Taylor series. - * - * @param x - * the value of x - * @param scale - * the desired scale of the result - * @return the result value - */ - private static BigDecimal expTaylor(BigDecimal x, int scale) { - BigDecimal factorial = BigDecimal.valueOf(1); - BigDecimal xPower = x; - BigDecimal sumPrev; - - // 1 + x - BigDecimal sum = x.add(BigDecimal.valueOf(1)); - // Loop until the sums converge - // (two successive sums are equal after rounding). - int i = 2; - do { - // x^i - xPower = xPower.multiply(x).setScale(scale, BigDecimal.ROUND_HALF_EVEN); - // i! - factorial = factorial.multiply(BigDecimal.valueOf(i)); - // x^i/i! - BigDecimal term = xPower.divide(factorial, scale, BigDecimal.ROUND_HALF_EVEN); - // sum = sum + x^i/i! - sumPrev = sum; - sum = sum.add(term); - - ++i; - } while (sum.compareTo(sumPrev) != 0); - - return sum; - } - - /** - * Compute the natural logarithm of x to a given scale, x > 0. - * @param x - * the value of x - * @param scale - * the desired scale of the result - * @return - * the natural logarithm of x - */ - public static BigDecimal ln(BigDecimal x, int scale) { - // Check that x > 0. - if (x.signum() <= 0) { - throw new ArithmeticException("x <= 0"); - } - // The number of digits to the left of the decimal point. - int magnitude = x.toString().length() - x.scale() - 1; - if (magnitude < 3) { - return lnNewton(x, scale); - } - // Compute magnitude*ln(x^(1/magnitude)). - else { - // x^(1/magnitude) - BigDecimal root = intRoot(x, BigInteger.valueOf(magnitude), scale); - // ln(x^(1/magnitude)) - BigDecimal lnRoot = lnNewton(root, scale); - // magnitude*ln(x^(1/magnitude)) - return BigDecimal.valueOf(magnitude).multiply(lnRoot) - .setScale(scale, BigDecimal.ROUND_HALF_EVEN); - } - } - - /** - * Compute the natural logarithm of x to a given scale, x > 0. Use Newton's - * algorithm. - */ - private static BigDecimal lnNewton(BigDecimal x, int scale) { - int sp1 = scale + 1; - BigDecimal n = x; - BigDecimal term; - - // Convergence tolerance = 5*(10^-(scale+1)) - BigDecimal tolerance = BigDecimal.valueOf(5).movePointLeft(sp1); - // Loop until the approximations converge - // (two successive approximations are within the tolerance). - do { - // e^x - BigDecimal eToX = exp(x, sp1); - // (e^x - n)/e^x - if (eToX.compareTo(BigDecimal.ZERO) == 0) { - break; - } - term = eToX.subtract(n).divide(eToX, sp1, BigDecimal.ROUND_DOWN); - // x - (e^x - n)/e^x - x = x.subtract(term); - - } while (term.compareTo(tolerance) > 0); - - return x.setScale(scale, BigDecimal.ROUND_HALF_EVEN); - } - - /** - * Compute the square root of x to a given scale, x >= 0. Use Newton's - * algorithm. - * - * @param x - * the value of x - * @param scale - * the desired scale of the result - * @return the result value - */ - public static BigDecimal sqrt(BigDecimal x, int scale) { - // Check that x >= 0. - if (x.signum() < 0) { - throw new ArithmeticException("x < 0"); - } - if (x.signum()==0) { - return BigDecimal.ZERO.setScale(scale); - } - - // n = x*(10^(2*scale)) - BigInteger n = x.movePointRight(scale << 1).toBigInteger(); - - // The first approximation is the upper half of n. - int bits = (n.bitLength() + 1) >> 1; - BigInteger ix = n.shiftRight(bits); - BigInteger ixPrev; - - // Loop until the approximations converge - // (two successive approximations are equal after rounding). - do { - ixPrev = ix; - // x = (x + n/x)/2 - ix = ix.add(n.divide(ix)).shiftRight(1); - - } while (ix.compareTo(ixPrev) != 0); - - return new BigDecimal(ix, scale); - } - - public static BigDecimal pow(BigDecimal a, BigDecimal b, int scale) { - if (a.signum() == -1) { - throw new ArithmeticException("x < 0"); - } - if (a.equals(BigDecimal.ZERO)) { - return BigDecimal.ZERO; - } - scale = Math.max(Math.max(a.precision(), b.precision()), scale) + 1; - MathContext mc = new MathContext(scale, RoundingMode.HALF_UP); - BigDecimal remainer = b.remainder(BigDecimal.ONE, mc); - if (remainer.equals(BigDecimal.ZERO)) { - return a.pow(b.intValue(), mc); - } - // else we have to do the more expansive route: - // a^b=exp(b*ln(a)) - return exp(b.multiply(ln(a, scale), mc), scale).setScale(scale - 1, RoundingMode.HALF_EVEN); - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesHashMap.java b/value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesHashMap.java deleted file mode 100644 index 846cd4aef..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesHashMap.java +++ /dev/null @@ -1,570 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.impl.util.collections; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.util.ShareableHashSet; - -/** - * A specialized version of the ShareableHashMap, specifically meant for storing values. - * - * @author Arnold Lankamp - */ -public final class ShareableValuesHashMap implements Map{ - private final static int INITIAL_LOG_SIZE = 4; - - private int modSize; - private int hashMask; - - private Entry[] data; // protected for easier access in inner class - - private int threshold; - - private int load; - - private int currentHashCode; - - @SuppressWarnings("unchecked") - public ShareableValuesHashMap(){ - super(); - - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - - currentHashCode = 0; - } - - public ShareableValuesHashMap(ShareableValuesHashMap shareableValuesHashMap){ - super(); - - modSize = shareableValuesHashMap.modSize; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = shareableValuesHashMap.data.clone(); - - threshold = tableSize; - - load = shareableValuesHashMap.load; - - currentHashCode = shareableValuesHashMap.currentHashCode; - } - - @SuppressWarnings("unchecked") - public void clear(){ - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - - currentHashCode = 0; - } - - @SuppressWarnings("unchecked") - private void rehash(){ - modSize++; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - Entry[] newData = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - Entry[] oldData = data; - for(int i = oldData.length - 1; i >= 0; i--){ - Entry entry = oldData[i]; - - if(entry != null){ - // Determine the last unchanged entry chain. - Entry lastUnchangedEntryChain = entry; - int newLastUnchangedEntryChainIndex = entry.hash & hashMask; - - Entry e = entry.next; - while(e != null){ - int newIndex = e.hash & hashMask; - if(newIndex != newLastUnchangedEntryChainIndex){ - lastUnchangedEntryChain = e; - newLastUnchangedEntryChainIndex = newIndex; - } - - e = e.next; - } - - newData[newLastUnchangedEntryChainIndex] = lastUnchangedEntryChain; - - // Reconstruct the other entries (if necessary). - while(entry != lastUnchangedEntryChain){ - int hash = entry.hash; - int position = hash & hashMask; - newData[position] = new Entry<>(hash, entry.key, entry.value, newData[position]); - - entry = entry.next; - } - } - } - - data = newData; - } - - private void ensureCapacity(){ - if(load > threshold){ - rehash(); - } - } - - private void replaceValue(int position, Entry entry, IValue newValue){ - Entry e = data[position]; - - // Reconstruct the updated entry. - data[position] = new Entry<>(entry.hash, entry.key, newValue, entry.next); - - // Reconstruct the other entries (if necessary). - while(e != entry){ - data[position] = new Entry<>(e.hash, e.key, e.value, data[position]); - - e = e.next; - } - } - - public IValue put(IValue key, IValue value){ - ensureCapacity(); - - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry currentStartEntry = data[position]; - // Check if the key is already in here. - if(currentStartEntry != null){ - Entry entry = currentStartEntry; - do{ - if(hash == entry.hash && entry.key.isEqual(key)){ // Replace if present. - replaceValue(position, entry, value); - - return entry.value; // Return the old value. - } - - entry = entry.next; - }while(entry != null); - } - - data[position] = new Entry<>(hash, key, value, currentStartEntry); // Insert the new entry. - - load++; - - currentHashCode ^= hash; // Update the current hashcode of this map. - - return null; - } - - public IValue remove(Object object){ - IValue key = (IValue) object; - - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry currentStartEntry = data[position]; - if(currentStartEntry != null){ - Entry entry = currentStartEntry; - do{ - if(hash == entry.hash && entry.key.isEqual(key)){ - Entry e = data[position]; - - data[position] = entry.next; - // Reconstruct the other entries (if necessary). - while(e != entry){ - data[position] = new Entry<>(e.hash, e.key, e.value, data[position]); - - e = e.next; - } - - load--; - - currentHashCode ^= hash; // Update the current hashcode of this map. - - return entry.value; // Return the value. - } - - entry = entry.next; - }while(entry != null); - } - - return null; // Not found. - } - - public IValue get(Object object){ - IValue key = (IValue) object; - - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && key.isEqual(entry.key)) return entry.value; - - entry = entry.next; - } - - return null; - } - - public boolean contains(IValue key){ - return (get(key) != null); - } - - public int size(){ - return load; - } - - public boolean isEmpty(){ - return (load == 0); - } - - public Iterator> entryIterator(){ - return new EntryIterator(data); - } - - public Iterator keysIterator(){ - return new KeysIterator(data); - } - - public Iterator valuesIterator(){ - return new ValuesIterator(data); - } - - @SuppressWarnings("unchecked") - public void putAll(Map otherMap){ - Set> entrySet = (Set>) (Set) otherMap.entrySet(); // Generics stink. - Iterator> entrySetIterator = entrySet.iterator(); - while(entrySetIterator.hasNext()){ - Map.Entry next = entrySetIterator.next(); - put(next.getKey(), next.getValue()); - } - } - - public boolean containsKey(Object object){ - IValue key = (IValue) object; - - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && key.isEqual(entry.key)) return true; - - entry = entry.next; - } - - return false; - } - - public boolean containsValue(Object object){ - IValue value = (IValue) object; - - Iterator valuesIterator = valuesIterator(); - while(valuesIterator.hasNext()){ - IValue nextValue = valuesIterator.next(); - if(nextValue == value || (nextValue != null && nextValue.isEqual(value))){ - return true; - } - } - - return false; - } - - public Set> entrySet(){ - ShareableHashSet> entrySet = new ShareableHashSet<>(); - - Iterator> entriesIterator = entryIterator(); - while(entriesIterator.hasNext()){ - entrySet.add(entriesIterator.next()); - } - - return entrySet; - } - - public Set keySet(){ - ShareableHashSet keysSet = new ShareableHashSet<>(); - - Iterator keysIterator = keysIterator(); - while(keysIterator.hasNext()){ - keysSet.add(keysIterator.next()); - } - - return keysSet; - } - - public Collection values(){ - ShareableHashSet valuesSet = new ShareableHashSet<>(); - - Iterator valuesIterator = valuesIterator(); - while(valuesIterator.hasNext()){ - valuesSet.add(valuesIterator.next()); - } - - return valuesSet; - } - - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('{'); - for(int i = 0; i < data.length; i++){ - buffer.append('['); - Entry e = data[i]; - if(e != null){ - buffer.append(e); - - e = e.next; - - while(e != null){ - buffer.append(','); - buffer.append(e); - - e = e.next; - } - } - buffer.append(']'); - } - buffer.append('}'); - - return buffer.toString(); - } - - public int hashCode(){ - return currentHashCode; - } - - public boolean isEqual(ShareableValuesHashMap other){ - if(other == null) { - return false; - } - if(other.currentHashCode != currentHashCode) { - return false; - } - if(other.size() != size()) { - return false; - } - if(isEmpty()) { - return true; // No need to check if the maps are empty. - } - - Iterator> otherIterator = other.entryIterator(); - while (otherIterator.hasNext()) { - Map.Entry entry = otherIterator.next(); - IValue otherValue = entry.getValue(); - IValue thisValue = get(entry.getKey()); - - if (thisValue == null) { - // Means the key from other is not present in this - return false; - } - - if(otherValue != thisValue - && !thisValue.isEqual(otherValue)) { - return false; - } - } - - return true; - } - - private IValue getTruelyEqual(IValue key){ - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && key.equals(entry.key)) return entry.value; - - entry = entry.next; - } - - return null; - } - - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - ShareableValuesHashMap other = (ShareableValuesHashMap) o; - - if(other.currentHashCode != currentHashCode) return false; - if(other.size() != size()) return false; - - if(isEmpty()) return true; // No need to check if the maps are empty. - - Iterator> otherIterator = other.entryIterator(); - while(otherIterator.hasNext()){ - Map.Entry entry = otherIterator.next(); - IValue otherValue = entry.getValue(); - IValue thisValue = getTruelyEqual(entry.getKey()); - - if(otherValue != thisValue && (thisValue == null || !thisValue.equals(otherValue))) return false; - } - return true; - } - - return false; - } - - private static class Entry implements Map.Entry{ - public final int hash; - public final K key; - public final V value; - - public final Entry next; - - public Entry(int hash, K key, V value, Entry next){ - super(); - - this.hash = hash; - this.key = key; - this.value = value; - - this.next = next; - } - - public K getKey(){ - return key; - } - - public V getValue(){ - return value; - } - - public V setValue(V value){ - throw new UnsupportedOperationException("The setting of values is not supported by this map implementation."); - } - - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('<'); - buffer.append(key); - buffer.append(':'); - buffer.append(value); - buffer.append('>'); - - return buffer.toString(); - } - } - - private static class EntryIterator implements Iterator>{ - private final Entry[] data; - - private Entry current; - private int index; - - public EntryIterator(Entry[] entries){ - super(); - - data = entries; - - index = data.length - 1; - current = new Entry<>(0, null, null, data[index]); - locateNext(); - } - - private void locateNext(){ - Entry next = current.next; - if(next != null){ - current = next; - return; - } - - for(int i = index - 1; i >= 0 ; i--){ - Entry entry = data[i]; - if(entry != null){ - current = entry; - index = i; - return; - } - } - - current = null; - index = 0; - } - - public boolean hasNext(){ - return (current != null); - } - - public Entry next(){ - if(!hasNext()) throw new UnsupportedOperationException("There are no more elements in this iterator."); - - Entry entry = current; - locateNext(); - - return entry; - } - - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } - - private static class KeysIterator implements Iterator{ - private final EntryIterator entryIterator; - - public KeysIterator(Entry[] entries){ - super(); - - entryIterator = new EntryIterator(entries); - } - - public boolean hasNext(){ - return entryIterator.hasNext(); - } - - public IValue next(){ - return entryIterator.next().key; - } - - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } - - private static class ValuesIterator implements Iterator{ - private final EntryIterator entryIterator; - - public ValuesIterator(Entry[] entries){ - super(); - - entryIterator = new EntryIterator(entries); - } - - public boolean hasNext(){ - return entryIterator.hasNext(); - } - - public IValue next(){ - return entryIterator.next().value; - } - - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesHashSet.java b/value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesHashSet.java deleted file mode 100644 index d7afe1aa4..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesHashSet.java +++ /dev/null @@ -1,462 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.impl.util.collections; - -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Set; - -import org.rascalmpl.value.IValue; - -/** - * A specialized version of the ShareableSet, specifically meant for storing values. - * - * @author Arnold Lankamp - */ -public final class ShareableValuesHashSet implements Set, Iterable{ - private final static int INITIAL_LOG_SIZE = 4; - - private int modSize; - private int hashMask; - - private Entry[] data; - - private int threshold; - - private int load; - - private int currentHashCode; - - @SuppressWarnings("unchecked") - public ShareableValuesHashSet(){ - super(); - - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - - currentHashCode = 0; - } - - public ShareableValuesHashSet(ShareableValuesHashSet shareableValuesHashSet){ - super(); - - modSize = shareableValuesHashSet.modSize; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = shareableValuesHashSet.data.clone(); - - threshold = tableSize; - - load = shareableValuesHashSet.load; - - currentHashCode = shareableValuesHashSet.currentHashCode; - } - - @SuppressWarnings("unchecked") - public void clear(){ - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - - currentHashCode = 0; - } - - @SuppressWarnings("unchecked") - private void rehash(){ - modSize++; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - Entry[] newData = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - Entry[] oldData = data; - for(int i = oldData.length - 1; i >= 0; i--){ - Entry entry = oldData[i]; - - if(entry != null){ - // Determine the last unchanged entry chain. - Entry lastUnchangedEntryChain = entry; - int newLastUnchangedEntryChainIndex = entry.hash & hashMask; - - Entry e = entry.next; - while(e != null){ - int newIndex = e.hash & hashMask; - if(newIndex != newLastUnchangedEntryChainIndex){ - lastUnchangedEntryChain = e; - newLastUnchangedEntryChainIndex = newIndex; - } - - e = e.next; - } - - newData[newLastUnchangedEntryChainIndex] = lastUnchangedEntryChain; - - // Reconstruct the other entries (if necessary). - while(entry != lastUnchangedEntryChain){ - int hash = entry.hash; - int position = hash & hashMask; - newData[position] = new Entry<>(hash, entry.value, newData[position]); - - entry = entry.next; - } - } - } - - data = newData; - } - - private void ensureCapacity(){ - if(load > threshold){ - rehash(); - } - } - - public boolean add(IValue value){ - ensureCapacity(); - - int hash = value.hashCode(); - int position = hash & hashMask; - - Entry currentStartEntry = data[position]; - // Check if the value is already in here. - if(currentStartEntry != null){ - Entry entry = currentStartEntry; - do{ - if(hash == entry.hash && entry.value.isEqual(value)){ - return false; // Return false if it's already present. - } - - entry = entry.next; - }while(entry != null); - } - - data[position] = new Entry<>(hash, value, currentStartEntry); // Insert the new entry. - - load++; - - currentHashCode ^= hash; // Update the current hashcode of this map. - - return true; - } - - public boolean contains(Object object){ - IValue value = (IValue) object; - - int hash = value.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && value.isEqual(entry.value)) return true; - - entry = entry.next; - } - - return false; - } - - public boolean remove(Object object){ - IValue value = (IValue) object; - - int hash = value.hashCode(); - int position = hash & hashMask; - - Entry currentStartEntry = data[position]; - if(currentStartEntry != null){ - Entry entry = currentStartEntry; - do{ - if(hash == entry.hash && entry.value.isEqual(value)){ - Entry e = data[position]; - - data[position] = entry.next; - // Reconstruct the other entries (if necessary). - while(e != entry){ - data[position] = new Entry<>(e.hash, e.value, data[position]); - - e = e.next; - } - - load--; - - currentHashCode ^= hash; // Update the current hashcode of this set. - - return true; - } - - entry = entry.next; - }while(entry != null); - } - - return false; - } - - public int size(){ - return load; - } - - public boolean isEmpty(){ - return (load == 0); - } - - public Iterator iterator(){ - return new SetIterator(data); - } - - public boolean addAll(Collection collection){ - boolean changed = false; - - Iterator collectionIterator = collection.iterator(); - while(collectionIterator.hasNext()){ - changed |= add(collectionIterator.next()); - } - - return changed; - } - - public boolean containsAll(Collection collection){ - Iterator collectionIterator = collection.iterator(); - while(collectionIterator.hasNext()){ - if(!contains(collectionIterator.next())) return false; - } - - return true; - } - - public boolean retainAll(Collection collection){ - boolean changed = false; - - Iterator valuesIterator = iterator(); - while(valuesIterator.hasNext()){ - IValue value = valuesIterator.next(); - if(!collection.contains(value)){ - remove(value); - - changed = true; - } - } - - return changed; - } - - public boolean removeAll(Collection collection){ - boolean changed = false; - - Iterator collectionIterator = collection.iterator(); - while(collectionIterator.hasNext()){ - Object value = collectionIterator.next(); - changed |= remove(value); - } - - return changed; - } - - public Object[] toArray(){ - Object[] values = new Object[load]; - - Iterator valuesIterator = iterator(); - int i = 0; - while(valuesIterator.hasNext()){ - values[i++] = valuesIterator.next(); - } - - return values; - } - - @SuppressWarnings("unchecked") - public T[] toArray(T[] array){ - if(array.length < load) return (T[]) toArray(); - - Iterator valuesIterator = iterator(); - int i = 0; - while(valuesIterator.hasNext()){ - array[i++] = (T) valuesIterator.next(); - } - - for(; i < load; i++){ - array[i] = null; - } - - return array; - } - - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('{'); - for(int i = 0; i < data.length; i++){ - buffer.append('['); - Entry e = data[i]; - if(e != null){ - buffer.append(e); - - e = e.next; - - while(e != null){ - buffer.append(','); - buffer.append(e); - - e = e.next; - } - } - buffer.append(']'); - } - buffer.append('}'); - - return buffer.toString(); - } - - public int hashCode(){ - return currentHashCode; - } - - public boolean isEqual(ShareableValuesHashSet other){ - if(other == null) return false; - - if(other.currentHashCode != currentHashCode) return false; - if(other.size() != size()) return false; - - if(isEmpty()) return true; // No need to check if the sets are empty. - - Iterator otherIterator = other.iterator(); - while(otherIterator.hasNext()){ - if(!contains(otherIterator.next())) return false; - } - return true; - } - - private boolean containsTruelyEqual(IValue value){ - int hash = value.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && value.equals(entry.value)) return true; - - entry = entry.next; - } - - return false; - } - - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - ShareableValuesHashSet other = (ShareableValuesHashSet) o; - - if(other.currentHashCode != currentHashCode) return false; - if(other.size() != size()) return false; - - if(isEmpty()) return true; // No need to check if the sets are empty. - - Iterator otherIterator = other.iterator(); - while(otherIterator.hasNext()){ - if(!containsTruelyEqual(otherIterator.next())) return false; - } - return true; - } - - return false; - } - - private static class Entry{ - public final int hash; - public final V value; - - public final Entry next; - - public Entry(int hash, V value, Entry next){ - super(); - - this.hash = hash; - this.value = value; - - this.next = next; - } - - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('<'); - buffer.append(value); - buffer.append('>'); - - return buffer.toString(); - } - } - - private static class SetIterator implements Iterator{ - private final Entry[] data; - - private Entry current; - private int index; - - public SetIterator(Entry[] entries){ - super(); - - data = entries; - - index = data.length - 1; - current = new Entry<>(0, null, data[index]); - locateNext(); - } - - private void locateNext(){ - Entry next = current.next; - if(next != null){ - current = next; - return; - } - - for(int i = index - 1; i >= 0 ; i--){ - Entry entry = data[i]; - if(entry != null){ - current = entry; - index = i; - return; - } - } - - current = null; - index = 0; - } - - public boolean hasNext(){ - return (current != null); - } - - public IValue next(){ - if(!hasNext()) throw new NoSuchElementException("There are no more elements in this iteration"); - - IValue value = current.value; - locateNext(); - - return value; - } - - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesList.java b/value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesList.java deleted file mode 100644 index fc194d816..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/util/collections/ShareableValuesList.java +++ /dev/null @@ -1,91 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.impl.util.collections; - -import java.util.Iterator; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.util.ShareableList; - -/** - * A specialized version of the ShareableList, specifically meant for storing values. - * - * @author Arnold Lankamp - */ -public class ShareableValuesList extends ShareableList{ - - public ShareableValuesList(){ - super(); - } - - public ShareableValuesList(ShareableValuesList shareableValuesList){ - super(shareableValuesList); - } - - public ShareableValuesList(ShareableValuesList shareableValuesList, int offset, int length){ - super(shareableValuesList, offset, length); - } - - public boolean isEqual(ShareableValuesList otherShareableValuesList){ - if(otherShareableValuesList == null) return false; - if(otherShareableValuesList.size() != size()) return false; - - if(otherShareableValuesList.isEmpty()) return true; - - Iterator thisListIterator = iterator(); - Iterator otherListIterator = otherShareableValuesList.iterator(); - while(thisListIterator.hasNext()){ - IValue thisValue = thisListIterator.next(); - IValue otherValue = otherListIterator.next(); - if(!thisValue.isEqual(otherValue)){ - return false; - } - } - - return true; - } - - public boolean contains(IValue value){ - Iterator valuesIterator = iterator(); - while(valuesIterator.hasNext()){ - IValue next = valuesIterator.next(); - if(next.isEqual(value)) return true; - } - - return false; - } - - public boolean remove(IValue value){ - int index = 0; - Iterator valuesIterator = iterator(); - while(valuesIterator.hasNext()){ - IValue next = valuesIterator.next(); - if(next.isEqual(value)) break; - - index++; - } - - if(index < size()){ - remove(index); - return true; - } - - return false; - } - - public ShareableValuesList subList(int offset, int length){ - if(offset < 0) throw new IndexOutOfBoundsException("Offset may not be smaller then 0."); - if(length < 0) throw new IndexOutOfBoundsException("Length may not be smaller then 0."); - if((offset + length) > size()) throw new IndexOutOfBoundsException("'offset + length' may not be larger then 'list.size()'"); - - return new ShareableValuesList(this, offset, length); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/IShareable.java b/value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/IShareable.java deleted file mode 100644 index c771618f3..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/IShareable.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.impl.util.sharing; - -/** - * Indicates that the implementing object is shareable. - * - * @author Arnold Lankamp - */ -public interface IShareable{ - - /** - * Computes the hashcode for 'this' object. - * - * @return The hashcode - * - * @see java.lang.Object#hashCode() - */ - int hashCode(); - - /** - * Checks if the given object is 'truely' equal to 'this' object. - * - * @param shareable - * The object to compare with. - * @return True if the given object is equal to 'this' object; false otherwise. - */ - boolean equivalent(IShareable shareable); -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/IndexedCache.java b/value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/IndexedCache.java deleted file mode 100644 index c75b42c8c..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/IndexedCache.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.impl.util.sharing; - -import java.util.concurrent.atomic.AtomicReferenceArray; - -/** - * This cache stores a predefined range of values.

- * Note that this class provides lock-free thread-safe access. - * - * @author Arnold Lankamp - * - * @param The content type. - */ -public class IndexedCache{ - private final AtomicReferenceArray atomicCacheArray; - private final int size; - - /** - * Constructor. - * - * @param size - * The range of values to cache (0 till 'size'). - */ - public IndexedCache(int size){ - super(); - - atomicCacheArray = new AtomicReferenceArray<>(size); - this.size = size; - } - - /** - * Returns the range of values that will be cached (0 till size). - * - * @return The range of values that will be cached (0 till size). - */ - public int size(){ - return size; - } - - /** - * Returns the unique representation of the given value that is located at the indicated index. - * - * @param index - * The index at which the value is located / must be inserted. - * @param prototype - * The value to use in case it have not yet been cached. - * @return The unique representation of the given value that is located at the indicated index. - */ - public T getOrDefine(int index, T prototype){ - if(index >= size) throw new IndexOutOfBoundsException("Index may not be larger then size."); - - if(atomicCacheArray.compareAndSet(index, null, prototype)){ - return prototype; // We just put the prototype in the cache. - } - return atomicCacheArray.get(index); // Someone beat us to it, use that one. - } - - /** - * Returns the value that is currently cached at the indicated position. - * - * @param index - * The index at which the requested value resides. Must be within the range of this - * cache. - * @return The requested value; may be null. - */ - public T get(int index){ - return atomicCacheArray.get(index); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/ShareableValuesFactory.java b/value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/ShareableValuesFactory.java deleted file mode 100644 index 0fc9a84de..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/impl/util/sharing/ShareableValuesFactory.java +++ /dev/null @@ -1,553 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.impl.util.sharing; - -import java.lang.ref.WeakReference; - -/** - * This is a 'weak' constant pool for uniquely represented objects. - *
- *
- * This implementation is thread-safe, but tries to avoid (contended) locking as much as is - * reasonably achievable. As a result this implementation scales fairly well on multi-core / - * processor systems. - *
- *
- * NOTE: It is highly recommended to leave this class alone; concurrency bugs can be very subtle, - * so please don't edit this class unless you know exactly what you're doing. - * - * @author Arnold Lankamp - */ -public final class ShareableValuesFactory{ - private final static int DEFAULT_LOG_NR_OF_SEGMENTS = 5; - - private final int logNrOfSegments; - private final Segment[] segments; - - /** - * Default constructor. - */ - @SuppressWarnings("unchecked") - public ShareableValuesFactory(){ - super(); - - logNrOfSegments = DEFAULT_LOG_NR_OF_SEGMENTS; - - segments = (Segment[]) new Segment[1 << logNrOfSegments]; - for(int i = segments.length - 1; i >= 0; i--){ - segments[i] = new Segment<>(logNrOfSegments); - } - } - - /** - * Constructor. - * - * @param logNrOfSegments - * Sets the amount of stripping to: (2 ^ logNrOfSegments). - * @throws IllegalArgumentException - * Thrown when logNrOfSegments is to high (logNrOfSegments > 32 - 5). - */ - @SuppressWarnings("unchecked") - public ShareableValuesFactory(int logNrOfSegments){ - super(); - - if((32 - logNrOfSegments) <= 5) throw new IllegalArgumentException("logNrOfSegments can not be larger then (32 - 5)."); - - this.logNrOfSegments = logNrOfSegments; - - segments = (Segment[]) new Segment[1 << logNrOfSegments]; - for(int i = segments.length - 1; i >= 0; i--){ - segments[i] = new Segment<>(logNrOfSegments); - } - } - - /** - * Removes stale entries from the set (if any). - */ - public void cleanup(){ - int nrOfSegments = segments.length; - for(int i = 0; i < nrOfSegments; i++){ - Segment segment = segments[i]; - synchronized(segment){ - segment.cleanup(); - } - } - } - - /** - * Returns statistics. - * - * @see java.lang.Object#toString() - */ - public String toString(){ - StringBuilder sb = new StringBuilder(); - int nrOfSegments = segments.length; - for(int i = 0; i < nrOfSegments; i++){ - Segment segment = segments[i]; - int maxSegmentBitSize = segment.maxSegmentBitSize; - - int startHash = i << maxSegmentBitSize; - int endHash = ((i + 1) << maxSegmentBitSize) - 1; - - sb.append("Segment hash range: "); - sb.append(startHash); - sb.append(" till "); - sb.append(endHash); - sb.append(" | "); - sb.append(segment.toString()); - sb.append("\n"); - } - return sb.toString(); - } - - /** - * Returns a unique version of the given shareable. - * - * @param shareable - * The shareable we want the unique reference too. - * @return The reference to the unique version of the given shareable. - */ - public E build(E shareable){ - int hash = shareable.hashCode(); - int segmentNr = hash >>> (32 - DEFAULT_LOG_NR_OF_SEGMENTS); - - return segments[segmentNr].get(shareable, hash); - } - - /** - * Segments are hashsets, which are responsible for elements in a certain hash-range. - * - * @author Arnold Lankamp - */ - private final static class Segment{ - private final static int DEFAULT_LOG_SEGMENT_SIZE = 5; - private final static float DEFAULT_LOAD_FACTOR = 2f; - - private final int maxSegmentBitSize; - - private volatile Entry[] entries; - - private volatile int hashMask; - private int bitSize; - - private int threshold; - private int load; - - private volatile boolean flaggedForCleanup; - private volatile WeakReference> garbageCollectionDetector; - private int cleanupScaler; - private int cleanupThreshold; - - /** - * Constructor. - * - * @param logNrOfSegments - * Specifies the maximal size this segment can grow to. - */ - @SuppressWarnings("unchecked") - public Segment(int logNrOfSegments){ - super(); - - maxSegmentBitSize = 32 - logNrOfSegments; - - bitSize = DEFAULT_LOG_SEGMENT_SIZE; - int nrOfEntries = 1 << bitSize; - - hashMask = nrOfEntries - 1; - - entries = (Entry[]) new Entry[nrOfEntries]; - - threshold = (int) (nrOfEntries * DEFAULT_LOAD_FACTOR); - load = 0; - - flaggedForCleanup = false; - garbageCollectionDetector = new WeakReference<>(new GarbageCollectionDetector<>(this)); // Allocate a (unreachable) GC detector. - cleanupScaler = 50; // Initially we set the average cleanup percentage to 50%, to make sure the cleanup can and will be executed the first time. - cleanupThreshold = cleanupScaler; - } - - /** - * Removes stale entries from this segment (if any). - */ - private void cleanup(){ - Entry[] table = entries; - int newLoad = load; - - for(int i = hashMask; i >= 0; i--){ - Entry e = table[i]; - if(e != null){ - Entry previous = null; - do{ - Entry next = e.next; - - if(e.get() == null){ - if(previous == null){ - table[i] = next; - }else{ - previous.next = next; - } - - newLoad--; - }else{ - previous = e; - } - - e = next; - }while(e != null); - } - } - - load = newLoad; - - entries = table; // Volatile write. - } - - /** - * Rehashes this set. All the entries will remain in the same order as they are in; this - * should improve look-up time in the general case and is more garbage collector friendly - * (you'll prevent old -> young references, contrary to the 'default' rehashing algorithm, - * which makes a complete mess of it). - */ - @SuppressWarnings("unchecked") - private void rehash(){ - int nrOfEntries = 1 << (++bitSize); - int newHashMask = nrOfEntries - 1; - - Entry[] oldEntries = entries; - Entry[] newEntries = (Entry[]) new Entry[nrOfEntries]; - - // Construct temporary entries that function as roots for the entries that remain in - // the current bucket and those that are being shifted. - Entry currentEntryRoot = new Entry<>(null, 0); - Entry shiftedEntryRoot = new Entry<>(null, 0); - - int newLoad = load; - int oldSize = oldEntries.length; - for(int i = oldSize - 1; i >= 0; i--){ - Entry e = oldEntries[i]; - if(e != null){ - Entry lastCurrentEntry = currentEntryRoot; - Entry lastShiftedEntry = shiftedEntryRoot; - do{ - if(e.get() != null){ // Cleared entries should not be copied. - int position = e.hash & newHashMask; - - if(position == i){ - lastCurrentEntry.next = e; - lastCurrentEntry = e; - }else{ - lastShiftedEntry.next = e; - lastShiftedEntry = e; - } - }else{ - newLoad --; - } - - e = e.next; - }while(e != null); - - // Set the next pointers of the last entries in the buckets to null. - lastCurrentEntry.next = null; - lastShiftedEntry.next = null; - - newEntries[i] = currentEntryRoot.next; - newEntries[i | oldSize] = shiftedEntryRoot.next; // The entries got shifted by the size of the old table. - } - } - - load = newLoad; - - threshold <<= 1; - entries = newEntries; // Volatile write. - hashMask = newHashMask; // Volatile write. - } - - /** - * Ensures the load in this segment will not exceed a certain threshold. - */ - private void ensureCapacity(){ - // Rehash if the load exceeds the threshold, unless the segment is already stretched to - // it's maximum (since that would be a useless thing to do). - if(load > threshold && bitSize < maxSegmentBitSize){ - rehash(); - } - } - - /** - * Attempts to run a cleanup if the garbage collector ran before the invocation of this - * function. This ensures that, in most cases, the buckets will contain no (or very little) - * cleared entries. This speeds up lookups significantly. - *
- *
- * Note that we automatically throttle the frequency of the cleanups. In case we hardly - * every collect anything (either because there is no garbage or collections occur very - * frequently) cleanups will be slowed down to as little as once every four minor garbage - * collections. When a lot of entries are being cleared the cleanup will run after every - * collection. - *
- * This is done in an attempt to balance the overhead a cleanup induces with the - * performance gains it has on lookups; while keeping the probability of long-lived stale - * entries relatively low. Additionally, linking the cleanup 'trigger' to garbage - * collections ensures that we clean the segment exactly when it is both needed and - * possible. - *
- *
- * NOTE: This may seem a bit 'dodgy' to some, but this does work on (at least) every major - * JVM since 1.2, and will remain working properly while weak-references keep functioning - * as intended. Apart from that, this way of handling it is significantly faster then any - * of the alternatives (i.e. using reference queues is slow as *bleep* in comparison). - * Additionally, it releases us from synchronizing during every single call. - */ - private void tryCleanup(){ - if(flaggedForCleanup){ - flaggedForCleanup = false; - - synchronized(this){ - if(garbageCollectionDetector == null){ // This being 'null' indicates the same thing as 'flaggedForCleanup' being 'true' (but we do it like this to prevent potential optimizations the VM probably doesn't, but could apply); and yes DCL like stuff works on volatiles. - if(cleanupThreshold > 8){ // The 'magic' number 8 is chosen, so the cleanup will be done at least once after every four garbage collections. - int oldLoad = load; - - cleanup(); - - int cleanupPercentate; - if(oldLoad == 0) cleanupPercentate = 50; // This prevents division by zero errors in case the table is empty (keep the cleanup percentage at 50% in this case). - else cleanupPercentate = 100 - ((load * 100) / oldLoad); // Calculate the percentage of entries that has been cleaned. - - cleanupScaler = (((cleanupScaler * 25) + (cleanupPercentate * 7)) >> 5); // Modify the scaler, depending on the history (weight = 25) and how much we cleaned up this time (weight = 7). - if(cleanupScaler > 0){ - cleanupThreshold = cleanupScaler; - }else{ - cleanupThreshold = 1; // If the scaler value became 0 (when we hardly every collect something), set the threshold to 1, so we only skip the next three garbage collections. - } - }else{ - cleanupThreshold <<= 1; - } - - garbageCollectionDetector = new WeakReference<>(new GarbageCollectionDetector<>(this)); // Allocate a new (unreachable) GC detector. - } - } - } - } - - /** - * Inserts the given shareable into this set. - * - * @param shareable - * The shareable to insert. - * @param hash - * The hash code that is associated with the given shareable. - */ - private void put(E shareable, int hash){ - Entry e = new Entry<>(shareable, hash); - - Entry[] table = entries; - int position = hash & hashMask; - e.next = table[position]; - table[position] = e; - - load++; - - table = entries; // Volatile write. - } - - /** - * Returns a reference to the unique version of the given shareable. - * - * @param shareable - * The shareable of which we want to obtain the reference to the unique version. - * @param hash - * The hash code that is associated with the given shareable. - * @return The reference to the unique version of the given shareable. - */ - public final E get(E shareable, int hash){ - // Cleanup if necessary. - tryCleanup(); - - // Find the object (lock free). - int position = hash & hashMask; - Entry e = entries[position]; // Volatile read. - if(e != null){ - do{ - if(hash == e.hash){ - E object = e.get(); - if(object != null){ - if(shareable.equivalent(object)){ - return object; - } - } - } - e = e.next; - }while(e != null); - } - - synchronized(this){ - // Try again while holding the global lock for this segment. - position = hash & hashMask; - e = entries[position]; - if(e != null){ - do{ - if(hash == e.hash){ - E object = e.get(); - if(object != null){ - if(shareable.equivalent(object)){ - return object; - } - } - } - e = e.next; - }while(e != null); - } - - // If we still can't find it, add it. - ensureCapacity(); - E result = shareable; - put(result, hash); - return result; - } - } - - /** - * Returns statistics. - * - * @see java.lang.Object#toString() - */ - public String toString(){ - StringBuilder sb = new StringBuilder(); - - synchronized(this){ - Entry[] table = entries; - - int tableSize = table.length; - - sb.append("Table size: "); - sb.append(tableSize); - sb.append(", "); - - sb.append("Number of entries: "); - sb.append(load); - sb.append(", "); - - sb.append("Threshold: "); - sb.append(threshold); - sb.append(", "); - - int nrOfFilledBuckets = 0; - int totalNrOfCollisions = 0; - int maxBucketLength = 0; - for(int i = 0; i < tableSize; i++){ - Entry e = table[i]; - if(e != null){ - nrOfFilledBuckets++; - int bucketLength = 1; - while((e = e.next) != null){ - bucketLength++; - } - if(bucketLength > maxBucketLength) maxBucketLength = bucketLength; - totalNrOfCollisions += bucketLength - 1; - } - } - // Do some voodoo to round the results on a certain amount of decimals (3 and 1 - // respectively); or at least attempt to do so .... - double averageBucketLength = 0; - double distribution = 100; - if(nrOfFilledBuckets != 0){ - averageBucketLength = (((double) ((totalNrOfCollisions * 1000) / nrOfFilledBuckets)) / 1000) + 1; - distribution = 100 - (((double) (((totalNrOfCollisions * 1000) / nrOfFilledBuckets) / DEFAULT_LOAD_FACTOR)) / 10); - } - - sb.append("Number of filled buckets: "); - sb.append(nrOfFilledBuckets); - sb.append(", "); - - sb.append("Load factor: "); - sb.append(DEFAULT_LOAD_FACTOR); - sb.append(", "); - - sb.append("Distribution (collisions vs filled buckets): "); // Total number of collisions vs number of filled buckets. - sb.append(distribution); - sb.append("%, "); - - sb.append("Total number of collisions: "); - sb.append(totalNrOfCollisions); - sb.append(", "); - - sb.append("Average (filled) bucket length: "); - sb.append(averageBucketLength); - sb.append(", "); - - sb.append("Maximal bucket length: "); - sb.append(maxBucketLength); - sb.append(", "); - - sb.append("Cleanup scaler: "); - sb.append(cleanupScaler); - sb.append("%"); - } - - return sb.toString(); - } - - /** - * An entry used for storing shareables in this segment. - * - * @author Arnold Lankamp - */ - private static class Entry extends WeakReference{ - public final int hash; - public Entry next; - - /** - * Constructor. - * - * @param shareable - * The shareable. - * @param hash - * The hashcode that is associated with the given shareable. - */ - public Entry(E shareable, int hash){ - super(shareable); - - this.hash = hash; - } - } - - /** - * An object that can be used to detect when a garbage collection has been executed. - * Instances of this object must be made weakly reachable for this to work. - * - * @author Arnold Lankamp - */ - private static class GarbageCollectionDetector{ - private final Segment segment; - - /** - * Constructor. - * - * @param segment - * The segment we need to flag after a garbage collection has occurred. - */ - public GarbageCollectionDetector(Segment segment){ - this.segment = segment; - } - - /** - * Executed after the garbage collector detects that this object is eligible for - * reclamation. When this happens it will flag the associated segment for cleanup. - * - * @see java.lang.Object#finalize - */ - protected void finalize(){ - segment.garbageCollectionDetector = null; - segment.flaggedForCleanup = true; - } - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/ATermReader.java b/value-core/src/main/java/org/rascalmpl/value/io/ATermReader.java deleted file mode 100644 index c3d8680de..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/ATermReader.java +++ /dev/null @@ -1,729 +0,0 @@ -/******************************************************************************* -* Copyright (c) INRIA-LORIA and CWI 2006-2009 -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Jurgen Vinju (jurgenv@cwi.nl) - initial API and implementation - -*******************************************************************************/ -package org.rascalmpl.value.io; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Set; - -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactParseError; -import org.rascalmpl.value.exceptions.IllegalOperationException; -import org.rascalmpl.value.exceptions.UndeclaredAbstractDataTypeException; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -// TODO: add support for values of type Value, for this we need overloading resolving -public class ATermReader extends AbstractBinaryReader { - private IValueFactory vf; - private TypeFactory tf = TypeFactory.getInstance(); - private TypeStore ts; - - public IValue read(IValueFactory factory, TypeStore store, Type type, InputStream stream) - throws FactParseError, IOException { - this.vf = factory; - this.ts = store; - - int firstToken; - do { - firstToken = stream.read(); - if (firstToken == -1) { - throw new IOException("Premature EOF."); - } - } while (Character.isWhitespace((char) firstToken)); - - char typeByte = (char) firstToken; - - if (typeByte == '!') { - SharingStream sreader = new SharingStream(stream); - sreader.initializeSharing(); - sreader.readSkippingWS(); - return parse(sreader, type); - } else if (typeByte == '?') { - throw new UnsupportedOperationException("nyi"); - } else if (Character.isLetterOrDigit(typeByte) || typeByte == '_' - || typeByte == '[' || typeByte == '-') { - SharingStream sreader = new SharingStream(stream); - sreader.last_char = typeByte; - return parse(sreader, type); - } else { - throw new RuntimeException("nyi"); - } - } - - - // TODO add support for anonymous constructors (is already done for the parseNumber case) - private IValue parse(SharingStream reader, Type expected) - throws IOException { - IValue result; - int start, end; - - start = reader.getPosition(); - switch (reader.getLastChar()) { - case -1: - throw new FactParseError("premature EOF encountered.", start); - case '#': - return parseAbbrev(reader); - case '[': - result = parseList(reader, expected); - break; - case '<': - throw new FactParseError("Placeholders are not supported", start); - case '"': - result = parseString(reader, expected); - break; - case '(': - result = parseTuple(reader, expected); - break; - case '-': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - result = parseNumber(reader, expected); - break; - default: - result = parseAppl(reader, expected); - } - - if (reader.getLastChar() == '{') { - result = parseAnnotations(reader, result); - } - - end = reader.getPosition(); - reader.storeNextTerm(result, end - start); - - return result; - } - - - private IValue parseAnnotations(SharingStream reader, IValue result) - throws IOException { - if (reader.readSkippingWS() == '}') { - reader.readSkippingWS(); - } else { - result = parseAnnos(reader, result); - if (reader.getLastChar() != '}') { - throw new FactParseError("'}' expected", reader.getPosition()); - } - } - return result; - } - - - private IValue parseAppl(SharingStream reader, Type expected) - throws IOException { - int c; - IValue result; - c = reader.getLastChar(); - if (Character.isLetter(c)) { - - String funname = parseId(reader); - - Type node; - if (expected.isAbstractData()) { - Set nodes = ts.lookupConstructor(expected, funname); - // TODO deal with overloading - Iterator iterator = nodes.iterator(); - if (!iterator.hasNext()) { - throw new UndeclaredAbstractDataTypeException(expected); - } - node = iterator.next(); - } - else { - node = expected; - } - - c = reader.skipWS(); - if (reader.getLastChar() == '(') { - c = reader.readSkippingWS(); - if (c == -1) { - throw new FactParseError("premature EOF encountered.", reader.getPosition()); - } - if (reader.getLastChar() == ')') { - - // result = node.make(vf, ts, funname, new IValue[0]); - if(node.isTop()) { - Type constr = ts.lookupFirstConstructor(funname, tf.tupleType(new Type[0])); - if(constr != null) node = constr; - } - if(node.isConstructor()) - result = vf.constructor(node, new IValue[0]); - else - result = vf.node(funname, new IValue[0]); - - } else { - IValue[] list; - if (expected.isAbstractData()) { - list = parseFixedSizeATermsArray(reader, node.getFieldTypes()); - } - else { - list = parseATermsArray(reader, TypeFactory.getInstance().valueType()); - } - - if (reader.getLastChar() != ')') { - throw new FactParseError("expected ')' but got '" - + (char) reader.getLastChar() + "'", reader.getPosition()); - } - - if(node.isTop()) { - Type constr = ts.lookupFirstConstructor(funname, tf.tupleType(list)); - if(constr != null) node = constr; - } - if (node.isConstructor()) - result = vf.constructor(node, list); - else - result = vf.node(funname, list); - } - c = reader.readSkippingWS(); - } else { - if (node.isConstructor()) { - result = vf.constructor(node); - } - else { - result = vf.node(funname); - } - } - } else { - throw new FactParseError("illegal character: " - + (char) reader.getLastChar(), reader.getPosition()); - } - return result; - } - - - private IValue parseTuple(SharingStream reader, Type expected) - throws IOException { - int c; - IValue result; - c = reader.readSkippingWS(); - if (c == -1) { - throw new FactParseError("premature EOF encountered.", reader.getPosition()); - } - if (reader.getLastChar() == ')') { - result = vf.tuple(); - } else { - IValue[] list = parseFixedSizeATermsArray(reader, expected); - - if (reader.getLastChar() != ')') { - throw new FactParseError("expected ')' but got '" - + (char) reader.getLastChar() + "'", reader.getPosition()); - } - - result = vf.tuple(list); - } - c = reader.readSkippingWS(); - - return result; - } - - - private IValue parseString(SharingStream reader, Type expected) throws IOException { - int c; - IValue result; - String str = parseStringLiteral(reader); - - // note that we interpret all strings as strings, not possible function names. - // this deviates from the ATerm library. - - result = vf.string(str); - - c = reader.readSkippingWS(); - if (c == -1) { - throw new FactParseError("premature EOF encountered.", reader.getPosition()); - } - return result; - } - - - private IValue parseList(SharingStream reader, Type expected) - throws IOException { - IValue result; - int c; - c = reader.readSkippingWS(); - if (c == -1) { - throw new FactParseError("premature EOF encountered.", reader.getPosition()); - } - - if (c == ']') { - c = reader.readSkippingWS(); - - if (expected.isList()) { - result = vf.list(expected.getElementType()); - } else if (expected.equivalent(TypeFactory.getInstance().valueType())) { - result = vf.list(tf.valueType()); - } - else { - throw new FactParseError("Did not expect a list, rather a " - + expected, reader.getPosition()); - } - } else { - result = parseATerms(reader, expected); - if (reader.getLastChar() != ']') { - throw new FactParseError("expected ']' but got '" - + (char) reader.getLastChar() + "'", reader.getPosition()); - } - c = reader.readSkippingWS(); - } - return result; - } - - private IValue parseAnnos(SharingStream reader, IValue result) throws IOException { - result = parseAnno(reader, result); - while (reader.getLastChar() == ',') { - reader.readSkippingWS(); - result = parseAnno(reader, result); - } - - return result; - } - - private IValue parseAnno(SharingStream reader, IValue result) throws IOException { - if (reader.getLastChar() == '[') { - int c = reader.readSkippingWS(); - - if (c == '"') { - String key = parseStringLiteral(reader); - Type annoType = ts.getAnnotationType(result.getType(), key); - - if (reader.readSkippingWS() == ',') { - reader.readSkippingWS(); - IValue value = parse(reader, annoType); - - if (result.getType().isAbstractData()) { - result = ((IConstructor) result).asAnnotatable().setAnnotation(key, value); - } - - if (reader.getLastChar() != ']') { - throw new FactParseError("expected a ] but got a " + reader.getLastChar(), reader.getPosition()); - } - - reader.readSkippingWS(); - return result; - } - - throw new FactParseError("expected a comma before the value of the annotation", reader.getPosition()); - } - - throw new FactParseError("expected a label for an annotation", reader.getPosition()); - } - - // no annotations - return result; - } - - static private boolean isBase64(int c) { - return Character.isLetterOrDigit(c) || c == '+' || c == '/'; - } - - private IValue parseAbbrev(SharingStream reader) throws IOException { - IValue result; - int abbrev; - - int c = reader.read(); - - abbrev = 0; - while (isBase64(c)) { - abbrev *= 64; - if (c >= 'A' && c <= 'Z') { - abbrev += c - 'A'; - } else if (c >= 'a' && c <= 'z') { - abbrev += c - 'a' + 26; - } else if (c >= '0' && c <= '9') { - abbrev += c - '0' + 52; - } else if (c == '+') { - abbrev += 62; - } else if (c == '/') { - abbrev += 63; - } else { - throw new RuntimeException("not a base-64 digit: " + c); - } - - c = reader.read(); - } - - result = reader.getTerm(abbrev); - - return result; - } - - private IValue parseNumber(SharingStream reader, Type expected) throws IOException { - StringBuilder str = new StringBuilder(); - IValue result; - - do { - str.append((char) reader.getLastChar()); - } while (Character.isDigit(reader.read())); - - if (reader.getLastChar() != '.' && reader.getLastChar() != 'e' - && reader.getLastChar() != 'E' && reader.getLastChar() != 'l' - && reader.getLastChar() != 'L') { - int val; - try { - val = Integer.parseInt(str.toString()); - } catch (NumberFormatException e) { - throw new FactParseError("malformed int:" + str, reader.getPosition()); - } - - result = vf.integer(val); - } else if (reader.getLastChar() == 'l' || reader.getLastChar() == 'L') { - reader.read(); - throw new FactParseError("No support for longs", reader.getPosition()); - } else { - if (reader.getLastChar() == '.') { - str.append('.'); - reader.read(); - if (!Character.isDigit(reader.getLastChar())) - throw new FactParseError("digit expected", reader.getPosition()); - do { - str.append((char) reader.getLastChar()); - } while (Character.isDigit(reader.read())); - } - if (reader.getLastChar() == 'e' || reader.getLastChar() == 'E') { - str.append((char) reader.getLastChar()); - reader.read(); - if (reader.getLastChar() == '-' || reader.getLastChar() == '+') { - str.append((char) reader.getLastChar()); - reader.read(); - } - if (!Character.isDigit(reader.getLastChar())) - throw new FactParseError("digit expected!", reader.getPosition()); - do { - str.append((char) reader.getLastChar()); - } while (Character.isDigit(reader.read())); - } - double val; - try { - val = Double.valueOf(str.toString()); - result = vf.real(val); - } catch (NumberFormatException e) { - throw new FactParseError("malformed real", reader.getPosition(), e); - } - } - - reader.skipWS(); - return result; - } - - private String parseId(SharingStream reader) throws IOException { - int c = reader.getLastChar(); - StringBuilder buf = new StringBuilder(32); - - do { - buf.append((char) c); - c = reader.read(); - } while (Character.isLetterOrDigit(c) || c == '_' || c == '-' - || c == '+' || c == '*' || c == '$' || c == '.'); - - // slight deviation here, allowing . inside of identifiers - return buf.toString(); - } - - private String parseStringLiteral(SharingStream reader) throws IOException { - boolean escaped; - StringBuilder str = new StringBuilder(); - - do { - escaped = false; - if (reader.read() == '\\') { - reader.read(); - escaped = true; - } - - int lastChar = reader.getLastChar(); - if(lastChar == -1) throw new IOException("Premature EOF."); - - if (escaped) { - switch (lastChar) { - case 'n': - str.append('\n'); - break; - case 't': - str.append('\t'); - break; - case 'b': - str.append('\b'); - break; - case 'r': - str.append('\r'); - break; - case 'f': - str.append('\f'); - break; - case '\\': - str.append('\\'); - break; - case '\'': - str.append('\''); - break; - case '\"': - str.append('\"'); - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - str.append(reader.readOct()); - break; - default: - str.append('\\').append((char) lastChar); - } - } else if (lastChar != '\"'){ - str.append((char) lastChar); - } - } while (escaped || reader.getLastChar() != '"'); - - return str.toString(); - } - - private IValue parseATerms(SharingStream reader, Type expected) - throws IOException { - Type base = expected; - Type elementType = getElementType(expected); - IValue[] terms = parseATermsArray(reader, elementType); - - if (base.isList() || base.equivalent(tf.valueType())) { - IListWriter w = vf.listWriter(); - - for (int i = terms.length - 1; i >= 0; i--) { - w.insert(terms[i]); - } - - return w.done(); - } else if (base.isSet()) { - ISetWriter w = vf.setWriter(); - w.insert(terms); - return w.done(); - } else if (base.isMap()) { - IMapWriter w = vf.mapWriter(); - - for (IValue elem : terms) { - ITuple tuple = (ITuple) elem; - w.put(tuple.get(0), tuple.get(1)); - } - - return w.done(); - } else if (base.isRelation()) { - ISetWriter w = vf.setWriter(); - w.insert(terms); - return w.done(); - } - - throw new FactParseError("Unexpected type " + expected, reader.getPosition()); - } - - private Type getElementType(Type expected) { - Type base = expected; - - if (base.isList()) { - return base.getElementType(); - } else if (base.isSet()) { - return base.getElementType(); - } else if (base.isMap()) { - return tf.tupleType(base.getKeyType(), base.getValueType()); - } else if (base.isRelation()) { - return base.getFieldTypes(); - } else if (base.isTop()) { - return base; - } - else { - throw new IllegalOperationException("getElementType", expected); - } - } - - private IValue[] parseATermsArray(SharingStream reader, - Type elementType) throws IOException { - List list = new ArrayList<>(2); - - IValue term = parse(reader, elementType); - list.add(term); - while (reader.getLastChar() == ',') { - reader.readSkippingWS(); - term = parse(reader, elementType); - list.add(term); - } - - IValue[] array = new IValue[list.size()]; - ListIterator iter = list.listIterator(); - int index = 0; - while (iter.hasNext()) { - array[index++] = iter.next(); - } - return array; - } - - private IValue[] parseFixedSizeATermsArray(SharingStream reader, - Type elementTypes) throws IOException { - List list = new ArrayList<>(elementTypes.getArity()); - int i = 0; - Type elementType = elementTypes.getFieldType(i++); - - IValue term = parse(reader, elementType); - list.add(term); - while (reader.getLastChar() == ',') { - elementType = elementTypes.getFieldType(i++); - reader.readSkippingWS(); - term = parse(reader, elementType); - list.add(term); - } - - IValue[] array = new IValue[list.size()]; - ListIterator iter = list.listIterator(); - int index = 0; - while (iter.hasNext()) { - array[index++] = iter.next(); - } - return array; - } - - - private static class SharingStream { - private static final int INITIAL_TABLE_SIZE = 2048; - private static final int TABLE_INCREMENT = 4096; - - private static final int INITIAL_BUFFER_SIZE = 1024; - - private InputStream reader; - - int last_char; - private int pos; - - private int nr_terms; - private IValue[] table; - - private byte[] buffer; - private int limit; - private int bufferPos; - - public SharingStream(InputStream reader) { - this(reader, INITIAL_BUFFER_SIZE); - } - - public SharingStream(InputStream stream, int bufferSize) { - this.reader = stream; - last_char = -1; - pos = 0; - - if (bufferSize < INITIAL_BUFFER_SIZE) - buffer = new byte[bufferSize]; - else - buffer = new byte[INITIAL_BUFFER_SIZE]; - limit = -1; - bufferPos = -1; - } - - public void initializeSharing() { - table = new IValue[INITIAL_TABLE_SIZE]; - nr_terms = 0; - } - - public void storeNextTerm(IValue t, int size) { - if (table == null) { - return; - } - - if (nr_terms == table.length) { - IValue[] new_table = new IValue[table.length + TABLE_INCREMENT]; - System.arraycopy(table, 0, new_table, 0, table.length); - table = new_table; - } - - table[nr_terms++] = t; - } - - public IValue getTerm(int index) { - if (index < 0 || index >= nr_terms) { - throw new RuntimeException("illegal index"); - } - return table[index]; - } - - public int read() throws IOException { - if (bufferPos == limit) { - limit = reader.read(buffer); - bufferPos = 0; - } - - if (limit == -1) { - last_char = -1; - } else { - last_char = buffer[bufferPos++]; - pos++; - } - - return last_char; - } - - public int readSkippingWS() throws IOException { - do { - last_char = read(); - } while (Character.isWhitespace(last_char)); - - return last_char; - - } - - public int skipWS() throws IOException { - while (Character.isWhitespace(last_char)) { - last_char = read(); - } - - return last_char; - } - - public int readOct() throws IOException { - int val = Character.digit(last_char, 8); - val += Character.digit(read(), 8); - - if (val < 0) { - throw new FactParseError("octal must have 3 octdigits.", getPosition()); - } - - val += Character.digit(read(), 8); - - if (val < 0) { - throw new FactParseError("octal must have 3 octdigits", getPosition()); - } - - return val; - } - - public int getLastChar() { - return last_char; - } - - public int getPosition() { - return pos; - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/ATermWriter.java b/value-core/src/main/java/org/rascalmpl/value/io/ATermWriter.java deleted file mode 100644 index 15e3d51ac..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/ATermWriter.java +++ /dev/null @@ -1,267 +0,0 @@ -/******************************************************************************* - * Copyright (c) CWI 2009 - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Jurgen Vinju (jurgenv@cwi.nl) - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.io; - -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IExternalValue; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.type.TypeStore; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * This class implements the ATerm readable syntax for {@link IValue}'s. - * See also {@link ATermReader} - */ -public class ATermWriter implements IValueTextWriter { - public void write(IValue value, java.io.Writer stream) throws IOException { - value.accept(new Writer(stream)); - } - - public void write(IValue value, java.io.Writer stream, TypeStore typeStore) throws IOException { - write(value, stream); - } - - private static class Writer implements IValueVisitor { - private java.io.Writer stream; - - public Writer(java.io.Writer stream) { - this.stream = stream; - } - - private void append(String string) throws IOException { - stream.write(string); - } - - private void append(char c) throws IOException { - stream.write(c); - } - - public IValue visitBoolean(IBool boolValue) throws IOException { - append(boolValue.getStringRepresentation()); - return boolValue; - } - - public IValue visitConstructor(IConstructor o) throws IOException { - return visitNode(o); - } - - public IValue visitReal(IReal o) throws IOException { - append(o.getStringRepresentation()); - return o; - } - - public IValue visitInteger(IInteger o) throws IOException { - append(o.getStringRepresentation()); - return o; - } - - // TODO: There probably isn't a good ATerm repr of rationals, - // what should we do here? - public IValue visitRational(IRational o) throws IOException { - append("rat"); - append('('); - append(o.numerator().getStringRepresentation()); - append(','); - append(o.denominator().getStringRepresentation()); - append(')'); - return o; - } - - public IValue visitList(IList o) throws IOException { - append('['); - - Iterator listIterator = o.iterator(); - if(listIterator.hasNext()){ - append(listIterator.next().toString()); - - while(listIterator.hasNext()){ - append(','); - listIterator.next().accept(this); - } - } - - append(']'); - - return o; - } - - public IValue visitMap(IMap o) throws IOException { - append('['); - - Iterator mapIterator = o.iterator(); - if(mapIterator.hasNext()){ - append('('); - IValue key = mapIterator.next(); - key.accept(this); - append(','); - o.get(key).accept(this); - append(')'); - - while(mapIterator.hasNext()){ - append(','); - append('('); - key = mapIterator.next(); - append(','); - o.get(key).accept(this); - append(')'); - } - } - - append(']'); - - return o; - } - - public IValue visitNode(INode o) throws IOException { - String name = o.getName(); - - append(name); - append('('); - - Iterator it = o.iterator(); - while (it.hasNext()) { - it.next().accept(this); - if (it.hasNext()) { - append(','); - } - } - append(')'); - - if (o.asAnnotatable().hasAnnotations()) { - append("{["); - int i = 0; - Map annotations = o.asAnnotatable().getAnnotations(); - for (Entry entry : annotations.entrySet()) { - append("[" + entry.getKey() + ","); - entry.getValue().accept(this); - append("]"); - - if (++i < annotations.size()) { - append(","); - } - } - append("]}"); - } - - return o; - } - - public IValue visitRelation(ISet o) throws IOException { - return visitSet(o); - } - - public IValue visitSet(ISet o) throws IOException { - append('['); - - Iterator setIterator = o.iterator(); - if(setIterator.hasNext()){ - setIterator.next().accept(this); - - while(setIterator.hasNext()){ - append(","); - setIterator.next().accept(this); - } - } - - append(']'); - return o; - } - - public IValue visitSourceLocation(ISourceLocation o) - throws IOException { - append("loc("); - append('\"'); - append(o.getURI().toString()); - append('\"'); - append("," + o.getOffset()); - append("," + o.getLength()); - append("," + o.getBeginLine()); - append("," + o.getBeginColumn()); - append("," + o.getEndLine()); - append("," + o.getEndColumn()); - append(')'); - return o; - } - - public IValue visitString(IString o) throws IOException { - // TODO optimize this implementation and finish all escapes - append('\"'); - append(o.getValue().replaceAll("\"", "\\\"").replaceAll("\n","\\\\n")); - append('\"'); - return o; - } - - public IValue visitTuple(ITuple o) throws IOException { - append('('); - - Iterator it = o.iterator(); - - if (it.hasNext()) { - it.next().accept(this); - } - - while (it.hasNext()) { - append(','); - it.next().accept(this); - } - append(')'); - - return o; - } - - public IValue visitExternal(IExternalValue externalValue) { - // ignore external values - return externalValue; - } - - public IValue visitDateTime(IDateTime o) throws IOException { - append("$"); - if (o.isDate()) { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); - append(df.format(new Date(o.getInstant()))); - } else if (o.isTime()) { - SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss.SSSZZZ"); - append("T"); - append(df.format(new Date(o.getInstant()))); - } else { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"); - append(df.format(new Date(o.getInstant()))); - } - return o; - } - - public IValue visitListRelation(IList o) - throws IOException { - visitList(o); - return o; - } - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/AbstractBinaryReader.java b/value-core/src/main/java/org/rascalmpl/value/io/AbstractBinaryReader.java deleted file mode 100644 index a9e6c99b9..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/AbstractBinaryReader.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.rascalmpl.value.io; - -import java.io.IOException; -import java.io.InputStream; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -public abstract class AbstractBinaryReader implements IValueBinaryReader { - public IValue read(IValueFactory factory, Type type, InputStream stream) - throws FactTypeUseException, IOException { - return read(factory, new TypeStore(), type, stream); - } - - public IValue read(IValueFactory factory, InputStream stream) - throws FactTypeUseException, IOException { - return read(factory, new TypeStore(), TypeFactory.getInstance().valueType(), stream); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/AbstractTextReader.java b/value-core/src/main/java/org/rascalmpl/value/io/AbstractTextReader.java deleted file mode 100644 index 765b1988a..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/AbstractTextReader.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.rascalmpl.value.io; - -import java.io.IOException; -import java.io.Reader; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -public abstract class AbstractTextReader implements IValueTextReader { - public IValue read(IValueFactory factory, Type type, Reader reader) - throws FactTypeUseException, IOException { - return read(factory, new TypeStore(), type, reader); - } - - public IValue read(IValueFactory factory, Reader reader) - throws FactTypeUseException, IOException { - return read(factory, new TypeStore(), TypeFactory.getInstance().valueType(), reader); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/BinaryValueReader.java b/value-core/src/main/java/org/rascalmpl/value/io/BinaryValueReader.java deleted file mode 100644 index 79a877992..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/BinaryValueReader.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.io; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.io.binary.BinaryReader; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeStore; - -/** - * A reader for PDB Binary Files (PBF). - * - * @author Arnold Lankamp - */ -public class BinaryValueReader implements IValueBinaryReader{ - - /** - * Constructor. - */ - public BinaryValueReader(){ - super(); - } - - /** - * @see IValueBinaryReader#read(IValueFactory, InputStream) - */ - public IValue read(IValueFactory valueFactory, InputStream inputStream) throws IOException{ - return doRead(valueFactory, new TypeStore(), inputStream); - } - - /** - * @see IValueBinaryReader#read(IValueFactory, Type, InputStream) - */ - public IValue read(IValueFactory valueFactory, Type type, InputStream inputStream) throws IOException{ - return doRead(valueFactory, new TypeStore(), inputStream); - } - - /** - * @see IValueBinaryReader#read(IValueFactory, TypeStore, Type, InputStream) - */ - public IValue read(IValueFactory valueFactory, TypeStore typeStore, Type type, InputStream inputStream) throws IOException{ - return doRead(valueFactory, typeStore, inputStream); - } - - private IValue doRead(IValueFactory valueFactory, TypeStore typeStore, InputStream inputStream) throws IOException{ - BinaryReader binaryReader = new BinaryReader(valueFactory, typeStore, inputStream); - return binaryReader.deserialize(); - } - - /** - * Reads the value from the given file. - * - * @param valueFactory - * The value factory to use. - * @param typeStore - * The typestore to use. - * @param file - * The file to read from. - * @return The resulting value. - * @throws IOException - * Thrown when something goes wrong. - */ - public static IValue readValueFromFile(IValueFactory valueFactory, TypeStore typeStore, File file) throws IOException{ - IValue result; - - InputStream fis = null; - try{ - fis = new BufferedInputStream(new FileInputStream(file)); - - BinaryReader binaryReader = new BinaryReader(valueFactory, typeStore, fis); - result = binaryReader.deserialize(); - }finally{ - if(fis != null){ - fis.close(); - } - } - - return result; - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/BinaryValueWriter.java b/value-core/src/main/java/org/rascalmpl/value/io/BinaryValueWriter.java deleted file mode 100644 index ac99ccc19..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/BinaryValueWriter.java +++ /dev/null @@ -1,136 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.io; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.io.binary.BinaryWriter; -import org.rascalmpl.value.type.TypeStore; - -/** - * Writer for PDB Binary Files (PBF). - * - * @author Arnold Lankamp - * @deprecated binary writer currently does not support keyword parameters. - */ -public class BinaryValueWriter implements IValueBinaryWriter{ - - /** - * Constructor. - */ - public BinaryValueWriter(){ - super(); - } - - /** - * Writes the given value to the given stream. - * - * @param value - * The value to write. - * @param outputStream - * The output stream to write to. - * @throws IOException - * Thrown when something goes wrong. - * @see IValueTextWriter#write(IValue, OutputStream) - */ - public void write(IValue value, OutputStream outputStream) throws IOException{ - write(value, outputStream, true); - } - /** - * Writes the given value to the given stream. - * - * @param value - * The value to write. - * @param outputStream - * The output stream to write to. - * @param compression - * If we want to enable maximal sharing compression - * @throws IOException - * Thrown when something goes wrong. - * @see IValueTextWriter#write(IValue, OutputStream) - */ - public void write(IValue value, OutputStream outputStream, boolean maximalSharing) throws IOException{ - BinaryWriter binaryWriter = new BinaryWriter(value, outputStream, maximalSharing, new TypeStore()); - binaryWriter.serialize(); - outputStream.flush(); - } - - /** - * Writes the given value to the given stream. - * - * @param value - * The value to write. - * @param outputStream - * The output stream to write to. - * @param typeStore - * The type store to use. - * @throws IOException - * Thrown when something goes wrong. - * @see IValueTextWriter#write(IValue, OutputStream) - */ - public void write(IValue value, OutputStream outputStream, TypeStore typeStore) throws IOException{ - write(value, outputStream, true, typeStore); - } - /** - * Writes the given value to the given stream. - * - * @param value - * The value to write. - * @param outputStream - * The output stream to write to. - * @param compression - * - * @param typeStore - * The type store to use. - * @throws IOException - * Thrown when something goes wrong. - * @see IValueTextWriter#write(IValue, OutputStream) - */ - public void write(IValue value, OutputStream outputStream, boolean maximalSharing, TypeStore typeStore) throws IOException{ - BinaryWriter binaryWriter = new BinaryWriter(value, outputStream, maximalSharing, typeStore); - binaryWriter.serialize(); - outputStream.flush(); - } - - /** - * Writes the given value to a file. - * - * @param value - * The value to write. - * @param file - * The file to write to. - * @param typeStore - * The type store to use. - * @throws IOException - * Thrown when something goes wrong. - - */ - @Deprecated - public static void writeValueToFile(IValue value, File file, TypeStore typeStore) throws IOException{ - OutputStream fos = null; - try{ - fos = new BufferedOutputStream(new FileOutputStream(file)); - - BinaryWriter binaryWriter = new BinaryWriter(value, fos, true, typeStore); - binaryWriter.serialize(); - fos.flush(); - }finally{ - if(fos != null){ - fos.close(); - } - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/SerializableValue.java b/value-core/src/main/java/org/rascalmpl/value/io/SerializableValue.java deleted file mode 100644 index cc49cd05a..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/SerializableValue.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.rascalmpl.value.io; - -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; - - -/** - * Experimental wrapper class for serializable IValues. - * Your mileage may vary due to use of the BinaryWriter. - */ -public class SerializableValue implements Serializable { - private static final long serialVersionUID = -5507315290306212326L; - private IValueFactory vf; - private T value; - - public SerializableValue(IValueFactory vf, T value) { - this.vf = vf; - this.value = value; - } - - public T getValue() { - return value; - } - - public void write(OutputStream out) throws IOException { - new ObjectOutputStream(out).writeObject(this); - } - - @SuppressWarnings("unchecked") - public static SerializableValue read(InputStream in) throws IOException { - try { - return (SerializableValue) new ObjectInputStream(in).readObject(); - } catch (ClassNotFoundException e) { - throw new IOException(e); - } - } - - @SuppressWarnings("deprecation") - private void writeObject(java.io.ObjectOutputStream out) throws IOException { - String factoryName = vf.getClass().getName(); - out.write("factory".getBytes()); - out.write(':'); - out.writeInt(factoryName.length()); - out.write(':'); - out.write(factoryName.getBytes("UTF8")); - out.write(':'); - new BinaryValueWriter().write(value, out); - } - - @SuppressWarnings("unchecked") - private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { - try { - in.read(new byte["factory".length()], 0, "factory".length()); - in.read(); // ':' - int length = in.readInt(); - in.read(); // ':' - byte[] factoryName = new byte[length]; - in.read(factoryName, 0, length); - in.read(); // ':' - Class clazz = getClass().getClassLoader().loadClass(new String(factoryName, "UTF8")); - this.vf = (IValueFactory) clazz.getMethod("getInstance").invoke(null, new Object[0]); - this.value = (T) new BinaryValueReader().read(vf, in); - } - catch (InvocationTargetException | IllegalAccessException | IllegalArgumentException | NoSuchMethodException | SecurityException | ClassCastException e) { - throw new IOException("Could not load IValueFactory", e); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/StandardTextReader.java b/value-core/src/main/java/org/rascalmpl/value/io/StandardTextReader.java deleted file mode 100644 index 394d938c2..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/StandardTextReader.java +++ /dev/null @@ -1,998 +0,0 @@ -/******************************************************************************* - * Copyright (c) CWI 2008 - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Jurgen Vinju (jurgenv@cwi.nl) - initial API and implementation - - *******************************************************************************/ - -package org.rascalmpl.value.io; - -import java.io.IOException; -import java.io.Reader; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.IWriter; -import org.rascalmpl.value.exceptions.FactParseError; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.OverloadingNotSupportedException; -import org.rascalmpl.value.exceptions.UnexpectedTypeException; -import org.rascalmpl.value.type.ExternalType; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -/** - * This class implements the standard readable syntax for {@link IValue}'s. - * Note that the parser also validates the input according to a given {@link Type}. - * - * Note however that overloaded constructors for abstract data-types are not supported. - * - * See also {@link StandardTextWriter} - */ -public class StandardTextReader extends AbstractTextReader { - - private static final char START_OF_LOC = '|'; - private static final char START_OF_STRING = '\"'; - private static final char END_OF_STRING = '\"'; - private static final char START_OF_MAP = '('; - private static final char START_OF_ARGUMENTS = '('; - private static final char END_OF_ARGUMENTS = ')'; - private static final char START_OF_TUPLE = '<'; - private static final char START_OF_SET = '{'; - private static final char START_OF_LIST = '['; - private static final char END_OF_TUPLE = '>'; - private static final char COMMA_SEPARATOR = ','; - private static final char END_OF_MAP = ')'; - private static final char DOUBLE_DOT = '.'; - private static final char RATIONAL_SEP = 'r'; - private static final char END_OF_SET = '}'; - private static final char END_OF_LIST = ']'; - private static final char END_OF_LOCATION = '|'; - private static final char START_OF_DATETIME = '$'; - private static final char END_OF_DATETIME = '$'; - - private static final char NEGATIVE_SIGN = '-'; - - - private TypeStore store; - private NoWhiteSpaceReader stream; - private IValueFactory factory; - private TypeFactory types; - private int current; - private LinkedHashMap sourceLocationCache; - - @SuppressWarnings("serial") - public IValue read(IValueFactory factory, TypeStore store, Type type, Reader stream) throws FactTypeUseException, IOException { - this.store = store; - this.stream = new NoWhiteSpaceReader(stream); - this.factory = factory; - this.types = TypeFactory.getInstance(); - - try { - sourceLocationCache = new LinkedHashMap(400*4/3, 0.75f, true) { - @Override - protected boolean removeEldestEntry(java.util.Map.Entry eldest) { - return size() > 400; - } - }; - current = this.stream.read(); - IValue result = readValue(type); - if (current != -1 || this.stream.read() != -1) { - unexpected(); - } - return result; - } - finally { - sourceLocationCache.clear(); - sourceLocationCache = null; - } - } - - private IValue readValue(Type expected) throws IOException { - IValue result = null; - - if (Character.isDigit(current) || current == DOUBLE_DOT || current == NEGATIVE_SIGN) { - result = readNumber(expected); - } - else if ((Character.isJavaIdentifierStart(current) && '$' != current) - || current == '\\') { - String id = readIdentifier(); - - if (id.equals("true")) { - return factory.bool(true); - } - else if (id.equals("false")) { - return factory.bool(false); - } - else if (current == '=') { - return factory.string(id); - } - else if (current == START_OF_ARGUMENTS) { - result = readConstructor(id, expected); - } - else { - throw new FactParseError("expected = or (", stream.offset); - } - } - else { - switch (current) { - case START_OF_STRING: - result = readString(expected); - break; - case START_OF_LIST: - result = readList(expected); - break; - case START_OF_SET: - result = readSet(expected); - break; - case START_OF_TUPLE: - result = readTuple(expected); - break; - case START_OF_MAP: - result = readMap(expected); - break; - case START_OF_LOC: - result = readLocation(expected); - break; - case START_OF_DATETIME: - result = readDateTime(expected); - break; - default: - unexpected(); - } - } - - if (!result.getType().isSubtypeOf(expected)) { - throw new UnexpectedTypeException(expected, result.getType()); - } - - if (current == '[') { - if (result.getType().isSubtypeOf(types.nodeType())) { - result = readAnnos(expected, (INode) result); - } - else { - unexpected(']'); - } - } - - return result; - } - - - private IValue readLocation(Type expected) throws IOException { - try { - - String url = parseURL(); - ISourceLocation loc = sourceLocationCache.get(url); - if (loc == null) { - loc = factory.sourceLocation(new URI(url)); - sourceLocationCache.put(url, loc); - } - if (current == START_OF_ARGUMENTS) { - ArrayList args = new ArrayList<>(4); - readFixed(types.valueType(), ')', args, null); - - if (args.size() >= 2) { - if (!args.get(0).getType().isSubtypeOf(types.integerType())) { - throw new UnexpectedTypeException(types.integerType(), args.get(0).getType()); - } - if (!args.get(1).getType().isSubtypeOf(types.integerType())) { - throw new UnexpectedTypeException(types.integerType(), args.get(1).getType()); - } - - Type posType = types.tupleType(types.integerType(), types.integerType()); - - if (args.size() == 4) { - if (!args.get(2).getType().isSubtypeOf(posType)) { - throw new UnexpectedTypeException(posType, args.get(2).getType()); - } - if (!args.get(3).getType().isSubtypeOf(posType)) { - throw new UnexpectedTypeException(posType, args.get(3).getType()); - } - } - - int offset = Integer.parseInt(args.get(0).toString()); - int length = Integer.parseInt(args.get(1).toString()); - - if (args.size() == 4) { - int beginLine = Integer.parseInt(((ITuple) args.get(2)).get(0).toString()); - int beginColumn = Integer.parseInt(((ITuple) args.get(2)).get(1).toString()); - int endLine = Integer.parseInt(((ITuple) args.get(3)).get(0).toString()); - int endColumn = Integer.parseInt(((ITuple) args.get(3)).get(1).toString()); - - return factory.sourceLocation(loc, offset, length, beginLine, endLine, beginColumn, endColumn); - } - - if (args.size() != 2) { - throw new FactParseError("source locations should have either 2 or 4 arguments", offset); - } - - return factory.sourceLocation(loc, offset, length); - } - } - - return loc; - - } catch (URISyntaxException e) { - throw new FactParseError(e.getMessage(), stream.offset, e); - } - } - - private String parseURL() throws IOException { - current = stream.read(); - StringBuilder result = new StringBuilder(); - - while (current != END_OF_LOCATION) { - result.append((char) current); - current = stream.read(); - if (current == -1) { - unexpected(); - } - } - - current = stream.read(); - - return result.toString(); - } - - private static final TypeFactory TF = TypeFactory.getInstance(); - private static final Type generalMapType = TF.mapType(TF.valueType(), TF.valueType()); - - private IValue readMap(Type expected) throws IOException { - Type keyType = expected.isSubtypeOf(generalMapType) ? expected.getKeyType() : types.valueType(); - Type valueType = expected.isSubtypeOf(generalMapType) ? expected.getValueType() : types.valueType(); - IMapWriter w = factory.mapWriter(); - - checkAndRead(START_OF_MAP); - - while (current != END_OF_MAP) { - IValue key = readValue(keyType); - checkAndRead(':'); - IValue value = readValue(valueType); - w.put(key, value); - - if (current != COMMA_SEPARATOR || current == END_OF_MAP) { - break; // no more elements, so expecting a ')' - } - else { - checkAndRead(COMMA_SEPARATOR); - } - } - - checkAndRead(END_OF_MAP); - - return w.done(); - } - - private IValue readTuple(Type expected) throws IOException { - ArrayList arr = new ArrayList<>(); - readFixed(expected, END_OF_TUPLE, arr, null); - IValue[] result = new IValue[arr.size()]; - return factory.tuple(arr.toArray(result)); - } - - private static final Type genericSetType = TF.setType(TF.valueType()); - - private IValue readSet(Type expected) throws FactTypeUseException, IOException { - Type elemType = expected.isSubtypeOf(genericSetType) ? expected.getElementType() : types.valueType(); - return readContainer(elemType, factory.setWriter(), END_OF_SET); - } - - private static final Type genericListType = TF.listType(TF.valueType()); - - private IValue readList(Type expected) throws FactTypeUseException, IOException { - Type elemType = expected.isSubtypeOf(genericListType) ? expected.getElementType() : types.valueType(); - return readList(elemType, factory.listWriter(), END_OF_LIST); - } - - private void checkMoreThanOnce(String input, char needle) { - boolean first = true; - for (int i=0; i < input.length(); i++) - { - if (input.charAt(i) == needle) - { - if (first) { - first = false; - } - else { - throw new FactParseError(needle +" occured for the second time", (this.stream.offset - input.length()) + i); - } - } - } - } - - - private IValue readNumber(Type expected) throws IOException { - StringBuilder builder = new StringBuilder(); - - do{ - builder.append((char) current); - current = stream.read(); - } while(Character.isDigit(current) || current == RATIONAL_SEP || current == DOUBLE_DOT || current == 'E' || current == 'e' || current == '+' || current == '-'); - - String val = builder.toString(); - checkMoreThanOnce(val, RATIONAL_SEP); - checkMoreThanOnce(val, DOUBLE_DOT); - checkMoreThanOnce(val, 'E'); - checkMoreThanOnce(val, 'e'); - - try { - if (val.contains(".") || val.contains("E") || val.contains("e")) { - return factory.real(val); - } - - return factory.integer(val); - } - catch (NumberFormatException e) { - // could happen - } - - try { - return factory.real(val); - } - catch (NumberFormatException e) { - // could happen - } - - try { - return factory.rational(val); - } - catch (NumberFormatException e) { - // could happen - } - - unexpected(current); - return null; - } - - private IValue readConstructor(String id, Type expected) throws IOException { - ArrayList arr = new ArrayList(); - Type args = expected; - Type constr = null; - if (expected.isExternalType()) { - expected = ((ExternalType) expected).asAbstractDataType(); - } - if (expected.isAbstractData() ) { - Set alternatives = store.lookupConstructor(expected, id); - if (alternatives.size() > 1) { - throw new OverloadingNotSupportedException(expected, id); - } - else if (alternatives.size() == 0) { - args = types.valueType(); - // TODO: Should not it be an undeclared abstract data/constructor exception?! - } - else { - constr = alternatives.iterator().next(); - args = constr.getFieldTypes(); - } - } - - Map kwParams = new HashMap<>(); - readFixed(args, END_OF_ARGUMENTS, arr, kwParams); - IValue[] result = new IValue[arr.size()]; - result = arr.toArray(result); - - if (expected.isTop()) { - constr = store.lookupFirstConstructor(id, TF.tupleType(result)); - } - - if (constr != null) { - return factory.constructor(constr, result, kwParams); - } else { - return factory.node(id, result, kwParams); - } - } - - /** - * Read in a single character from the input stream and append it to the - * given buffer only if it is numeric. - * - * @param buf The buffer to which the read character should be appended - * - * @return True if the input character was numeric [0-9] and was appended, - * false otherwise. - * - * @throws IOException when an error is encountered reading the input stream - */ - private boolean readAndAppendIfNumeric(StringBuilder buf) throws IOException { - current = stream.read(); - if (Character.isDigit(current)) { - buf.append((char)current); - return true; - } else { - return false; - } - } - - /** - * Read in a date value, given as a string of the form NNNN-NN-NN, where each - * N is a digit [0-9]. The groups are the year, month, and day of month. - * - * @return A DateParts object with year, month, and day filled in. - * - * @throws IOException when an error is encountered reading the input stream - * @throws FactParseError when the correct characters are not found while lexing - * the date - */ - private DateParts readDate(char firstChar) throws IOException, FactParseError { - StringBuilder buf = new StringBuilder(); - buf.append(firstChar); - - // The first four characters should be the year - for (int i = 0; i < 3; ++i) { - boolean res = readAndAppendIfNumeric(buf); - if (!res) { - throw new FactParseError("Error reading date, expected digit, found: " + current, stream.offset); - } - } - - // The next character should be a '-' - current = stream.read(); - if ('-' != current) { - throw new FactParseError("Error reading date, expected '-', found: " + current, stream.offset); - } - - // The next two characters should be the month - for (int i = 0; i < 2; ++i) { - boolean res = readAndAppendIfNumeric(buf); - if (!res) { - throw new FactParseError("Error reading date, expected digit, found: " + current, stream.offset); - } - } - - // The next character should be a '-' - current = stream.read(); - if ('-' != current) { - throw new FactParseError("Error reading date, expected '-', found: " + current, stream.offset); - } - - // The next two characters should be the day - for (int i = 0; i < 2; ++i) { - boolean res = readAndAppendIfNumeric(buf); - if (!res) { - throw new FactParseError("Error reading date, expected digit, found: " + current, stream.offset); - } - } - - String dateString = buf.toString(); - return new DateParts( - Integer.parseInt(dateString.substring(0, 4)), // year - Integer.parseInt(dateString.substring(4,6)), // month - Integer.parseInt(dateString.substring(6))); // day - } - - /** - * Read in a time value, given as a string of the form NN:NN:NN.NNN[+-]NN:NN, - * where each N is a digit [0-9]. The groups are the hour, minute, second, - * millisecond, timezone hour offset, and timezone minute offset. - * - * @return A TimeParts objects with hours, minutes, seconds, milliseconds, - * and timezone information filled in. - * - * @throws IOException when an error is encountered reading the input stream - * @throws FactParseError when the correct characters are not found while lexing - * the time - */ - private TimeParts readTime() throws IOException, FactParseError { - StringBuilder buf = new StringBuilder(); - - // The first two characters should be the hour - for (int i = 0; i < 2; ++i) { - boolean res = readAndAppendIfNumeric(buf); - if (!res) { - throw new FactParseError("Error reading time, expected digit, found: " + current, stream.offset); - } - } - - // The next character should be a ':' - current = stream.read(); - if (':' != current) { - throw new FactParseError("Error reading time, expected ':', found: " + current, stream.offset); - } - - // The next two characters should be the minute - for (int i = 0; i < 2; ++i) { - boolean res = readAndAppendIfNumeric(buf); - if (!res) { - throw new FactParseError("Error reading time, expected digit, found: " + current, stream.offset); - } - } - - // The next character should be a ':' - current = stream.read(); - if (':' != current) { - throw new FactParseError("Error reading time, expected ':', found: " + current, stream.offset); - } - - // The next two characters should be the second - for (int i = 0; i < 2; ++i) { - boolean res = readAndAppendIfNumeric(buf); - if (!res) { - throw new FactParseError("Error reading time, expected digit, found: " + current, stream.offset); - } - } - - // The next character should be a '.' - current = stream.read(); - if ('.' != current) { - throw new FactParseError("Error reading time, expected '.', found: " + current, stream.offset); - } - - // The next three characters should be the millisecond - for (int i = 0; i < 3; ++i) { - boolean res = readAndAppendIfNumeric(buf); - if (!res) { - throw new FactParseError("Error reading time, expected digit, found: " + current, stream.offset); - } - } - - // The next character should be '+' or '-' - current = stream.read(); - if (! ('+' == current || '-' == current)) { - throw new FactParseError("Error reading time, expected '+' or '-', found: " + current, stream.offset); - } - buf.append((char)current); - - // The next two characters should be the hour offset - for (int i = 0; i < 2; ++i) { - boolean res = readAndAppendIfNumeric(buf); - if (!res) { - throw new FactParseError("Error reading time, expected digit, found: " + current, stream.offset); - } - } - - // The next two characters should be the minute offset - for (int i = 0; i < 2; ++i) { - boolean res = readAndAppendIfNumeric(buf); - if (current == ':' && i == 0) { - // skip optional : separator between hour and minute offset - i = -1; - res = true; - } - if (!res) { - throw new FactParseError("Error reading time, expected digit, found: " + current, stream.offset); - } - } - - String timeString = buf.toString(); - boolean negativeTZHours = timeString.substring(9,10).equals("-"); - return new TimeParts( - Integer.parseInt(timeString.substring(0,2)), // hour - Integer.parseInt(timeString.substring(2,4)), // minutes - Integer.parseInt(timeString.substring(4,6)), // seconds - Integer.parseInt(timeString.substring(6,9)), // milliseconds - Integer.parseInt(timeString.substring(10,12)) * (negativeTZHours ? -1 : 1), // timezone hours - Integer.parseInt(timeString.substring(12))); // timezone minutes - } - - private IValue readDateTime(Type expected) throws IOException, FactParseError { - DateParts dateParts = null; - TimeParts timeParts = null; - boolean isDate = false; - boolean isTime = false; - - // Retrieve the string to parse and pick the correct format string, - // based on whether we are reading a time, a date, or a datetime. - current = stream.read(); - - if ('T' == current || 't' == current) { - timeParts = readTime(); - isTime = true; - current = stream.read(); // advance to next character for parsing - } else { - dateParts = readDate((char)current); - current = stream.read(); - if ('T' == current || 't' == current) { - timeParts = readTime(); - current = stream.read(); // advance to next character for parsing - } else { - isDate = true; - // no need to advance here, already did when checked for T - } - } - - if (END_OF_DATETIME == current) { - // new-style datatime literal, consume the end character and advance - current = stream.read(); - } - - if (isDate) { - return factory.date(dateParts.getYear(), dateParts.getMonth(), dateParts.getDay()); - } else { - if (isTime) { - return factory.time(timeParts.getHour(), timeParts.getMinute(), timeParts.getSecond(), timeParts.getMillisecond(), timeParts.getTimezoneHours(), timeParts.getTimezoneMinutes()); - } else { - return factory.datetime(dateParts.getYear(), dateParts.getMonth(), dateParts.getDay(), timeParts.getHour(), timeParts.getMinute(), timeParts.getSecond(), timeParts.getMillisecond(), timeParts.getTimezoneHours(), timeParts.getTimezoneMinutes()); - } - } - } - - private String readIdentifier() throws IOException { - StringBuilder builder = new StringBuilder(); - boolean escaped = (current == '\\'); - - if (escaped) { - current = stream.read(); - } - - while (Character.isJavaIdentifierStart(current) - || Character.isJavaIdentifierPart(current) - || (escaped && current == '-')) { - builder.append((char) current); - current = stream.read(); - } - - return builder.toString(); - } - - private IValue readString(Type expected) throws IOException { - StringBuilder builder = new StringBuilder(); - current = stream.read(); - - while (current != END_OF_STRING) { - if (current == '\\') { - current = stream.read(); - switch (current) { - case 'n': - builder.append('\n'); - break; - case 't': - builder.append('\t'); - break; - case 'r': - builder.append('\r'); - break; - case 'b': - builder.append('\b'); - break; - case '\"': - builder.append('\"'); - break; - case '>': - builder.append('>'); - break; - case '<': - builder.append('<'); - break; - case '\'': - builder.append('\''); - break; - case '\\': - builder.append('\\'); - break; - case 'a': - StringBuilder a = new StringBuilder(); - a.append((char)stream.read()); - a.append((char)stream.read()); - builder.append((char) Integer.parseInt(a.toString(), 16)); - break; - case 'u': - StringBuilder u = new StringBuilder(); - u.append((char) stream.read()); - u.append((char)stream.read()); - u.append((char)stream.read()); - u.append((char)stream.read()); - builder.append((char) Integer.parseInt(u.toString(), 16)); - break; - case 'U': - StringBuilder U = new StringBuilder(); - U.append((char)stream.read()); - U.append((char)stream.read()); - U.append((char)stream.read()); - U.append((char)stream.read()); - U.append((char)stream.read()); - U.append((char)stream.read()); - int cp = Integer.parseInt(U.toString(), 16); - - if (!Character.isValidCodePoint(cp)) { - throw new FactParseError(U + " is not a valid 24 bit Unicode character", stream.getOffset()); - } - builder.appendCodePoint(cp); - break; - default: - if (current == -1) { - throw new FactParseError("End of input before finding end of String", stream.offset); - } - builder.append(current); - } - current = stream.read(); - } - else if (current == -1) { - throw new FactParseError("End of input before finding end of String", stream.offset); - } - else { - builder.appendCodePoint(current); - current = stream.read(); - } - } - - String str = builder.toString(); - current = stream.read(); - - - if (current == START_OF_ARGUMENTS) { - ArrayList arr = new ArrayList<>(); - Map kwParams = new HashMap<>(); - readFixed(expected, END_OF_ARGUMENTS, arr, kwParams); - IValue[] result = new IValue[arr.size()]; - result = arr.toArray(result); - - return factory.node(str, result, kwParams); - } - - return factory.string(str); - } - - private IValue readAnnos(Type expected, INode result) throws IOException { - current = stream.read(); - - while (current != ']') { - checkAndRead('@'); - String key = readIdentifier(); - checkAndRead('='); - - Type annoType = getAnnoType(expected, key); - IValue value = readValue(annoType); - - result = result.asAnnotatable().setAnnotation(key, value); - if (current == ']') { - current = stream.read(); - break; - } - checkAndRead(','); - } - - return result; - } - - private Type getAnnoType(Type expected, String key) { - Type annoType; - if (expected.isStrictSubtypeOf(TF.nodeType())) { - if (expected.declaresAnnotation(store, key)) { - annoType = store.getAnnotationType(expected, key); - } - else { - annoType = types.valueType(); - } - } - else { - annoType = types.valueType(); - } - return annoType; - } - - private void readFixed(Type expected, char end, List arr, Map kwParams) throws IOException { - current = stream.read(); - - for (int i = 0; current != end; i++) { - Type exp = expected.isFixedWidth() ? expected.getFieldType(i) : types.valueType(); - IValue elem = readValue(exp); - - if (current == '=') { - String label = ((IString) elem).getValue(); - current = stream.read(); - if (expected.isConstructor() && expected.hasField(label)) { - kwParams.put(label, readValue(expected.getFieldType(label))); - } - else { - kwParams.put(label, readValue(types.valueType())); - } - } - else { - arr.add(elem); - } - - if (current != ',' || current == end) { - break; // no more elements, so expecting a 'end', or '=' - } - current = stream.read(); - } - - checkAndRead(end); - } - - private IValue readContainer(Type elemType, IWriter w, char end) throws FactTypeUseException, IOException { - current = stream.read(); - while(current != end) { - w.insert(readValue(elemType)); - - if (current != ',' || current == end) { - break; // no more elements, so expecting a '}' - } - current = stream.read(); - } - - checkAndRead(end); - - return w.done(); - } - - private IValue readList(Type elemType, IListWriter w, char end) throws FactTypeUseException, IOException { - current = stream.read(); - while (current != end) { - w.append(readValue(elemType)); - - if (current != ',' || current == end) { - break; // no more elements, so expecting a '}' - } - current = stream.read(); - } - - checkAndRead(end); - - return w.done(); - } - - private void checkAndRead(char c) throws IOException { - if (current != c) { - unexpected(c); - } - current = stream.read(); - } - - private void unexpected(int c) { - throw new FactParseError("Expected " + ((char) c) + " but got " + ((char) current), stream.getOffset()); - } - - private void unexpected() { - throw new FactParseError("Unexpected " + ((char) current), stream.getOffset()); - } - - private static class NoWhiteSpaceReader extends Reader { - private Reader wrapped; - int offset; - boolean inString = false; - boolean escaping = false; - - public NoWhiteSpaceReader(Reader wrapped) { - this.wrapped = wrapped; - } - - @Override - public int read(char[] cbuf, int off, int len) throws IOException { - throw new UnsupportedOperationException(); - } - - @Override - public int read() throws IOException { - int r = wrapped.read(); - offset++; - - if (!inString) { - while (Character.isWhitespace(r)) { - offset++; - r = wrapped.read(); - } - } - - if (!inString && r == '\"') { - inString = true; - } - else if (inString) { - if (escaping) { - // previous was escaping, so no interpretation of current char. - escaping = false; - } - else if (r == '\\') { - escaping = true; - } - else if (r == '"') { - // if we were not escaped, a double quote exits a string - inString = false; - } - } - - return r; - } - - int getOffset() { - return offset; - } - - @Override - public void close() throws IOException { - wrapped.close(); - } - } - - private static class DateParts { - private final int year; - private final int month; - private final int day; - - public DateParts(int year, int month, int day) { - this.year = year; - this.month = month; - this.day = day; - } - - public int getYear() { - return year; - } - - public int getMonth() { - return month; - } - - public int getDay() { - return day; - } - - public String toString() { - return String.format("%04d", year) + "-" + String.format("%02d", month) + "-" + String.format("%02d", day); - } - } - - private static class TimeParts { - private final int hour; - private final int minute; - private final int second; - private final int millisecond; - private final int timezoneHours; - private final int timezoneMinutes; - - public TimeParts(int hour, int minute, int second, int millisecond, int timezoneHours, int timezoneMinutes) { - this.hour = hour; - this.minute = minute; - this.second = second; - this.millisecond = millisecond; - this.timezoneHours = timezoneHours; - this.timezoneMinutes = timezoneMinutes; - } - - public int getHour() { - return hour; - } - - public int getMinute() { - return minute; - } - - public int getSecond() { - return second; - } - - public int getMillisecond() { - return millisecond; - } - - public int getTimezoneHours() { - return timezoneHours; - } - - public int getTimezoneMinutes() { - return timezoneMinutes; - } - - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(String.format("%02d",hour)).append(":").append(String.format("%02d",minute)).append(":").append(String.format("%02d",second)).append(".").append(String.format("%03d",millisecond)); - if (timezoneHours < 0) - sb.append("-"); - else - sb.append("+"); - sb.append(String.format("%02d",Math.abs(timezoneHours))).append(":").append(String.format("%02d",timezoneMinutes)); - return sb.toString(); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/StandardTextWriter.java b/value-core/src/main/java/org/rascalmpl/value/io/StandardTextWriter.java deleted file mode 100644 index 00d976c9b..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/StandardTextWriter.java +++ /dev/null @@ -1,711 +0,0 @@ -/******************************************************************************* - * Copyright (c) CWI 2009 - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Jurgen Vinju (jurgenv@cwi.nl) - initial API and implementation - *******************************************************************************/ -package org.rascalmpl.value.io; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IExternalValue; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.type.ITypeVisitor; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeStore; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * This class implements the standard readable syntax for {@link IValue}'s. - * See also {@link StandardTextReader} - */ -public class StandardTextWriter implements IValueTextWriter { - protected final boolean indent; - protected final int tabSize; - - public StandardTextWriter() { - this(false); - } - - public StandardTextWriter(boolean indent) { - this(indent, 2); - } - - public StandardTextWriter(boolean indent, int tabSize) { - this.indent = indent; - this.tabSize = tabSize; - } - - public static String valueToString(IValue value) { - try(StringWriter stream = new StringWriter()) { - new StandardTextWriter().write(value, stream); - return stream.toString(); - } catch (IOException ioex) { - throw new RuntimeException("Should have never happened.", ioex); - } - } - - public void write(IValue value, java.io.Writer stream) throws IOException { - try { - value.accept(new Writer(stream, indent, tabSize)); - } - finally { - stream.flush(); - } - } - - public void write(IValue value, java.io.Writer stream, TypeStore typeStore) throws IOException { - write(value, stream); - } - - protected static class Writer implements IValueVisitor { - private final java.io.Writer stream; - private final int tabSize; - private final boolean indent; - private int tab = 0; - - public Writer(java.io.Writer stream, boolean indent, int tabSize) { - this.stream = stream; - this.indent = indent; - this.tabSize = tabSize; - } - - private void append(String string) throws IOException { - stream.write(string); - } - - private void append(char c) throws IOException { - stream.write(c); - } - - private void tab() { - this.tab++; - } - - private void untab() { - this.tab--; - } - - public IValue visitBoolean(IBool boolValue) - throws IOException { - append(boolValue.getValue() ? "true" : "false"); - return boolValue; - } - - public IValue visitReal(IReal o) throws IOException { - append(o.getStringRepresentation()); - return o; - } - - public IValue visitInteger(IInteger o) throws IOException { - append(o.getStringRepresentation()); - return o; - } - - public IValue visitRational(IRational o) throws IOException { - append(o.getStringRepresentation()); - return o; - } - - public IValue visitList(IList o) throws IOException { - append('['); - - boolean indent = checkIndent(o); - Iterator listIterator = o.iterator(); - tab(); - indent(indent); - if(listIterator.hasNext()){ - listIterator.next().accept(this); - - while(listIterator.hasNext()){ - append(','); - if (indent) indent(); - listIterator.next().accept(this); - } - } - untab(); - indent(indent); - append(']'); - - return o; - } - - public IValue visitMap(IMap o) throws IOException { - append('('); - tab(); - boolean indent = checkIndent(o); - indent(indent); - Iterator mapIterator = o.iterator(); - if(mapIterator.hasNext()){ - IValue key = mapIterator.next(); - key.accept(this); - append(':'); - o.get(key).accept(this); - - while(mapIterator.hasNext()){ - append(','); - indent(indent); - key = mapIterator.next(); - key.accept(this); - append(':'); - o.get(key).accept(this); - } - } - untab(); - indent(indent); - append(')'); - - return o; - } - - public IValue visitConstructor(IConstructor o) throws IOException { - String name = o.getName(); - if (name == null) - System.err.println("hello"); - if (name.equals("loc")) { - append('\\'); - } - - if (name.indexOf('-') != -1) { - append('\\'); - } - append(name); - - boolean indent = checkIndent(o); - - append('('); - tab(); - indent(indent); - Iterator it = o.iterator(); - int k = 0; - while (it.hasNext()) { - it.next().accept(this); - if (it.hasNext()) { - append(','); - indent(indent); - } - k++; - } - - if (o.mayHaveKeywordParameters()) { - IWithKeywordParameters wkw = o.asWithKeywordParameters(); - if (wkw.hasParameters()) { - if (k > 0) { - append(','); - } - - Iterator> iterator = wkw.getParameters().entrySet().iterator(); - while (iterator.hasNext()) { - Entry e = iterator.next(); - - append(e.getKey()); - append('='); - e.getValue().accept(this); - - if (iterator.hasNext()) { - append(','); - } - } - } - } - - append(')'); - untab(); - if (o.isAnnotatable() && o.asAnnotatable().hasAnnotations()) { - append('['); - tab(); - indent(); - int i = 0; - Map annotations = o.asAnnotatable().getAnnotations(); - for (Entry entry : annotations.entrySet()) { - append("@" + entry.getKey() + "="); - entry.getValue().accept(this); - - if (++i < annotations.size()) { - append(","); - indent(); - } - } - untab(); - indent(); - append(']'); - } - - return o; - } - - private void indent() throws IOException { - indent(indent); - } - - private void indent(boolean indent) throws IOException { - if (indent) { - append('\n'); - for (int i = 0; i < tabSize * tab; i++) { - append(' '); - } - } - } - - public IValue visitRelation(ISet o) throws IOException { - return visitSet(o); - } - - public IValue visitSet(ISet o) throws IOException { - append('{'); - - boolean indent = checkIndent(o); - tab(); - indent(indent); - Iterator setIterator = o.iterator(); - if(setIterator.hasNext()){ - setIterator.next().accept(this); - - while(setIterator.hasNext()){ - append(","); - indent(indent); - setIterator.next().accept(this); - } - } - untab(); - indent(indent); - append('}'); - return o; - } - - private boolean checkIndent(ISet o) { - if (indent && o.size() > 1) { - for (IValue x : o) { - Type type = x.getType(); - return indented(type); - } - } - return false; - } - - private boolean indented(Type type) { - return type.accept(new ITypeVisitor() { - @Override - public Boolean visitReal(Type type) { - return false; - } - - @Override - public Boolean visitInteger(Type type) { - return false; - } - - @Override - public Boolean visitRational(Type type) { - return false; - } - - @Override - public Boolean visitList(Type type) { - return true; - } - - @Override - public Boolean visitMap(Type type) { - return true; - } - - @Override - public Boolean visitNumber(Type type) { - return false; - } - - @Override - public Boolean visitAlias(Type type) { - return type.getAliased().accept(this); - } - - @Override - public Boolean visitSet(Type type) { - return true; - } - - @Override - public Boolean visitSourceLocation(Type type) { - return true; - } - - @Override - public Boolean visitString(Type type) { - return false; - } - - @Override - public Boolean visitNode(Type type) { - return true; - } - - @Override - public Boolean visitConstructor(Type type) { - return true; - } - - @Override - public Boolean visitAbstractData(Type type) { - return true; - } - - @Override - public Boolean visitTuple(Type type) { - return true; - } - - @Override - public Boolean visitValue(Type type) { - return false; - } - - @Override - public Boolean visitVoid(Type type) { - return false; - } - - @Override - public Boolean visitBool(Type type) { - return false; - } - - @Override - public Boolean visitParameter(Type type) { - return type.getBound().accept(this); - } - - @Override - public Boolean visitExternal(Type type) { - return false; - } - - @Override - public Boolean visitDateTime(Type type) { - return false; - } - }); - } - - private boolean checkIndent(IList o) { - if (indent && o.length() > 1) { - for (IValue x : o) { - Type type = x.getType(); - if (indented(type)) { - return true; - } - } - } - return false; - } - - private boolean checkIndent(INode o) { - if (indent && o.arity() > 1) { - for (IValue x : o) { - Type type = x.getType(); - if (indented(type)) { - return true; - } - } - } - return false; - } - - private boolean checkIndent(IMap o) { - if (indent && o.size() > 1) { - for (IValue x : o) { - Type type = x.getType(); - Type vType = o.get(x).getType(); - if (indented(type)) { - return true; - } - if (indented(vType)) { - return true; - } - } - } - return false; - } - - public IValue visitSourceLocation(ISourceLocation o) - throws IOException { - append('|'); - append(o.getURI().toString()); - append('|'); - - if (o.hasOffsetLength()) { - append('('); - append(Integer.toString(o.getOffset())); - append(','); - append(Integer.toString(o.getLength())); - - if (o.hasLineColumn()) { - append(','); - append('<'); - append(Integer.toString(o.getBeginLine())); - append(','); - append(Integer.toString(o.getBeginColumn())); - append('>'); - append(','); - append('<'); - append(Integer.toString(o.getEndLine())); - append(','); - append(Integer.toString(o.getEndColumn())); - append('>'); - } - append(')'); - } - return o; - } - - public IValue visitString(IString o) throws IOException { - printString(o.getValue()); - return o; - } - - private void printString(String o) throws IOException { - append('\"'); - char[] chars = o.toCharArray(); - for (int i = 0; i < chars.length; i++) { - char ch = chars[i]; - switch (ch) { - case '\"': - append('\\'); - append('\"'); - break; - case '>': - append('\\'); - append('>'); - break; - case '<': - append('\\'); - append('<'); - break; - case '\'': - append('\\'); - append('\''); - break; - case '\\': - append('\\'); - append('\\'); - break; - case '\n': - append('\\'); - append('n'); - break; - case '\r': - append('\\'); - append('r'); - break; - case '\t': - append('\\'); - append('t'); - break; - case ' ': - // needed because other space chars will be escaped in the default branch - append(' '); - break; - default: - int cp = Character.codePointAt(chars, i); - - if (Character.isSpaceChar(cp) - || Character.isISOControl(cp) - || Character.UnicodeBlock.SPECIALS.equals(Character.UnicodeBlock.of(cp))) { - // these characters are invisible or otherwise unreadable and we escape them here - // for clarity of the serialized string - - if (cp <= Byte.MAX_VALUE) { - append("\\a" + String.format("%02x", (int) ch)); - } - else if (cp <= Character.MAX_VALUE) { - append("\\u" + String.format("%04x", (int) ch)); - } - else { - append("\\U" + String.format("%06x", (int) ch)); - } - - if (Character.isHighSurrogate(ch)) { - i++; // skip the next char - } - } - else { - append(ch); - - if (Character.isHighSurrogate(ch) && i + 1 < chars.length) { - append(chars[++i]); - } - } - } - } - append('\"'); - } - - public IValue visitTuple(ITuple o) throws IOException { - append('<'); - - Iterator it = o.iterator(); - - if (it.hasNext()) { - it.next().accept(this); - } - - while (it.hasNext()) { - append(','); - it.next().accept(this); - } - append('>'); - - return o; - } - - public IValue visitExternal(IExternalValue externalValue) throws IOException { - return visitConstructor(externalValue.encodeAsConstructor()); - } - - public IValue visitDateTime(IDateTime o) throws IOException { - append("$"); - if (o.isDate()) { - append(String.format("%04d", o.getYear())); - append("-"); - append(String.format("%02d", o.getMonthOfYear())); - append("-"); - append(String.format("%02d", o.getDayOfMonth())); - } else if (o.isTime()) { - append("T"); - append(String.format("%02d", o.getHourOfDay())); - append(":"); - append(String.format("%02d", o.getMinuteOfHour())); - append(":"); - append(String.format("%02d", o.getSecondOfMinute())); - append("."); - append(String.format("%03d", o.getMillisecondsOfSecond())); - if (o.getTimezoneOffsetHours() < 0) - append("-"); - else - append("+"); - append(String.format("%02d", o.getTimezoneOffsetHours())); - append(":"); - append(String.format("%02d", o.getTimezoneOffsetMinutes())); - } else { - append(String.format("%04d", o.getYear())); - append("-"); - append(String.format("%02d", o.getMonthOfYear())); - append("-"); - append(String.format("%02d", o.getDayOfMonth())); - - append("T"); - append(String.format("%02d", o.getHourOfDay())); - append(":"); - append(String.format("%02d", o.getMinuteOfHour())); - append(":"); - append(String.format("%02d", o.getSecondOfMinute())); - append("."); - append(String.format("%03d", o.getMillisecondsOfSecond())); - if (o.getTimezoneOffsetHours() < 0) - append("-"); - else - append("+"); - append(String.format("%02d", o.getTimezoneOffsetHours())); - append(":"); - append(String.format("%02d", o.getTimezoneOffsetMinutes())); - } - append("$"); - return o; - } - - public IValue visitListRelation(IList o) - throws IOException { - visitList(o); - return o; - } - - public IValue visitNode(INode o) throws IOException { - printString(o.getName()); - - boolean indent = checkIndent(o); - - append('('); - tab(); - indent(indent); - Iterator it = o.iterator(); - int k = 0; - while (it.hasNext()) { - it.next().accept(this); - if (it.hasNext()) { - append(','); - indent(indent); - } - k++; - } - - - if (o.mayHaveKeywordParameters()) { - IWithKeywordParameters wkw = o.asWithKeywordParameters(); - if (wkw.hasParameters()) { - if (k > 0) { - append(','); - } - - Iterator> kwIt = wkw.getParameters().entrySet().iterator(); - while (kwIt.hasNext()) { - Entry e = kwIt.next(); - append(e.getKey()); - append('='); - e.getValue().accept(this); - - if (kwIt.hasNext()) { - append(','); - } - - } - } - } - append(')'); - untab(); - if (o.isAnnotatable() && o.asAnnotatable().hasAnnotations()) { - append('['); - tab(); - indent(); - int i = 0; - Map annotations = o.asAnnotatable().getAnnotations(); - for (Entry entry : annotations.entrySet()) { - append("@" + entry.getKey() + "="); - entry.getValue().accept(this); - - if (++i < annotations.size()) { - append(","); - indent(); - } - } - untab(); - indent(); - append(']'); - } - - return o; - } - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/XMLReader.java b/value-core/src/main/java/org/rascalmpl/value/io/XMLReader.java deleted file mode 100644 index da523feb5..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/XMLReader.java +++ /dev/null @@ -1,361 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008 CWI. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* jurgen@vinju.org - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value.io; - -import java.io.IOException; -import java.io.Reader; -import java.util.Set; - -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactParseError; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.exceptions.UnsupportedTypeException; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * This IValueReader parses and validates certain forms of XML and deserializes - * it as IValues. The forms of XML allowed are limited by a number of different - * value types. In particular, it allows:
    - *
  • TreeSortTypes and TreeNodeTypes
  • - *
  • lists, sets, relations and maps, but not unless they are wrapped by a single - * ConstructorType. I.o.w. a container must be the only child of a tree node. - * Elements of containers are juxtapositioned as children of this node.
  • - *
  • tuples, but not nested ones. And tuples of containers are not allowed. - * elements of tuples are juxtapositioned in the xml files.
  • - *
  • basic types, such as str, int, double; with the same restriction as for - * container types, they must be the only child of a tree node.
  • - *
  • lists of tuples, sets of tuples and maps of tuples are allowed, but not - * lists of lists, tuples of tuples, lists in tuples, sets in tuples, etc. - * If such nesting is needed, it is required to use a wrapping tree node.
  • - *
- * There is no support for NamedTypes yet, only TreeSortType and ConstructorType are - * allowed. - * - * The limitations of this class are governed by wanting to avoid ambiguity - * while validating XML using the pdb's type system and the inherent impedance - * mismatch between the type system of pdb and the structure of XML. - * - * Use this class to import many forms of XML data into PDB. - * - */ -public class XMLReader extends AbstractTextReader { - private DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); - private IValueFactory vf; - private static final TypeFactory TF = TypeFactory.getInstance(); - private TypeStore ts; - - public IValue read(IValueFactory factory, TypeStore store, Type type, Reader stream) - throws FactTypeUseException, IOException { - this.vf = factory; - this.ts = store; - - try { - Document doc = domFactory.newDocumentBuilder().parse(new InputSource(stream)); - return parse(doc.getDocumentElement(), type); - } catch (SAXException se) { - throw new IOException("Parsing of value failed because XML was invalid: " + se.getMessage()); - } catch (ParserConfigurationException pce) { - throw new IOException("Parsing of value failed because XML configuration is wrong: " + pce.getMessage()); - } catch (DOMException de) { - throw new IOException("Parsing of value failed because of a XML document failure: " + de.getMessage()); - } catch (NumberFormatException nfe) { - throw new FactParseError("Expected a number, got something different", nfe); - } - } - - private IValue parse(Node node, Type expected) { - if (expected.isAbstractData()) { - Type sort = expected; - String name = node.getNodeName(); - - if (isListWrapper(name, sort)) { - return parseList(node, sort); - } - else if (isSetWrapper(name, sort)) { - return parseSet(node, sort); - } - else if (isRelationWrapper(name, sort)) { - return parseRelation(node, sort); - } - else if (isMapWrapper(name, sort)) { - return parseMap(node, sort); - } - else { - return parseTreeSort(node, sort); - } - } - else if (expected.equivalent(TF.stringType())) { - return parseString(node); - } - else if (expected.equivalent(TF.integerType())) { - return parseInt(node); - } - else if (expected.equivalent(TF.realType())) { - return parseDouble(node); - } - else if (expected.equivalent(TF.rationalType())) { - return parseRational(node); - } - else if (expected.isExternalType()) { - // external types default to string - return parseString(node); - } - - throw new UnsupportedTypeException( - "Outermost or nested tuples, lists, sets, relations or maps are not allowed.", expected); - } - - private boolean isListWrapper(String name, Type expected) { - Set nodeTypes = ts.lookupConstructor(expected, name); - - if (nodeTypes.size() > 0) { - Type nodeType = nodeTypes.iterator().next(); - return nodeType.getArity() == 1 - && nodeType.getFieldTypes().getFieldType(0).isSubtypeOf(TF.listType(TF.valueType())); - } - - return false; - } - - private boolean isSetWrapper(String name, Type expected) { - Set nodeTypes = ts.lookupConstructor(expected, name); - - if (nodeTypes.size() > 0) { - Type nodeType = nodeTypes.iterator().next(); - return nodeType.getArity() == 1 - && nodeType.getFieldTypes().getFieldType(0).isSubtypeOf(TF.setType(TF.valueType())); - } - - return false; - } - - private boolean isRelationWrapper(String name, Type expected) { - Set nodeTypes = ts.lookupConstructor(expected, name); - - if (nodeTypes.size() > 0) { - Type nodeType = nodeTypes.iterator().next(); - return nodeType.getArity() == 1 - && nodeType.getFieldTypes().getFieldType(0).isSubtypeOf(TF.setType(TF.valueType())) - && nodeType.getFieldTypes().getFieldType(0).getElementType().isFixedWidth(); - } - - return false; - } - - private boolean isMapWrapper(String name, Type expected) { - Set nodeTypes = ts.lookupConstructor(expected, name); - - if (nodeTypes.size() > 0) { - Type nodeType = nodeTypes.iterator().next(); - return nodeType.getArity() == 1 - && nodeType.getFieldTypes().getFieldType(0).isMap(); - } - - return false; - } - - // TODO: implement this - private IValue parseRational(Node node) { - String contents = node.getNodeValue().trim(); - String[] parts = contents.split("r"); - if (parts.length == 2) { - return vf.rational(vf.integer(Integer.parseInt(parts[0])), vf.integer(Integer.parseInt(parts[0]))); - } - throw new FactParseError(contents, 0); - } - - private IValue parseDouble(Node node) { - return vf.real(Double.parseDouble(node.getNodeValue().trim())); - } - - private IValue parseInt(Node node) { - return vf.integer(Integer.parseInt(node.getNodeValue().trim())); - } - - private IValue parseString(Node node) { - return vf.string(node.getNodeValue()); - } - - private IValue parseMap(Node node, Type expected) { - Set nodeTypes = ts.lookupConstructor(expected, node.getNodeName()); - // TODO: implement overloading - Type nodeType = nodeTypes.iterator().next(); - Type mapType = nodeType.getFieldType(0); - Type keyType = mapType.getKeyType(); - Type valueType = mapType.getValueType(); - NodeList children = node.getChildNodes(); - IMapWriter writer = vf.mapWriter(); - - for (int i = 0; i + 1 < children.getLength(); ) { - IValue key, value; - - if (keyType.isFixedWidth()) { - Type tuple = keyType; - IValue [] elements = new IValue[tuple.getArity()]; - for (int j = 0; j < tuple.getArity(); j++) { - elements[i] = parse(children.item(i++), tuple.getFieldType(j)); - } - - key = vf.tuple(elements); - } - else { - key = parse(children.item(i++), keyType); - } - - if (valueType.isFixedWidth()) { - Type tuple = keyType; - IValue [] elements = new IValue[tuple.getArity()]; - for (int j = 0; j < tuple.getArity(); j++) { - elements[i] = parse(children.item(i++), tuple.getFieldType(j)); - } - - value = vf.tuple(elements); - } - else { - value = parse(children.item(i++), valueType); - } - - writer.put(key, value); - } - - - return vf.constructor(nodeType, writer.done()); - } - - private IValue parseRelation(Node node, Type expected) { - Set nodeTypes = ts.lookupConstructor(expected, node.getNodeName()); - // TODO implement overloading - Type nodeType = nodeTypes.iterator().next(); - Type relType = nodeType.getFieldType(0); - Type fields = relType.getFieldTypes(); - NodeList children = node.getChildNodes(); - ISetWriter writer = vf.setWriter(); - - for (int i = 0; i < children.getLength(); ) { - IValue[] elements = new IValue[fields.getArity()]; - - for (int j = 0; i < children.getLength() && j < fields.getArity(); j++) { - elements[j] = parse(children.item(i++), fields.getFieldType(j)); - } - - writer.insert(vf.tuple(elements)); - } - - return vf.constructor(nodeType, writer.done()); - } - - private IValue parseSet(Node node, Type expected) { - Set nodeTypes = ts.lookupConstructor(expected, node.getNodeName()); - // TODO implement overloading - Type nodeType = nodeTypes.iterator().next(); - Type setType = nodeType.getFieldType(0); - Type elementType = setType.getElementType(); - NodeList children = node.getChildNodes(); - ISetWriter writer = vf.setWriter(); - - if (!elementType.isFixedWidth()) { - for (int i = 0; i < children.getLength(); i++) { - writer.insert(parse(children.item(i), elementType)); - } - } else { - Type tuple = elementType; - for (int i = 0; i < children.getLength(); ) { - IValue[] elements = new IValue[tuple.getArity()]; - - for (int j = 0; i < children.getLength() && j < tuple.getArity(); j++) { - elements[j] = parse(children.item(i++), tuple.getFieldType(j)); - } - - writer.insert(vf.tuple(elements)); - } - } - - return vf.constructor(nodeType, writer.done()); - } - - private IValue parseList(Node node, Type expected) { - Set nodeTypes = ts.lookupConstructor(expected, node.getNodeName()); - // TODO implement overloading - Type nodeType = nodeTypes.iterator().next(); - Type listType = nodeType.getFieldType(0); - Type elementType = listType.getElementType(); - NodeList children = node.getChildNodes(); - IListWriter writer = vf.listWriter(); - - if (!elementType.isFixedWidth()) { - for (int i = 0; i < children.getLength(); i++) { - writer.append(parse(children.item(i), elementType)); - } - } else { - Type tuple = elementType; - for (int i = 0; i < children.getLength(); ) { - IValue[] elements = new IValue[tuple.getArity()]; - - for (int j = 0; i < children.getLength() && j < tuple.getArity(); j++) { - elements[j] = parse(children.item(i++), tuple.getFieldType(j)); - } - - writer.append(vf.tuple(elements)); - } - } - - return vf.constructor(nodeType, writer.done()); - } - - private IValue parseTreeSort(Node node, Type expected) { - // TODO deal with overloading - Type nodeType = ts.lookupConstructor(expected, node.getNodeName()).iterator().next(); - Type childrenTypes = nodeType.getFieldTypes(); - NodeList children = node.getChildNodes(); - - IValue[] values = new IValue[nodeType.getArity()]; - - int sourceIndex = 0; - int targetIndex = 0; - - while(sourceIndex < children.getLength() && targetIndex < nodeType.getArity()) { - Type childType = childrenTypes.getFieldType(targetIndex); - - if (childType.isFixedWidth()) { - Type tuple = childType; - IValue[] elements = new IValue[tuple.getArity()]; - - for (int tupleIndex = 0; tupleIndex < tuple.getArity() && sourceIndex < children.getLength(); tupleIndex++, sourceIndex++) { - elements[tupleIndex] = parse(children.item(sourceIndex), tuple.getFieldType(tupleIndex)); - } - - values[targetIndex++] = vf.tuple(elements); - } - else { - values[targetIndex++] = parse(children.item(sourceIndex++), childType); - } - } - - return vf.constructor(nodeType, values); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/XMLWriter.java b/value-core/src/main/java/org/rascalmpl/value/io/XMLWriter.java deleted file mode 100644 index aefcd0621..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/XMLWriter.java +++ /dev/null @@ -1,256 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008 CWI. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* jurgen@vinju.org - initial API and implementation - -*******************************************************************************/ -package org.rascalmpl.value.io; - -import java.io.IOException; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IExternalValue; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.UnsupportedTypeException; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeStore; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -/** - * This IValueWriter serializes values to XML documents. - * It will not serialize all IValues, see XMLReader for limitations. - */ -public class XMLWriter implements IValueTextWriter { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - private DocumentBuilder fBuilder; - - public void write(IValue value, java.io.Writer stream) throws IOException { - try { - fBuilder = dbf.newDocumentBuilder(); - Document doc = fBuilder.newDocument(); - - Node top = yield(value, doc); - doc.appendChild(top); - - Transformer t = TransformerFactory.newInstance().newTransformer(); - t.setOutputProperty(OutputKeys.INDENT, "yes"); - - t.transform(new DOMSource(doc), new StreamResult(stream)); - } catch (ParserConfigurationException e) { - throw new IOException("XML configuration is invalid: " + e.getMessage()); - } catch (TransformerException e) { - throw new IOException("Exception while serializing XML: " + e.getMessage()); - } - } - - public void write(IValue value, java.io.Writer stream, TypeStore typeStore) throws IOException { - write(value, stream); - } - - private Node yield(IValue value, Document doc) { - Type type = value.getType(); - - if (type.isAbstractData()) { - Type node = ((IConstructor) value).getConstructorType(); - - if (isListWrapper(node)) { - return yieldList((INode) value, doc); - } - else if (isSetWrapper(node)) { - return yieldSet((INode) value, doc); - } - else if (isRelationWrapper(node)) { - return yieldRelation((INode) value, doc); - } - else if (isMapWrapper(node)) { - return yieldMap((INode) value, doc); - } - else { - return yieldTree((INode) value, doc); - } - } - else if (type.isString()) { - return yieldString((IString) value, doc); - } - else if (type.isInteger()) { - return yieldInt((IInteger) value, doc); - } - else if (type.isRational()) { - return yieldRational((IRational) value, doc); - } - else if (type.isReal()) { - return yieldDouble((IReal) value, doc); - } - else if (type.isExternalType()) { - return yieldExternal((IExternalValue) value, doc); - } - - throw new UnsupportedTypeException( - "Outermost or nested tuples, lists, sets, relations or maps are not allowed.", type); - } - - private boolean isListWrapper(Type nodeType) { - return nodeType.getArity() == 1 - && nodeType.getFieldTypes().getFieldType(0).isList(); - } - - private boolean isSetWrapper(Type nodeType) { - return nodeType.getArity() == 1 - && nodeType.getFieldTypes().getFieldType(0).isSet(); - } - - private boolean isRelationWrapper(Type nodeType) { - return nodeType.getArity() == 1 - && nodeType.getFieldTypes().getFieldType(0) - .isRelation(); - } - - private boolean isMapWrapper(Type nodeType) { - return nodeType.getArity() == 1 - && nodeType.getFieldTypes().getFieldType(0).isMap(); - } - - - private Node yieldDouble(IReal value, Document doc) { - return doc.createTextNode(value.toString()); - } - - private Node yieldInt(IInteger value, Document doc) { - return doc.createTextNode(value.toString()); - } - - private Node yieldRational(IRational value, Document doc) { -/* Element element = doc.createElementNS("values", "rat"); - element.setAttribute("num", value.numerator().toString()); - element.setAttribute("denom", value.denominator().toString()); - return element; -*/ - return null; - } - - private Node yieldString(IString value, Document doc) { - return doc.createTextNode(value.getValue()); - } - - private Node yieldExternal(IExternalValue value, Document doc) { - return doc.createTextNode(value.toString()); - } - - private Node yieldMap(INode node, Document doc) { - Element treeNode = doc.createElement(node.getName()); - IMap map = (IMap) node.get(0); - - for (IValue key : map) { - IValue value = map.get(key); - - if (key.getType().isTuple()) { - appendTupleElements(doc, treeNode, key); - } - else { - treeNode.appendChild(yield(key, doc)); - } - - if (value.getType().isTuple()) { - appendTupleElements(doc, treeNode, value); - } - else { - treeNode.appendChild(yield(value, doc)); - } - } - - return treeNode; - } - - private void appendTupleElements(Document doc, Element treeNode, IValue tupleValue) { - ITuple tuple = (ITuple) tupleValue; - - for (IValue element : tuple) { - treeNode.appendChild(yield(element, doc)); - } - } - - private Node yieldRelation(INode node, Document doc) { - Element treeNode = doc.createElement(node.getName()); - ISet relation = (ISet) node.get(0); - assert (relation.getType().isRelation()); - - for (IValue tuple : relation) { - appendTupleElements(doc, treeNode, tuple); - } - - return treeNode; - } - - private Node yieldSet(INode node, Document doc) { - Element treeNode = doc.createElement(node.getName()); - ISet set = (ISet) node.get(0); - - for (IValue elem : set) { - if (elem.getType().isTuple()) { - appendTupleElements(doc, treeNode, elem); - } - else { - treeNode.appendChild(yield(elem, doc)); - } - } - - return treeNode; - } - - private Node yieldList(INode node, Document doc) { - Element treeNode = doc.createElement(node.getName()); - IList list = (IList) node.get(0); - - for (IValue elem : list) { - if (elem.getType().isTuple()) { - appendTupleElements(doc, treeNode, elem); - } - else { - treeNode.appendChild(yield(elem, doc)); - } - } - - return treeNode; - } - - private Node yieldTree(INode value, Document doc) { - Element treeNode = doc.createElement(value.getName()); - - for (IValue child : value) { - if (child.getType().isTuple()) { - appendTupleElements(doc, treeNode, child); - } - else { - treeNode.appendChild(yield(child, doc)); - } - } - - return treeNode; - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/binary/BinaryReader.java b/value-core/src/main/java/org/rascalmpl/value/io/binary/BinaryReader.java deleted file mode 100644 index e2538f64b..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/binary/BinaryReader.java +++ /dev/null @@ -1,1020 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009, 2015 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -* Anya Helene Bagge - labeled map types; safer reading -*******************************************************************************/ -package org.rascalmpl.value.io.binary; - -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; -import java.util.Map.Entry; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactParseError; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; -import org.rascalmpl.value.util.ResizingArray; -import org.rascalmpl.value.util.ShareableHashMap; - -// TODO Change this thing so it doesn't use recursion. -/** - * @author Arnold Lankamp - */ -public class BinaryReader{ - private final static int DEFAULT_SHARED_VALUES_STORE_SIZE = 1024; - private final static int DEFAULT_SHARED_TYPES_STORE_SIZE = 128; - private final static int DEFAULT_SHARED_PATHS_STORE_SIZE = 128; - private final static int DEFAULT_SHARED_NAMES_STORE_SIZE = 128; - - private final static int BOOL_HEADER = 0x01; - private final static int INTEGER_HEADER = 0x02; - private final static int BIG_INTEGER_HEADER = 0x03; // Special case of INTEGER_HEADER (flags for alternate encoding). - private final static int DOUBLE_HEADER = 0x04; - private final static int IEEE754_ENCODED_DOUBLE_HEADER = 0x14; - private final static int STRING_HEADER = 0x05; - private final static int SOURCE_LOCATION_HEADER = 0x06; - private final static int DATE_TIME_HEADER = 0x10; - private final static int TUPLE_HEADER = 0x07; - private final static int NODE_HEADER = 0x08; - private final static int ANNOTATED_NODE_HEADER = 0x09; - private final static int CONSTRUCTOR_HEADER = 0x0a; - private final static int ANNOTATED_CONSTRUCTOR_HEADER = 0x0b; - private final static int LIST_HEADER = 0x0c; - private final static int SET_HEADER = 0x0d; - private final static int RELATION_HEADER = 0x0e; - private final static int MAP_HEADER = 0x0f; - private final static int RATIONAL_HEADER = 0x11; - private final static int KEYWORDED_NODE_HEADER = 0x12; - private final static int KEYWORDED_CONSTRUCTOR_HEADER = 0x13; - - private final static int VALUE_TYPE_HEADER = 0x01; - private final static int VOID_TYPE_HEADER = 0x02; - private final static int BOOL_TYPE_HEADER = 0x03; - private final static int INTEGER_TYPE_HEADER = 0x04; - private final static int DOUBLE_TYPE_HEADER = 0x05; - private final static int STRING_TYPE_HEADER = 0x06; - private final static int SOURCE_LOCATION_TYPE_HEADER = 0x07; - - private final static int DATE_TIME_TYPE_HEADER = 0x14; - private final static int NODE_TYPE_HEADER = 0x08; - private final static int TUPLE_TYPE_HEADER = 0x09; - private final static int LIST_TYPE_HEADER = 0x0a; - private final static int SET_TYPE_HEADER = 0x0b; - private final static int RELATION_TYPE_HEADER = 0x0c; - private final static int MAP_TYPE_HEADER = 0x0d; - private final static int PARAMETER_TYPE_HEADER = 0x0e; - private final static int ADT_TYPE_HEADER = 0x0f; - private final static int CONSTRUCTOR_TYPE_HEADER = 0x10; - private final static int ALIAS_TYPE_HEADER = 0x11; - private final static int ANNOTATED_NODE_TYPE_HEADER = 0x12; - private final static int ANNOTATED_CONSTRUCTOR_TYPE_HEADER = 0x13; - private final static int RATIONAL_TYPE_HEADER = 0x15; - private final static int NUM_TYPE_HEADER = 0x16; - private final static int KEYWORDED_CONSTRUCTOR_TYPE_HEADER = 0x17; - - private final static int TYPE_MASK = 0x1f; - - private final static int SHARED_FLAG = 0x80; - private final static int TYPE_SHARED_FLAG = 0x40; - private final static int URL_SHARED_FLAG = 0x20; - private final static int NAME_SHARED_FLAG = 0x20; - - private final static int HAS_FIELD_NAMES = 0x20; - - private final static int DATE_TIME_INDICATOR = 0x01; - private final static int DATE_INDICATOR = 0x02; - - private final static TypeFactory tf = TypeFactory.getInstance(); - - private final ResizingArray sharedValues; - private int currentSharedValueId; - private final ResizingArray sharedTypes; - private int currentSharedTypeId; - private final ResizingArray sharedPaths; - private int currentSharedPathId; - private final ResizingArray sharedNames; - private int currentSharedNamesId; - - private final IValueFactory valueFactory; - private final TypeStore typeStore; - private final InputStream in; - - public BinaryReader(IValueFactory valueFactory, TypeStore typeStore, InputStream inputStream){ - super(); - - this.valueFactory = valueFactory; - this.typeStore = typeStore; - this.in = inputStream; - - sharedValues = new ResizingArray<>(DEFAULT_SHARED_VALUES_STORE_SIZE); - currentSharedValueId = 0; - sharedTypes = new ResizingArray<>(DEFAULT_SHARED_TYPES_STORE_SIZE); - currentSharedTypeId = 0; - sharedPaths = new ResizingArray<>(DEFAULT_SHARED_PATHS_STORE_SIZE); - currentSharedPathId = 0; - sharedNames = new ResizingArray<>(DEFAULT_SHARED_NAMES_STORE_SIZE); - currentSharedNamesId = 0; - } - - public IValue deserialize() throws IOException{ - int header = read(); - if((header & SHARED_FLAG) == SHARED_FLAG){ - return sharedValues.get(parseInteger()); - } - - IValue value; - - int valueType = header & TYPE_MASK; - switch(valueType){ - case BOOL_HEADER: - value = readBool(); - break; - case INTEGER_HEADER: - value = readInteger(); - break; - case BIG_INTEGER_HEADER: - value = readBigInteger(); - break; - case DOUBLE_HEADER: - value = readDouble(); - break; - case IEEE754_ENCODED_DOUBLE_HEADER: - value = readIEEE754EncodedDouble(); - break; - case STRING_HEADER: - value = readString(); - break; - case SOURCE_LOCATION_HEADER: - value = readSourceLocation(header); - break; - case DATE_TIME_HEADER: - value = readDateTime(); - break; - case TUPLE_HEADER: - value = readTuple(); - break; - case NODE_HEADER: - value = readNode(header); - break; - case ANNOTATED_NODE_HEADER: - value = readAnnotatedNode(header); - break; - case CONSTRUCTOR_HEADER: - value = readConstructor(header); - break; - case ANNOTATED_CONSTRUCTOR_HEADER: - value = readAnnotatedConstructor(header); - break; - case LIST_HEADER: - value = readList(header); - break; - case SET_HEADER: - value = readSet(header); - break; - case RELATION_HEADER: - value = readRelation(header); - break; - case MAP_HEADER: - value = readMap(header); - break; - case RATIONAL_HEADER: - value = readRational(); - break; - case KEYWORDED_NODE_HEADER: - value = readKeywordedNode(header); - break; - case KEYWORDED_CONSTRUCTOR_HEADER: - value = readKeywordedConstructor(header); - break; - default: - throw new RuntimeException("Unknow value type: "+valueType); - } - - boolean hashValue = true; - - if (value.getType().isAbstractData()) { - IConstructor consValue = (IConstructor)value; - if (!(consValue.mayHaveKeywordParameters() && consValue.asWithKeywordParameters().hasParameters()) && (consValue.isAnnotatable() && consValue.asAnnotatable().hasAnnotations())) { - Map amap = consValue.asAnnotatable().getAnnotations(); - for (Entry aEntry : amap.entrySet()) { - Type aType = aEntry.getValue().getType(); - if (!aType.equivalent(tf.voidType()) && aType.isSourceLocation()) { - hashValue = false; - break; - } - } - } - } - - if (hashValue) { - sharedValues.set(value, currentSharedValueId++); - } - - return value; - } - - // Called by value stuff. - private Type readType(int header) throws IOException{ - if((header & TYPE_SHARED_FLAG) == TYPE_SHARED_FLAG){ - return sharedTypes.get(parseInteger()); - } - - return doReadType(read()); - } - - // Called by type stuff. - private Type doReadType() throws IOException{ - return doReadType(read()); - } - - private Type doReadType(int typeHeader) throws IOException{ - if((typeHeader & SHARED_FLAG) == SHARED_FLAG){ - return sharedTypes.get(parseInteger()); - } - - Type type; - - int typeType = typeHeader & TYPE_MASK; - switch(typeType){ - case VALUE_TYPE_HEADER: - type = readValueType(); - break; - case VOID_TYPE_HEADER: - type = readVoidType(); - break; - case BOOL_TYPE_HEADER: - type = readBoolType(); - break; - case INTEGER_TYPE_HEADER: - type = readIntegerType(); - break; - case DOUBLE_TYPE_HEADER: - type = readDoubleType(); - break; - case STRING_TYPE_HEADER: - type = readStringType(); - break; - case SOURCE_LOCATION_TYPE_HEADER: - type = readSourceLocationType(); - break; - case DATE_TIME_TYPE_HEADER: - type = readDateTimeType(); - break; - case NODE_TYPE_HEADER: - type = readNodeType(); - break; - case TUPLE_TYPE_HEADER: - type = readTupleType(typeHeader); - break; - case LIST_TYPE_HEADER: - type = readListType(); - break; - case SET_TYPE_HEADER: - type = readSetType(); - break; - case RELATION_TYPE_HEADER: - type = readRelationType(); - break; - case MAP_TYPE_HEADER: - type = readMapType(typeHeader); - break; - case PARAMETER_TYPE_HEADER: - type = readParameterType(); - break; - case ADT_TYPE_HEADER: - type = readADTType(); - break; - case CONSTRUCTOR_TYPE_HEADER: - type = readConstructorType(); - break; - case ALIAS_TYPE_HEADER: - type = readAliasType(); - break; - case ANNOTATED_NODE_TYPE_HEADER: - type = readAnnotatedNodeType(); - break; - case ANNOTATED_CONSTRUCTOR_TYPE_HEADER: - type = readAnnotatedConstructorType(); - break; - case RATIONAL_TYPE_HEADER: - type = readRationalType(); - break; - case NUM_TYPE_HEADER: - type = readNumType(); - break; - case KEYWORDED_CONSTRUCTOR_TYPE_HEADER: - type = readKeywordedConstructorType(); - break; - default: - throw new RuntimeException("Unkown type type: "+typeType); - } - - sharedTypes.set(type, currentSharedTypeId++); - - return type; - } - - private IBool readBool() throws IOException{ - int bool = read(); - - return valueFactory.bool(bool == 0 ? false : true); - } - - private IInteger readInteger() throws IOException{ - int integerValue = parseInteger(); - - return valueFactory.integer(integerValue); - } - - private IInteger readBigInteger() throws IOException{ - int length = parseInteger(); - byte[] integerData = new byte[length]; - read(integerData, 0, length); - - return valueFactory.integer(integerData); - } - - private IRational readRational() throws IOException{ - int length = parseInteger(); - byte[] valueData = new byte[length]; - read(valueData, 0, length); - IInteger num = valueFactory.integer(valueData); - - length = parseInteger(); - valueData = new byte[length]; - read(valueData, 0, length); - IInteger denom = valueFactory.integer(valueData); - - return valueFactory.rational(num, denom); - } - - private IReal readDouble() throws IOException{ - int length = parseInteger(); - byte[] unscaledValueData = new byte[length]; - read(unscaledValueData, 0, length); - int scale = parseInteger(); - - return valueFactory.real(new BigDecimal(new BigInteger(unscaledValueData), scale).toString()); // The toString call kind of stinks. - } - - private IReal readIEEE754EncodedDouble() throws IOException{ - double theDouble = parseDouble(); - - return valueFactory.real(theDouble); // The toString call kind of stinks. - } - - private IString readString() throws IOException{ - int size = parseInteger(); - - byte[] data = new byte[size]; - for(int i = 0; i< size; i++){ - data[i] = (byte) read(); - } - - return valueFactory.string(new String(data, BinaryWriter.CharEncoding)); - } - - private ISourceLocation readSourceLocation(int header) throws IOException{ - ISourceLocation path; - if((header & URL_SHARED_FLAG) == URL_SHARED_FLAG){ - int path_id = parseInteger(); - path = sharedPaths.get(path_id); - }else{ - int pathSize = parseInteger(); - - byte[] data = new byte[pathSize]; - for(int i = 0; i< pathSize; i++){ - data[i] = (byte) read(); - } - - try{ - path = valueFactory.sourceLocation(new URI(new String(data, BinaryWriter.CharEncoding))); - }catch(URISyntaxException e){ - throw new FactParseError("Illegal URI", e); // Can't happen. - } - sharedPaths.set(path, currentSharedPathId++); - } - - - int offset = parseInteger(); - int length = parseInteger(); - int beginLine = parseInteger(); - int endLine = parseInteger(); - int beginCol = parseInteger(); - int endCol = parseInteger(); - - if (offset < 0) { - return path; - } - - if (beginLine < 0) { - return valueFactory.sourceLocation(path, offset, length); - } - return valueFactory.sourceLocation(path, offset, length, beginLine, endLine, beginCol, endCol); - } - - private IDateTime readDateTime() throws IOException{ - int typeIndicator = read(); - - if(typeIndicator == DATE_TIME_INDICATOR){ - int year = parseInteger(); - int month = parseInteger(); - int day = parseInteger(); - - int hour = parseInteger(); - int minute = parseInteger(); - int second = parseInteger(); - int millisecond = parseInteger(); - - int timeZoneHourOffset = parseInteger(); - int timeZoneMinuteOffset = parseInteger(); - - return valueFactory.datetime(year, month, day, hour, minute, second, millisecond, timeZoneHourOffset, timeZoneMinuteOffset); - }else if(typeIndicator == DATE_INDICATOR){ - int year = parseInteger(); - int month = parseInteger(); - int day = parseInteger(); - - return valueFactory.date(year, month, day); - }else{ - int hour = parseInteger(); - int minute = parseInteger(); - int second = parseInteger(); - int millisecond = parseInteger(); - - int timeZoneHourOffset = parseInteger(); - int timeZoneMinuteOffset = parseInteger(); - - return valueFactory.time(hour, minute, second, millisecond, timeZoneHourOffset, timeZoneMinuteOffset); - } - } - - private ITuple readTuple() throws IOException{ - int arity = parseInteger(); - - IValue[] content = new IValue[arity]; - for(int i = 0; i < arity; i++){ - content[i] = deserialize(); - } - - return valueFactory.tuple(content); - } - - private INode readNode(int header) throws IOException{ - String nodeName; - if((header & NAME_SHARED_FLAG) == NAME_SHARED_FLAG){ - nodeName = sharedNames.get(parseInteger()); - }else{ - int nodeNameLength = parseInteger(); - - byte[] data = new byte[nodeNameLength]; - for(int i = 0; i < nodeNameLength; i++){ - data[i] = (byte) read(); - } - nodeName = new String(data, BinaryWriter.CharEncoding); - - sharedNames.set(nodeName, currentSharedNamesId++); - } - - int arity = parseInteger(); - - IValue[] content = new IValue[arity]; - for(int i = 0; i < arity; i++){ - content[i] = deserialize(); - } - - return valueFactory.node(nodeName, content); - } - private INode readKeywordedNode(int header) throws IOException{ - String nodeName; - if((header & NAME_SHARED_FLAG) == NAME_SHARED_FLAG){ - nodeName = sharedNames.get(parseInteger()); - }else{ - int nodeNameLength = parseInteger(); - - byte[] data = new byte[nodeNameLength]; - for(int i = 0; i < nodeNameLength; i++){ - data[i] = (byte) read(); - } - nodeName = new String(data, BinaryWriter.CharEncoding); - - sharedNames.set(nodeName, currentSharedNamesId++); - } - - int arity = parseInteger(); - - IValue[] content = new IValue[arity]; - for(int i = 0; i < arity; i++){ - content[i] = deserialize(); - } - - int numberOfKeywordParameters = parseInteger(); - - ShareableHashMap kwParams = new ShareableHashMap<>(); - for(int i = numberOfKeywordParameters - 1; i >= 0; i--){ - int nameLength = parseInteger(); - byte[] nameData = new byte[nameLength]; - read(nameData); - String name = new String(nameData, BinaryWriter.CharEncoding); - - IValue value = deserialize(); - - kwParams.put(name, value); - } - - return valueFactory.node(nodeName, content, kwParams); - } - - private INode readAnnotatedNode(int header) throws IOException{ - String nodeName; - if((header & NAME_SHARED_FLAG) == NAME_SHARED_FLAG){ - nodeName = sharedNames.get(parseInteger()); - }else{ - int nodeNameLength = parseInteger(); - - byte[] data = new byte[nodeNameLength]; - for(int i = 0; i < nodeNameLength; i++){ - data[i] = (byte) read(); - } - nodeName = new String(data, BinaryWriter.CharEncoding); - - sharedNames.set(nodeName, currentSharedNamesId++); - } - - int arity = parseInteger(); - - IValue[] content = new IValue[arity]; - for(int i = 0; i < arity; i++){ - content[i] = deserialize(); - } - - int numberOfAnnotations = parseInteger(); - - ShareableHashMap annotations = new ShareableHashMap<>(); - for(int i = numberOfAnnotations - 1; i >= 0; i--){ - int labelLength = parseInteger(); - byte[] labelData = new byte[labelLength]; - read(labelData); - String label = new String(labelData, BinaryWriter.CharEncoding); - - IValue value = deserialize(); - - annotations.put(label, value); - } - - INode node = valueFactory.node(nodeName, content); - return node.asAnnotatable().setAnnotations(annotations); - } - - private IConstructor readConstructor(int header) throws IOException{ - Type constructorType = readType(header); - - int arity = parseInteger(); - - IValue[] content = new IValue[arity]; - for(int i = 0; i < arity; i++){ - content[i] = deserialize(); - } - - return valueFactory.constructor(constructorType, content); - } - - private IConstructor readKeywordedConstructor(int header) throws IOException{ - Type constructorType = readType(header); - - int arity = parseInteger(); - - IValue[] content = new IValue[arity]; - for(int i = 0; i < arity; i++){ - content[i] = deserialize(); - } - - int numberOfKeywordParams = parseInteger(); - - ShareableHashMap kwParams = new ShareableHashMap<>(); - for(int i = numberOfKeywordParams - 1; i >= 0; i--){ - int nameLength = parseInteger(); - byte[] nameData = new byte[nameLength]; - read(nameData); - String name = new String(nameData, BinaryWriter.CharEncoding); - - IValue value = deserialize(); - - kwParams.put(name, value); - } - - return valueFactory.constructor(constructorType, content, kwParams); - } - - private IConstructor readAnnotatedConstructor(int header) throws IOException{ - Type constructorType = readType(header); - - int arity = parseInteger(); - - IValue[] content = new IValue[arity]; - for(int i = 0; i < arity; i++){ - content[i] = deserialize(); - } - - int numberOfAnnotations = parseInteger(); - - ShareableHashMap annotations = new ShareableHashMap<>(); - for(int i = numberOfAnnotations - 1; i >= 0; i--){ - int labelLength = parseInteger(); - byte[] labelData = new byte[labelLength]; - read(labelData); - String label = new String(labelData, BinaryWriter.CharEncoding); - - IValue value = deserialize(); - - annotations.put(label, value); - } - - IConstructor constructor = valueFactory.constructor(constructorType, content); - return constructor.asAnnotatable().setAnnotations(annotations); - } - - private IList readList(int header) throws IOException{ - Type elementType = readType(header); - - int length = parseInteger(); - - IListWriter listWriter = valueFactory.listWriter(elementType); - for(int i = 0; i < length; i++){ - listWriter.append(deserialize()); - } - - return listWriter.done(); - } - - private ISet readSet(int header) throws IOException{ - Type elementType = readType(header); - - int length = parseInteger(); - - ISetWriter setWriter = valueFactory.setWriter(elementType); - for(int i = 0; i < length; i++){ - setWriter.insert(deserialize()); - } - - return setWriter.done(); - } - - private ISet readRelation(int header) throws IOException{ - Type elementType = readType(header); - - int length = parseInteger(); - - ISetWriter relationWriter = valueFactory.relationWriter(elementType); - for(int i = 0; i < length; i++){ - relationWriter.insert(deserialize()); - } - - return relationWriter.done(); - } - - private IMap readMap(int header) throws IOException{ - Type mapType = readType(header); - - int length = parseInteger(); - - IMapWriter mapWriter = valueFactory.mapWriter(mapType); - for(int i = 0; i < length; i++){ - IValue key = deserialize(); - IValue value = deserialize(); - - mapWriter.put(key, value); - } - - return mapWriter.done(); - } - - private Type readValueType(){ - return tf.valueType(); - } - - private Type readVoidType(){ - return tf.voidType(); - } - - private Type readBoolType(){ - return tf.boolType(); - } - - private Type readIntegerType(){ - return tf.integerType(); - } - - private Type readNumType(){ - return tf.numberType(); - } - - private Type readRationalType(){ - return tf.rationalType(); - } - - private Type readDoubleType(){ - return tf.realType(); - } - - private Type readStringType(){ - return tf.stringType(); - } - - private Type readSourceLocationType(){ - return tf.sourceLocationType(); - } - - private Type readDateTimeType(){ - return tf.dateTimeType(); - } - - private Type readNodeType(){ - return tf.nodeType(); - } - - private Type readAnnotatedNodeType() throws IOException{ - Type nodeType = tf.nodeType(); - - int nrOfAnnotations = parseInteger(); - for(--nrOfAnnotations; nrOfAnnotations >= 0; nrOfAnnotations--){ - int nrOfLabelBytes = parseInteger(); - byte[] labelBytes = new byte[nrOfLabelBytes]; - read(labelBytes); - String label = new String(labelBytes, BinaryWriter.CharEncoding); - - Type valueType = doReadType(); - - typeStore.declareAnnotation(nodeType, label, valueType); - } - - return nodeType; - } - - private Type readTupleType(int header) throws IOException{ - boolean hasFieldNames = ((header & HAS_FIELD_NAMES) == HAS_FIELD_NAMES); - - if(hasFieldNames){ - int arity = parseInteger(); - - Type[] fields = new Type[arity]; - String[] fieldNames = new String[arity]; - for(int i = 0; i < arity; i++){ - fields[i] = doReadType(); - - int fieldNameLength = parseInteger(); - byte[] fieldNameData = new byte[fieldNameLength]; - read(fieldNameData); - fieldNames[i] = new String(fieldNameData, BinaryWriter.CharEncoding); - } - - return tf.tupleType(fields, fieldNames); - } - - int arity = parseInteger(); - - Type[] fields = new Type[arity]; - for(int i = 0; i < arity; i++){ - fields[i] = doReadType(); - } - - return tf.tupleType(fields); - } - - private Type readListType() throws IOException{ - Type elementType = doReadType(); - - return tf.listType(elementType); - } - - private Type readSetType() throws IOException{ - Type elementType = doReadType(); - - return tf.setType(elementType); - } - - private Type readRelationType() throws IOException{ - Type elementType = doReadType(); - - return tf.relTypeFromTuple(elementType); - } - - private Type readMapType(int header) throws IOException{ - boolean hasFieldNames = ((header & HAS_FIELD_NAMES) == HAS_FIELD_NAMES); - - if(hasFieldNames){ - Type keyType = doReadType(); - int keyLabelLength = parseInteger(); - byte[] keyLabelData = new byte[keyLabelLength]; - read(keyLabelData); - String keyLabel = new String(keyLabelData, BinaryWriter.CharEncoding); - - Type valueType = doReadType(); - int valueLabelLength = parseInteger(); - byte[] valueLabelData = new byte[valueLabelLength]; - read(valueLabelData); - String valueLabel = new String(valueLabelData, BinaryWriter.CharEncoding); - - return tf.mapType(keyType, keyLabel, valueType, valueLabel); - } - else { - Type keyType = doReadType(); - Type valueType = doReadType(); - - - return tf.mapType(keyType, valueType); - } - } - - private Type readParameterType() throws IOException{ - int nameLength = parseInteger(); - byte[] nameData = new byte[nameLength]; - read(nameData); - String name = new String(nameData, BinaryWriter.CharEncoding); - - Type bound = doReadType(); - - return tf.parameterType(name, bound); - } - - private Type readADTType() throws IOException{ - int nameLength = parseInteger(); - byte[] nameData = new byte[nameLength]; - read(nameData); - String name = new String(nameData, BinaryWriter.CharEncoding); - - Type parameters = doReadType(); - - return tf.abstractDataTypeFromTuple(typeStore, name, parameters); - } - - private Type readConstructorType() throws IOException{ - int nameLength = parseInteger(); - byte[] nameData = new byte[nameLength]; - read(nameData); - String name = new String(nameData, BinaryWriter.CharEncoding); - - Type fieldTypes = doReadType(); - - Type adtType = doReadType(); - - return tf.constructorFromTuple(typeStore, adtType, name, fieldTypes); - } - - private Type readKeywordedConstructorType() throws IOException{ - int nameLength = parseInteger(); - byte[] nameData = new byte[nameLength]; - read(nameData); - String name = new String(nameData, BinaryWriter.CharEncoding); - - Type fieldTypes = doReadType(); - - Type adtType = doReadType(); - - return tf.constructorFromTuple(typeStore, adtType, name, fieldTypes); - } - - private Type readAnnotatedConstructorType() throws IOException{ - int nameLength = parseInteger(); - byte[] nameData = new byte[nameLength]; - read(nameData); - String name = new String(nameData, BinaryWriter.CharEncoding); - - Type fieldTypes = doReadType(); - - Type adtType = doReadType(); - - Type constructorType = tf.constructorFromTuple(typeStore, adtType, name, fieldTypes); - - int nrOfAnnotations = parseInteger(); - for(--nrOfAnnotations; nrOfAnnotations >= 0; nrOfAnnotations--){ - int nrOfLabelBytes = parseInteger(); - byte[] labelBytes = new byte[nrOfLabelBytes]; - read(labelBytes); - String label = new String(labelBytes, BinaryWriter.CharEncoding); - - Type valueType = doReadType(); - - typeStore.declareAnnotation(constructorType, label, valueType); - } - - return constructorType; - } - - private Type readAliasType() throws IOException{ - int nameLength = parseInteger(); - byte[] nameData = new byte[nameLength]; - read(nameData); - String name = new String(nameData, BinaryWriter.CharEncoding); - - Type aliasedType = doReadType(); - - Type parameters = doReadType(); - - return tf.aliasTypeFromTuple(typeStore, name, aliasedType, parameters); - } - - private final static int SEVENBITS = 0x0000007f; - private final static int SIGNBIT = 0x00000080; - - private int parseInteger() throws IOException{ - int part = read(); - int result = (part & SEVENBITS); - - if((part & SIGNBIT) == 0) return result; - - part = read(); - result |= ((part & SEVENBITS) << 7); - if((part & SIGNBIT) == 0) return result; - - part = read(); - result |= ((part & SEVENBITS) << 14); - if((part & SIGNBIT) == 0) return result; - - part = read(); - result |= ((part & SEVENBITS) << 21); - if((part & SIGNBIT) == 0) return result; - - part = read(); - result |= ((part & SEVENBITS) << 28); - return result; - } - - private final static int BYTEMASK = 0x000000ff; - private final static int BYTEBITS = 8; - private final static int LONGBITS = 8; - - private double parseDouble() throws IOException{ - long result = 0; - for(int i = 0; i < LONGBITS; i++){ - result |= ((((long) read()) & BYTEMASK) << (i * BYTEBITS)); - } - return Double.longBitsToDouble(result); - } - - private int read() throws IOException { - int b = in.read(); - - if(b == -1) { - throw new UnexpectedEOF(); - } - - return b; - } - - private void read(byte[] buffer) throws IOException { - read(buffer, 0, buffer.length); - } - - private void read(byte[] buffer, int offset, int length) throws IOException { - int read; - - while(length > 0) { - read = in.read(buffer, offset, length); - - if(read == -1) { - throw new UnexpectedEOF(); - } - - length = length - read; - offset = offset + read; - } - } - - static class UnexpectedEOF extends IOException { - private static final long serialVersionUID = -907629554395808678L; - - public UnexpectedEOF() { - super("unexpected end of file"); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/io/binary/BinaryWriter.java b/value-core/src/main/java/org/rascalmpl/value/io/binary/BinaryWriter.java deleted file mode 100644 index 9e4a5055d..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/io/binary/BinaryWriter.java +++ /dev/null @@ -1,1092 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009-2015 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -* Anya Helene Bagge - labeled map types -* Jurgen Vinju - externa; types -*******************************************************************************/ -package org.rascalmpl.value.io.binary; - -import java.io.IOException; -import java.io.OutputStream; -import java.net.URI; -import java.util.Iterator; -import java.util.Map; -import java.util.Objects; -import java.util.Map.Entry; - -import org.rascalmpl.value.IAnnotatable; -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IWithKeywordParameters; -import org.rascalmpl.value.type.ExternalType; -import org.rascalmpl.value.type.ITypeVisitor; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeStore; -import org.rascalmpl.value.util.IndexedSet; -import org.rascalmpl.value.visitors.IValueVisitor; - -// TODO Change this thing so it doesn't use recursion. -/** - * @author Arnold Lankamp - */ -public class BinaryWriter{ - public static final class IdentityValue implements IValue { - private final IValue wrapped; - public IdentityValue(IValue toWrap) { - wrapped = toWrap; - } - - @Override - public int hashCode() { - return System.identityHashCode(wrapped); - } - - @Override - public boolean equals(Object obj) { - return obj instanceof IdentityValue && wrapped == ((IdentityValue)obj).wrapped; - } - - @Override - public Type getType() { - throw new UnsupportedOperationException(); - } - @Override - public T accept(IValueVisitor v) throws E { - throw new UnsupportedOperationException(); - } - @Override - public boolean isEqual(IValue other) { - throw new UnsupportedOperationException(); - } - @Override - public boolean isAnnotatable() { - throw new UnsupportedOperationException(); - } - @Override - public IAnnotatable asAnnotatable() { - throw new UnsupportedOperationException(); - } - @Override - public boolean mayHaveKeywordParameters() { - throw new UnsupportedOperationException(); - } - @Override - public IWithKeywordParameters asWithKeywordParameters() { - throw new UnsupportedOperationException(); - } - - } - - /*package*/ static final String CharEncoding = "UTF8"; - private final static int BOOL_HEADER = 0x01; -// private final static int INTEGER_HEADER = 0x02; - private final static int BIG_INTEGER_HEADER = 0x03; // Special case of INTEGER_HEADER (flags for alternate encoding). - private final static int DOUBLE_HEADER = 0x04; - private final static int STRING_HEADER = 0x05; - private final static int SOURCE_LOCATION_HEADER = 0x06; - private final static int DATE_TIME_HEADER = 0x10; - private final static int TUPLE_HEADER = 0x07; - private final static int NODE_HEADER = 0x08; - private final static int ANNOTATED_NODE_HEADER = 0x09; - private final static int CONSTRUCTOR_HEADER = 0x0a; - private final static int ANNOTATED_CONSTRUCTOR_HEADER = 0x0b; - private final static int LIST_HEADER = 0x0c; - private final static int SET_HEADER = 0x0d; - private final static int MAP_HEADER = 0x0f; - private final static int RATIONAL_HEADER = 0x11; - private final static int KEYWORDED_NODE_HEADER = 0x12; - private final static int KEYWORDED_CONSTRUCTOR_HEADER = 0x13; - - - private final static int VALUE_TYPE_HEADER = 0x01; - private final static int VOID_TYPE_HEADER = 0x02; - private final static int BOOL_TYPE_HEADER = 0x03; - private final static int INTEGER_TYPE_HEADER = 0x04; - private final static int DOUBLE_TYPE_HEADER = 0x05; - private final static int STRING_TYPE_HEADER = 0x06; - private final static int SOURCE_LOCATION_TYPE_HEADER = 0x07; - private final static int DATE_TIME_TYPE_HEADER = 0x14; - private final static int NODE_TYPE_HEADER = 0x08; - private final static int TUPLE_TYPE_HEADER = 0x09; - private final static int LIST_TYPE_HEADER = 0x0a; - private final static int SET_TYPE_HEADER = 0x0b; - private final static int MAP_TYPE_HEADER = 0x0d; - private final static int PARAMETER_TYPE_HEADER = 0x0e; - private final static int ADT_TYPE_HEADER = 0x0f; - private final static int CONSTRUCTOR_TYPE_HEADER = 0x10; - private final static int ALIAS_TYPE_HEADER = 0x11; - private final static int ANNOTATED_NODE_TYPE_HEADER = 0x12; - private final static int ANNOTATED_CONSTRUCTOR_TYPE_HEADER = 0x13; - private final static int RATIONAL_TYPE_HEADER = 0x15; - private final static int NUM_TYPE_HEADER = 0x16; - - private final static int SHARED_FLAG = 0x80; - private final static int TYPE_SHARED_FLAG = 0x40; - private final static int URL_SHARED_FLAG = 0x20; - private final static int NAME_SHARED_FLAG = 0x20; - - private final static int HAS_FIELD_NAMES = 0x20; - - private final static int DATE_TIME_INDICATOR = 0x01; - private final static int DATE_INDICATOR = 0x02; - private final static int TIME_INDICATOR = 0x03; - - private final IndexedSet sharedValues; - private final IndexedSet sharedTypes; - private final IndexedSet sharedPaths; - private final IndexedSet sharedNames; - - private final IValue value; - private final OutputStream out; - private final TypeStore typeStore; - private final boolean maximalSharing; - - public BinaryWriter(IValue value, OutputStream outputStream, TypeStore typeStore){ - this(value, outputStream, true, typeStore); - } - public BinaryWriter(IValue value, OutputStream outputStream, boolean maximalSharing, TypeStore typeStore){ - super(); - - this.value = value; - this.out = outputStream; - this.typeStore = typeStore; - this.maximalSharing = maximalSharing; - - sharedValues = new IndexedSet<>(); - sharedTypes = new IndexedSet<>(); - sharedPaths = new IndexedSet<>(); - sharedNames = new IndexedSet<>(); - } - - public void serialize() throws IOException{ - doSerialize(value); - } - - private void doSerialize(IValue value) throws IOException{ - // This special cases the hashing logic: if we have a constructor with - // at least one location annotation, don't try to hash it - boolean tryHashing = true; - - if (tryHashing && value.getType().isAbstractData()) { - IConstructor consValue = (IConstructor)value; - if (consValue.isAnnotatable() && consValue.asAnnotatable().hasAnnotations()) { - Map amap = consValue.asAnnotatable().getAnnotations(); - for (Entry aEntry : amap.entrySet()) { - Type aType = aEntry.getValue().getType(); - if (!aType.isBottom() && aType.isSourceLocation()) { - tryHashing = false; - break; - } - } - } - } - - boolean alwaysMaximallyShare = value.getType().isString() || value.getType().isNumber() || value.getType().isSourceLocation(); - if (tryHashing) { - int valueId; - if (maximalSharing || alwaysMaximallyShare) { - valueId = sharedValues.get(value); - } - else { - valueId = sharedValues.get(new IdentityValue(value)); - } - if(valueId != -1){ - out.write(SHARED_FLAG); - printInteger(valueId); - return; - } - } - - // This sucks and is order dependent :-/. - if(value instanceof IBool){ - writeBool((IBool) value); - }else if(value instanceof IInteger){ - writeInteger((IInteger) value); - }else if(value instanceof IRational){ - writeRational((IRational) value); - }else if(value instanceof IReal){ - writeDouble((IReal) value); - }else if(value instanceof IString){ - writeString((IString) value); - }else if(value instanceof ISourceLocation){ - writeSourceLocation((ISourceLocation) value); - }else if(value instanceof IDateTime){ - writeDateTime((IDateTime) value); - }else if(value instanceof ITuple){ - writeTuple((ITuple) value); - }else if(value instanceof IConstructor){ - IConstructor constructor = (IConstructor) value; - if (constructor.mayHaveKeywordParameters() && constructor.asWithKeywordParameters().hasParameters()) { - writeKeywordedConstructor(constructor); - } - else if (!constructor.mayHaveKeywordParameters() && constructor.isAnnotatable() && constructor.asAnnotatable().hasAnnotations()) { - writeAnnotatedConstructor(constructor); - } - else { - writeConstructor(constructor); - } - }else if(value instanceof INode){ - INode node = (INode) value; - if (node.mayHaveKeywordParameters() && node.asWithKeywordParameters().hasParameters()) { - writeKeywordedNode(node); - } - else if (!node.mayHaveKeywordParameters() && node.asAnnotatable().hasAnnotations()) { - writeAnnotatedNode(node); - } - else { - writeNode(node); - } - }else if(value instanceof IList){ - writeList((IList) value); - }else if(value instanceof ISet){ - writeSet((ISet) value); - }else if(value instanceof IMap){ - writeMap((IMap) value); - } - - if (tryHashing) { - if (maximalSharing || alwaysMaximallyShare) { - sharedValues.store(value); - } - else { - sharedValues.store(new IdentityValue(value)); - } - } - } - - private void doWriteType(Type type) throws IOException{ - // This sucks and is order dependent :-/. - type.accept(new ITypeVisitor() { - - @Override - public Type visitReal(Type type) throws IOException { - writeDoubleType(); - return type; - } - - @Override - public Type visitInteger(Type type) throws IOException { - writeIntegerType(); - return type; - } - - @Override - public Type visitRational(Type type) throws IOException { - writeRationalType(); - return type; - } - - @Override - public Type visitList(Type type) throws IOException { - writeListType(type); - return type; - } - - @Override - public Type visitMap(Type type) throws IOException { - writeMapType(type); - return type; - } - - @Override - public Type visitNumber(Type type) throws IOException { - writeNumType(); - return type; - } - - @Override - public Type visitAlias(Type type) throws IOException { - writeAliasType(type); - return type; - } - - @Override - public Type visitSet(Type type) throws IOException { - writeSetType(type); - return type; - } - - @Override - public Type visitSourceLocation(Type type) throws IOException { - writeSourceLocationType(); - return type; - } - - @Override - public Type visitString(Type type) throws IOException { - writeStringType(); - return type; - } - - @Override - public Type visitNode(Type type) throws IOException { - writeNodeType(type); - return type; - } - - @Override - public Type visitConstructor(Type type) throws IOException { - writeConstructorType(type); - return type; - } - - @Override - public Type visitAbstractData(Type type) throws IOException { - writeADTType(type); - return type; - } - - @Override - public Type visitTuple(Type type) throws IOException { - writeTupleType(type); - return type; - } - - @Override - public Type visitValue(Type type) throws IOException { - writeValueType(); - return type; - } - - @Override - public Type visitVoid(Type type) throws IOException { - writeVoidType(); - return type; - } - - @Override - public Type visitBool(Type type) throws IOException { - writeBoolType(); - return type; - } - - @Override - public Type visitParameter(Type type) throws IOException { - writeParameterType(type); - return type; - } - - @Override - public Type visitExternal(Type type) throws IOException { - return visitAbstractData(((ExternalType) type).asAbstractDataType()); - } - - @Override - public Type visitDateTime(Type type) throws IOException { - writeDateTimeType(type); - return type; - } - }); - } - - private void writeType(Type type) throws IOException{ - int typeId = sharedTypes.get(type); - if(typeId != -1){ - out.write(SHARED_FLAG); - printInteger(typeId); - return; - } - - doWriteType(type); - - sharedTypes.store(type); - } - - private void writeBool(IBool bool) throws IOException{ - out.write(BOOL_HEADER); - - if(bool.getValue()){ - out.write(1); - }else{ - out.write(0); - } - } - - private void writeInteger(IInteger integer) throws IOException{ - byte[] valueData = integer.getTwosComplementRepresentation(); - int length = valueData.length; - out.write(BIG_INTEGER_HEADER); - printInteger(length); - out.write(valueData, 0, length); - } - - /** - * Format: - * header - * length of numerator - * numerator byte[] - * length of denominator - * denominator byte[] - */ - private void writeRational(IRational rational) throws IOException{ - out.write(RATIONAL_HEADER); - - byte[] valueData = rational.numerator().getTwosComplementRepresentation(); - int length = valueData.length; - printInteger(length); - out.write(valueData, 0, length); - - valueData = rational.denominator().getTwosComplementRepresentation(); - length = valueData.length; - printInteger(length); - out.write(valueData, 0, length); - - } - private void writeDouble(IReal real) throws IOException{ - out.write(DOUBLE_HEADER); - - byte[] valueData = real.unscaled().getTwosComplementRepresentation(); - int length = valueData.length; - printInteger(length); - out.write(valueData, 0, length); - - printInteger(real.scale()); - } - - private void writeString(IString string) throws IOException{ - out.write(STRING_HEADER); - - String theString = string.getValue(); - - byte[] stringData = theString.getBytes(CharEncoding); - printInteger(stringData.length); - out.write(stringData); - } - - private void writeSourceLocation(ISourceLocation sourceLocation) throws IOException{ - URI uri = sourceLocation.getURI(); - String path = uri.toString(); - int id = sharedPaths.store(path); - - int header = SOURCE_LOCATION_HEADER; - - if(id == -1){ - out.write(header); - - byte[] pathData = path.getBytes(CharEncoding); - printInteger(pathData.length); - out.write(pathData); - } else{ - out.write(header | URL_SHARED_FLAG); - - printInteger(id); - } - - int beginLine, beginColumn, endLine, endColumn; - - if (!sourceLocation.hasLineColumn()) { - beginLine = -1; - endLine = -1; - beginColumn = -1; - endColumn = -1; - } - else { - beginLine = sourceLocation.getBeginLine(); - endLine = sourceLocation.getEndLine(); - beginColumn = sourceLocation.getBeginColumn(); - endColumn = sourceLocation.getEndColumn(); - } - - int offset, length; - if (!sourceLocation.hasOffsetLength()) { - offset = -1; - length = -1; - } - else { - offset = sourceLocation.getOffset(); - length = sourceLocation.getLength(); - } - - printInteger(offset); - printInteger(length); - printInteger(beginLine); - printInteger(endLine); - printInteger(beginColumn); - printInteger(endColumn); - } - - private void writeDateTime(IDateTime dateTime) throws IOException{ - out.write(DATE_TIME_HEADER); - - if(dateTime.isDateTime()){ - out.write(DATE_TIME_INDICATOR); - - printInteger(dateTime.getYear()); - printInteger(dateTime.getMonthOfYear()); - printInteger(dateTime.getDayOfMonth()); - - printInteger(dateTime.getHourOfDay()); - printInteger(dateTime.getMinuteOfHour()); - printInteger(dateTime.getSecondOfMinute()); - printInteger(dateTime.getMillisecondsOfSecond()); - - printInteger(dateTime.getTimezoneOffsetHours()); - printInteger(dateTime.getTimezoneOffsetMinutes()); - }else if(dateTime.isDate()){ - out.write(DATE_INDICATOR); - - printInteger(dateTime.getYear()); - printInteger(dateTime.getMonthOfYear()); - printInteger(dateTime.getDayOfMonth()); - }else{ - out.write(TIME_INDICATOR); - - printInteger(dateTime.getHourOfDay()); - printInteger(dateTime.getMinuteOfHour()); - printInteger(dateTime.getSecondOfMinute()); - printInteger(dateTime.getMillisecondsOfSecond()); - - printInteger(dateTime.getTimezoneOffsetHours()); - printInteger(dateTime.getTimezoneOffsetMinutes()); - } - } - - private void writeTuple(ITuple tuple) throws IOException{ - out.write(TUPLE_HEADER); - - int arity = tuple.arity(); - printInteger(arity); - - for(int i = 0; i < arity; i++){ - doSerialize(tuple.get(i)); - } - } - - private void writeNode(INode node) throws IOException{ - String nodeName = node.getName(); - int nodeNameId = sharedNames.store(nodeName); - - if(nodeNameId == -1){ - out.write(NODE_HEADER); - - byte[] nodeData = nodeName.getBytes(CharEncoding); - printInteger(nodeData.length); - out.write(nodeData); - }else{ - out.write(NODE_HEADER | NAME_SHARED_FLAG); - - printInteger(nodeNameId); - } - - int arity = node.arity(); - printInteger(arity); - - for(int i = 0; i < arity; i++){ - doSerialize(node.get(i)); - } - } - - private void writeKeywordedNode(INode node) throws IOException{ - String nodeName = node.getName(); - int nodeNameId = sharedNames.store(nodeName); - - if(nodeNameId == -1){ - out.write(KEYWORDED_NODE_HEADER); - - byte[] nodeData = nodeName.getBytes(CharEncoding); - printInteger(nodeData.length); - out.write(nodeData); - }else{ - out.write(KEYWORDED_NODE_HEADER | NAME_SHARED_FLAG); - - printInteger(nodeNameId); - } - - int arity = node.arity(); - printInteger(arity); - - for(int i = 0; i < arity; i++){ - doSerialize(node.get(i)); - } - - Map kwParams = node.asWithKeywordParameters().getParameters(); - - printInteger(kwParams.size()); - - for (Map.Entry param : kwParams.entrySet()) { - String label = param.getKey(); - byte[] labelData = label.getBytes(CharEncoding); - printInteger(labelData.length); - out.write(labelData); - - IValue value = param.getValue(); - doSerialize(value); - } - } - private void writeAnnotatedNode(INode node) throws IOException{ - String nodeName = node.getName(); - int nodeNameId = sharedNames.store(nodeName); - - if(nodeNameId == -1){ - out.write(ANNOTATED_NODE_HEADER); - - byte[] nodeData = nodeName.getBytes(CharEncoding); - printInteger(nodeData.length); - out.write(nodeData); - }else{ - out.write(ANNOTATED_NODE_HEADER | NAME_SHARED_FLAG); - - printInteger(nodeNameId); - } - - int arity = node.arity(); - printInteger(arity); - - for(int i = 0; i < arity; i++){ - doSerialize(node.get(i)); - } - - Map annotations = node.asAnnotatable().getAnnotations(); - - printInteger(annotations.size()); - - Iterator> annotationsIterator = annotations.entrySet().iterator(); - while(annotationsIterator.hasNext()){ - Map.Entry annotation = annotationsIterator.next(); - String label = annotation.getKey(); - byte[] labelData = label.getBytes(CharEncoding); - printInteger(labelData.length); - out.write(labelData); - - IValue value = annotation.getValue(); - doSerialize(value); - } - } - - private void writeConstructor(IConstructor constructor) throws IOException{ - Type constructorType = constructor.getUninstantiatedConstructorType(); - int constructorTypeId = sharedTypes.get(constructorType); - - if(constructorTypeId == -1){ - out.write(CONSTRUCTOR_HEADER); - - doWriteType(constructorType); - - sharedTypes.store(constructorType); - }else{ - out.write(CONSTRUCTOR_HEADER | TYPE_SHARED_FLAG); - - printInteger(constructorTypeId); - } - - int arity = constructor.arity(); - printInteger(arity); - - for(int i = 0; i < arity; i++){ - doSerialize(constructor.get(i)); - } - } - - private void writeKeywordedConstructor(IConstructor constructor) throws IOException{ - Type constructorType = constructor.getConstructorType(); - int constructorTypeId = sharedTypes.get(constructorType); - - if(constructorTypeId == -1){ - out.write(KEYWORDED_CONSTRUCTOR_HEADER); - - doWriteType(constructorType); - - sharedTypes.store(constructorType); - }else{ - out.write(KEYWORDED_CONSTRUCTOR_HEADER | TYPE_SHARED_FLAG); - - printInteger(constructorTypeId); - } - - int arity = constructor.arity(); - printInteger(arity); - - for(int i = 0; i < arity; i++){ - doSerialize(constructor.get(i)); - } - - Map kwParams = constructor.asWithKeywordParameters().getParameters(); - - printInteger(kwParams.size()); - - for (Map.Entry param: kwParams.entrySet()) { - String label = param.getKey(); - byte[] labelData = label.getBytes(CharEncoding); - printInteger(labelData.length); - out.write(labelData); - - IValue value = param.getValue(); - doSerialize(value); - } - } - - private void writeAnnotatedConstructor(IConstructor constructor) throws IOException{ - Type constructorType = constructor.getConstructorType(); - int constructorTypeId = sharedTypes.get(constructorType); - - if(constructorTypeId == -1){ - out.write(ANNOTATED_CONSTRUCTOR_HEADER); - - doWriteType(constructorType); - - sharedTypes.store(constructorType); - }else{ - out.write(ANNOTATED_CONSTRUCTOR_HEADER | TYPE_SHARED_FLAG); - - printInteger(constructorTypeId); - } - - int arity = constructor.arity(); - printInteger(arity); - - for(int i = 0; i < arity; i++){ - doSerialize(constructor.get(i)); - } - - Map annotations = constructor.asAnnotatable().getAnnotations(); - - printInteger(annotations.size()); - - Iterator> annotationsIterator = annotations.entrySet().iterator(); - while(annotationsIterator.hasNext()){ - Map.Entry annotation = annotationsIterator.next(); - String label = annotation.getKey(); - byte[] labelData = label.getBytes(CharEncoding); - printInteger(labelData.length); - out.write(labelData); - - IValue value = annotation.getValue(); - doSerialize(value); - } - } - - private void writeList(IList list) throws IOException{ - Type elementType = list.getElementType(); - int elementTypeId = sharedTypes.get(elementType); - - if(elementTypeId == -1){ - out.write(LIST_HEADER); - - doWriteType(elementType); - - sharedTypes.store(elementType); - }else{ - out.write(LIST_HEADER | TYPE_SHARED_FLAG); - - printInteger(elementTypeId); - } - - int length = list.length(); - printInteger(length); - for(int i = 0; i < length; i++){ - doSerialize(list.get(i)); - } - } - - private void writeSet(ISet set) throws IOException{ - Type elementType = set.getElementType(); - int elementTypeId = sharedTypes.get(elementType); - - if(elementTypeId == -1){ - out.write(SET_HEADER); - - doWriteType(elementType); - - sharedTypes.store(elementType); - }else{ - out.write(SET_HEADER | TYPE_SHARED_FLAG); - - printInteger(elementTypeId); - } - - printInteger(set.size()); - - Iterator content = set.iterator(); - while(content.hasNext()){ - doSerialize(content.next()); - } - } - - private void writeMap(IMap map) throws IOException{ - Type mapType = map.getType(); - int mapTypeId = sharedTypes.get(mapType); - - if(mapTypeId == -1){ - out.write(MAP_HEADER); - - doWriteType(mapType); - - sharedTypes.store(mapType); - }else{ - out.write(MAP_HEADER | TYPE_SHARED_FLAG); - - printInteger(mapTypeId); - } - - printInteger(map.size()); - - Iterator> content = map.entryIterator(); - while(content.hasNext()){ - Map.Entry entry = content.next(); - - doSerialize(entry.getKey()); - doSerialize(entry.getValue()); - } - } - - private void writeValueType() throws IOException{ - out.write(VALUE_TYPE_HEADER); - } - - private void writeVoidType() throws IOException{ - out.write(VOID_TYPE_HEADER); - } - - private void writeBoolType() throws IOException{ - out.write(BOOL_TYPE_HEADER); - } - - private void writeIntegerType() throws IOException{ - out.write(INTEGER_TYPE_HEADER); - } - - private void writeNumType() throws IOException { - out.write(NUM_TYPE_HEADER); - } - - private void writeRationalType() throws IOException{ - out.write(RATIONAL_TYPE_HEADER); - } - - private void writeDoubleType() throws IOException{ - out.write(DOUBLE_TYPE_HEADER); - } - - private void writeStringType() throws IOException{ - out.write(STRING_TYPE_HEADER); - } - - private void writeSourceLocationType() throws IOException{ - out.write(SOURCE_LOCATION_TYPE_HEADER); - } - - private void writeDateTimeType(Type dateTimeType) throws IOException{ - out.write(DATE_TIME_TYPE_HEADER); - } - - private void writeNodeType(Type nodeType) throws IOException{ - Map declaredAnnotations = typeStore.getAnnotations(nodeType); - if(declaredAnnotations.isEmpty()){ - out.write(NODE_TYPE_HEADER); - }else{ - out.write(ANNOTATED_NODE_TYPE_HEADER); - - // Annotations. - int nrOfAnnotations = declaredAnnotations.size(); - printInteger(nrOfAnnotations); - - Iterator> declaredAnnotationsIterator = declaredAnnotations.entrySet().iterator(); - while(declaredAnnotationsIterator.hasNext()){ - Map.Entry declaredAnnotation = declaredAnnotationsIterator.next(); - - String label = declaredAnnotation.getKey(); - byte[] labelBytes = label.getBytes(CharEncoding); - printInteger(labelBytes.length); - out.write(labelBytes); - - writeType(declaredAnnotation.getValue()); - } - } - } - - private void writeTupleType(Type tupleType) throws IOException{ - boolean hasFieldNames = tupleType.hasFieldNames(); - - if(hasFieldNames){ - out.write(TUPLE_TYPE_HEADER | HAS_FIELD_NAMES); - - int arity = tupleType.getArity(); - printInteger(arity); - for(int i = 0; i < arity; i++){ - writeType(tupleType.getFieldType(i)); - - String name = tupleType.getFieldName(i); - byte[] nameData = name.getBytes(CharEncoding); - printInteger(nameData.length); - out.write(nameData); - } - }else{ - out.write(TUPLE_TYPE_HEADER); - - int arity = tupleType.getArity(); - printInteger(arity); - for(int i = 0; i < arity; i++){ - writeType(tupleType.getFieldType(i)); - } - } - } - - private void writeListType(Type listType) throws IOException{ - out.write(LIST_TYPE_HEADER); - - writeType(listType.getElementType()); - } - - private void writeSetType(Type setType) throws IOException{ - out.write(SET_TYPE_HEADER); - - writeType(setType.getElementType()); - } - - private void writeMapType(Type mapType) throws IOException{ - boolean hasFieldNames = mapType.hasFieldNames(); - - if(hasFieldNames){ - out.write(MAP_TYPE_HEADER | HAS_FIELD_NAMES); - - String name; - byte[] nameData; - - writeType(mapType.getKeyType()); - name = mapType.getKeyLabel(); - nameData = name.getBytes(CharEncoding); - printInteger(nameData.length); - out.write(nameData); - - writeType(mapType.getValueType()); - name = mapType.getValueLabel(); - nameData = name.getBytes(CharEncoding); - printInteger(nameData.length); - out.write(nameData); - } - else { - out.write(MAP_TYPE_HEADER); - writeType(mapType.getKeyType()); - writeType(mapType.getValueType()); - } - } - - private void writeParameterType(Type parameterType) throws IOException{ - out.write(PARAMETER_TYPE_HEADER); - - String name = parameterType.getName(); - byte[] nameData = name.getBytes(CharEncoding); - printInteger(nameData.length); - out.write(nameData); - - writeType(parameterType.getBound()); - } - - private void writeADTType(Type adtType) throws IOException{ - out.write(ADT_TYPE_HEADER); - - String name = adtType.getName(); - byte[] nameData = name.getBytes(CharEncoding); - printInteger(nameData.length); - out.write(nameData); - - writeType(adtType.getTypeParameters()); - } - - private void writeConstructorType(Type constructorType) throws IOException{ - Map declaredAnnotations = typeStore.getAnnotations(constructorType); - if(declaredAnnotations.isEmpty()){ - out.write(CONSTRUCTOR_TYPE_HEADER); - - String name = constructorType.getName(); - byte[] nameData = name.getBytes(CharEncoding); - printInteger(nameData.length); - out.write(nameData); - - writeType(constructorType.getFieldTypes()); - - writeType(constructorType.getAbstractDataType()); - }else{ - out.write(ANNOTATED_CONSTRUCTOR_TYPE_HEADER); - - String name = constructorType.getName(); - byte[] nameData = name.getBytes(CharEncoding); - printInteger(nameData.length); - out.write(nameData); - - writeType(constructorType.getFieldTypes()); - - writeType(constructorType.getAbstractDataType()); - - // Annotations. - int nrOfAnnotations = declaredAnnotations.size(); - printInteger(nrOfAnnotations); - - Iterator> declaredAnnotationsIterator = declaredAnnotations.entrySet().iterator(); - while(declaredAnnotationsIterator.hasNext()){ - Map.Entry declaredAnnotation = declaredAnnotationsIterator.next(); - - String label = declaredAnnotation.getKey(); - byte[] labelBytes = label.getBytes(CharEncoding); - printInteger(labelBytes.length); - out.write(labelBytes); - - writeType(declaredAnnotation.getValue()); - } - } - } - - private void writeAliasType(Type aliasType) throws IOException{ - out.write(ALIAS_TYPE_HEADER); - - String name = aliasType.getName(); - byte[] nameData = name.getBytes(CharEncoding); - printInteger(nameData.length); - out.write(nameData); - - writeType(aliasType.getAliased()); - - writeType(aliasType.getTypeParameters()); - } - - private final static int SEVENBITS = 0x0000007f; - private final static int SIGNBIT = 0x00000080; - - private void printInteger(int value) throws IOException{ - int intValue = value; - - if((intValue & 0xffffff80) == 0){ - out.write((byte) (intValue & SEVENBITS)); - return; - } - out.write((byte) ((intValue & SEVENBITS) | SIGNBIT)); - - if((intValue & 0xffffc000) == 0){ - out.write((byte) ((intValue >>> 7) & SEVENBITS)); - return; - } - out.write((byte) (((intValue >>> 7) & SEVENBITS) | SIGNBIT)); - - if((intValue & 0xffe00000) == 0){ - out.write((byte) ((intValue >>> 14) & SEVENBITS)); - return; - } - out.write((byte) (((intValue >>> 14) & SEVENBITS) | SIGNBIT)); - - if((intValue & 0xf0000000) == 0){ - out.write((byte) ((intValue >>> 21) & SEVENBITS)); - return; - } - out.write((byte) (((intValue >>> 21) & SEVENBITS) | SIGNBIT)); - - out.write((byte) ((intValue >>> 28) & SEVENBITS)); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/util/AbstractTypeBag.java b/value-core/src/main/java/org/rascalmpl/value/util/AbstractTypeBag.java deleted file mode 100644 index 431edefa0..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/util/AbstractTypeBag.java +++ /dev/null @@ -1,162 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2014 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.util; - -import static io.usethesource.capsule.AbstractSpecialisedImmutableMap.mapOf; - -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -import io.usethesource.capsule.ImmutableMap; - -/** - * Stores mapping (Type -> Integer) to keep track of a collection's element - * types. The least upper bound type of is calculated on basis of the map keys. - */ -public abstract class AbstractTypeBag implements Cloneable { - - public abstract AbstractTypeBag increase(Type t); - - public abstract AbstractTypeBag decrease(Type t); - - @Deprecated - public abstract AbstractTypeBag setLabel(String label); - - @Deprecated - public abstract String getLabel(); - - public abstract Type lub(); - - public abstract AbstractTypeBag clone(); - - public static AbstractTypeBag of(Type... ts) { - return of(null, ts); - } - - public static AbstractTypeBag of(String label, Type... ts) { - return new TypeBag(label, ts); - } - - public abstract int size(); - - /** - * Implementation of <@link AbstractTypeBag/> that cached the current least - * upper bound. - */ - private static class TypeBag extends AbstractTypeBag { - private final String label; - private final ImmutableMap countMap; - - private Type cachedLub; - - private TypeBag(String label, ImmutableMap countMap) { - this(label, countMap, null); - } - - private TypeBag(String label, ImmutableMap countMap, Type cachedLub) { - this.label = label; - this.countMap = countMap; - this.cachedLub = cachedLub; - } - - private TypeBag(Type... ts) { - this(null, ts); - } - - private TypeBag(String label, Type... ts) { - this.label = label; - this.countMap = mapOf(); - - for (Type t : ts) { - this.increase(t); - } - } - - @Override - public AbstractTypeBag increase(Type t) { - final Integer oldCount = countMap.get(t); - final ImmutableMap newCountMap; - - if (oldCount == null) { - newCountMap = countMap.__put(t, 1); - - if (cachedLub == null) { - return new TypeBag(label, newCountMap); - } else { - // update cached type - final Type newCachedLub = cachedLub.lub(t); - return new TypeBag(label, newCountMap, newCachedLub); - } - } else { - newCountMap = countMap.__put(t, oldCount + 1); - return new TypeBag(label, newCountMap); - } - } - - @Override - public AbstractTypeBag decrease(Type t) { - final Integer oldCount = countMap.get(t); - - if (oldCount == null) { - throw new IllegalStateException(String.format("Type '%s' was not present.", t)); - } else if (oldCount > 1) { - // update and decrease count; lub stays the same - final ImmutableMap newCountMap = countMap.__put(t, oldCount - 1); - return new TypeBag(label, newCountMap, cachedLub); - } else { - // count was zero, thus remove entry and invalidate cached type - final ImmutableMap newCountMap = countMap.__remove(t); - return new TypeBag(label, newCountMap); - } - } - - @Deprecated - @Override - public AbstractTypeBag setLabel(String label) { - return new TypeBag(label, countMap, cachedLub); - } - - @Deprecated - @Override - public String getLabel() { - return label; - } - - @Override - public Type lub() { - if (cachedLub == null) { - Type inferredLubType = TypeFactory.getInstance().voidType(); - for (Type t : countMap.keySet()) { - inferredLubType = inferredLubType.lub(t); - } - cachedLub = inferredLubType; - } - return cachedLub; - } - - @Override - public AbstractTypeBag clone() { - return new TypeBag(label, countMap); - } - - @Override - public String toString() { - return countMap.toString(); - } - - @Override - public int size() { - return countMap.size(); - } - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/util/EqualityUtils.java b/value-core/src/main/java/org/rascalmpl/value/util/EqualityUtils.java deleted file mode 100644 index a45b50a73..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/util/EqualityUtils.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * - * * Michael Steindorfer - Michael.Steindorfer@cwi.nl - CWI - *******************************************************************************/ -package org.rascalmpl.value.util; - -import java.util.Comparator; -import java.util.Objects; - -import org.rascalmpl.value.IValue; - -public class EqualityUtils { - - /** - * Temporary function in order to support different equality checks. - */ - @SuppressWarnings("rawtypes") - public static Comparator getDefaultEqualityComparator() { - return new Comparator() { - @Override - public int compare(Object a, Object b) { - return Objects.equals(a, b) ? 0 : -1; - } - }; - } - - /** - * Temporary function in order to support equivalence. Note, this - * implementation is only works for {@link IValue} arguments. If arguments - * are of a different type, an unchecked exception will be thrown. - */ - @SuppressWarnings("rawtypes") - public static Comparator getEquivalenceComparator() { - return new Comparator() { - @Override - public int compare(Object a, Object b) { - IValue v = (IValue) a; - IValue w = (IValue) b; - - if ((v == w) || (v != null && v.isEqual(w))) - return 0; - else - return -1; - } - }; - } - -} diff --git a/value-core/src/main/java/org/rascalmpl/value/util/IndexedSet.java b/value-core/src/main/java/org/rascalmpl/value/util/IndexedSet.java deleted file mode 100644 index 9f8e630b8..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/util/IndexedSet.java +++ /dev/null @@ -1,167 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.util; - -/** - * This is a hashset which assigns a unique identifier to every inserted entry. Identifiers will be - * generated in order, starting at 0. - * - * @author Arnold Lankamp - * - * @param The value type. - */ -public final class IndexedSet{ - private final static int INITIAL_LOG_SIZE = 4; - - private int modSize; - private int hashMask; - - private Entry[] data; - - private int threshold; - - private int load; - - /** - * Constructor. - */ - public IndexedSet(){ - super(); - - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - } - - private void rehash(){ - modSize++; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - Entry[] newData = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - Entry[] oldData = data; - for(int i = oldData.length - 1; i >= 0; i--){ - Entry entry = oldData[i]; - - if(entry != null){ - // Determine the last unchanged entry chain. - Entry lastUnchangedEntryChain = entry; - int newLastUnchangedEntryChainIndex = entry.hash & hashMask; - - Entry e = entry.next; - while(e != null){ - int newIndex = e.hash & hashMask; - if(newIndex != newLastUnchangedEntryChainIndex){ - lastUnchangedEntryChain = e; - newLastUnchangedEntryChainIndex = newIndex; - } - - e = e.next; - } - - newData[newLastUnchangedEntryChainIndex] = lastUnchangedEntryChain; - - // Reconstruct the other entries (if necessary). - while(entry != lastUnchangedEntryChain){ - int hash = entry.hash; - int position = hash & hashMask; - newData[position] = new Entry<>(hash, entry.key, entry.value, newData[position]); - - entry = entry.next; - } - } - } - - data = newData; - } - - private void ensureCapacity(){ - if(load > threshold){ - rehash(); - } - } - - /** - * Stores the given element into this set or returns its identifier in case it was already - * present. - * - * @param element - * The element to store. - * @return The identifier associated with the given value; -1 if the element wasn't present yet. - */ - public int store(E element){ - int hash = element.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && element.equals(entry.key)) return entry.value; - - entry = entry.next; - } - - // Not present - - ensureCapacity(); - - position = hash & hashMask; - - data[position] = new Entry<>(hash, element, load++, data[position]); - - return -1; - } - - /** - * Attempts to find the identifier associted with the given element. - * - * @param element - * The element to retrieve the identifier from. - * @return The identifier associated with the given element; -1 if not present, - */ - public int get(E element){ - int hash = element.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && element.equals(entry.key)) return entry.value; - - entry = entry.next; - } - - return -1; - } - - private static class Entry{ - public final int hash; - public final E key; - public final int value; - - public final Entry next; - - public Entry(int hash, E key, int value, Entry next){ - super(); - - this.hash = hash; - this.key = key; - this.value = value; - - this.next = next; - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/util/ResizingArray.java b/value-core/src/main/java/org/rascalmpl/value/util/ResizingArray.java deleted file mode 100644 index fc0a7e381..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/util/ResizingArray.java +++ /dev/null @@ -1,78 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.util; - -/** - * This array will always have enough space. - * - * @author Arnold Lankamp - * - * @param The value type. - */ -public class ResizingArray{ - private final static int DEFAULT_INITIAL_SIZE = 32; - - private E[] content; - - /** - * Constructor. - */ - public ResizingArray(){ - super(); - - content = (E[]) new Object[DEFAULT_INITIAL_SIZE]; - } - - /** - * Constructor. - * - * @param initialSize - * The initial size of the backing array. - */ - public ResizingArray(int initialSize){ - super(); - - content = (E[]) new Object[initialSize]; - } - - private void ensureCapacity(int max){ - if(max >= content.length){ - E[] newContent = (E[]) new Object[max << 2]; - System.arraycopy(content, 0, newContent, 0, content.length); - content = newContent; - } - } - - /** - * Set the give element at 'index'. - * - * @param element - * The element to set. - * @param index - * The index at which to set. - */ - public void set(E element, int index){ - ensureCapacity(index); - - content[index] = element; - } - - /** - * Returns the element located at 'index'. - * - * @param index - * The index to retrieve the element from. - * @return The element. - */ - public E get(int index){ - return content[index]; - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/util/RotatingQueue.java b/value-core/src/main/java/org/rascalmpl/value/util/RotatingQueue.java deleted file mode 100644 index c9f181eba..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/util/RotatingQueue.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.util; - -/** - * A simple (fast) queue. - * - * @author Arnold Lankamp - * - * @param The value type. - */ -public final class RotatingQueue{ - private final static int DEFAULT_CAPACITY = 16; - private final static int DEFAULT_CAPACITY_MASK = DEFAULT_CAPACITY - 1; - - private T[] queue; - private int capacity; - private int capacityMask; - private int nextPutIndex; - private int getIndex; - - /** - * Constructor. - */ - public RotatingQueue(){ - super(); - - capacity = DEFAULT_CAPACITY; - capacityMask = DEFAULT_CAPACITY_MASK; - - queue = (T[]) new Object[capacity]; - - nextPutIndex = 1; - getIndex = 0; - } - - private void ensureCapacity(){ - if(nextPutIndex == getIndex){ - int size = capacity; - capacity <<= 1; - capacityMask = capacity - 1; - T[] newQueue = (T[]) new Object[capacity]; - if(getIndex == 0){ - System.arraycopy(queue, 0, newQueue, 0, queue.length); - - nextPutIndex = size; - }else{ - int numElemsTillEnd = size - getIndex; - System.arraycopy(queue, getIndex, newQueue, 0, numElemsTillEnd); - System.arraycopy(queue, 0, newQueue, numElemsTillEnd, getIndex); - - getIndex = 0; - nextPutIndex = size; - } - - queue = newQueue; - } - } - - /** - * Enqueues the given element. - * - * @param element - * The element to enqueue. - */ - public void put(T element){ - ensureCapacity(); - - queue[nextPutIndex] = element; - - nextPutIndex = (nextPutIndex + 1) & capacityMask; - } - - /** - * Check if the queue contains any elements. - * - * @return True if the queue contains any elements; false otherwise. - */ - public boolean isEmpty(){ - return (nextPutIndex == ((getIndex + 1) & capacityMask)); - } - - /** - * Returns and removes the next element from the queue. - * - * @return The next element from the queue; null if the queue was empty. - */ - public T get(){ - if(isEmpty()) return null; - - getIndex = (getIndex + 1) & capacityMask; - T element = queue[getIndex]; - queue[getIndex] = null; - - return element; - } -} \ No newline at end of file diff --git a/value-core/src/main/java/org/rascalmpl/value/util/ShareableHashMap.java b/value-core/src/main/java/org/rascalmpl/value/util/ShareableHashMap.java deleted file mode 100644 index 8be56c889..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/util/ShareableHashMap.java +++ /dev/null @@ -1,802 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.util; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -/** - * This map implementation is shareable and can be easily cloned - * (simple arraycopy of the entries array). - * - * @author Arnold Lankamp - * - * @param - * The key type - * @param - * The value type - */ -public final class ShareableHashMap implements Map{ - private final static int INITIAL_LOG_SIZE = 4; - - private int modSize; - private int hashMask; - - private Entry[] data; - - private int threshold; - - private int load; - - private int currentHashCode; - - /** - * Constructor. - */ - public ShareableHashMap(){ - super(); - - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - - currentHashCode = 0; - } - - /** - * Copy constructor - * - * @param sharedHashMap - * The map to copy. - */ - public ShareableHashMap(ShareableHashMap sharedHashMap){ - super(); - - modSize = sharedHashMap.modSize; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = sharedHashMap.data.clone(); - - threshold = tableSize; - - load = sharedHashMap.load; - - currentHashCode = sharedHashMap.currentHashCode; - } - - /** - * Removes all the entries from this map. - */ - public void clear(){ - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - - currentHashCode = 0; - } - - /** - * Rehashes this map. - */ - private void rehash(){ - modSize++; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - Entry[] newData = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - Entry[] oldData = data; - for(int i = oldData.length - 1; i >= 0; i--){ - Entry entry = oldData[i]; - - if(entry != null){ - // Determine the last unchanged entry chain. - Entry lastUnchangedEntryChain = entry; - int newLastUnchangedEntryChainIndex = entry.hash & hashMask; - - Entry e = entry.next; - while(e != null){ - int newIndex = e.hash & hashMask; - if(newIndex != newLastUnchangedEntryChainIndex){ - lastUnchangedEntryChain = e; - newLastUnchangedEntryChainIndex = newIndex; - } - - e = e.next; - } - - newData[newLastUnchangedEntryChainIndex] = lastUnchangedEntryChain; - - // Reconstruct the other entries (if necessary). - while(entry != lastUnchangedEntryChain){ - int hash = entry.hash; - int position = hash & hashMask; - newData[position] = new Entry<>(hash, entry.key, entry.value, newData[position]); - - entry = entry.next; - } - } - } - - data = newData; - } - - /** - * Makes sure the size of the entry array and the load of the map stay in proper relation to - * eachother. - */ - private void ensureCapacity(){ - if(load > threshold){ - rehash(); - } - } - - /** - * Replaces the value in the entry by the given value. - * - * @param position - * The position in the entry array where the entry is located. - * @param entry - * The entry in which the value must be replaced. - * @param newValue - * The value. - */ - private void replaceValue(int position, Entry entry, V newValue){ - Entry e = data[position]; - - // Reconstruct the updated entry. - data[position] = new Entry<>(entry.hash, entry.key, newValue, entry.next); - - // Reconstruct the other entries (if necessary). - while(e != entry){ - data[position] = new Entry<>(e.hash, e.key, e.value, data[position]); - - e = e.next; - } - } - - /** - * Inserts the given key-value pair into this map. In case there already is a value associated - * with the given key, the value will be updated and the previous value returned. - * - * @param key - * The key - * @param value - * The value - * @return The previous value that was associated with the key (if any); null otherwise. - */ - public V put(K key, V value){ - ensureCapacity(); - - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry currentStartEntry = data[position]; - // Check if the key is already in here. - if(currentStartEntry != null){ - Entry entry = currentStartEntry; - do{ - if(hash == entry.hash && entry.key.equals(key)){ // Replace if present. - replaceValue(position, entry, value); - - return entry.value; // Return the old value. - } - - entry = entry.next; - }while(entry != null); - } - - data[position] = new Entry<>(hash, key, value, currentStartEntry); // Insert the new entry. - - load++; - - currentHashCode ^= hash; // Update the current hashcode of this map. - - return null; - } - - /** - * Removes the entry from this map that is identified by the given key (if present). - * - * @param key - * The key that identifies the entry to remove. - * @return The value that was associated with the given key; null if the key was not present in - * the map. - */ - public V remove(Object key){ - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry currentStartEntry = data[position]; - if(currentStartEntry != null){ - Entry entry = currentStartEntry; - do{ - if(hash == entry.hash && entry.key.equals(key)){ - Entry e = data[position]; - - data[position] = entry.next; - // Reconstruct the other entries (if necessary). - while(e != entry){ - data[position] = new Entry<>(e.hash, e.key, e.value, data[position]); - - e = e.next; - } - - load--; - - currentHashCode ^= hash; // Update the current hashcode of this map. - - return entry.value; // Return the value. - } - - entry = entry.next; - }while(entry != null); - } - - return null; // Not found. - } - - /** - * Retrieves the value from the entry in this map which is identified by the given key - * (if present). - * - * @param key - * The key that identifies the entry that contains the value. - * @return The retrieved value; null if not present. - */ - public V get(Object key){ - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && key.equals(entry.key)) return entry.value; - - entry = entry.next; - } - - return null; - } - - /** - * Checks if there is an entry present in this map, which is identified by the given key. - * - * @param key - * The key that identifies the entry. - * @return True if this map contains an entry which is identified by the given key; - * false otherwise. - */ - public boolean contains(K key){ - return (get(key) != null); - } - - /** - * Returns the number of entries this map contains. - * - * @return The number of entries this map contains. - */ - public int size(){ - return load; - } - - /** - * Checks whether or not this map is empty. - * - * @return True if this map was empty; false otherwise. - */ - public boolean isEmpty(){ - return (load == 0); - } - - /** - * Constructs an iterator for the entries in this map. - * - * @return An iterator for the entries in this map. - */ - public Iterator> entryIterator(){ - return new EntryIterator<>(data); - } - - /** - * Constructs an iterator for the keys in this map. - * - * @return An iterator for the keys in this map. - */ - public Iterator keysIterator(){ - return new KeysIterator<>(data); - } - - /** - * Constructs an iterator for the values in this map. - * - * @return An iterator for the values in this map. - */ - public Iterator valuesIterator(){ - return new ValuesIterator<>(data); - } - - /** - * Copies over all entries from the given map, to this map. - */ - public void putAll(Map otherMap){ - Set> entrySet = (Set>) (Set) otherMap.entrySet(); // Generics stink. - Iterator> entrySetIterator = entrySet.iterator(); - while(entrySetIterator.hasNext()){ - Map.Entry next = entrySetIterator.next(); - put(next.getKey(), next.getValue()); - } - } - - /** - * Checks if this map contains an entry with the given key. - */ - public boolean containsKey(Object key){ - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && key.equals(entry.key)) return true; - - entry = entry.next; - } - - return false; - } - - /** - * Checks if this map contains an entry with the given value. - */ - public boolean containsValue(Object value){ - Iterator valuesIterator = valuesIterator(); - while(valuesIterator.hasNext()){ - V nextValue = valuesIterator.next(); - if(nextValue == value || (nextValue != null && nextValue.equals(value))){ - return true; - } - } - - return false; - } - - /** - * Constructs a set containing all entries from this map. - */ - public Set> entrySet(){ - ShareableHashSet> entrySet = new ShareableHashSet<>(); - - Iterator> entriesIterator = entryIterator(); - while(entriesIterator.hasNext()){ - entrySet.add(entriesIterator.next()); - } - - return entrySet; - } - - /** - * Constructs a set containing all keys from this map. - */ - public Set keySet(){ - ShareableHashSet keysSet = new ShareableHashSet<>(); - - Iterator keysIterator = keysIterator(); - while(keysIterator.hasNext()){ - keysSet.add(keysIterator.next()); - } - - return keysSet; - } - - /** - * Constructs a collection containing all values from this map. - */ - public Collection values(){ - ShareableHashSet valuesSet = new ShareableHashSet<>(); - - Iterator valuesIterator = valuesIterator(); - while(valuesIterator.hasNext()){ - valuesSet.add(valuesIterator.next()); - } - - return valuesSet; - } - - /** - * Prints the internal representation of this map to a string. - * - * @see java.lang.Object#toString() - */ - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('{'); - for(int i = 0; i < data.length; i++){ - buffer.append('['); - Entry e = data[i]; - if(e != null){ - buffer.append(e); - - e = e.next; - - while(e != null){ - buffer.append(','); - buffer.append(e); - - e = e.next; - } - } - buffer.append(']'); - } - buffer.append('}'); - - return buffer.toString(); - } - - /** - * Returns the current hash code of this map. - * - * @return The current hash code of this map. - * - * @see java.lang.Object#hashCode() - */ - public int hashCode(){ - return currentHashCode; - } - - /** - * Check whether or not the current content of this set is equal to that of the given object / map. - * - * @return True if the content of this set is equal to the given object / map. - * - * @see java.lang.Object#equals(Object) - */ - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - ShareableHashMap other = (ShareableHashMap) o; - - if(other.currentHashCode != currentHashCode) return false; - if(other.size() != size()) return false; - - if(isEmpty()) return true; // No need to check if the maps are empty. - - Iterator> otherIterator = other.entryIterator(); - while(otherIterator.hasNext()){ - Map.Entry entry = otherIterator.next(); - V otherValue = entry.getValue(); - V thisValue = get(entry.getKey()); - if(otherValue != thisValue && thisValue != null && !thisValue.equals(entry.getValue())) return false; - } - return true; - } - - return false; - } - - /** - * Entry, used for containing key-value pairs and constructing buckets. - * - * @author Arnold Lankamp - * - * @param - * The key type - * @param - * The value type - */ - private static class Entry implements Map.Entry{ - public final int hash; - public final K key; - public final V value; - - public final Entry next; - - /** - * Constructor - * - * @param hash - * The hash code of the key - * @param key - * The key - * @param value - * The value - * @param next - * A reference to the next entry in the bucket (if any). - */ - public Entry(int hash, K key, V value, Entry next){ - super(); - - this.hash = hash; - this.key = key; - this.value = value; - - this.next = next; - } - - /** - * Returns a reference to the key. - * - * @return A reference to the key. - */ - public K getKey(){ - return key; - } - - /** - * Returns a reference to the value. - * - * @return A reference to the value. - */ - public V getValue(){ - return value; - } - - /** - * Unsupported operation. - * - * @param value - * The value which we will not set. - * @return Null. - * @throws java.lang.UnsupportedOperationException - * - * @see java.util.Map.Entry#setValue(Object) - */ - public V setValue(V value){ - throw new UnsupportedOperationException("The setting of values is not supported by this map implementation."); - } - - /** - * Prints the internal representation of this entry to a string. - * - * @see java.lang.Object#toString() - */ - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('<'); - buffer.append(key); - buffer.append(':'); - buffer.append(value); - buffer.append('>'); - - return buffer.toString(); - } - } - - /** - * Iterator for entries. - * - * @author Arnold Lankamp - * - * @param - * The key type. - * @param - * The value type. - */ - private static class EntryIterator implements Iterator>{ - private final Entry[] data; - - private Entry current; - private int index; - - /** - * Constructor. - * - * @param sharedHashMap - * The map to iterator over. - */ - public EntryIterator(Entry[] entries){ - super(); - - data = entries; - - index = data.length - 1; - current = new Entry<>(0, null, null, data[index]); - locateNext(); - } - - /** - * Locates the next entry in the map. - */ - private void locateNext(){ - Entry next = current.next; - if(next != null){ - current = next; - return; - } - - for(int i = index - 1; i >= 0 ; i--){ - Entry entry = data[i]; - if(entry != null){ - current = entry; - index = i; - return; - } - } - - current = null; - index = 0; - } - - /** - * Check if there are more elements in this iteration. - * - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext(){ - return (current != null); - } - - /** - * Returns the next element in this iteration. - * - * @return The next element in this iteration. - * @throws NoSuchElementException - * Thrown if there are no more elements in this iteration when calling this - * method. - * - * @see java.util.Iterator#next() - */ - public Entry next(){ - if(!hasNext()) throw new UnsupportedOperationException("There are no more elements in this iterator."); - - Entry entry = current; - locateNext(); - - return entry; - } - - /** - * Removal is not supported by this iterator. - * - * @throws java.lang.UnsupportedOperationException - * - * @see java.util.Iterator#remove() - */ - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } - - /** - * Iterator for keys. - * - * @author Arnold Lankamp - * - * @param - * The key type. - * @param - * The value type. - */ - private static class KeysIterator implements Iterator{ - private final EntryIterator entryIterator; - - /** - * Constructor. - * - * @param entries - * The entries to iterate over. - */ - public KeysIterator(Entry[] entries){ - super(); - - entryIterator = new EntryIterator<>(entries); - } - - /** - * Check if there are more elements in this iteration. - * - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext(){ - return entryIterator.hasNext(); - } - - /** - * Returns the next element in this iteration. - * - * @return The next element in this iteration. - * @throws NoSuchElementException - * Thrown if there are no more elements in this iteration when calling this - * method. - * - * @see java.util.Iterator#next() - */ - public K next(){ - return entryIterator.next().key; - } - - /** - * Removal is not supported by this iterator. - * - * @throws java.lang.UnsupportedOperationException - * - * @see java.util.Iterator#remove() - */ - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } - - /** - * Iterator for values. - * - * @author Arnold Lankamp - * - * @param - * The key type. - * @param - * The value type. - */ - private static class ValuesIterator implements Iterator{ - private final EntryIterator entryIterator; - - /** - * Constructor. - * - * @param entries - * The entries to iterate over. - */ - public ValuesIterator(Entry[] entries){ - super(); - - entryIterator = new EntryIterator<>(entries); - } - - /** - * Check if there are more elements in this iteration. - * - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext(){ - return entryIterator.hasNext(); - } - - /** - * Returns the next element in this iteration. - * - * @return The next element in this iteration. - * @throws NoSuchElementException - * Thrown if there are no more elements in this iteration when calling this - * method. - * - * @see java.util.Iterator#next() - */ - public V next(){ - return entryIterator.next().value; - } - - /** - * Removal is not supported by this iterator. - * - * @throws java.lang.UnsupportedOperationException - * - * @see java.util.Iterator#remove() - */ - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/util/ShareableHashSet.java b/value-core/src/main/java/org/rascalmpl/value/util/ShareableHashSet.java deleted file mode 100644 index 6fd55c691..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/util/ShareableHashSet.java +++ /dev/null @@ -1,607 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.util; - -import java.util.Collection; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.Set; - -/** - * This set implementation is shareable and can be easily cloned - * (simple arraycopy of the entries array). - * - * @author Arnold Lankamp - * - * @param - * The value type. - */ -public final class ShareableHashSet implements Set, Iterable{ - private final static int INITIAL_LOG_SIZE = 4; - - private int modSize; - private int hashMask; - - private Entry[] data; - - private int threshold; - - private int load; - - private int currentHashCode; - - /** - * Default constructor. - */ - public ShareableHashSet(){ - super(); - - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - - currentHashCode = 0; - } - - /** - * Copy constructor. - * - * @param sharedHashSet - * The set to copy. - */ - public ShareableHashSet(ShareableHashSet sharedHashSet){ - super(); - - modSize = sharedHashSet.modSize; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = sharedHashSet.data.clone(); - - threshold = tableSize; - - load = sharedHashSet.load; - - currentHashCode = sharedHashSet.currentHashCode; - } - - /** - * Removes all the entries from this set. - */ - public void clear(){ - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - - currentHashCode = 0; - } - - /** - * Rehashes this set. - */ - private void rehash(){ - modSize++; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - Entry[] newData = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - Entry[] oldData = data; - for(int i = oldData.length - 1; i >= 0; i--){ - Entry entry = oldData[i]; - - if(entry != null){ - // Determine the last unchanged entry chain. - Entry lastUnchangedEntryChain = entry; - int newLastUnchangedEntryChainIndex = entry.hash & hashMask; - - Entry e = entry.next; - while(e != null){ - int newIndex = e.hash & hashMask; - if(newIndex != newLastUnchangedEntryChainIndex){ - lastUnchangedEntryChain = e; - newLastUnchangedEntryChainIndex = newIndex; - } - - e = e.next; - } - - newData[newLastUnchangedEntryChainIndex] = lastUnchangedEntryChain; - - // Reconstruct the other entries (if necessary). - while(entry != lastUnchangedEntryChain){ - int hash = entry.hash; - int position = hash & hashMask; - newData[position] = new Entry<>(hash, entry.value, newData[position]); - - entry = entry.next; - } - } - } - - data = newData; - } - - /** - * Makes sure the size of the entry array and the load of the set stay in proper relation to - * eachother. - */ - private void ensureCapacity(){ - if(load > threshold){ - rehash(); - } - } - - /** - * Inserts the given value into this set. - * - * @param value - * The value to insert. - * @return Returns true if this set didn't contain the given value yet; false if it did. - */ - public boolean add(V value){ - ensureCapacity(); - - int hash = value.hashCode(); - int position = hash & hashMask; - - Entry currentStartEntry = data[position]; - // Check if the value is already in here. - if(currentStartEntry != null){ - Entry entry = currentStartEntry; - do{ - if(hash == entry.hash && entry.value.equals(value)){ - return false; // Return false if it's already present. - } - - entry = entry.next; - }while(entry != null); - } - - data[position] = new Entry<>(hash, value, currentStartEntry); // Insert the new entry. - - load++; - - currentHashCode ^= hash; // Update the current hashcode of this map. - - return true; - } - - /** - * Checks if this set contains the given value. - * - * @param value - * The value to check for. - * @return True if this set contains the given value; false otherwise. - */ - public boolean contains(Object value){ - int hash = value.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && value.equals(entry.value)) return true; - - entry = entry.next; - } - - return false; - } - - /** - * Removes the given object from this set (if present.) - * - * @param value - * The value to remove. - * @return True if this set contained the given object; false otherwise. - */ - public boolean remove(Object value){ - int hash = value.hashCode(); - int position = hash & hashMask; - - Entry currentStartEntry = data[position]; - if(currentStartEntry != null){ - Entry entry = currentStartEntry; - do{ - if(hash == entry.hash && entry.value.equals(value)){ - Entry e = data[position]; - - data[position] = entry.next; - // Reconstruct the other entries (if necessary). - while(e != entry){ - data[position] = new Entry<>(e.hash, e.value, data[position]); - - e = e.next; - } - - load--; - - currentHashCode ^= hash; // Update the current hashcode of this set. - - return true; - } - - entry = entry.next; - }while(entry != null); - } - - return false; - } - - /** - * Returns the number of values this set currently contains. - * - * @return The number of values this set currently contains. - */ - public int size(){ - return load; - } - - /** - * Checks whether or not this set is empty. - * - * @return True is this set is empty; false otherwise. - */ - public boolean isEmpty(){ - return (load == 0); - } - - /** - * Constructs an iterator for this set. - * - * @return An iterator for this set. - * - * @see java.lang.Iterable#iterator() - */ - public Iterator iterator(){ - return new SetIterator<>(data); - } - - /** - * Adds all the elements from the given collection to this set. - * - * @param collection - * The collection that contains the elements to add. - * @return True if this set changed; false if it didn't. - */ - public boolean addAll(Collection collection){ - boolean changed = false; - - Iterator collectionIterator = collection.iterator(); - while(collectionIterator.hasNext()){ - changed |= add(collectionIterator.next()); - } - - return changed; - } - - /** - * Checks if the collection contains all the elements in the given collection. - * - * @param collection - * The collection that contains the elements to check for. - * @return True if this set contains all the elements in the given collections; false if it - * didn't. - */ - public boolean containsAll(Collection collection){ - Iterator collectionIterator = collection.iterator(); - while(collectionIterator.hasNext()){ - if(!contains(collectionIterator.next())) return false; - } - - return true; - } - - /** - * Removes all the elements from this set which are not present in the given collection. - * - * @param collection - * The collection that contains the elements which need to be retained. - * @return True if this set changed; false if it didn't. - */ - public boolean retainAll(Collection collection){ - boolean changed = false; - - Iterator valuesIterator = iterator(); - while(valuesIterator.hasNext()){ - V value = valuesIterator.next(); - if(!collection.contains(value)){ - remove(value); - - changed = true; - } - } - - return changed; - } - - /** - * Removes all the elements in the given collection from this set. - * - * @param collection - * The collection that contains the elements to remove from this set. - * @return True if this set change; false if it didn't. - */ - public boolean removeAll(Collection collection){ - boolean changed = false; - - Iterator collectionIterator = collection.iterator(); - while(collectionIterator.hasNext()){ - Object value = collectionIterator.next(); - changed |= remove(value); - } - - return changed; - } - - /** - * Returns all the elements from this set in an array. - * - * @return All the elements from this set in an array. - */ - public Object[] toArray(){ - Object[] values = new Object[load]; - - Iterator valuesIterator = iterator(); - int i = 0; - while(valuesIterator.hasNext()){ - values[i++] = valuesIterator.next(); - } - - return values; - } - - - /** - * Returns all the elements from this set in an array. - * - * @param array - * The array to use; in case it isn't large enough a new one will be allocated. - * @return All the elements from this set in an array. - */ - public T[] toArray(T[] array){ - if(array.length < load) return (T[]) toArray(); - - Iterator valuesIterator = iterator(); - int i = 0; - while(valuesIterator.hasNext()){ - array[i++] = (T) valuesIterator.next(); - } - - for(; i < load; i++){ - array[i] = null; - } - - return array; - } - - /** - * Prints the internal representation of this set to a string. - * - * @see java.lang.Object#toString() - */ - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('{'); - for(int i = 0; i < data.length; i++){ - buffer.append('['); - Entry e = data[i]; - if(e != null){ - buffer.append(e); - - e = e.next; - - while(e != null){ - buffer.append(','); - buffer.append(e); - - e = e.next; - } - } - buffer.append(']'); - } - buffer.append('}'); - - return buffer.toString(); - } - - /** - * Returns the current hash code of this set. - * - * @return The current hash code of this set. - * - * @see java.lang.Object#hashCode() - */ - public int hashCode(){ - return currentHashCode; - } - - /** - * Check whether or not the current content of this set is equal to that of the given object / set. - * - * @return True if the content of this set is equal to the given object / set. - * - * @see java.lang.Object#equals(Object) - */ - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - ShareableHashSet other = (ShareableHashSet) o; - - if(other.currentHashCode != currentHashCode) return false; - if(other.size() != size()) return false; - - if(isEmpty()) return true; // No need to check if the sets are empty. - - Iterator otherIterator = other.iterator(); - while(otherIterator.hasNext()){ - if(!contains(otherIterator.next())) return false; - } - return true; - } - - return false; - } - - /** - * Entry, used for containing values and constructing buckets. - * - * @author Arnold Lankamp - * - * @param - * The value type. - */ - private static class Entry{ - public final int hash; - public final V value; - - public final Entry next; - - /** - * Constructor. - * - * @param hash - * The hash code of the value - * @param value - * The value - * @param next - * A reference to the next entry in the bucket (if any). - */ - public Entry(int hash, V value, Entry next){ - super(); - - this.hash = hash; - this.value = value; - - this.next = next; - } - - /** - * Prints the internal representation of this entry to a string. - * - * @see java.lang.Object#toString() - */ - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('<'); - buffer.append(value); - buffer.append('>'); - - return buffer.toString(); - } - } - - /** - * Iterator for this set. - * - * @author Arnold Lankamp - * - * @param - * The value type. - */ - private static class SetIterator implements Iterator{ - private final Entry[] data; - - private Entry current; - private int index; - - /** - * Constructor. - * - * @param entries - * The entries to iterator over. - */ - public SetIterator(Entry[] entries){ - super(); - - data = entries; - - index = data.length - 1; - current = new Entry<>(0, null, data[index]); - locateNext(); - } - - /** - * Locates the next value in the set. - */ - private void locateNext(){ - Entry next = current.next; - if(next != null){ - current = next; - return; - } - - for(int i = index - 1; i >= 0 ; i--){ - Entry entry = data[i]; - if(entry != null){ - current = entry; - index = i; - return; - } - } - - current = null; - index = 0; - } - - /** - * Checks if there are more elements in this iteration. - * - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext(){ - return (current != null); - } - - /** - * Returns the next element in this iteration. - * - * @return The next element in this iteration. - * @throws NoSuchElementException - * Thrown if there are no more elements in this iteration when calling this - * method. - * - * @see java.util.Iterator#next() - */ - public V next(){ - if(!hasNext()) throw new NoSuchElementException("There are no more elements in this iteration"); - - V value = current.value; - locateNext(); - - return value; - } - - /** - * Removal is not supported by this iterator. - * - * @throws java.lang.UnsupportedOperationException - * - * @see java.util.Iterator#remove() - */ - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/util/ShareableList.java b/value-core/src/main/java/org/rascalmpl/value/util/ShareableList.java deleted file mode 100644 index a0f314e7b..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/util/ShareableList.java +++ /dev/null @@ -1,637 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.util; - -import java.util.Iterator; -import java.util.NoSuchElementException; - -/** - * This list implementation is shareable and guarantees that the following operations can be done - * in constant time: - * -insert (front) - * -append (back) - * -get (ordered) - * -get (random) - * -set (random) - * -remove (front) - * -remove (back) - * -reverse - * Additionally both cloning this list as the sublist operation are relatively cheap, - * (two simple arraycopies). - * - * @author Arnold Lankamp - * - * @param - * The element type. - */ -public class ShareableList implements Iterable{ - private final static int INITIAL_LOG_SIZE = 2; - - private int frontCapacity; - private E[] frontData; - private int frontIndex; - - private int backCapacity; - private E[] backData; - private int backIndex; - - /** - * Default constructor - */ - public ShareableList(){ - super(); - - frontCapacity = 1 << INITIAL_LOG_SIZE; - frontData = (E[]) new Object[frontCapacity]; - frontIndex = 0; - - backCapacity = 1 << INITIAL_LOG_SIZE; - backData = (E[]) new Object[backCapacity]; - backIndex = 0; - } - - /** - * Copy constructor. - * - * @param shareableList - * The list to copy. - */ - public ShareableList(ShareableList shareableList){ - super(); - - frontCapacity = shareableList.frontCapacity; - frontData = shareableList.frontData.clone(); - frontIndex = shareableList.frontIndex; - - backCapacity = shareableList.backCapacity; - backData = shareableList.backData.clone(); - backIndex = shareableList.backIndex; - } - - /** - * SubList copy constructor. - * - * @param shareableList - * The list to copy. - * @param offset - * The start index of the sublist. - * @param length - * The length of the sublist. - */ - protected ShareableList(ShareableList shareableList, int offset, int length){ - super(); - - int backStartIndex = shareableList.backIndex - offset; - if(backStartIndex <= 0){// Front only - backIndex = 0; - backCapacity = 2; - backData = (E[]) new Object[backCapacity]; - - int frontStartIndex = -backStartIndex; - - frontIndex = length; - frontCapacity = closestPowerOfTwo(length); - frontData = (E[]) new Object[frontCapacity]; - System.arraycopy(shareableList.frontData, frontStartIndex, frontData, 0, length); - }else{ - if((offset + length) <= shareableList.backIndex){ // Back only - backIndex = length; - backCapacity = closestPowerOfTwo(length); - backData = (E[]) new Object[backCapacity]; - System.arraycopy(shareableList.backData, backStartIndex - length, backData, 0, length); - - frontIndex = 0; - frontCapacity = 2; - frontData = (E[]) new Object[frontCapacity]; - }else{ // Front and Back overlap - backIndex = backStartIndex; - backCapacity = closestPowerOfTwo(backStartIndex); - backData = (E[]) new Object[backCapacity]; - System.arraycopy(shareableList.backData, 0, backData, 0, backStartIndex); - - int frontLength = length - backStartIndex; - - frontIndex = frontLength; - frontCapacity = closestPowerOfTwo(frontLength); - frontData = (E[]) new Object[frontCapacity]; - System.arraycopy(shareableList.frontData, 0, frontData, 0, frontLength); - } - } - } - - private static int closestPowerOfTwo(int number){ - int power = 0; - do{/* Nothing. */}while((1 << (++power)) < number); - - return (1 << power); - } - - /** - * Removes all the elements from this list. - */ - public void clear(){ - frontCapacity = 1 << INITIAL_LOG_SIZE; - frontData = (E[]) new Object[frontCapacity]; - frontIndex = 0; - - backCapacity = 1 << INITIAL_LOG_SIZE; - backData = (E[]) new Object[backCapacity]; - backIndex = 0; - } - - /** - * Calling this will guarantee that there is enough space for the next single element insert. - */ - private void ensureFrontCapacity(){ - if(frontCapacity == frontIndex){ - frontCapacity <<= 1; - E[] newFrontData = (E[]) new Object[frontCapacity]; - System.arraycopy(frontData, 0, newFrontData, 0, frontData.length); - frontData = newFrontData; - } - } - - /** - * Calling this will guarantee that there is enough space for the next single element append. - */ - private void ensureBackCapacity(){ - if(backCapacity == backIndex){ - backCapacity <<= 1; - E[] newBackData = (E[]) new Object[backCapacity]; - System.arraycopy(backData, 0, newBackData, 0, backData.length); - backData = newBackData; - } - } - - /** - * Calling this will guarantee that there is enough space for the next batch of inserted elements. - * - * @param nrOfElements - * The amount of free space that is required. - */ - private void ensureFrontBulkCapacity(int nrOfElements){ - int requiredCapacity = frontIndex + nrOfElements; - if(frontCapacity <= requiredCapacity){ - do{ - frontCapacity <<= 1; - }while(frontCapacity <= requiredCapacity); - - E[] newFrontData = (E[]) new Object[frontCapacity]; - System.arraycopy(frontData, 0, newFrontData, 0, frontData.length); - frontData = newFrontData; - } - } - - /** - * Calling this will guarantee that there is enough space for the next batch of appended elements. - * - * @param nrOfElements - * The amount of free space that is required. - */ - private void ensureBackBulkCapacity(int nrOfElements){ - int requiredCapacity = backIndex + nrOfElements; - - if(backCapacity <= requiredCapacity){ - do{ - backCapacity <<= 1; - }while(backCapacity <= requiredCapacity); - - E[] newBackData = (E[]) new Object[backCapacity]; - System.arraycopy(backData, 0, newBackData, 0, backData.length); - backData = newBackData; - } - } - - /** - * Appends the given element to the end of this list. - * - * @param element - * The element to append. - */ - public void append(E element){ - ensureFrontCapacity(); - - frontData[frontIndex++] = element; - } - - /** - * Appends the given batch of element to the end of this list. - * - * @param elements - * The batch of elements to append. - */ - public void appendAll(E[] elements){ - int nrOfElements = elements.length; - - ensureFrontBulkCapacity(nrOfElements); - - System.arraycopy(elements, 0, frontData, frontIndex, nrOfElements); - frontIndex += nrOfElements; - } - - /** - * Appends the indicated range of elements from the given batch of elements to the end of this - * list. - * - * @param elements - * The batch that contains the elements to append. - * @param offset - * The position in the given batch to start at. - * @param length - * The number of elements from the given batch to append. - */ - public void appendAllAt(E[] elements, int offset, int length){ - if(offset < 0) throw new IllegalArgumentException("Offset must be > 0."); - if((offset + length) > elements.length) throw new IllegalArgumentException("(offset + length) must be <= elements.length."); - - ensureFrontBulkCapacity(length); - - System.arraycopy(elements, offset, frontData, frontIndex, length); - frontIndex += length; - } - - /** - * Inserts the given element to the start of this list. - * - * @param element - * The element to insert. - */ - public void insert(E element){ - ensureBackCapacity(); - - backData[backIndex++] = element; - } - - /** - * Inserts the given batch of elements to the start of this list. - * - * @param elements - * The batch of elements to insert. - */ - public void insertAll(E[] elements){ - int nrOfElements = elements.length; - - ensureBackBulkCapacity(nrOfElements); - - for(int i = nrOfElements - 1; i >= 0; i--){ - backData[backIndex++] = elements[i]; - } - } - - /** - * Inserts the given element at the indicated position in this list. - * - * @param index - * The index to insert the element at. - * @param element - * The element to insert. - */ - public void insertAt(int index, E element){ - int realIndex = index - backIndex; - if(realIndex >= 0){ - ensureFrontCapacity(); - - if(realIndex > frontIndex) throw new ArrayIndexOutOfBoundsException(index+" > the the current size of the list ("+size()+")"); - - int elementsToMove = frontIndex - realIndex; - System.arraycopy(frontData, realIndex, frontData, realIndex + 1, elementsToMove); - frontData[realIndex] = element; - frontIndex++; - }else{ - ensureBackCapacity(); - - realIndex = 0 - realIndex; - - if(realIndex > backIndex) throw new ArrayIndexOutOfBoundsException(index+" < 0"); - - int elementsToMove = backIndex - realIndex; - System.arraycopy(backData, realIndex, backData, realIndex + 1, elementsToMove); - backData[realIndex] = element; - backIndex++; - } - } - - /** - * Replaces the element at the indicated position in this list by the given element. - * - * @param index - * The index to replace the element at. - * @param element - * The element to place at the indicated position. - * @return The element that was located at the indicated position prior to the execution of this - * operation. - */ - public E set(int index, E element){ - int realIndex = index - backIndex; - if(realIndex >= 0){ - if(realIndex >= frontIndex) throw new ArrayIndexOutOfBoundsException(index+" >= the current size of the list ("+size()+")"); - - E oldElement = frontData[realIndex]; - frontData[realIndex] = element; - - return oldElement; - } - - realIndex = -1 - realIndex; - - if(realIndex >= backIndex) throw new ArrayIndexOutOfBoundsException(index+" < 0"); - - E oldElement = backData[realIndex]; - backData[realIndex] = element; - - return oldElement; - } - - /** - * Retrieves the element at the indicated position from this list. - * - * @param index - * The position to retrieve the element from. - * @return The retrieved element. - */ - public E get(int index){ - int realIndex = index - backIndex; - if(realIndex >= 0){ - if(realIndex >= frontIndex) { - throw new ArrayIndexOutOfBoundsException(index+" >= the current size of the list ("+size()+")"); - } - - return frontData[realIndex]; - } - - realIndex = -1 - realIndex; - - if(realIndex >= backIndex) throw new ArrayIndexOutOfBoundsException(index+" < 0"); - - return backData[realIndex]; - } - - /** - * Removes the element at the indicated position from this list. - * - * @param index - * The position to remove the element from. - * @return The element that was located at the indicated position prior to the execution of - * this operation. - */ - public E remove(int index){ - int realIndex = index - backIndex; - if(realIndex >= 0){ - if(realIndex >= frontIndex) throw new ArrayIndexOutOfBoundsException(index+" >= the current size of the list ("+size()+")"); - - E oldElement = frontData[realIndex]; - - int elementsToMove = --frontIndex - realIndex; - if(elementsToMove > 0) System.arraycopy(frontData, realIndex + 1, frontData, realIndex, elementsToMove); - frontData[frontIndex] = null; // Remove the 'old' reference at the end of the array. - - return oldElement; - } - - realIndex = -1 - realIndex; - - if(realIndex >= backIndex) throw new ArrayIndexOutOfBoundsException(index+" < 0"); - - E oldElement = backData[realIndex]; - - int elementsToMove = --backIndex - realIndex; - if(elementsToMove > 0) System.arraycopy(backData, realIndex + 1, backData, realIndex, elementsToMove); - backData[backIndex] = null; // Remove the 'old' reference at the end of the array. - - return oldElement; - } - - /** - * Constructs a sublist of this list. - * - * @param offset - * The offset to start at. - * @param length - * The number of elements. - * @return The constructed sublist. - */ - public ShareableList subList(int offset, int length){ - if(offset < 0) throw new IndexOutOfBoundsException("Offset may not be smaller then 0."); - if(length < 0) throw new IndexOutOfBoundsException("Length may not be smaller then 0."); - if((offset + length) > size()) throw new IndexOutOfBoundsException("'offset + length' may not be larger then 'list.size()'"); - - return new ShareableList<>(this, offset, length); - } - - /** - * Reverses the order of the elements in this list. - * - * @return A reference to this list. - */ - public ShareableList reverse(){ - int tempCapacity = frontCapacity; - E[] tempData = frontData; - int tempIndex = frontIndex; - - frontCapacity = backCapacity; - frontData = backData; - frontIndex = backIndex; - - backCapacity = tempCapacity; - backData = tempData; - backIndex = tempIndex; - - return this; - } - - /** - * Returns the number of elements that are currently present in this list. - * - * @return The number of elements that are currently present in this list. - */ - public int size(){ - return (frontIndex + backIndex); - } - - /** - * Checks whether or not this list is empty. - * - * @return True if this list is empty; false otherwise. - */ - public boolean isEmpty(){ - return (size() == 0); - } - - /** - * Constructs an iterator for this list. - * - * @return An iterator for this list. - * - * @see java.lang.Iterable#iterator() - */ - public Iterator iterator(){ - return new ListIterator<>(this); - } - - /** - * Computes the current hash code of this list. - * - * @return The current hash code of this list. - * - * @see java.lang.Object#hashCode() - */ - public int hashCode(){ - int hash = 0; - - Iterator iterator = iterator(); - while(iterator.hasNext()){ - E element = iterator.next(); - hash = (hash << 1) ^ element.hashCode(); - } - - return hash; - } - - /** - * Check whether or not the current content of this list is equal to that of the given object / list. - * - * @return True if the content of this list is equal to the given object / list. - * - * @see java.lang.Object#equals(Object) - */ - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - ShareableList other = (ShareableList) o; - - if(other.size() == size()){ - if(isEmpty()) return true; // No need to check if the lists are empty. - - Iterator thisIterator = iterator(); - Iterator otherIterator = other.iterator(); - while(thisIterator.hasNext()){ - if(!thisIterator.next().equals(otherIterator.next())) return false; - } - return true; - } - } - - return false; - } - - /** - * Prints the internal representation of this list to a string. - * - * @see java.lang.Object#toString() - */ - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('['); - - Iterator iterator = iterator(); - if(iterator.hasNext()){ - E element = iterator.next(); - buffer.append(element); - - while(iterator.hasNext()){ - element = iterator.next(); - - buffer.append(','); - buffer.append(element); - } - } - - buffer.append(']'); - - return buffer.toString(); - } - - /** - * Iterator for this list. - * - * @author Arnold Lankamp - * - * @param - * The element type. - */ - private static class ListIterator implements Iterator{ - private final ShareableList shareableList; - - private int currentIndex; - private boolean front; - - /** - * Constructor. - * - * @param shareableList - * The list to iterator over. - */ - public ListIterator(ShareableList shareableList){ - super(); - - this.shareableList = shareableList; - - currentIndex = shareableList.backIndex - 1; - front = false; - if(currentIndex < 0){ - currentIndex = 0; - front = true; - } - } - - /** - * Check whether or not there are more elements in this iteration. - * - * @return True if there are more element in this iteration. - * - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext(){ - return front ? (currentIndex < shareableList.frontIndex) : (currentIndex >= 0); - } - - /** - * Returns the next element in this iteration. - * - * @return The next element in this iteration. - * @throws java.util.NoSuchElementException - * Thrown when there are no more elements in this iteration when calling this - * method. - * - * @see java.util.Iterator#next() - */ - public E next(){ - if(!hasNext()) throw new NoSuchElementException("There are no more elements in this iteration."); - - E element; - - if(front){ - element = shareableList.frontData[currentIndex++]; - }else{ - element = shareableList.backData[currentIndex--]; - if(currentIndex == -1){ - front = true; - currentIndex = 0; - } - } - - return element; - } - - /** - * This iterator does not support removal. - * - * @throws java.lang.UnsupportedOperationException - * - * @see java.util.Iterator#remove() - */ - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/util/ValueIndexedHashMap.java b/value-core/src/main/java/org/rascalmpl/value/util/ValueIndexedHashMap.java deleted file mode 100644 index df664cbcb..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/util/ValueIndexedHashMap.java +++ /dev/null @@ -1,802 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.util; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.impl.util.collections.ShareableValuesHashSet; - -/** - * This map is similar to the ShareableHashMap, but is indexed by a value (check with isEqual). - * - * @author Arnold Lankamp - * - * @param - * The value type - */ -public final class ValueIndexedHashMap implements Map{ - private final static int INITIAL_LOG_SIZE = 4; - - private int modSize; - private int hashMask; - - private Entry[] data; - - private int threshold; - - private int load; - - /** - * Constructor. - */ - public ValueIndexedHashMap(){ - super(); - - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - } - - /** - * Copy constructor - * - * @param valueIndexedHashMap - * The map to copy. - */ - public ValueIndexedHashMap(ValueIndexedHashMap valueIndexedHashMap){ - super(); - - modSize = valueIndexedHashMap.modSize; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = valueIndexedHashMap.data.clone(); - - threshold = tableSize; - - load = valueIndexedHashMap.load; - } - - /** - * Removes all the entries from this map. - */ - public void clear(){ - modSize = INITIAL_LOG_SIZE; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - data = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - load = 0; - } - - /** - * Rehashes this map. - */ - private void rehash(){ - modSize++; - int tableSize = 1 << modSize; - hashMask = tableSize - 1; - Entry[] newData = (Entry[]) new Entry[tableSize]; - - threshold = tableSize; - - Entry[] oldData = data; - for(int i = oldData.length - 1; i >= 0; i--){ - Entry entry = oldData[i]; - - if(entry != null){ - // Determine the last unchanged entry chain. - Entry lastUnchangedEntryChain = entry; - int newLastUnchangedEntryChainIndex = entry.hash & hashMask; - - Entry e = entry.next; - while(e != null){ - int newIndex = e.hash & hashMask; - if(newIndex != newLastUnchangedEntryChainIndex){ - lastUnchangedEntryChain = e; - newLastUnchangedEntryChainIndex = newIndex; - } - - e = e.next; - } - - newData[newLastUnchangedEntryChainIndex] = lastUnchangedEntryChain; - - // Reconstruct the other entries (if necessary). - while(entry != lastUnchangedEntryChain){ - int hash = entry.hash; - int position = hash & hashMask; - newData[position] = new Entry<>(hash, entry.key, entry.value, newData[position]); - - entry = entry.next; - } - } - } - - data = newData; - } - - /** - * Makes sure the size of the entry array and the load of the map stay in proper relation to - * eachother. - */ - private void ensureCapacity(){ - if(load > threshold){ - rehash(); - } - } - - /** - * Replaces the value in the entry by the given value. - * - * @param position - * The position in the entry array where the entry is located. - * @param entry - * The entry in which the value must be replaced. - * @param newValue - * The value. - */ - private void replaceValue(int position, Entry entry, V newValue){ - Entry e = data[position]; - - // Reconstruct the updated entry. - data[position] = new Entry<>(entry.hash, entry.key, newValue, entry.next); - - // Reconstruct the other entries (if necessary). - while(e != entry){ - data[position] = new Entry<>(e.hash, e.key, e.value, data[position]); - - e = e.next; - } - } - - /** - * Inserts the given key-value pair into this map. In case there already is a value associated - * with the given key, the value will be updated and the previous value returned. - * - * @param key - * The key - * @param value - * The value - * @return The previous value that was associated with the key (if any); null otherwise. - */ - public V put(IValue key, V value){ - ensureCapacity(); - - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry currentStartEntry = data[position]; - // Check if the key is already in here. - if(currentStartEntry != null){ - Entry entry = currentStartEntry; - do{ - if(hash == entry.hash && entry.key.isEqual(key)){ // Replace if present. - replaceValue(position, entry, value); - - return entry.value; // Return the old value. - } - - entry = entry.next; - }while(entry != null); - } - - data[position] = new Entry<>(hash, key, value, currentStartEntry); // Insert the new entry. - - load++; - - return null; - } - - /** - * Removes the entry from this map that is identified by the given key (if present). - * - * @param key - * The key that identifies the entry to remove. - * @return The value that was associated with the given key; null if the key was not present in - * the map. - */ - public V remove(Object object){ - IValue key = (IValue) object; - - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry currentStartEntry = data[position]; - if(currentStartEntry != null){ - Entry entry = currentStartEntry; - do{ - if(hash == entry.hash && entry.key.isEqual(key)){ - Entry e = data[position]; - - data[position] = entry.next; - // Reconstruct the other entries (if necessary). - while(e != entry){ - data[position] = new Entry<>(e.hash, e.key, e.value, data[position]); - - e = e.next; - } - - load--; - - return entry.value; // Return the value. - } - - entry = entry.next; - }while(entry != null); - } - - return null; // Not found. - } - - /** - * Retrieves the value from the entry in this map which is identified by the given key - * (if present). - * - * @param key - * The key that identifies the entry that contains the value. - * @return The retrieved value; null if not present. - */ - public V get(Object object){ - IValue key = (IValue) object; - - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && key.isEqual(entry.key)) return entry.value; - - entry = entry.next; - } - - return null; - } - - /** - * Checks if there is an entry present in this map, which is identified by the given key. - * - * @param key - * The key that identifies the entry. - * @return True if this map contains an entry which is identified by the given key; - * false otherwise. - */ - public boolean contains(IValue key){ - return (get(key) != null); - } - - /** - * Returns the number of entries this map contains. - * - * @return The number of entries this map contains. - */ - public int size(){ - return load; - } - - /** - * Checks whether or not this map is empty. - * - * @return True if this map was empty; false otherwise. - */ - public boolean isEmpty(){ - return (load == 0); - } - - /** - * Constructs an iterator for the entries in this map. - * - * @return An iterator for the entries in this map. - */ - public Iterator> entryIterator(){ - return new EntryIterator<>(data); - } - - /** - * Constructs an iterator for the keys in this map. - * - * @return An iterator for the keys in this map. - */ - public Iterator keysIterator(){ - return new KeysIterator<>(data); - } - - /** - * Constructs an iterator for the values in this map. - * - * @return An iterator for the values in this map. - */ - public Iterator valuesIterator(){ - return new ValuesIterator<>(data); - } - - /** - * Copies over all entries from the given map, to this map. - */ - public void putAll(Map otherMap){ - Set> entrySet = (Set>) (Set) otherMap.entrySet(); // Generics stink. - Iterator> entrySetIterator = entrySet.iterator(); - while(entrySetIterator.hasNext()){ - Map.Entry next = entrySetIterator.next(); - put(next.getKey(), next.getValue()); - } - } - - /** - * Checks if this map contains an entry with the given key. - */ - public boolean containsKey(Object object){ - IValue key = (IValue) object; - - int hash = key.hashCode(); - int position = hash & hashMask; - - Entry entry = data[position]; - while(entry != null){ - if(hash == entry.hash && key.isEqual(entry.key)) return true; - - entry = entry.next; - } - - return false; - } - - /** - * Checks if this map contains an entry with the given value. - */ - public boolean containsValue(Object value){ - Iterator valuesIterator = valuesIterator(); - while(valuesIterator.hasNext()){ - V nextValue = valuesIterator.next(); - if(nextValue == value || (nextValue != null && nextValue.equals(value))){ - return true; - } - } - - return false; - } - - /** - * Constructs a set containing all entries from this map. - */ - public Set> entrySet(){ - ShareableHashSet> entrySet = new ShareableHashSet<>(); - - Iterator> entriesIterator = entryIterator(); - while(entriesIterator.hasNext()){ - entrySet.add(entriesIterator.next()); - } - - return entrySet; - } - - /** - * Constructs a set containing all keys from this map. - */ - public Set keySet(){ - ShareableValuesHashSet keysSet = new ShareableValuesHashSet(); - - Iterator keysIterator = keysIterator(); - while(keysIterator.hasNext()){ - keysSet.add(keysIterator.next()); - } - - return keysSet; - } - - /** - * Constructs a collection containing all values from this map. - */ - public Collection values(){ - ShareableHashSet valuesSet = new ShareableHashSet<>(); - - Iterator valuesIterator = valuesIterator(); - while(valuesIterator.hasNext()){ - valuesSet.add(valuesIterator.next()); - } - - return valuesSet; - } - - /** - * Prints the internal representation of this map to a string. - * - * @see java.lang.Object#toString() - */ - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('{'); - for(int i = 0; i < data.length; i++){ - buffer.append('['); - Entry e = data[i]; - if(e != null){ - buffer.append(e); - - e = e.next; - - while(e != null){ - buffer.append(','); - buffer.append(e); - - e = e.next; - } - } - buffer.append(']'); - } - buffer.append('}'); - - return buffer.toString(); - } - - /** - * Returns the current hash code of this map. - * - * @return The current hash code of this map. - * - * @see java.lang.Object#hashCode() - */ - public int hashCode(){ - int hash = 0; - - Iterator keysIterator = keysIterator(); - while(keysIterator.hasNext()){ - hash ^= keysIterator.next().hashCode(); - } - - return hash; - } - - /** - * Check whether or not the current content of this set is equal to that of the given object / map. - * - * @return True if the content of this set is equal to the given object / map. - * - * @see java.lang.Object#equals(Object) - */ - public boolean equals(Object o){ - if(o == null) return false; - - if(o.getClass() == getClass()){ - ValueIndexedHashMap other = (ValueIndexedHashMap) o; - - if(other.size() != size()) return false; - - if(isEmpty()) return true; // No need to check if the maps are empty. - - Iterator> otherIterator = other.entryIterator(); - while(otherIterator.hasNext()){ - Map.Entry entry = otherIterator.next(); - V otherValue = entry.getValue(); - V thisValue = get(entry.getKey()); - if(otherValue != thisValue && thisValue != null && !thisValue.equals(entry.getValue())) return false; - } - return true; - } - - return false; - } - - /** - * Entry, used for containing key-value pairs and constructing buckets. - * - * @author Arnold Lankamp - * - * @param - * The key type - * @param - * The value type - */ - private static class Entry implements Map.Entry{ - public final int hash; - public final IValue key; - public final V value; - - public final Entry next; - - /** - * Constructor - * - * @param hash - * The hash code of the key - * @param key - * The key - * @param value - * The value - * @param next - * A reference to the next entry in the bucket (if any). - */ - public Entry(int hash, IValue key, V value, Entry next){ - super(); - - this.hash = hash; - this.key = key; - this.value = value; - - this.next = next; - } - - /** - * Returns a reference to the key. - * - * @return A reference to the key. - */ - public IValue getKey(){ - return key; - } - - /** - * Returns a reference to the value. - * - * @return A reference to the value. - */ - public V getValue(){ - return value; - } - - /** - * Unsupported operation. - * - * @param value - * The value which we will not set. - * @return Null. - * @throws java.lang.UnsupportedOperationException - * - * @see java.util.Map.Entry#setValue(Object) - */ - public V setValue(V value){ - throw new UnsupportedOperationException("The setting of values is not supported by this map implementation."); - } - - /** - * Prints the internal representation of this entry to a string. - * - * @see java.lang.Object#toString() - */ - public String toString(){ - StringBuilder buffer = new StringBuilder(); - - buffer.append('<'); - buffer.append(key); - buffer.append(':'); - buffer.append(value); - buffer.append('>'); - - return buffer.toString(); - } - } - - /** - * Iterator for entries. - * - * @author Arnold Lankamp - * - * @param - * The key type. - * @param - * The value type. - */ - private static class EntryIterator implements Iterator>{ - private final Entry[] data; - - private Entry current; - private int index; - - /** - * Constructor. - * - * @param entries - * The entries to iterator over. - */ - public EntryIterator(Entry[] entries){ - super(); - - data = entries; - - index = data.length - 1; - current = new Entry<>(0, null, null, data[index]); - locateNext(); - } - - /** - * Locates the next entry in the map. - */ - private void locateNext(){ - Entry next = current.next; - if(next != null){ - current = next; - return; - } - - for(int i = index - 1; i >= 0 ; i--){ - Entry entry = data[i]; - if(entry != null){ - current = entry; - index = i; - return; - } - } - - current = null; - index = 0; - } - - /** - * Check if there are more elements in this iteration. - * - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext(){ - return (current != null); - } - - /** - * Returns the next element in this iteration. - * - * @return The next element in this iteration. - * @throws NoSuchElementException - * Thrown if there are no more elements in this iteration when calling this - * method. - * - * @see java.util.Iterator#next() - */ - public Entry next(){ - if(!hasNext()) throw new UnsupportedOperationException("There are no more elements in this iterator."); - - Entry entry = current; - locateNext(); - - return entry; - } - - /** - * Removal is not supported by this iterator. - * - * @throws java.lang.UnsupportedOperationException - * - * @see java.util.Iterator#remove() - */ - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } - - /** - * Iterator for keys. - * - * @author Arnold Lankamp - * - * @param - * The key type. - * @param - * The value type. - */ - private static class KeysIterator implements Iterator{ - private final EntryIterator entryIterator; - - /** - * Constructor. - * - * @param entries - * The entries to iterate over. - */ - public KeysIterator(Entry[] entries){ - super(); - - entryIterator = new EntryIterator<>(entries); - } - - /** - * Check if there are more elements in this iteration. - * - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext(){ - return entryIterator.hasNext(); - } - - /** - * Returns the next element in this iteration. - * - * @return The next element in this iteration. - * @throws NoSuchElementException - * Thrown if there are no more elements in this iteration when calling this - * method. - * - * @see java.util.Iterator#next() - */ - public IValue next(){ - return entryIterator.next().key; - } - - /** - * Removal is not supported by this iterator. - * - * @throws java.lang.UnsupportedOperationException - * - * @see java.util.Iterator#remove() - */ - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } - - /** - * Iterator for values. - * - * @author Arnold Lankamp - * - * @param - * The key type. - * @param - * The value type. - */ - private static class ValuesIterator implements Iterator{ - private final EntryIterator entryIterator; - - /** - * Constructor. - * - * @param entries - * The entries to iterate over. - */ - public ValuesIterator(Entry[] entries){ - super(); - - entryIterator = new EntryIterator<>(entries); - } - - /** - * Check if there are more elements in this iteration. - * - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext(){ - return entryIterator.hasNext(); - } - - /** - * Returns the next element in this iteration. - * - * @return The next element in this iteration. - * @throws NoSuchElementException - * Thrown if there are no more elements in this iteration when calling this - * method. - * - * @see java.util.Iterator#next() - */ - public V next(){ - return entryIterator.next().value; - } - - /** - * Removal is not supported by this iterator. - * - * @throws java.lang.UnsupportedOperationException - * - * @see java.util.Iterator#remove() - */ - public void remove(){ - throw new UnsupportedOperationException("This iterator doesn't support removal."); - } - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/visitors/BottomUpTransformer.java b/value-core/src/main/java/org/rascalmpl/value/visitors/BottomUpTransformer.java deleted file mode 100644 index f87721d80..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/visitors/BottomUpTransformer.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008 CWI. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* jurgen@vinju.org - -*******************************************************************************/ -package org.rascalmpl.value.visitors; - -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IExternalValue; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * This visitor will apply another visitor in a bottom-up fashion to an IValue - * - */ -public class BottomUpTransformer extends VisitorAdapter { - protected IValueFactory fFactory; - - public BottomUpTransformer(IValueVisitor visitor, IValueFactory factory) { - super(visitor); - this.fFactory = factory; - } - - @Override - public IValue visitNode(INode o) throws E { - for (int i = 0; i < o.arity(); i++) { - o = o.set(i, o.get(i).accept(this)); - } - - return fVisitor.visitNode(o); - } - - public IValue visitConstructor(IConstructor o) throws E { - for (int i = 0; i < o.arity(); i++) { - o = o.set(i, o.get(i).accept(this)); - } - - return fVisitor.visitConstructor(o); - } - - @Override - public IValue visitList(IList o) throws E { - IListWriter w = fFactory.listWriter(); - for (IValue elem : o) { - w.append(elem.accept(this)); - } - - return fVisitor.visitList(w.done()); - } - - @Override - public IValue visitSet(ISet o) throws E { - ISetWriter w = fFactory.setWriter(); - for (IValue elem : o) { - w.insert(elem.accept(this)); - } - - return fVisitor.visitSet(w.done()); - } - - @Override - public IValue visitMap(IMap o) throws E { - IMapWriter w = fFactory.mapWriter(); - for (IValue elem : o) { - w.put(elem.accept(this), o.get(elem).accept(this)); - } - - return fVisitor.visitMap(w.done()); - } - - @Override - public IValue visitRelation(ISet o) throws E { - ISetWriter w = fFactory.setWriter(); - - for (IValue tuple : o) { - w.insert((ITuple) tuple.accept(this)); - } - - return fVisitor.visitRelation(w.done()); - } - - @Override - public IValue visitTuple(ITuple o) throws E { - for (int i = 0; i < o.arity(); i++) { - o.set(i, o.get(i).accept(this)); - } - - return fVisitor.visitTuple(o); - } - - public IValue visitExternal(IExternalValue externalValue) throws E { - return fVisitor.visitExternal(externalValue); - } - - public IValue visitListRelation(IList o) throws E { - IListWriter w = fFactory.listWriter(); - - for (IValue tuple : o) { - w.insert((ITuple) tuple.accept(this)); - } - - return fVisitor.visitListRelation(w.done()); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/visitors/BottomUpVisitor.java b/value-core/src/main/java/org/rascalmpl/value/visitors/BottomUpVisitor.java deleted file mode 100644 index ec87e9fd6..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/visitors/BottomUpVisitor.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008 CWI. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* jurgen@vinju.org - -*******************************************************************************/ -package org.rascalmpl.value.visitors; - -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IExternalValue; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * This visitor will apply another visitor in a bottom-up fashion to an IValue - * - */ -public class BottomUpVisitor extends VisitorAdapter { - protected IValueFactory fFactory; - - public BottomUpVisitor(IValueVisitor visitor, IValueFactory factory) { - super(visitor); - this.fFactory = factory; - } - - @Override - public T visitNode(INode o) throws E { - for (int i = 0; i < o.arity(); i++) { - o.get(i).accept(this); - } - - return fVisitor.visitNode(o); - } - - public T visitConstructor(IConstructor o) throws E { - for (int i = 0; i < o.arity(); i++) { - o.get(i).accept(this); - } - - return fVisitor.visitConstructor(o); - } - - @Override - public T visitList(IList o) throws E { - IListWriter w = fFactory.listWriter(); - for (IValue elem : o) { - elem.accept(this); - } - - return fVisitor.visitList(w.done()); - } - - @Override - public T visitSet(ISet o) throws E { - ISetWriter w = fFactory.setWriter(); - for (IValue elem : o) { - elem.accept(this); - } - - return fVisitor.visitSet(w.done()); - } - - @Override - public T visitMap(IMap o) throws E { - IMapWriter w = fFactory.mapWriter(); - for (IValue elem : o) { - elem.accept(this); - o.get(elem).accept(this); - } - - return fVisitor.visitMap(w.done()); - } - - @Override - public T visitRelation(ISet o) throws E { - ISetWriter w = fFactory.setWriter(); - - for (IValue tuple : o) { - tuple.accept(this); - } - - return fVisitor.visitRelation(w.done()); - } - - @Override - public T visitTuple(ITuple o) throws E { - for (int i = 0; i < o.arity(); i++) { - o.get(i).accept(this); - } - - return fVisitor.visitTuple(o); - } - - public T visitExternal(IExternalValue externalValue) throws E { - return fVisitor.visitExternal(externalValue); - } - - public T visitListRelation(IList o) throws E { - IListWriter w = fFactory.listWriter(); - - for (IValue tuple : o) { - tuple.accept(this); - } - - return fVisitor.visitListRelation(w.done()); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/visitors/IdentityVisitor.java b/value-core/src/main/java/org/rascalmpl/value/visitors/IdentityVisitor.java deleted file mode 100644 index 108e083e9..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/visitors/IdentityVisitor.java +++ /dev/null @@ -1,99 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008 CWI. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* jurgen@vinju.org -*******************************************************************************/ -package org.rascalmpl.value.visitors; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IExternalValue; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * This abstract class does nothing except implementing identity. Extend it - * to easily implement a visitor that visits selected types of IValues. - * - */ -public abstract class IdentityVisitor implements IValueVisitor { - public IValue visitReal(IReal o) throws E{ - return o; - } - - public IValue visitInteger(IInteger o) throws E{ - return o; - } - - public IValue visitRational(IRational o) throws E{ - return o; - } - - public IValue visitList(IList o) throws E{ - return o; - } - - public IValue visitMap(IMap o) throws E{ - return o; - } - - public IValue visitRelation(ISet o) throws E{ - return o; - } - - public IValue visitListRelation(IList o) throws E{ - return o; - } - - public IValue visitSet(ISet o) throws E{ - return o; - } - - public IValue visitSourceLocation(ISourceLocation o) throws E{ - return o; - } - - public IValue visitString(IString o) throws E{ - return o; - } - - public IValue visitNode(INode o) throws E{ - return o; - } - - public IValue visitConstructor(IConstructor o) throws E { - return o; - } - - public IValue visitTuple(ITuple o) throws E{ - return o; - } - - public IValue visitBoolean(IBool o) throws E { - return o; - } - - public IValue visitExternal(IExternalValue o) throws E { - return o; - } - - public IValue visitDateTime(IDateTime o) throws E { - return o; - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/visitors/NullVisitor.java b/value-core/src/main/java/org/rascalmpl/value/visitors/NullVisitor.java deleted file mode 100644 index 085d552b2..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/visitors/NullVisitor.java +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008 CWI. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* jurgen@vinju.org -*******************************************************************************/ -package org.rascalmpl.value.visitors; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IExternalValue; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * This abstract class does nothing except returning null. Extend it - * to easily implement a visitor that visits selected types of IValues. - * - */ -public abstract class NullVisitor implements IValueVisitor { - public T visitReal(IReal o) throws E{ - return null; - } - - public T visitInteger(IInteger o) throws E{ - return null; - } - - public T visitRational(IRational o) throws E{ - return null; - } - - public T visitList(IList o) throws E{ - return null; - } - - public T visitMap(IMap o) throws E{ - return null; - } - - public T visitRelation(ISet o) throws E{ - return null; - } - - public T visitSet(ISet o) throws E{ - return null; - } - - public T visitSourceLocation(ISourceLocation o) throws E{ - return null; - } - - public T visitString(IString o) throws E{ - return null; - } - - public T visitNode(INode o) throws E{ - return null; - } - - public T visitConstructor(IConstructor o) throws E { - return null; - } - - public T visitTuple(ITuple o) throws E{ - return null; - } - - public T visitBoolean(IBool boolValue) throws E { - return null; - } - - public T visitExternal(IExternalValue externalValue) throws E { - return null; - } - - public T visitDateTime(IDateTime o) throws E { - return null; - } - - public T visitListRelation(IList o) throws E { - return null; - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/visitors/VisitorAdapter.java b/value-core/src/main/java/org/rascalmpl/value/visitors/VisitorAdapter.java deleted file mode 100644 index 65bf43e27..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/visitors/VisitorAdapter.java +++ /dev/null @@ -1,103 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008 CWI. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* jurgen@vinju.org -*******************************************************************************/ -package org.rascalmpl.value.visitors; - -import org.rascalmpl.value.IBool; -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IExternalValue; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.visitors.IValueVisitor; - -/** - * Extend this class to easily create a reusable generic visitor implementation. - * - */ -public abstract class VisitorAdapter implements IValueVisitor { - protected IValueVisitor fVisitor; - - public VisitorAdapter(IValueVisitor visitor) { - this.fVisitor = visitor; - } - - public T visitReal(IReal o) throws E { - return fVisitor.visitReal(o); - } - - public T visitInteger(IInteger o) throws E { - return fVisitor.visitInteger(o); - } - - public T visitRational(IRational o) throws E { - return fVisitor.visitRational(o); - } - - public T visitList(IList o) throws E { - return fVisitor.visitList(o); - } - - public T visitMap(IMap o) throws E { - return fVisitor.visitMap(o); - } - - public T visitRelation(ISet o) throws E { - return fVisitor.visitRelation(o); - } - - public T visitSet(ISet o) throws E { - return fVisitor.visitSet(o); - } - - public T visitSourceLocation(ISourceLocation o) throws E { - return fVisitor.visitSourceLocation(o); - } - - public T visitString(IString o) throws E { - return fVisitor.visitString(o); - } - - public T visitNode(INode o) throws E { - return fVisitor.visitNode(o); - } - - public T visitConstructor(IConstructor o) throws E { - return fVisitor.visitNode(o); - } - - public T visitTuple(ITuple o) throws E { - return fVisitor.visitTuple(o); - } - - public T visitBoolean(IBool o) throws E { - return fVisitor.visitBoolean(o); - } - - public T visitDateTime(IDateTime o) throws E { - return fVisitor.visitDateTime(o); - } - @Override - public T visitListRelation(IList o) throws E { - return fVisitor.visitListRelation(o); - } - @Override - public T visitExternal(IExternalValue externalValue) throws E { - return fVisitor.visitExternal(externalValue); - } -} diff --git a/value-core/src/main/java/org/rascalmpl/value/visitors/VisitorException.java b/value-core/src/main/java/org/rascalmpl/value/visitors/VisitorException.java deleted file mode 100644 index b1ac2a727..000000000 --- a/value-core/src/main/java/org/rascalmpl/value/visitors/VisitorException.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2008 CWI. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* jurgen@vinju.org - -*******************************************************************************/ -package org.rascalmpl.value.visitors; - -/** - * This class can be used to wrap exceptions that occur during visiting - * such that clients of a visitor can deal with them appropriately. - */ -public class VisitorException extends Exception { - private static final long serialVersionUID = 4217829420715152023L; - - public VisitorException(String msg) { - super(msg); - } - - public VisitorException(String msg, Throwable cause) { - super(msg, cause); - } - - public VisitorException(Throwable cause) { - super(cause); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/AllTests.java b/value-core/src/test/java/org/rascalmpl/value/AllTests.java deleted file mode 100644 index f94a4e6f3..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/AllTests.java +++ /dev/null @@ -1,81 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value; - -import junit.framework.Test; -import junit.framework.TestSuite; - -public class AllTests { - - // TODO: this test suite tests the basic functionality of sets, relations and lists; - // it also checks the functionality of the type factory and the computation of - // the least upperbound of types and the isSubtypeOf method. It needs more tests - // for named types and the way they are checked and produced by the implementations - // of IRelation, ISet and IList. - - public static Test suite() { - TestSuite suite = new TestSuite( - "Test for org.eclipse.imp.pdb"); - - suite.addTestSuite(TestType.class); - suite.addTestSuite(TestTypeFactory.class); - suite.addTestSuite(TestIO.class); - suite.addTestSuite(TestBinaryIO.class); - - addReferenceTests(suite); - addFastTests(suite); - addPersistentTests(suite); - - return suite; - } - - private static void addReferenceTests(TestSuite suite) { - suite.addTestSuite(org.rascalmpl.value.reference.TestAnnotations.class); - suite.addTestSuite(org.rascalmpl.value.reference.TestBasicValues.class); - suite.addTestSuite(org.rascalmpl.value.reference.TestEquality.class); - suite.addTestSuite(org.rascalmpl.value.reference.TestList.class); - suite.addTestSuite(org.rascalmpl.value.reference.TestListRelation.class); - suite.addTestSuite(org.rascalmpl.value.reference.TestMap.class); - suite.addTestSuite(org.rascalmpl.value.reference.TestRandomValues.class); - suite.addTestSuite(org.rascalmpl.value.reference.TestRelation.class); - suite.addTestSuite(org.rascalmpl.value.reference.TestSet.class); - suite.addTestSuite(org.rascalmpl.value.reference.TestValueFactory.class); - } - - private static void addFastTests(TestSuite suite) { - suite.addTestSuite(org.rascalmpl.value.fast.TestAnnotations.class); - suite.addTestSuite(org.rascalmpl.value.fast.TestBasicValues.class); - suite.addTestSuite(org.rascalmpl.value.fast.TestEquality.class); - suite.addTestSuite(org.rascalmpl.value.fast.TestList.class); - suite.addTestSuite(org.rascalmpl.value.fast.TestListRelation.class); - suite.addTestSuite(org.rascalmpl.value.fast.TestMap.class); - suite.addTestSuite(org.rascalmpl.value.fast.TestRandomValues.class); - suite.addTestSuite(org.rascalmpl.value.fast.TestRelation.class); - suite.addTestSuite(org.rascalmpl.value.fast.TestSet.class); - suite.addTestSuite(org.rascalmpl.value.fast.TestValueFactory.class); - } - - private static void addPersistentTests(TestSuite suite) { - suite.addTestSuite(org.rascalmpl.value.persistent.TestAnnotations.class); - suite.addTestSuite(org.rascalmpl.value.persistent.TestBasicValues.class); - suite.addTestSuite(org.rascalmpl.value.persistent.TestEquality.class); - suite.addTestSuite(org.rascalmpl.value.persistent.TestList.class); - suite.addTestSuite(org.rascalmpl.value.persistent.TestListRelation.class); - suite.addTestSuite(org.rascalmpl.value.persistent.TestMap.class); - suite.addTestSuite(org.rascalmpl.value.persistent.TestRandomValues.class); - suite.addTestSuite(org.rascalmpl.value.persistent.TestRelation.class); - suite.addTestSuite(org.rascalmpl.value.persistent.TestSet.class); - suite.addTestSuite(org.rascalmpl.value.persistent.TestValueFactory.class); - } - -} diff --git a/value-core/src/test/java/org/rascalmpl/value/BaseTestAnnotations.java b/value-core/src/test/java/org/rascalmpl/value/BaseTestAnnotations.java deleted file mode 100644 index afa1b5271..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/BaseTestAnnotations.java +++ /dev/null @@ -1,293 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value; - -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeDeclarationException; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -import junit.framework.TestCase; - -public abstract class BaseTestAnnotations extends TestCase { - private IValueFactory vf; - private TypeFactory tf = TypeFactory.getInstance(); - private TypeStore ts = new TypeStore(); - private Type E; - private Type N; - - protected void setUp(IValueFactory factory) throws Exception { - super.setUp(); - vf = factory; - E = tf.abstractDataType(ts, "E"); - N = tf.constructor(ts, E, "n", tf.integerType()); - ts.declareAnnotation(E, "x", tf.integerType()); - } - - public void testDeclarationOnNonAllowedType() { - try { - ts.declareAnnotation(tf.integerType(), "a", tf.integerType()); - } - catch (FactTypeDeclarationException e) { - // this should happen - } - try { - ts.declareAnnotation(tf.realType(), "a", tf.integerType()); - } - catch (FactTypeDeclarationException e) { - // this should happen - } - } - - public void testDoubleDeclaration() { - try { - ts.declareAnnotation(E, "size", tf.integerType()); - } - catch (FactTypeDeclarationException | FactTypeUseException e) { - fail(e.toString()); - } - - try { - ts.declareAnnotation(E, "size", tf.realType()); - fail("double declaration is not allowed"); - } - catch (FactTypeDeclarationException e) { - // this should happen - } - } - - public void testSetAnnotation() { - IConstructor n = vf.constructor(N, vf.integer(0)); - ts.declareAnnotation(E, "size", tf.integerType()); - - try { - n.asAnnotatable().setAnnotation("size", vf.integer(0)); - } - catch (FactTypeDeclarationException | FactTypeUseException e) { - fail(e.toString()); - } - } - - public void testGetAnnotation() { - IConstructor n = vf.constructor(N, vf.integer(0)); - ts.declareAnnotation(E, "size", tf.integerType()); - - try { - if (n.asAnnotatable().getAnnotation("size") != null) { - fail("annotation should be null"); - } - } catch (FactTypeUseException e) { - fail(e.toString()); - } - - IConstructor m = n.asAnnotatable().setAnnotation("size", vf.integer(1)); - IValue b = m.asAnnotatable().getAnnotation("size"); - if (!b.isEqual(vf.integer(1))) { - fail(); - } - } - - public void testImmutability() { - IConstructor n = vf.constructor(N, vf.integer(0)); - ts.declareAnnotation(E, "size", tf.integerType()); - - IConstructor m = n.asAnnotatable().setAnnotation("size", vf.integer(1)); - - if (m == n) { - fail("annotation setting should change object identity"); - } - - assertTrue(m.isEqual(n)); - } - - public void testDeclaresAnnotation() { - IConstructor n = vf.constructor(N, vf.integer(0)); - ts.declareAnnotation(E, "size", tf.integerType()); - - if (!n.declaresAnnotation(ts, "size")) { - fail(); - } - - if (n.declaresAnnotation(ts, "size2")) { - fail(); - } - } - - public void testEqualityNode() { - final INode n = vf.node("hello"); - final INode na = n.asAnnotatable().setAnnotation("audience", vf.string("world")); - - assertEqualityOfValueWithAndWithoutAnnotations(n, na); - } - - public void testEqualityConstructor() { - final IConstructor n = vf.constructor(N, vf.integer(1)); - final IConstructor na = n.asAnnotatable().setAnnotation("x", vf.integer(1)); - - assertEqualityOfValueWithAndWithoutAnnotations(n, na); - } - - public void assertEqualityOfValueWithAndWithoutAnnotations(IValue n, IValue na) { - - assertIsEqualButNotEquals(n, na); - - assertIsEqualButNotEquals(vf.set(n), vf.set(na)); - assertIsEqualButNotEquals(vf.set(vf.set(n)), vf.set(vf.set(na))); - - assertIsEqualButNotEquals(vf.list(n), vf.list(na)); - assertIsEqualButNotEquals(vf.list(vf.list(n)), vf.list(vf.list(na))); - - // check: with keys - { - final IMap mapN = createMap(n, vf.integer(1)); - final IMap mapNA = createMap(na, vf.integer(1)); - final IMap mapMapN = createMap(mapN, vf.integer(1)); - final IMap mapMapNA = createMap(mapNA, vf.integer(1)); - - assertIsEqualButNotEquals(mapN, mapNA); - assertIsEqualButNotEquals(mapMapN, mapMapNA); - } - - // check: with values - { - final IMap mapN = createMap(vf.integer(1), n); - final IMap mapNA = createMap(vf.integer(1), na); - final IMap mapMapN = createMap(vf.integer(1), mapN); - final IMap mapMapNA = createMap(vf.integer(1), mapNA); - - assertIsEqualButNotEquals(mapN, mapNA); - assertIsEqualButNotEquals(mapMapN, mapMapNA); - } - - assertIsEqualButNotEquals(vf.node("nestingInNode", n), vf.node("nestingInNode", na)); - - final TypeStore ts = new TypeStore(); - final Type adtType = tf.abstractDataType(ts, "adtTypeNameThatIsIgnored"); - final Type constructorType = tf.constructor(ts, adtType, "nestingInConstructor", tf.valueType()); - - assertIsEqualButNotEquals(vf.constructor(constructorType, n), vf.constructor(constructorType, na)); - } - - /** - * Create a @IMap from a variable argument list. - * - * @param keyValuePairs - * a sequence of alternating keys and values - * @return an new @IMap instance - */ - public IMap createMap(IValue... keyValuePairs) { - assert (keyValuePairs.length % 2 == 0); - - IMapWriter w = vf.mapWriter(); - - for (int i = 0; i < keyValuePairs.length / 2; i++) { - w.put(keyValuePairs[i], keyValuePairs[i+1]); - } - - return w.done(); - } - - /** - * Asserting the current implementation w.r.t. hash codes and different - * equalities. Note, that this does not reflect the envisioned design that - * we are working towards (= structurally where annotations contribute to - * equality and hash code). - * - * @param a - * an object that does not use annotations - * @param b - * a structurally equal object to {@literal a} with annotations - */ - public void assertIsEqualButNotEquals(IValue a, IValue b) { - assertFalse(a.equals(b)); - - assertTrue(a.isEqual(b)); - assertTrue(a.hashCode() == b.hashCode()); - } - - - public void testNoKeywordParametersOnAnnotatedNode() { - try { - vf.node("hallo") - .asAnnotatable() - .setAnnotation("a", vf.integer(1)) - .asWithKeywordParameters() - .setParameter("b", vf.integer(2)); - } - catch (UnsupportedOperationException e) { - assertTrue(true); - } - } - - public void testAnnotationsOnNodeWithKeywordParameters() { - try { - vf.node("hallo") - .asWithKeywordParameters() - .setParameter("b", vf.integer(2)) - .asAnnotatable() - .setAnnotation("a", vf.integer(1)); - } - catch (UnsupportedOperationException e) { - assertTrue(true); - } - } - - public void testNodeAnnotation() { - ts.declareAnnotation(tf.nodeType(), "foo", tf.boolType()); - INode n = vf.node("hello"); - INode na = n.asAnnotatable().setAnnotation("foo", vf.bool(true)); - - assertTrue(na.asAnnotatable().getAnnotation("foo").getType().isBool()); - - // annotations on node type should be propagated - assertTrue(ts.getAnnotationType(tf.nodeType(), "foo").isBool()); - assertTrue(ts.getAnnotations(E).containsKey("foo")); - - // annotations sets should not collapse into one big set - ts.declareAnnotation(E, "a", tf.integerType()); - ts.declareAnnotation(N, "b", tf.boolType()); - assertTrue(!ts.getAnnotations(E).equals(ts.getAnnotations(N))); - } - - - public void testNodeKeywordParameter() { - INode n = vf.node("hello"); - INode na = n.asWithKeywordParameters().setParameter("foo", vf.bool(true)); - - assertTrue(na.asWithKeywordParameters().getParameter("foo").getType().isBool()); - assertTrue(na.asWithKeywordParameters().getParameter("foo").equals(vf.bool(true))); - } - - public void testConstructorKeywordParameter() { - TypeStore ts = new TypeStore(); - Type adt = tf.abstractDataType(ts, "adt"); - Type cons = tf.constructorFromTuple(ts, adt, "cons", tf.tupleEmpty()); - - IConstructor n1 = vf.constructor(cons); - - // overrides work - IConstructor n2 = n1.asWithKeywordParameters().setParameter("foo", vf.bool(false)); - assertTrue(n2.asWithKeywordParameters().getParameter("foo").isEqual(vf.bool(false))); - - // keywordparameters work on equality: - assertFalse(n1.isEqual(n2)); - } - -} diff --git a/value-core/src/test/java/org/rascalmpl/value/BaseTestBasicValues.java b/value-core/src/test/java/org/rascalmpl/value/BaseTestBasicValues.java deleted file mode 100644 index 351d659d2..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/BaseTestBasicValues.java +++ /dev/null @@ -1,194 +0,0 @@ -package org.rascalmpl.value; - -import java.net.URISyntaxException; - -import org.rascalmpl.value.IDateTime; -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.INumber; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISourceLocation; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.type.TypeFactory; - -import junit.framework.TestCase; - -abstract public class BaseTestBasicValues extends TestCase { - protected IValueFactory vf; - protected TypeFactory tf = TypeFactory.getInstance(); - - // TODO add more test cases - protected void setUp(IValueFactory factory) throws Exception { - super.setUp(); - vf = factory; - } - - protected void assertEqual(IValue l, IValue r) { - assertTrue("Expected " + l + " got " + r, l.isEqual(r)); - } - - public void testRationalToReal() { - assertTrue(vf.rational(1, 4).toReal(3).isEqual(vf.real(0.25))); - } - - public void testStringRepresentation() { - assertTrue(vf.string("\uD83C\uDF5D").isEqual(vf.string("🍝"))); - assertTrue(vf.string(new String(Character.toChars(0x1F35D))).isEqual(vf.string("🍝"))); - } - - public void testStringLength() { - assertTrue(vf.string("\uD83C\uDF5D").length() == 1); - assertTrue(vf.string("\uD83C\uDF5D\uD83C\uDF5D").length() == 2); - assertTrue(vf.string("🍝").length() == 1); - assertTrue(vf.string("🍝🍝").length() == 2); - assertTrue(vf.string("é").length() == 1); - assertTrue(vf.string("").length() == 0); - } - - public void testStringReverse() { - assertTrue(vf.string("").reverse().isEqual(vf.string(""))); - assertTrue(vf.string("🍝").reverse().isEqual(vf.string("🍝"))); - assertTrue(vf.string("🍝🍝").reverse().isEqual(vf.string("🍝🍝"))); - assertTrue(vf.string("🍝x🍝").reverse().isEqual(vf.string("🍝x🍝"))); - assertTrue(vf.string("🍝🍞").reverse().getValue().equals("🍞🍝")); - } - - public void testStringSubString() { - assertTrue(vf.string("").substring(0,0).isEqual(vf.string(""))); - assertTrue(vf.string("🍝").substring(0,1).isEqual(vf.string("🍝"))); - assertTrue(vf.string("🍝🍝").substring(0,1).isEqual(vf.string("🍝"))); - assertTrue(vf.string("🍝x🍝").substring(1,2).isEqual(vf.string("x"))); - assertTrue(vf.string("🍝x🍝").substring(1,3).isEqual(vf.string("x🍝"))); - } - - public void testStringCharAt() { - assertTrue(vf.string("🍝").charAt(0) == 0x1F35D); - assertTrue(vf.string("🍝🍞").charAt(1) == 0x1F35E); - assertTrue(vf.string("🍝x🍝").charAt(1) == 'x'); - assertTrue(vf.string("🍝x🍞").charAt(2) == 0x1F35E); - } - - public void testStringConcat() { - assertTrue(vf.string("").concat(vf.string("")).isEqual(vf.string(""))); - assertTrue(vf.string("x").concat(vf.string("y")).isEqual(vf.string("xy"))); - assertTrue(vf.string("🍝").concat(vf.string("y")).isEqual(vf.string("🍝y"))); - assertTrue(vf.string("x").concat(vf.string("🍝")).isEqual(vf.string("x🍝"))); - assertTrue(vf.string("🍝").concat(vf.string("🍝")).isEqual(vf.string("🍝🍝"))); - } - - public void testStringReplace() { - assertTrue(vf.string("").replace(0, 1, 0, vf.string("x")).isEqual(vf.string("x"))); - assertTrue(vf.string("x").replace(0, 1, 0, vf.string("")).isEqual(vf.string("x"))); - assertTrue(vf.string("xy").replace(0, 1, 1, vf.string("p")).isEqual(vf.string("py"))); - assertTrue(vf.string("xy").replace(1, 1, 0, vf.string("p")).isEqual(vf.string("xp"))); - assertTrue(vf.string("xy").replace(0, 1, 1, vf.string("pq")).isEqual(vf.string("pqy"))); - assertTrue(vf.string("xy").replace(1, 1, 0, vf.string("pq")).isEqual(vf.string("xqp"))); - assertTrue(vf.string("xy").replace(0, 1, 0, vf.string("pq")).isEqual(vf.string("pqxy"))); - assertTrue(vf.string("xy").replace(1, 1, 1, vf.string("pq")).isEqual(vf.string("xpqy"))); - - assertTrue(vf.string("🍝y").replace(0, 1, 1, vf.string("p")).isEqual(vf.string("py"))); - assertTrue(vf.string("🍝y").replace(1, 1, 0, vf.string("p")).isEqual(vf.string("🍝p"))); - assertTrue(vf.string("xy").replace(0, 1, 1, vf.string("🍝")).isEqual(vf.string("🍝y"))); - assertTrue(vf.string("").replace(0, 1, 0, vf.string("🍝")).isEqual(vf.string("🍝"))); - assertTrue(vf.string("🍝").replace(0, 1, 0, vf.string("")).isEqual(vf.string("🍝"))); - assertTrue(vf.string("🍝y").replace(0, 1, 1, vf.string("p")).isEqual(vf.string("py"))); - assertTrue(vf.string("🍝y").replace(1, 1, 0, vf.string("p")).isEqual(vf.string("🍝p"))); - assertTrue(vf.string("x🍝").replace(0, 1, 1, vf.string("p")).isEqual(vf.string("p🍝"))); - assertTrue(vf.string("x🍝").replace(1, 1, 0, vf.string("p")).isEqual(vf.string("xp"))); - assertTrue(vf.string("🍝y").replace(0, 1, 1, vf.string("p🍝")).isEqual(vf.string("p🍝y"))); - assertTrue(vf.string("🍝y").replace(1, 1, 0, vf.string("p🍝")).isEqual(vf.string("🍝🍝p"))); - assertTrue(vf.string("🍝y").replace(0, 1, 0, vf.string("🍝q")).isEqual(vf.string("🍝q🍝y"))); - assertTrue(vf.string("x🍝").replace(1, 1, 1, vf.string("🍝q")).isEqual(vf.string("x🍝q🍝"))); - assertTrue(vf.string("🍝y🍝").replace(1, 1, 2, vf.string("🍝")).isEqual(vf.string("🍝🍝🍝"))); - } - - - - public void testIntAddition() { - assertTrue(vf.integer(1).add(vf.integer(1)).isEqual(vf.integer(2))); - } - - public void testReal() { - assertTrue(vf.real("1.5").floor().isEqual(vf.real("1"))); - assertTrue(vf.real("1.5").round().isEqual(vf.real("2"))); - } - - public void testNumberSubTypes() { - assertTrue(tf.integerType().isSubtypeOf(tf.numberType())); - assertFalse(tf.numberType().isSubtypeOf(tf.integerType())); - assertTrue(tf.realType().isSubtypeOf(tf.numberType())); - assertFalse(tf.numberType().isSubtypeOf(tf.realType())); - assertTrue(tf.rationalType().isSubtypeOf(tf.numberType())); - assertFalse(tf.numberType().isSubtypeOf(tf.rationalType())); - - assertTrue(tf.integerType().lub(tf.realType()).equivalent(tf.numberType())); - assertTrue(tf.integerType().lub(tf.rationalType()).equivalent(tf.numberType())); - assertTrue(tf.integerType().lub(tf.numberType()).equivalent(tf.numberType())); - assertTrue(tf.realType().lub(tf.numberType()).equivalent(tf.numberType())); - assertTrue(tf.rationalType().lub(tf.integerType()).equivalent(tf.numberType())); - assertTrue(tf.rationalType().lub(tf.realType()).equivalent(tf.numberType())); - assertTrue(tf.rationalType().lub(tf.numberType()).equivalent(tf.numberType())); - } - - public void testNumberArithmatic() { - INumber i1 = vf.integer(1); - INumber i2 = vf.integer(2); - INumber r1 = vf.real(1.0); - INumber r2 = vf.real(2.0); - INumber q1 = vf.rational(1, 1); - INumber q2 = vf.rational(2, 1); - - assertEqual(i1.add(i2),vf.integer(3)); - assertEqual(i1.add(r2),vf.real(3)); - assertEqual(i1.add(q2),vf.rational(3, 1)); - assertEqual(q1.add(i2),vf.rational(3, 1)); - assertEqual(q1.add(q2),vf.rational(3, 1)); - assertEqual(r1.add(r2),vf.real(3)); - assertEqual(r1.add(i2),vf.real(3)); - assertEqual(r1.add(q2),vf.real(3)); - - assertEqual(i1.subtract(i2),vf.integer(-1)); - assertEqual(i1.subtract(r2),vf.real(-1)); - assertEqual(r1.subtract(r2),vf.real(-1)); - assertEqual(r1.subtract(i2),vf.real(-1)); - assertEqual(q1.subtract(q2),vf.rational(-1,1)); - assertEqual(q1.subtract(r2),vf.real(-1)); - assertEqual(q1.subtract(i2),vf.rational(-1,1)); - assertEqual(r1.subtract(q2),vf.real(-1)); - - IInteger i5 = vf.integer(5); - assertEqual(i5.divide(i2, 80*80),vf.real(2.5)); - assertEqual(i5.divide(i2.toRational()),vf.rational(5, 2)); - - assertEqual(vf.integer(0), vf.integer(0).abs()); - assertEqual(vf.rational(0, 1), vf.rational(0, 1).abs()); - assertEqual(vf.real(0), vf.real(0).abs()); - } - - - public void testPreciseRealDivision() { - IReal e100 = vf.real("1E100"); - IReal maxDiff = vf.real("1E-6300"); - IReal r9 = vf.real("9"); - assertTrue(e100.subtract(e100.divide(r9,80*80).multiply(r9)).lessEqual(maxDiff).getValue()); - } - - public void testDateTimeLongConversion() { - long l = 1156521600000L; - IDateTime dt = vf.datetime(l); - assertEqual(dt, vf.datetime(dt.getInstant())); - } - - public void testDateTimeLongConversionWithTimezone() { - IDateTime dt = vf.datetime(2014, 10, 13, 10, 7, 50, 1, 7, 0); - assertEqual(dt, vf.datetime(dt.getInstant(), dt.getTimezoneOffsetHours(), dt.getTimezoneOffsetMinutes())); - } - - public void testLocationTop() throws URISyntaxException { - ISourceLocation l = vf.sourceLocation("tmp","","/file.txt"); - assertTrue(l.top() == l); - - ISourceLocation m = vf.sourceLocation(l, 10, 20); - assertEquals(m.top(), l); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/BaseTestEquality.java b/value-core/src/test/java/org/rascalmpl/value/BaseTestEquality.java deleted file mode 100644 index 03ab83566..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/BaseTestEquality.java +++ /dev/null @@ -1,114 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value; - -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.INode; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -import junit.framework.TestCase; - -// TODO: this class could use more tests -public abstract class BaseTestEquality extends TestCase { - private IValueFactory vf; - private TypeFactory tf = TypeFactory.getInstance(); - - protected void setUp(IValueFactory factory) throws Exception { - super.setUp(); - vf = factory; - } - - public void testInteger() { - assertTrue(vf.integer(0).isEqual(vf.integer(0))); - assertFalse(vf.integer(0).isEqual(vf.integer(1))); - } - - public void testDouble() { - assertTrue(vf.real(0.0).isEqual(vf.real(0.0))); - assertTrue(vf.real(1.0).isEqual(vf.real(1.00000))); - assertFalse(vf.real(0.0).isEqual(vf.real(1.0))); - } - - public void testString() { - assertTrue(vf.string("").isEqual(vf.string(""))); - assertTrue(vf.string("a").isEqual(vf.string("a"))); - assertFalse(vf.string("a").isEqual(vf.string("b"))); - } - - public void testEmptyCollectionsAreVoid() { - assertTrue(vf.list(tf.integerType()).getElementType().isSubtypeOf(tf.voidType())); - assertTrue(vf.set(tf.integerType()).getElementType().isSubtypeOf(tf.voidType())); - assertTrue(vf.map(tf.integerType(),tf.integerType()).getKeyType().isSubtypeOf(tf.voidType())); - assertTrue(vf.map(tf.integerType(),tf.integerType()).getValueType().isSubtypeOf(tf.voidType())); - assertTrue(vf.relation(tf.tupleType(tf.integerType(),tf.integerType())).getElementType().isSubtypeOf(tf.voidType())); - - assertTrue(vf.listWriter(tf.integerType()).done().getElementType().isSubtypeOf(tf.voidType())); - assertTrue(vf.setWriter(tf.integerType()).done().getElementType().isSubtypeOf(tf.voidType())); - assertTrue(vf.mapWriter(tf.integerType(),tf.integerType()).done().getKeyType().isSubtypeOf(tf.voidType())); - assertTrue(vf.mapWriter(tf.integerType(),tf.integerType()).done().getValueType().isSubtypeOf(tf.voidType())); - assertTrue(vf.relationWriter(tf.tupleType(tf.integerType(),tf.integerType())).done().getElementType().isSubtypeOf(tf.voidType())); - } - - public void testList() { - assertTrue("element types are comparable", vf.list(tf.voidType()).isEqual(vf.list(tf.integerType()))); - assertTrue("empty lists are always equal", vf.list(tf.realType()).isEqual(vf.list(tf.integerType()))); - - assertTrue(vf.list(vf.integer(1)).isEqual(vf.list(vf.integer(1)))); - assertFalse(vf.list(vf.integer(1)).isEqual(vf.list(vf.integer(0)))); - - assertTrue(vf.list(vf.list(tf.voidType())).isEqual(vf.list(vf.list(tf.integerType())))); - assertTrue(vf.list(vf.list(tf.realType())).isEqual(vf.list(vf.list(tf.integerType())))); - } - - public void testSet() { - assertTrue("element types are comparable", vf.set(tf.voidType()).isEqual(vf.set(tf.integerType()))); - assertTrue("empty sets are always equal", vf.set(tf.realType()).isEqual(vf.set(tf.integerType()))); - - assertTrue(vf.set(vf.integer(1)).isEqual(vf.set(vf.integer(1)))); - assertFalse(vf.set(vf.integer(1)).isEqual(vf.set(vf.integer(0)))); - - assertTrue(vf.set(vf.set(tf.voidType())).isEqual(vf.set(vf.set(tf.integerType())))); - assertTrue(vf.set(vf.set(tf.realType())).isEqual(vf.set(vf.set(tf.integerType())))); - } - - /** - * Documenting the current relationship between Node and Constructor in - * terms of equality and hash codes. - */ - public void testConstructorIsEqualToConstructor() { - final INode n = vf.node("constructorComparableName", vf.integer(1), vf.integer(2)); - - final TypeStore ts = new TypeStore(); - final Type adtType = tf.abstractDataType(ts, "adtTypeNameThatIsIgnored"); - final Type constructorType = tf.constructor(ts, adtType, "constructorComparableName", tf.integerType(), tf.integerType()); - - final IConstructor c = vf.constructor(constructorType, vf.integer(1), vf.integer(2)); - - // they are not the same - assertFalse(n.equals(c)); - assertFalse(c.equals(n)); - /* - * TODO: what is the general contract between isEqual() and hashCode()? - */ - assertFalse(n.hashCode() == c.hashCode()); - - // unidirectional: n -> c = false - assertFalse(n.isEqual(c)); - - // unidirectional: c -> n = false - assertFalse(c.isEqual(n)); - } -} \ No newline at end of file diff --git a/value-core/src/test/java/org/rascalmpl/value/BaseTestList.java b/value-core/src/test/java/org/rascalmpl/value/BaseTestList.java deleted file mode 100644 index 06d08ddb5..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/BaseTestList.java +++ /dev/null @@ -1,330 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value; - -import java.util.HashSet; -import java.util.Iterator; -import java.util.Random; -import java.util.Set; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.type.TypeFactory; - -import junit.framework.TestCase; - -public abstract class BaseTestList extends TestCase { - private IValueFactory vf; - private TypeFactory tf = TypeFactory.getInstance(); - - private IValue[] integers; - private IList integerList; - private IList emptyIntegerList; - - protected void setUp(IValueFactory factory) throws Exception { - super.setUp(); - vf = factory; - - integers = new IValue[20]; - IListWriter w = vf.listWriter(tf.integerType()); - - for (int i = 0; i < integers.length; i++) { - integers[i] = vf.integer(i); - } - - for (int i = integers.length - 1; i >= 0; i--) { - w.insert(vf.integer(i)); - } - - integerList = w.done(); - - emptyIntegerList = vf.listWriter(tf.integerType()).done(); - } - - public void testGetElementType() { - if (!integerList.getElementType().isSubtypeOf(tf.integerType())) { - fail("funny getElementType"); - } - } - - public void testAppend() { - try { - IValue newValue = vf.integer(integers.length); - IList longer = integerList.append(newValue); - - if (longer.length() != integerList.length() + 1) { - fail("append failed"); - } - - if (!longer.get(integerList.length()).isEqual(newValue)) { - fail("element was not appended"); - } - - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - - try { - if (!integerList.append(vf.real(2)).getElementType().equivalent(tf.numberType())) { - fail("append should lub the element type"); - } - } catch (FactTypeUseException e) { - // this should happen - } - } - - public void testGet() { - for (int i = 0; i < integers.length; i++) { - if (!integerList.get(i).isEqual(integers[i])) { - fail("get failed"); - } - } - } - - public void testInsert() { - try { - IValue newValue = vf.integer(integers.length); - IList longer = integerList.insert(newValue); - - if (longer.length() != integerList.length() + 1) { - fail("append failed"); - } - - if (!longer.get(0).isEqual(newValue)) { - fail("element was not insrrted"); - } - - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - - try { - if (!integerList.insert(vf.real(2)).getElementType().equivalent(tf.numberType())) { - fail("insert should lub the element type"); - } - } catch (FactTypeUseException e) { - // this should happen - } - } - - public void testLength() { - if (vf.list(tf.integerType()).length() != 0) { - fail("empty list should be size 0"); - } - - if (integerList.length() != integers.length) { - fail("length does not count amount of elements"); - } - } - - public void testReverse() { - IList reverse = integerList.reverse(); - - if (reverse.getType() != integerList.getType()) { - fail("reverse should keep type"); - } - - if (reverse.length() != integerList.length()) { - fail("length of reverse is different"); - } - - for (int i = 0; i < integers.length; i++) { - if (!reverse.get(i).isEqual(integers[integers.length - i - 1])) { - fail("reverse did something funny: " + reverse + " is not reverse of " + integerList); - } - } - } - - public void testShuffle() { - IList shuffle = integerList.shuffle(new Random()); - - if (shuffle.getType() != integerList.getType()) { - fail("shuffle should keep type"); - } - - if (shuffle.length() != integerList.length()) { - fail("length after shuffle is different"); - } - } - // doesn't completly test distribution, but at least protects against some cases - public void testShuffleFirstLast() { - Set first = new HashSet<>(); - Set last = new HashSet<>(); - Random r = new Random(); - for (int i=0; i < 20 * integerList.length(); i++) { - IList shuffled = integerList.shuffle(r); - first.add(shuffled.get(0)); - last.add(shuffled.get(shuffled.length() - 1)); - } - for (IValue v: integerList) { - if (!first.contains(v)) { - fail("The shuffle doesn't shuffle the first index correctly"); - } - if (!last.contains(v)) { - fail("The shuffle doesn't shuffle the last index correctly"); - } - } - } - - public void testReverseEmpty() { - IList reverse = emptyIntegerList.reverse(); - - if (reverse.getType() != emptyIntegerList.getType()) { - fail("reverse should keep type"); - } - - if (reverse.length() != emptyIntegerList.length()) { - fail("length of reverse is different"); - } - } - - public void testIterator() { - Iterator it = integerList.iterator(); - - int i; - for (i = 0; it.hasNext(); i++) { - IValue v = it.next(); - if (!v.isEqual(integers[i])) { - fail("iterator does not iterate in order"); - } - } - } - - // NOTE: This is not a very good test, but sufficient for it's purpose. - public void testSubList(){ - // Front - IListWriter flw = vf.listWriter(tf.integerType()); - for(int i = 0; i < 20; i++){ - flw.append(vf.integer(i)); - } - IList fList = flw.done(); - - // Back - IListWriter blw = vf.listWriter(tf.integerType()); - for(int i = 19; i >= 0; i--){ - blw.insert(vf.integer(i)); - } - IList bList = blw.done(); - - // Overlap - IListWriter olw = vf.listWriter(tf.integerType()); - for(int i = 9; i >= 0; i--){ - olw.insert(vf.integer(i)); - } - for(int i = 10; i < 20; i++){ - olw.append(vf.integer(i)); - } - IList oList = olw.done(); - - IList fSubList = fList.sublist(0, 5); - IList bSubList = bList.sublist(0, 5); - IList oSubList = oList.sublist(0, 5); - checkSubListEquality(fSubList, bSubList, oSubList); - - fSubList = fList.sublist(1, 5); - bSubList = bList.sublist(1, 5); - oSubList = oList.sublist(1, 5); - checkSubListEquality(fSubList, bSubList, oSubList); - - fSubList = fList.sublist(0, 15); - bSubList = bList.sublist(0, 15); - oSubList = oList.sublist(0, 15); - checkSubListEquality(fSubList, bSubList, oSubList); - - fSubList = fList.sublist(1, 15); - bSubList = bList.sublist(1, 15); - oSubList = oList.sublist(1, 15); - checkSubListEquality(fSubList, bSubList, oSubList); - - fSubList = fList.sublist(5, 5); - bSubList = bList.sublist(5, 5); - oSubList = oList.sublist(5, 5); - checkSubListEquality(fSubList, bSubList, oSubList); - - fSubList = fList.sublist(5, 10); - bSubList = bList.sublist(5, 10); - oSubList = oList.sublist(5, 10); - checkSubListEquality(fSubList, bSubList, oSubList); - - fSubList = fList.sublist(15, 5); - bSubList = bList.sublist(15, 5); - oSubList = oList.sublist(15, 5); - checkSubListEquality(fSubList, bSubList, oSubList); - } - - private static void checkSubListEquality(IList fList, IList bList, IList oList){ - if(!fList.isEqual(bList) || !bList.isEqual(oList)) fail("IList#subList is broken: "+fList+" "+bList+" "+oList); - } - - public void testIsSubListOf(){ - IListWriter w = vf.listWriter(tf.integerType()); - - for (int i = integers.length - 1; i >= 0; i -= 2) { - w.insert(vf.integer(i)); - } - - IList even = w.done(); - - w = vf.listWriter(tf.integerType()); - - for (int i = integers.length - 2; i >= 0; i -= 2) { - w.insert(vf.integer(i)); - } - - IList odd = w.done(); - if(!integerList.isSubListOf(integerList)) - fail("integerList should be sublist of integerList"); - if(!even.isSubListOf(integerList)) - fail("even should be sublist of integerList"); - if(!odd.isSubListOf(integerList)) - fail("odd should be sublist of integerList"); - - if(integerList.isSubListOf(even)) - fail("integerList cannot be sublist of even"); - if(integerList.isSubListOf(odd)) - fail("integerList cannot be sublist of odd"); - if(even.isSubListOf(odd)) - fail("even cannot be sublist of odd"); - if(odd.isSubListOf(even)) - fail("odd cannot be sublist of even"); - - IList L123 = vf.list(integers[1], integers[2], integers[3]); - IList L918273 = vf.list(integers[9], integers[1], integers[8],integers[2], integers[7], integers[3]); - IList L918372 = vf.list(integers[9], integers[1], integers[8],integers[3], integers[7], integers[2]); - - if(!L123.isSubListOf(L918273)) - fail("123 is sublist of 918273"); - if(L123.isSubListOf(L918372)) - fail("123 is not a sublist of 918372"); - } - - public void testSubtract(){ - IList L12312 = vf.list(integers[1], integers[2], integers[3], integers[1], integers[2]); - IList L123 = vf.list(integers[1], integers[2], integers[3]); - IList L12 = vf.list(integers[1], integers[2]); - IList L321321 = vf.list(integers[3], integers[2], integers[1],integers[3], integers[2], integers[1]); - - if(!checkListEquality(L12312.subtract(L123), L12)) - fail("12312 subtract 123 should be 12"); - if(!L12312.subtract(L321321).isEmpty()) - fail("12312 subtract 123213213 should be empty"); - } - - private boolean checkListEquality(IList lst1, IList lst2){ - return lst1.isSubListOf(lst2) && lst2.isSubListOf(lst2); - - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/BaseTestListRelation.java b/value-core/src/test/java/org/rascalmpl/value/BaseTestListRelation.java deleted file mode 100644 index db09ec5d9..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/BaseTestListRelation.java +++ /dev/null @@ -1,478 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value; - -import java.util.Iterator; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IListWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -import junit.framework.TestCase; - -public abstract class BaseTestListRelation extends TestCase { - private IValueFactory vf; - private TypeFactory tf; - private IValue[] integers; - private ITuple[] integerTuples; - private IList listOfIntegers; - private IList integerListRelation; - private IValue[] doubles; - private IList listOfDoubles; - private IList doubleListRelation; - private ITuple[] doubleTuples; - - protected void setUp(IValueFactory factory) throws Exception { - super.setUp(); - vf = factory; - tf = TypeFactory.getInstance(); - - integers = new IValue[5]; - IListWriter lw = vf.listWriter(tf.integerType()); - - for (int i = 0; i < integers.length; i++) { - IValue iv = vf.integer(i); - integers[i] = iv; - lw.insert(iv); - } - listOfIntegers = lw.done(); - - doubles = new IValue[10]; - IListWriter lw2 = vf.listWriter(tf.realType()); - - for (int i = 0; i < doubles.length; i++) { - IValue iv = vf.real(i); - doubles[i] = iv; - lw2.insert(iv); - } - listOfDoubles = lw2.done(); - IListWriter rw = vf.listRelationWriter(tf.tupleType(tf.integerType(), tf.integerType())); - integerTuples = new ITuple[integers.length * integers.length]; - - for (int i = 0; i < integers.length; i++) { - for (int j = 0; j < integers.length; j++) { - ITuple t = vf.tuple(integers[i], integers[j]); - integerTuples[i * integers.length + j] = t; - rw.insert(t); - } - } - integerListRelation = rw.done(); - - IListWriter rw2 = vf.listRelationWriter(tf.tupleType(tf.realType(), tf.realType())); - doubleTuples = new ITuple[doubles.length * doubles.length]; - - for (int i = 0; i < doubles.length; i++) { - for (int j = 0; j < doubles.length; j++) { - ITuple t = vf.tuple(doubles[i], doubles[j]); - doubleTuples[i * doubles.length + j] = t; - rw2.insert(t); - } - } - doubleListRelation = rw2.done(); - } - - public void testIsEmpty() { - if (integerListRelation.isEmpty()) { - fail("integerRelation is not empty"); - } - - if (!vf.listRelation(tf.tupleType(tf.integerType())).isEmpty()) { - fail("this relation should be empty"); - } - - IList emptyRel = vf.listRelation(); - if (!emptyRel.isEmpty()) { - fail("empty relation is not empty?"); - } - if (!emptyRel.getType().isListRelation()) { - fail("empty relation should have relation type"); - } - - - } - - public void testSize() { - if (integerListRelation.length() != integerTuples.length) { - fail("relation size is not correct"); - } - } - - public void testArity() { - if (integerListRelation.asRelation().arity() != 2) { - fail("arity should be 2"); - } - } - - public void testProductIRelation() { - IList prod = integerListRelation.product(integerListRelation); - - if (prod.asRelation().arity() != 2 ) { - fail("arity of product should be 2"); - } - - if (prod.length() != integerListRelation.length() * integerListRelation.length()) { - fail("size of product should be square of size of integerRelation"); - } - } - - public void testProductIList() { - IList prod = integerListRelation.product(listOfIntegers); - - if (prod.asRelation().arity() != 2) { - fail("arity of product should be 2"); - } - - if (prod.length() != integerListRelation.length() * listOfIntegers.length()) { - fail("size of product should be square of size of integerRelation"); - } - } - - public void testClosure() { - try { - if (!integerListRelation.asRelation().closure().isEqual(integerListRelation)) { - fail("closure adds extra tuples?"); - } - } catch (FactTypeUseException e) { - fail("integerRelation is reflexive, so why an error?"); - } - - try { - ITuple t1 = vf.tuple(integers[0], integers[1]); - IList rel = vf.listRelation(t1); - - rel.asRelation().closure(); - } - catch (FactTypeUseException e) { - fail("reflexivity with subtyping is allowed"); - } - - try { - ITuple t1 = vf.tuple(integers[0], integers[1]); - ITuple t2 = vf.tuple(integers[1], integers[2]); - ITuple t3 = vf.tuple(integers[2], integers[3]); - ITuple t4 = vf.tuple(integers[0], integers[2]); - ITuple t5 = vf.tuple(integers[1], integers[3]); - ITuple t6 = vf.tuple(integers[0], integers[3]); - - IList test = vf.listRelation(t1, t2, t3); - IList closed = test.asRelation().closure(); - - if (closed.asRelation().arity() != test.asRelation().arity()) { - fail("closure should produce relations of same arity"); - } - - if (closed.length() != 6) { - fail("closure contains too few elements"); - } - - if (!closed.intersect(test).isEqual(test)) { - fail("closure should contain all original elements"); - } - - if (!closed.contains(t4) || !closed.contains(t5) || !closed.contains(t6)) { - fail("closure does not contain required elements"); - } - - } catch (FactTypeUseException e) { - fail("this should all be type correct"); - } - } - - public void testCompose() { - try { - IList comp = integerListRelation.asRelation().compose(integerListRelation.asRelation()); - - if (comp.asRelation().arity() != integerListRelation.asRelation().arity() * 2 - 2) { - fail("composition is a product with the last column of the first relation and the first column of the last relation removed"); - } - - if (comp.length() != integerListRelation.length() * integers.length) { - fail("number of expected tuples is off"); - } - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - - try { - ITuple t1 = vf.tuple(integers[0], doubles[0]); - ITuple t2 = vf.tuple(integers[1], doubles[1]); - ITuple t3 = vf.tuple(integers[2], doubles[2]); - IList rel1 = vf.listRelation(t1, t2, t3); - - ITuple t4 = vf.tuple(doubles[0], integers[0]); - ITuple t5 = vf.tuple(doubles[1], integers[1]); - ITuple t6 = vf.tuple(doubles[2], integers[2]); - IList rel2 = vf.listRelation(t4, t5, t6); - - ITuple t7 = vf.tuple(integers[0], integers[0]); - ITuple t8 = vf.tuple(integers[1], integers[1]); - ITuple t9 = vf.tuple(integers[2], integers[2]); - IList rel3 = vf.listRelation(t7, t8, t9); - - try { - vf.listRelation(vf.tuple(doubles[0],doubles[0])).asRelation().compose(rel1.asRelation()); - fail("relations should not be composable"); - } - catch (FactTypeUseException e) { - // this should happen - } - - IList comp = rel1.asRelation().compose(rel2.asRelation()); - - if (!comp.isEqual(rel3)) { - fail("composition does not produce expected result"); - } - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - } - - public void testContains() { - try { - for (ITuple t : integerTuples) { - if (!integerListRelation.contains(t)) { - fail("contains returns false instead of true"); - } - } - } catch (FactTypeUseException e) { - fail("this should be type correct"); - } - } - - public void testInsert() { - try { -// IList rel = integerListRelation.insert(vf.tuple(vf.integer(0),vf.integer(0))); -// -// if (!rel.isEqual(integerListRelation)) { -// fail("insert into a relation of an existing tuple should not change the relation"); -// } - - IListWriter relw3 = vf.listRelationWriter(tf.tupleType(tf.integerType(), tf.integerType())); - relw3.insertAll(integerListRelation); - IList rel3 = relw3.done(); - - final ITuple tuple = vf.tuple(vf.integer(100), vf.integer(100)); - IList rel4 = rel3.insert(tuple); - - if (rel4.length() != integerListRelation.length() + 1) { - fail("insert failed"); - } - - if (!rel4.contains(tuple)) { - fail("insert failed"); - } - - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - } - - public void testIntersectIRelation() { - IList empty1 = vf.listRelation(tf.tupleType(tf.integerType())); - IList empty2 = vf.listRelation(tf.tupleType(tf.realType())); - - try { - final IList intersection = empty1.intersect(empty2); - if (!intersection.isEmpty()) { - fail("empty intersection failed"); - } - - Type type = intersection.getType(); - if (!type.getFieldType(0).isBottom()) { - fail("intersection should produce lub types"); - } - } catch (FactTypeUseException e) { - fail("intersecting types which have a lub should be possible"); - } - - try { - if (!integerListRelation.intersect(doubleListRelation).isEmpty()) { - fail("non-intersecting relations should produce empty intersections"); - } - - IList oneTwoThree = vf.listRelation(integerTuples[0], - integerTuples[1], integerTuples[2]); - IList threeFourFive = vf.listRelation(integerTuples[2], - integerTuples[3], integerTuples[4]); - IList result = vf.listRelation(integerTuples[2]); - - if (!oneTwoThree.intersect(threeFourFive).isEqual(result)) { - fail("intersection failed"); - } - if (!threeFourFive.intersect(oneTwoThree).isEqual(result)) { - fail("intersection should be commutative"); - } - - if (!oneTwoThree.intersect(vf.listRelation(tf.tupleType(tf.integerType(),tf.integerType()))).isEmpty()) { - fail("intersection with empty set should produce empty"); - } - - } catch (FactTypeUseException e) { - fail("the above should all be type safe"); - } - } - - public void testIntersectIList() { - IList empty1 = vf.listRelation(tf.tupleType(tf.integerType())); - IList empty2 = vf.list(tf.tupleType(tf.realType())); - - try { - final IList intersection = empty1.intersect(empty2); - if (!intersection.isEmpty()) { - fail("empty intersection failed"); - } - - Type type = intersection.getType(); - if (!type.getFieldType(0).isBottom()) { - fail("empty intersection should produce void type"); - } - } catch (FactTypeUseException e) { - fail("intersecting types which have a lub should be possible"); - } - - try { - if (!integerListRelation.intersect(doubleListRelation).isEmpty()) { - fail("non-intersecting relations should produce empty intersections"); - } - - IList oneTwoThree = vf.listRelation(integerTuples[0], - integerTuples[1], integerTuples[2]); - IList threeFourFive = vf.list(integerTuples[2], - integerTuples[3], integerTuples[4]); - IList result = vf.listRelation(integerTuples[2]); - - if (!oneTwoThree.intersect(threeFourFive).isEqual(result)) { - fail("intersection failed"); - } - if (!threeFourFive.intersect(oneTwoThree).isEqual(result)) { - fail("intersection should be commutative"); - } - - if (!oneTwoThree.intersect(vf.listRelation(tf.tupleType(tf.integerType(),tf.integerType()))).isEmpty()) { - fail("intersection with empty list should produce empty"); - } - - } catch (FactTypeUseException e) { - fail("the above should all be type safe"); - } - } - - public void testConcatIListRelation() { - IList empty1 = vf.listRelation(tf.tupleType(tf.integerType())); - IList empty2 = vf.listRelation(tf.tupleType(tf.realType())); - - try { - final IList concat = (IList) empty1.concat(empty2); - if (!concat.isEmpty()) { - fail("empty concat failed"); - } - - Type type = concat.getType(); - if (!type.getFieldType(0).isBottom()) { - fail("concat should produce void type"); - } - } catch (FactTypeUseException e) { - fail("concat types which have a lub should be possible"); - } - - try { - if (integerListRelation.concat(doubleListRelation).length() != integerListRelation.length() + doubleListRelation.length()) { - fail("non-intersecting non-intersectiopn relations should produce relation that is the sum of the sizes"); - } - - IList oneTwoThree = vf.listRelation(integerTuples[0], - integerTuples[1], integerTuples[2]); - IList threeFourFive = vf.listRelation(integerTuples[3], integerTuples[4]); - IList result1 = vf.listRelation(integerTuples[0], - integerTuples[1], integerTuples[2], integerTuples[3], integerTuples[4]); - IList result2 = vf.listRelation(integerTuples[3], - integerTuples[4], integerTuples[0], integerTuples[1], integerTuples[2]); - - if (!oneTwoThree.concat(threeFourFive).isEqual(result1)) { - fail("concat 1 failed"); - } - if (!threeFourFive.concat(oneTwoThree).isEqual(result2)) { - fail("concat 2 failed"); - } - - if (!oneTwoThree.concat(vf.listRelation(tf.tupleType(tf.integerType(),tf.integerType()))).isEqual(oneTwoThree)) { - fail("concat with empty set should produce same set"); - } - - } catch (FactTypeUseException e) { - fail("the above should all be type safe"); - } - } - - public void testIterator() { - try { - Iterator it = integerListRelation.iterator(); - - int i; - for (i = 0; it.hasNext(); i++) { - ITuple t = (ITuple) it.next(); - - if (!integerListRelation.contains(t)) { - fail("iterator produces strange elements?"); - } - } - - if (i != integerListRelation.length()) { - fail("iterator skipped elements"); - } - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - } - - public void testCarrier() { - IList carrier = integerListRelation.asRelation().carrier(); - - if (!carrier.isEqual(listOfIntegers)) { - fail("carrier should be equal to this set"); - } - - try { - ITuple t1 = vf.tuple(integers[0], doubles[0]); - ITuple t2 = vf.tuple(integers[1], doubles[1]); - ITuple t3 = vf.tuple(integers[2], doubles[2]); - IList rel1 = vf.listRelation(t1, t2, t3); - - IList carrier1 = rel1.asRelation().carrier(); - - if (carrier1.getElementType() != tf.numberType()) { - fail("expected number type on carrier"); - } - - if (carrier1.length() != 6) { - fail("carrier does not contain all elements"); - } - - if (carrier1.intersect(listOfIntegers).length() != 3) { - fail("integers should be in there still"); - } - - if (carrier1.intersect(listOfDoubles).length() != 3) { - fail("doubles should be in there still"); - } - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/BaseTestMap.java b/value-core/src/test/java/org/rascalmpl/value/BaseTestMap.java deleted file mode 100644 index d4932a7a6..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/BaseTestMap.java +++ /dev/null @@ -1,551 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Centrum Wiskunde en Informatica (CWI) - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Anya Helene Bagge (University of Bergen) - implementation - * Arnold Lankamp - base implementation (from TestBinaryIO.java) - *******************************************************************************/ -package org.rascalmpl.value; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import org.rascalmpl.value.IConstructor; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IMapWriter; -import org.rascalmpl.value.IString; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.io.binary.BinaryReader; -import org.rascalmpl.value.io.binary.BinaryWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -import junit.framework.TestCase; - -/** - * @author Anya Helene Bagge - */ -public abstract class BaseTestMap extends TestCase { - protected final TypeStore ts = new TypeStore(); - protected final TypeFactory tf = TypeFactory.getInstance(); - private final Type fromToMapType = tf.mapType(tf.stringType(), "from", tf.stringType(), "to"); - private final Type fromToValueMapType = tf.mapType(tf.valueType(), "from", tf.valueType(), "to"); - private final Type keyValueMapType = tf.mapType(tf.stringType(), "key", tf.stringType(), "value"); - private final Type unlabeledMapType = tf.mapType(tf.stringType(), tf.stringType()); - enum Kind { BINARY }; - protected IValueFactory vf; - private Type a; - private Type b; - private TestValue[] testValues; - private IMap[] testMaps; - private StringPair[] keyValues; - - protected void setUp(IValueFactory factory) throws Exception { - vf = factory; - a = tf.abstractDataType(ts, "A"); - b = tf.abstractDataType(ts, "B"); - testValues = new TestValue[]{ - new TestValue(this, "Bergen", "Amsterdam", "from", "to"), - new TestValue(this, "New York", "London", null, null), - new TestValue(this, "Banana", "Fruit", "key", "value"), - }; - - testMaps = new IMap[] { - vf.map(fromToMapType), - vf.map(keyValueMapType), - vf.map(unlabeledMapType), - vf.map(fromToMapType).put(vf.string("Bergen"), vf.string("Amsterdam")), - vf.map(fromToValueMapType).put(vf.string("Bergen"), vf.string("Amsterdam")).put(vf.string("Mango"), vf.string("Yummy")), - vf.map(fromToMapType).put(vf.string("Bergen"), vf.string("Amsterdam")).put(vf.string("Amsterdam"), vf.string("Frankfurt")), - vf.map(fromToMapType).put(vf.string("Bergen"), vf.string("Amsterdam")).put(vf.string("Amsterdam"), vf.string("Frankfurt")).put(vf.string("Frankfurt"), vf.string("Moscow")), - vf.map(keyValueMapType).put(vf.string("Bergen"), vf.string("Rainy")).put(vf.string("Helsinki"), vf.string("Cold")), - vf.map(unlabeledMapType).put(vf.string("Mango"), vf.string("Sweet")).put(vf.string("Banana"), vf.string("Yummy")), - }; - - String[] strings = new String[] { "Bergen", "Amsterdam", "Frankfurt", "Helsinki", "Moscow", "Rainy", "Cold", "Mango", "Banana", "Sweet", "Yummy" }; - List list1 = Arrays.asList(strings); - List list2 = Arrays.asList(strings); - Collections.shuffle(list1); - Collections.shuffle(list2); - keyValues = new StringPair[strings.length]; - for(int i = 0; i < strings.length; i++) { - keyValues[i] = new StringPair(vf.string(list1.get(i)), vf.string(list2.get(i))); - } - } - - public void testNoLabels() { - // make a non-labeled map type, and the labels should be null - Type type = tf.mapType(a, b); - - assertNull(type.getKeyLabel()); - assertNull(type.getValueLabel()); - } - - public void testLabels() { - // make a labeled map type, and the labels should match - Type type = tf.mapType(a, "apple", b, "banana"); - - assertEquals("apple", type.getKeyLabel()); - assertEquals("banana", type.getValueLabel()); - } - - public void testTwoLabels1() { - // make two map types with same key/value types but different labels, - // and the labels should be kept distinct - Type type1 = tf.mapType(a, "apple", b, "banana"); - Type type2 = tf.mapType(a, "orange", b, "mango"); - Type type3 = tf.mapType(a, b); - - assertEquals("apple", type1.getKeyLabel()); - assertEquals("banana", type1.getValueLabel()); - assertEquals("orange", type2.getKeyLabel()); - assertEquals("mango", type2.getValueLabel()); - assertNull(type3.getKeyLabel()); - assertNull(type3.getValueLabel()); - } - - public void testTwoLabels2() { - Type type1 = tf.mapType(a, "apple", b, "banana"); - Type type2 = tf.mapType(a, "orange", b, "mango"); - - assertTrue("Two map types with different labels should be equivalent", type1.equivalent(type2)); - assertTrue("Two map types with different labels should be equivalent", type2.equivalent(type1)); - assertFalse("Two map types with different labels should not be equals", type1.equals(type2)); - assertFalse("Two map types with different labels should not be equals", type2.equals(type1)); - - Type type3 = tf.mapType(a, b); - assertTrue("Labeled and unlabeled maps should be equivalent", type1.equivalent(type3)); - assertTrue("Labeled and unlabeled maps should be equivalent", type3.equivalent(type1)); - assertTrue("Labeled and unlabeled maps should be equivalent", type2.equivalent(type3)); - assertTrue("Labeled and unlabeled maps should be equivalent", type3.equivalent(type2)); - assertFalse("Labeled and unlabeled maps should not be equals", type1.equals(type3)); - assertFalse("Labeled and unlabeled maps should not be equals", type3.equals(type1)); - assertFalse("Labeled and unlabeled maps should not be equals", type2.equals(type3)); - assertFalse("Labeled and unlabeled maps should not be equals", type3.equals(type2)); - } - - /** - * Check basic properties of put() - */ - public void testPut() { - for(IMap map : testMaps) { - for(StringPair p : keyValues) { - IMap newMap = map.put(p.a, p.b); - assertTrue(newMap.containsKey(p.a)); - assertEquals(p.b, newMap.get(p.a)); - assertEquals(map.getType().getKeyLabel(), newMap.getType().getKeyLabel()); - assertEquals(map.getType().getValueLabel(), newMap.getType().getValueLabel()); - assertTrue(map.getType().isSubtypeOf(newMap.getType())); - } - } - } - - /** - * Check that putting doesn't modify original map, and doesn't modify other elements. - */ - public void testPutModification() { - for(IMap map : testMaps) { - for(StringPair p : keyValues) { // testing with an arbitrary element of map is sufficient - if(map.containsKey(p.a)) { - IValue val = map.get(p.a); - for(StringPair q : keyValues) { - IMap newMap = map.put(q.a, q.b); - assertEquals(val, map.get(p.a)); // original is never modified - if(!p.a.isEqual(q.a)) - assertEquals(val, newMap.get(p.a)); // only element q.a is modified - } - } - - } - } - } - - public void testCommon() { - for(IMap map1 : testMaps) { - for(IMap map2 : testMaps) { - IMap map3 = map1.common(map2); - // all common values are present - for(IValue key : map1) { - if(map1.get(key).equals(map2.get(key))) { - assertEquals(map1.get(key), map3.get(key)); - } - } - // type is lub of map1 and map2 types - if(!map3.isEmpty()) { - assertTrue(map1.getType().toString() + " <: " + map3.getType(), map1.getType().isSubtypeOf(map3.getType())); - assertTrue(map2.getType().toString() + " <: " + map3.getType(), map2.getType().isSubtypeOf(map3.getType())); - } - - // check labels - if(!map2.getType().hasFieldNames()) { - assertEquals(map1.getType().getKeyLabel(), map3.getType().getKeyLabel()); - assertEquals(map1.getType().getValueLabel(), map3.getType().getValueLabel()); - } - if(!map1.getType().hasFieldNames()) { - assertEquals(map2.getType().getKeyLabel(), map3.getType().getKeyLabel()); - assertEquals(map2.getType().getValueLabel(), map3.getType().getValueLabel()); - } - } - - } - } - - public void testJoin() { - for(IMap map1 : testMaps) { - for(IMap map2 : testMaps) { - IMap map3 = map1.join(map2); - // should contain all values from map2... - for(IValue key : map2) { - assertEquals(map2.get(key), map3.get(key)); - } - // ...and all values from map1 unless the keys are in map2 - for(IValue key : map1) { - if(!map2.containsKey(key)) { - assertEquals(map1.get(key), map3.get(key)); - } - } - - // type is lub of map1 and map2 types - if(!map3.isEmpty()) { - assertTrue(map1.getType().toString() + " <: " + map3.getType(), map1.getType().isSubtypeOf(map3.getType())); - assertTrue(map2.getType().toString() + " <: " + map3.getType(), map2.getType().isSubtypeOf(map3.getType())); - } - - // check labels - if(!map2.getType().hasFieldNames()) { - assertEquals(map1.getType().getKeyLabel(), map3.getType().getKeyLabel()); - assertEquals(map1.getType().getValueLabel(), map3.getType().getValueLabel()); - } - if(!map1.getType().hasFieldNames()) { - assertEquals(map2.getType().getKeyLabel(), map3.getType().getKeyLabel()); - assertEquals(map2.getType().getValueLabel(), map3.getType().getValueLabel()); - } - } - - } - } - - public void testCompose() { - for(IMap map1 : testMaps) { - for(IMap map2 : testMaps) { - IMap map3 = map1.compose(map2); - // should map keys in map1 to values in map2 - for(IValue key : map1) { - if(map2.containsKey(map1.get(key))) - assertEquals(map2.get(map1.get(key)), map3.get(key)); - else - assertNull(map3.get(key)); - } - - // type is key type of map1 and value type of map2 - if(!map3.isEmpty()) { - assertEquals(map1.getType().getKeyType(), map3.getType().getKeyType()); - assertEquals(map2.getType().getValueType(), map3.getType().getValueType()); - } - - // check labels - if(map1.getType().hasFieldNames() && map2.getType().hasFieldNames()) { - assertEquals(map1.getType().getKeyLabel(), map3.getType().getKeyLabel()); - assertEquals(map2.getType().getValueLabel(), map3.getType().getValueLabel()); - } - else { - assertFalse(map3.getType().hasFieldNames()); - } - } - - } - } - - public void testRemove() { - for(IMap map1 : testMaps) { - for(IMap map2 : testMaps) { - IMap map3 = map1.remove(map2); - for(IValue key : map2) { - assertFalse("Key " + key + " should not exist", map3.containsKey(key)); - } - - // type is same as map1 - if(!map3.isEmpty()) { - assertEquals(map1.getType(), map3.getType()); - } - - // labels are same as map1 - if(map1.getType().hasFieldNames()) { - assertEquals(map1.getType().getKeyLabel(), map3.getType().getKeyLabel()); - assertEquals(map1.getType().getValueLabel(), map3.getType().getValueLabel()); - } - } - - } - } - - public void testLabelsIO(){ - try{ - for(int i = 0; i < testValues.length; i++){ - for(Kind k : Kind.values()) { - TestValue testValue = testValues[i]; - - assertEquals(testValue.keyLabel, testValue.value.getType().getKeyLabel()); - assertEquals(testValue.valueLabel, testValue.value.getType().getValueLabel()); - - System.out.println(testValue + " : " + testValue.value.getType()); // Temp - - IValue result = doIO(testValue.value, k); - System.out.println(result + " : " + result.getType()); // Temp - System.out.println(); // Temp - - if(!testValue.value.isEqual(result)){ - String message = "Not equal: \n\t"+testValue+" : "+testValue.value.getType()+"\n\t"+result+" : "+result.getType(); - System.err.println(message); - fail(message); - } - - Type resultType = result.getType(); - assertEquals("Labels should be preserved by " + k.name() + " IO: ", testValue.keyLabel, resultType.getKeyLabel()); - assertEquals("Labels should be preserved by " + k.name() + " IO: ", testValue.valueLabel, resultType.getValueLabel()); - } - } - }catch(IOException ioex){ - ioex.printStackTrace(); - fail(ioex.getMessage()); - } - } - - private IValue doIO(IValue val, Kind kind) throws IOException { - switch(kind) { - case BINARY: { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - BinaryWriter binaryWriter = new BinaryWriter(val, baos, ts); - binaryWriter.serialize(); - - byte[] data = baos.toByteArray(); - ByteArrayInputStream bais = new ByteArrayInputStream(data); - BinaryReader binaryReader = new BinaryReader(vf, ts, bais); - System.out.print("data: "); - printBytes(data); // Temp - return binaryReader.deserialize(); - } - /*// Doesn't work, but should, perhaps? - case XML: { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - XMLWriter writer = new XMLWriter(); - writer.write(val, new OutputStreamWriter(baos), ts); - - byte[] data = baos.toByteArray(); - ByteArrayInputStream bais = new ByteArrayInputStream(data); - XMLReader reader = new XMLReader(); - printBytes(data); // Temp - return reader.read(vf, new InputStreamReader(bais)); - } - */ - - /* TEXT IO shouldn't work, since the labels aren't present in the standard text representation */ - - /* // Doesn't work, but should, perhaps? - case ATERM: { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ATermWriter writer = new ATermWriter(); - writer.write(val, new OutputStreamWriter(baos), ts); - - byte[] data = baos.toByteArray(); - ByteArrayInputStream bais = new ByteArrayInputStream(data); - ATermReader reader = new ATermReader(); - printBytes(data); // Temp - return reader.read(vf, bais); - } - */ - default: - throw new RuntimeException("Missing case: " + kind.name()); - } - } - - private final static String[] HEX = new String[]{"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; - - // May be handy when debugging. - private static void printBytes(byte[] bytes){ - for(int i = 0; i < bytes.length; i++){ - byte b = bytes[i]; - int higher = (b & 0xf0) >> 4; - int lower = b & 0xf; - System.out.print("0x"); - System.out.print(HEX[higher]); - System.out.print(HEX[lower]); - System.out.print(" "); - } - System.out.println(); - } - - static class TestValue { - Type type; - IValue value; - String keyLabel; - String valueLabel; - - TestValue(BaseTestMap baseTestMap, String key, String value, String keyLabel, String valueLabel) { - TypeFactory tf = baseTestMap.tf; - IValueFactory vf = baseTestMap.vf; - this.keyLabel = keyLabel; - this.valueLabel = valueLabel; - if(keyLabel != null && valueLabel != null) - type = tf.mapType(tf.stringType(), keyLabel, tf.stringType(), valueLabel); - else - type = tf.mapType(tf.stringType(), tf.stringType()); - this.value = vf.map(type).put(vf.string(key), vf.string(value)); - } - - public String toString() { - return value.toString(); - } - } - - static class StringPair { - IString a; - IString b; - - StringPair(IString a, IString b) { - this.a = a; - this.b = b; - } - - @Override - public String toString() { - return String.format("(%s,%s)", a, b); - } - } - - public void testPutReplaceGet() { - final IMap m1 = vf.mapWriter().done() - .put(vf.integer(1), vf.integer(1)) - .put(vf.integer(1), vf.integer(2)); - - assertEquals(1, m1.size()); - assertEquals(vf.integer(2), m1.get(vf.integer(1))); - } - - public void testDynamicTypesAfterMapUpdatesGrow() { - final IMap m1 = vf.mapWriter().done() - .put(vf.integer(1), vf.integer(1)) - .put(vf.integer(1), vf.real(1)); - - assertEquals(1, m1.size()); - assertEquals(tf.integerType(), m1.getType().getKeyType()); - assertEquals(tf.realType(), m1.getType().getValueType()); - } - - public void testDynamicTypesAfterMapWriterUpdatesGrow() { - final IMapWriter w1 = vf.mapWriter(); - w1.put(vf.integer(1), vf.integer(1)); - w1.put(vf.integer(1), vf.real(1)); - - final IMap m1 = w1.done(); - - assertEquals(1, m1.size()); - assertEquals(tf.integerType(), m1.getType().getKeyType()); - assertEquals(tf.realType(), m1.getType().getValueType()); - } - - public void testDynamicTypesAfterMapUpdatesShrink() { - final IMap m1 = vf.mapWriter().done() - .put(vf.integer(1), vf.integer(1)) - .put(vf.integer(1), vf.real(1)) - .put(vf.integer(1), vf.integer(1)); - - assertEquals(1, m1.size()); - assertEquals(tf.integerType(), m1.getType().getKeyType()); - assertEquals(tf.integerType(), m1.getType().getValueType()); - } - - public void testDynamicTypesAfterMapWriterUpdatesShrink() { - final IMapWriter w1 = vf.mapWriter(); - w1.put(vf.integer(1), vf.integer(1)); - w1.put(vf.integer(1), vf.real(1)); - w1.put(vf.integer(1), vf.integer(1)); - - final IMap m1 = w1.done(); - - assertEquals(1, m1.size()); - assertEquals(tf.integerType(), m1.getType().getKeyType()); - assertEquals(tf.integerType(), m1.getType().getValueType()); - } - - public void testPutReplaceWithAnnotations_Map() { - final Type E = tf.abstractDataType(ts, "E"); - final Type N = tf.constructor(ts, E, "n", tf.integerType()); - ts.declareAnnotation(E, "x", tf.integerType()); - - final IConstructor n = vf.constructor(N, vf.integer(1)); - final IConstructor na = n.asAnnotatable().setAnnotation("x", vf.integer(1)); - - final IMap m1 = vf.mapWriter().done() - .put(n, vf.integer(1)) - .put(na, vf.integer(1)); - - assertEquals(1, m1.size()); - assertEquals(vf.integer(1), m1.get(n)); - assertEquals(vf.integer(1), m1.get(na)); - } - - public void testPutReplaceWithAnnotationsValue_Map() { - final Type E = tf.abstractDataType(ts, "E"); - final Type N = tf.constructor(ts, E, "n", tf.integerType()); - ts.declareAnnotation(E, "x", tf.integerType()); - - final IConstructor n = vf.constructor(N, vf.integer(1)); - final IConstructor na = n.asAnnotatable().setAnnotation("x", vf.integer(1)); - - final IMap m1 = vf.mapWriter().done() - .put(vf.integer(1), n) - .put(vf.integer(1), na); - - assertEquals(1, m1.size()); - assertEquals(na, m1.get(vf.integer(1))); - } - - public void testPutReplaceWithAnnotations_MapWriter() { - final Type E = tf.abstractDataType(ts, "E"); - final Type N = tf.constructor(ts, E, "n", tf.integerType()); - ts.declareAnnotation(E, "x", tf.integerType()); - - final IConstructor n = vf.constructor(N, vf.integer(1)); - final IConstructor na = n.asAnnotatable().setAnnotation("x", vf.integer(1)); - - final IMapWriter w1 = vf.mapWriter(); - w1.put(n, vf.integer(1)); - w1.put(na, vf.integer(1)); - - final IMap m1 = w1.done(); - - assertEquals(1, m1.size()); - assertEquals(vf.integer(1), m1.get(n)); - assertEquals(vf.integer(1), m1.get(na)); - } - - public void testPutReplaceWithAnnotationsValue_MapWriter() { - final Type E = tf.abstractDataType(ts, "E"); - final Type N = tf.constructor(ts, E, "n", tf.integerType()); - ts.declareAnnotation(E, "x", tf.integerType()); - - final IConstructor n = vf.constructor(N, vf.integer(1)); - final IConstructor na = n.asAnnotatable().setAnnotation("x", vf.integer(1)); - - final IMapWriter w1 = vf.mapWriter(); - w1.put(vf.integer(1), n); - w1.put(vf.integer(1), na); - - final IMap m1 = w1.done(); - - assertEquals(1, m1.size()); - assertEquals(na, m1.get(vf.integer(1))); - } - -} diff --git a/value-core/src/test/java/org/rascalmpl/value/BaseTestRandomValues.java b/value-core/src/test/java/org/rascalmpl/value/BaseTestRandomValues.java deleted file mode 100644 index 26cfb26d1..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/BaseTestRandomValues.java +++ /dev/null @@ -1,629 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2011 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Anya Helene Bagge (anya@ii.uib.no) - initial API and implementation -*******************************************************************************/ -package org.rascalmpl.value; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.INumber; -import org.rascalmpl.value.IRational; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.io.BinaryValueReader; -import org.rascalmpl.value.io.BinaryValueWriter; -import org.rascalmpl.value.io.IValueBinaryReader; -import org.rascalmpl.value.io.IValueBinaryWriter; -import org.rascalmpl.value.io.IValueTextReader; -import org.rascalmpl.value.io.IValueTextWriter; -import org.rascalmpl.value.io.StandardTextReader; -import org.rascalmpl.value.io.StandardTextWriter; -import org.rascalmpl.value.random.DataGenerator; -import org.rascalmpl.value.random.RandomIntegerGenerator; -import org.rascalmpl.value.random.RandomNumberGenerator; -import org.rascalmpl.value.random.RandomRationalGenerator; -import org.rascalmpl.value.random.RandomRealGenerator; -import org.rascalmpl.value.type.Type; - -import junit.framework.AssertionFailedError; -import junit.framework.TestCase; - - -/** - * Implements random testing of algebraic properties of the PDB values numeric - * types (aka axiom-based testing or property-based testing). - * - * Data is generated using the random data genererator in the random subpackage. - * @author anya - * - */ -abstract public class BaseTestRandomValues extends TestCase { - protected IValueFactory vf; - protected IInteger INT_ONE; - protected IInteger INT_ZERO; - protected IRational RAT_ONE; - protected IRational RAT_ZERO; - protected IReal REAL_ONE; - protected IReal REAL_ZERO; - protected IReal MAX_ERROR_RATIO; - protected double DOUBLE_MAX_ERROR_RATIO; - protected IReal EPSILON; - protected double DOUBLE_EPSILON; - protected static final int PRECISION = 100; - // number of iterations per axiom - protected int N = 500; - // TODO add more test cases - protected List intTestSet; - protected List ratTestSet; - protected List realTestSet; - private DataGenerator generator; - protected List mixedTestSet; - protected static final boolean noisy = true; - protected void setUp(IValueFactory factory) throws Exception { - super.setUp(); - vf = factory; - vf.setPrecision(PRECISION); - INT_ONE = vf.integer(1); - INT_ZERO = vf.integer(0); - RAT_ONE = vf.rational(1,1); - RAT_ZERO = vf.rational(0,1); - REAL_ONE = vf.real(1.0); - REAL_ZERO = vf.real(0.0); - // For approximate equality of reals a ~= b: - // this is the max allowable ratio of (a-b) to max(a,b) - MAX_ERROR_RATIO = vf.real(1e-15); - DOUBLE_MAX_ERROR_RATIO = 1e-10; - // this is the max allowed difference between a and b - EPSILON = vf.real(1e-10); - DOUBLE_EPSILON = 1e-10; - intTestSet = Arrays.asList(vf.integer(0), vf.integer(1), vf.integer(-1), - vf.integer(2), vf.integer(-2), vf.integer(Long.MAX_VALUE), - vf.integer(Long.MIN_VALUE), - vf.integer(Long.MAX_VALUE).multiply(vf.integer(Long.MAX_VALUE)), - vf.integer(Long.MIN_VALUE).multiply(vf.integer(Long.MAX_VALUE))); - ratTestSet = Arrays.asList(vf.rational(0,1), vf.rational(1,1), vf.rational(-1,1), - vf.rational(1,2), vf.rational(2,1), - vf.rational(-1,2), vf.rational(-2,1), - vf.rational(Long.MAX_VALUE,Long.MIN_VALUE)); - realTestSet = new ArrayList<>(); - mixedTestSet = new ArrayList<>(); - for(IInteger i : intTestSet) { - if(!ratTestSet.contains(i.toRational())) { - realTestSet.add(i.toReal(PRECISION)); - } - } - for(IRational r : ratTestSet) { - realTestSet.add(r.toReal(PRECISION)); - } - realTestSet.addAll(Arrays.asList(vf.real(Float.MAX_VALUE), vf.real(Float.MIN_VALUE))); - mixedTestSet.addAll(intTestSet); - mixedTestSet.addAll(ratTestSet); - mixedTestSet.addAll(realTestSet); - generator = new DataGenerator(); - generator.addGenerator(IInteger.class, intTestSet, new RandomIntegerGenerator(vf)); - generator.addGenerator(IRational.class, ratTestSet, new RandomRationalGenerator(vf)); - generator.addGenerator(IReal.class, realTestSet, new RandomRealGenerator(vf)); - } - - - protected void assertEqual(IValue l, IValue r) { - assertTrue("Expected " + l + " got " + r, l.isEqual(r)); - } - - protected void assertEqualNumber(INumber l, INumber r) { - assertTrue("Expected " + l + " got " + r, l.equal(r).getValue()); - } - - - protected void assertEqual(String message, IValue l, IValue r) { - assertTrue(message + ": Expected " + l + " got " + r, l.isEqual(r)); - } - - protected void assertEqualNumber(String message, INumber l, INumber r) { - assertTrue(message + ": Expected " + l + " got " + r, l.equal(r).getValue()); - } - /** - * Test that the difference between two reals is insignificant. - */ - protected void assertApprox(IReal l, IReal r) { - assertTrue("Expected ~" + l + " got " + r + " (diff magnitude " + ((IReal)l.subtract(r).abs()).scale() + ")", approxEqual(l, r)); - } - - protected void assertApprox(double l, double r) { - assertTrue("Expected ~" + l + " got " + r, approxEqual(l, r)); - } - - protected void assertApprox(String message, IReal l, IReal r) { - assertTrue(message + ": Expected ~" + l + " got " + r + " (diff magnitude " + ((IReal)l.subtract(r).abs()).scale() + ")", approxEqual(l, r)); - } - - protected void assertApprox(String message, double l, double r) { - assertTrue(message + ": Expected ~" + l + " got " + r, approxEqual(l, r)); - } -/** - * @return true if the two arguments are approximately equal - */ - protected boolean approxEqual(IReal l, IReal r) { - if(l.equals(r)) - return true; // really equal - IReal max = (IReal) l.abs(); - if(((IReal)r.abs()).greater(max).getValue()) - max = (IReal) r.abs(); - - IReal diff = (IReal) l.subtract(r).abs(); - if(diff.less(EPSILON).getValue()) - return true; // absolute difference is very small - - IReal relativeDiff = diff.divide(max, PRECISION); - - if(!relativeDiff.less(MAX_ERROR_RATIO).getValue()) - System.out.println(""); - - // otherwise test relative difference - return relativeDiff.less(MAX_ERROR_RATIO).getValue(); - } - - /** - * @return true if the two arguments are approximately equal - */ - protected boolean approxEqual(double l, double r) { - if(l == r) - return true; // really equal - double max = Math.abs(l); - if(Math.abs(r) > max) - max = Math.abs(r); - - double diff = Math.abs(l - r); - if(diff < DOUBLE_EPSILON) - return true; // absolute difference is very small - - double relativeDiff = diff / max; - - // otherwise test relative difference - return relativeDiff < DOUBLE_MAX_ERROR_RATIO; - } - - protected void assertEqual(Type l, Type r) { - assertTrue("Expected " + l + " got " + r, l.equivalent(r)); - } - - public void testIO() throws IOException { - if(noisy) - System.out.println("Test I/O: " + "(" + getClass().getPackage().getName() + ")"); - - ioHelperBin("PBF", new BinaryValueReader(), new BinaryValueWriter()); - ioHelperText("Text", new StandardTextReader(), new StandardTextWriter()); - } - - private void ioHelperText(String io, IValueTextReader reader, IValueTextWriter writer) throws IOException { - ioHelperText2(io + " Integers", reader, writer, new DataGenerator(generator, INumber.class, intTestSet, new RandomIntegerGenerator(vf))); - ioHelperText2(io + " Rationals", reader, writer, new DataGenerator(generator, INumber.class, ratTestSet, new RandomRationalGenerator(vf))); - ioHelperText2(io + " Reals", reader, writer, new DataGenerator(generator, INumber.class, realTestSet, new RandomRealGenerator(vf))); - } - - private void ioHelperBin(String io, IValueBinaryReader reader, IValueBinaryWriter writer) throws IOException { - ioHelperBin2(io + " Integers", reader, writer, new DataGenerator(generator, INumber.class, intTestSet, new RandomIntegerGenerator(vf))); - ioHelperBin2(io + " Rationals", reader, writer, new DataGenerator(generator, INumber.class, ratTestSet, new RandomRationalGenerator(vf))); - ioHelperBin2(io + " Reals", reader, writer, new DataGenerator(generator, INumber.class, realTestSet, new RandomRealGenerator(vf))); - } - - - private void ioHelperText2(String typeName, IValueTextReader reader, IValueTextWriter writer, DataGenerator g) throws IOException { - if(noisy) - System.out.printf(" %-16s ", typeName + ":"); - int count = 0; - for(INumber n : g.generate(INumber.class, N*10)) { - ioHelperText3(reader, writer, n); - count++; - } - if(noisy) - System.out.println("" + count + " values"); - } - - private void ioHelperBin2(String typeName, IValueBinaryReader reader, IValueBinaryWriter writer, DataGenerator g) throws IOException { - if(noisy) - System.out.printf(" %-16s ", typeName + ":"); - int count = 0; - for(INumber n : g.generate(INumber.class, N*10)) { - ioHelperBin3(reader, writer, n); - count++; - } - if(noisy) - System.out.println("" + count + " values"); - } - - - private void ioHelperText3(IValueTextReader reader, IValueTextWriter writer, INumber n) - throws IOException, AssertionFailedError { - StringWriter output = new StringWriter(); - writer.write(n, output); - output.close(); - StringReader input = new StringReader(output.toString()); - IValue v = reader.read(vf, input); - assertEqual(n, v); - } - - private void ioHelperBin3(IValueBinaryReader reader, IValueBinaryWriter writer, INumber n) - throws IOException, AssertionFailedError { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - writer.write(n, output); - output.close(); - ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); - IValue v = reader.read(vf, input); - assertEqual(n, v); - } - /** - * Run all axioms in the current class, i.e. all *public* methos - * with names starting with "axiom". - * - * Constructs argument lists using the data generator, and calls - * the axioms using reflection. - * - * @throws Throwable - */ - public void testAxioms() throws Throwable { - if(noisy) - System.out.println("Test Axioms: " + "(" + getClass().getPackage().getName() + ")"); - Method[] methods = getClass().getMethods(); - long millis = System.currentTimeMillis(); - for(Method m : methods) { - if(m.getName().startsWith("axiom")) { - Class[] params = m.getParameterTypes(); - // if at least one argument is an INumber, we want to - // test the axiom for all numeric types - if(hasINumber(params)) { - if(noisy) - System.out.print(m.getName() + "\n Integers: "); - callAxiom(m, params, new Object[params.length], 0, - new DataGenerator(generator, INumber.class, intTestSet, new RandomIntegerGenerator(vf))); - if(noisy) - System.out.print(" " + count + " calls\n" + m.getName() + "\n Rationals: "); - callAxiom(m, params, new Object[params.length], 0, - new DataGenerator(generator, INumber.class, ratTestSet, new RandomRationalGenerator(vf))); - if(noisy) - System.out.print(" " + count + " calls\n" + m.getName() + "\n Reals: "); - callAxiom(m, params, new Object[params.length], 0, - new DataGenerator(generator, INumber.class, realTestSet, new RandomRealGenerator(vf))); - if(noisy) - System.out.print(" " + count + " calls\n" + m.getName() + "\n Mixed: "); - callAxiom(m, params, new Object[params.length], 0, - new DataGenerator(generator, INumber.class, mixedTestSet, new RandomNumberGenerator(vf))); - } - else { - if(noisy) System.out.print(m.getName() + "\n : "); - callAxiom(m, params, new Object[params.length], 0, generator); - } - if(noisy) - System.out.println(" " + count + " calls"); - } - } - System.out.println("Axiom tests done in " + (System.currentTimeMillis()-millis) + " ms " - + "(" + getClass().getPackage().getName() + ")"); - } - - private boolean hasINumber(Class[] params) { - for(Class p : params) { - if(p.isAssignableFrom(INumber.class)) { - return true; - } - } - return false; - } - - /** - * Keeps track of the number of times an axiom has been called. - */ - private int count = 0; - - /** - * @param m The axiom method - * @param params The list of parameter types - * @param args The argument list we've built so far - * @param k The number of arguments we've added so far - * @param g The data generator - * @throws Throwable if anything went wrong - */ - private void callAxiom(Method m, Class[] params, Object[] args, int k, DataGenerator g) - throws Throwable { - if(k == 0) - count = 0; - if(params.length == k) { // we have a complete argument list - try { - - m.invoke(this, args); - } - catch(InvocationTargetException e) { - if (noisy) { - System.err.println("FAIL: " + m.getName() + "(" + Arrays.toString(args) + ")"); - } - - if(e.getCause() != null) - throw e.getCause(); - else - throw e; - } - count ++; - if(noisy) - if(count % 1000 == 0) System.out.print("."); - if(noisy) - if(count % 80000 == 0) System.out.print("\n "); - } - else { - // try with all possible values from the data generator for - // this argument - for(Object t : g.generate(params[k], numberOfValuesFor(params.length))) { - args[k] = t; - callAxiom(m, params, args, k+1, g); - } - } - } - - /** - * Restrict the number of random values for long argument lists, - * or we'll end up with billions of calls. - * - * @return the number of random values we should generate for an argument - * list of the given length. - */ - private int numberOfValuesFor(int length) { - if(length >= 3) - return N/70; - else if(length == 2) - return N/10; - else - return N*10; - } - - - /** - * Relationship between compare() and the comparison functions, - * and between the various comparisons. - */ - public void axiomCompare(INumber a, INumber b) { - int cmp = a.compare(b); - assertEquals(cmp == 0, b.compare(a) == 0); // negating and comparing directly isn't safe - assertEquals(cmp < 0, b.compare(a) > 0); - assertEquals(cmp > 0, b.compare(a) < 0); - assertEquals(cmp < 0, a.less(b).getValue()); - assertEquals(cmp > 0, a.greater(b).getValue()); - assertEquals(cmp == 0, a.equal(b).getValue()); - assertEquals(cmp <= 0, a.less(b).getValue() || a.equal(b).getValue()); - assertEquals(cmp >= 0, a.greater(b).getValue() || a.equal(b).getValue()); - - assertEquals(a.less(b), b.greater(a)); - assertEquals(a.greaterEqual(b), b.lessEqual(a)); - assertEquals(a.lessEqual(b).getValue(), a.less(b).getValue() || a.equal(b).getValue()); - assertEquals(a.greaterEqual(b).getValue(), a.greater(b).getValue() || a.equal(b).getValue()); - - assertEquals(a.less(b).getValue() || a.greater(b).getValue(), !a.equal(b).getValue()); - assertEquals(a.equal(b).getValue(), b.equal(a).getValue()); - assertTrue(a.equal(a).getValue()); - - if(a.equals(b) && a.getType() == b.getType()) { - assertEquals("" + a + ".hashCode() != " + b + ".hashCode()", a.hashCode(), b.hashCode()); - - if(!(a instanceof IReal || b instanceof IReal) && a.getType().equivalent(b.getType())) { - assertEquals("" + a + ".toString() != " + b + ".toString()", a.toString(), b.toString()); - } - } - - if(a.getType().equivalent(b.getType())) { - INumber c = b.abs(); - // add/subtract a non-negative number gives a greater/smaller or equal result - assertTrue("" + a + " + " + c + " >= " + a, a.add(c).greaterEqual(a).getValue()); - assertTrue("" + a + " + -" + c + " >= " + a, a.add(c.negate()).lessEqual(a).getValue()); - } - } - - /** - * Closure: These operations should yield a result of the same type. - */ - public void axiomClosure(INumber a, INumber b) { - if(a.signum() == 0 && b.signum() == 0) - a.signum(); - if(a.getType().equivalent(b.getType())) { - assertEqual(a.getType(), a.add(b).getType()); - assertEqual(a.getType(), a.multiply(b).getType()); - assertEqual(a.getType(), a.subtract(b).getType()); - assertEqual(a.getType(), a.abs().getType()); - assertEqual(a.getType(), a.negate().getType()); - } - } - - /** - * Associativity: addition and multiplication - * - * (Possibly not strictly true for reals.) - */ - public void axiomAssociativity(INumber a, INumber b, INumber c) { - if(!(a instanceof IReal || b instanceof IReal || c instanceof IReal)) { - assertEqualNumber(a.add(b.add(c)), a.add(b).add(c)); - assertEqualNumber(a.multiply(b.multiply(c)), a.multiply(b).multiply(c)); - } - } - - - /** - * Commutativity: addition and multiplication - */ - public void axiomCommutativity(INumber a, INumber b) { - assertEqualNumber(a.toString() + " + " + b.toString(), a.add(b), b.add(a)); - assertEqualNumber(a.toString() + " * " + b.toString(), a.multiply(b), b.multiply(a)); - } - - - /** - * 0 or 1 are identities for all the binary ops - */ - public void axiomIdentity(INumber a) { - assertEqualNumber(a, a.add(INT_ZERO)); - assertEqualNumber(a, a.multiply(INT_ONE)); - assertEqualNumber(a, a.subtract(INT_ZERO)); - if(a instanceof IInteger) - assertEqualNumber(a, ((IInteger)a).divide(INT_ONE)); - if(a instanceof IRational) - assertEqualNumber(a, ((IRational)a).divide(RAT_ONE)); - if(a instanceof IReal) - assertEqualNumber(a, ((IReal)a).divide(REAL_ONE, ((IReal)a).precision())); - } - - /** - * Subtraction is inverse of addition. - * Division is inverse of non-integer multiplication. - */ - public void axiomInverse(INumber a) { - if(a instanceof IInteger) { - IInteger i = (IInteger)a; - assertEqualNumber(INT_ZERO, i.add(i.negate())); - assertEqualNumber(INT_ZERO, i.subtract(i)); - if(i.signum() != 0) { - assertEqualNumber(INT_ONE, i.divide(i)); - } - } - if(a instanceof IRational) { - IRational r = (IRational)a; - assertEqualNumber(RAT_ZERO, r.add(r.negate())); - assertEqualNumber(RAT_ZERO, r.subtract(r)); - if(r.signum() != 0) { - assertEqualNumber(RAT_ONE, r.divide(r)); - assertEqualNumber(RAT_ONE, r.multiply(RAT_ONE.divide(r))); - } - } - if(a instanceof IReal) { - IReal r = (IReal)a; - // this should hold: - assertEqualNumber(REAL_ZERO, r.add(r.negate())); - // this one only approximately - try { - assertApprox(REAL_ONE, r.divide(r, 80)); - assertApprox(REAL_ONE, r.multiply(REAL_ONE.divide(r, 80))); - } - catch(ArithmeticException e) { - // ignore division by zero - } - } - } - - - /** - * Multiplication distributes over addition. - * - * (Possibly not strictly true for reals.) - */ - public void axiomDistributivity(INumber a, INumber b, INumber c) { - if(!(a instanceof IReal || b instanceof IReal || c instanceof IReal)) { - assertEqualNumber(String.format("a=%s, b=%s, c=%s", a.toString(), b.toString(), c.toString()), - a.multiply(b.add(c)), a.multiply(b).add(a.multiply(c))); - } - else { - //assertApprox(String.format("a=%s, b=%s, c=%s", a.toString(), b.toString(), c.toString()), - // a.multiply(b.add(c)).toReal(), a.multiply(b).add(a.multiply(c)).toReal()); - } - } - - - /** - * This may not be strictly true for reals. - */ - public void axiomTransitivity(INumber a, INumber b, INumber c) { - if(a.equal(b).getValue() && b.equal(c).getValue()) - assertTrue("" + a + " == " + b + " == " + c, a.equal(c).getValue()); - if(a.lessEqual(b).getValue() && b.lessEqual(c).getValue()) - assertTrue("" + a + " <= " + b + " <= " + c, - a.lessEqual(c).getValue()); - } - - public void axiomNoEqualInt(IInteger i) { - assertFalse(i.toReal(PRECISION).equals(i)); - assertTrue(i.toReal(PRECISION).equal(i).getValue()); - assertFalse(i.toRational().equals(i)); - assertTrue(i.toRational().equal(i).getValue()); - } - - public void axiomNoEqualRat(IRational i) { - assertFalse(i.toReal(PRECISION).equals(i)); - assertTrue(i.toReal(PRECISION).equal(i).getValue()); - assertFalse(i.toInteger().equals(i)); - } - - public void axiomNoEqualReal(IReal i) { - assertFalse(i.toInteger().equals(i)); - } - - /** - * Check that behavour of add/subtract/multiply/divide of integers is - * approximately the same as for reals - **/ - public void axiomRationalBehavior(IRational a, IRational b) { - assertEqualNumber(a, a.add(b).subtract(b)); - assertEqualNumber(a, a.subtract(b).add(b)); - if(b.signum() != 0) { - assertEqualNumber(a, a.divide(b).multiply(b)); - assertEqualNumber(a, a.multiply(b).divide(b)); - } - assertEqualNumber(a, a.negate().negate()); - assertEqualNumber(a, a.abs().multiply(vf.integer(a.signum()))); - assertEqualNumber(a, a.numerator().toRational().divide(a.denominator().toRational())); - - assertApprox(a.doubleValue() + b.doubleValue(), a.add(b).doubleValue()); - assertApprox(a.doubleValue() - b.doubleValue(), a.subtract(b).doubleValue()); - assertApprox(a.doubleValue() * b.doubleValue(), a.multiply(b).doubleValue()); - try { - assertApprox(a.doubleValue() / b.doubleValue(), a.divide(b).doubleValue()); - } - catch(ArithmeticException e) { - } - } - - /** - * Check various behaviour + - * Check that behavour of add/subtract/multiply of rationals is - * the same as that for reals and rationals. - **/ - public void axiomIntegerBehavior(IInteger a, IInteger b) { - assertEqualNumber(a, a.add(b).subtract(b)); - assertEqualNumber(a, a.subtract(b).add(b)); - if(b.signum() != 0) { - assertEqualNumber(a, a.divide(b).multiply(b).add(a.remainder(b))); - assertEqualNumber(a, a.multiply(b).divide(b)); - } - assertEqualNumber(a, a.negate().negate()); - assertEqualNumber(a, a.abs().multiply(vf.integer(a.signum()))); - if(b.signum() != 0) - assertTrue(a.mod(b.abs()).less(b.abs()).getValue()); - - // check vs. rational - assertEqualNumber(a.toRational().add(b.toRational()).toInteger(), a.add(b)); - assertEqualNumber(a.toRational().subtract(b.toRational()).toInteger(), a.subtract(b)); - assertEqualNumber(a.toRational().multiply(b.toRational()).toInteger(), a.multiply(b)); - } - - public void axiomRealBehavior(IReal a, IReal b) { - assertApprox(a, a.add(b).subtract(b)); - assertApprox(a, a.subtract(b).add(b)); - try { - assertApprox(a, a.divide(b, PRECISION).multiply(b)); - assertApprox(a, a.multiply(b).divide(b, PRECISION)); - } - catch(ArithmeticException e) { - } - assertEqualNumber(a, a.negate().negate()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/BaseTestRelation.java b/value-core/src/test/java/org/rascalmpl/value/BaseTestRelation.java deleted file mode 100644 index 7301e9083..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/BaseTestRelation.java +++ /dev/null @@ -1,557 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value; - -import java.util.Iterator; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; - -import junit.framework.TestCase; - -public abstract class BaseTestRelation extends TestCase { - private IValueFactory vf; - private TypeFactory tf; - private IValue[] integers; - private ITuple[] integerTuples; - private ISet setOfIntegers; - private ISet integerRelation; - private IValue[] doubles; - private ISet setOfDoubles; - private ISet doubleRelation; - private ITuple[] doubleTuples; - - protected void setUp(IValueFactory factory) throws Exception { - super.setUp(); - vf = factory; - tf = TypeFactory.getInstance(); - - integers = new IValue[5]; - ISetWriter sw = vf.setWriter(tf.integerType()); - - for (int i = 0; i < integers.length; i++) { - IValue iv = vf.integer(i); - integers[i] = iv; - sw.insert(iv); - } - setOfIntegers = sw.done(); - - doubles = new IValue[10]; - ISetWriter sw2 = vf.setWriter(tf.realType()); - - for (int i = 0; i < doubles.length; i++) { - IValue iv = vf.real(i); - doubles[i] = iv; - sw2.insert(iv); - } - setOfDoubles = sw2.done(); - - ISetWriter rw = vf.setWriter(tf.tupleType(tf.integerType(), tf.integerType())); - integerTuples = new ITuple[integers.length * integers.length]; - - for (int i = 0; i < integers.length; i++) { - for (int j = 0; j < integers.length; j++) { - ITuple t = vf.tuple(integers[i], integers[j]); - integerTuples[i * integers.length + j] = t; - rw.insert(t); - } - } - integerRelation = rw.done(); - - ISetWriter rw2 = vf.setWriter(tf.tupleType(tf.realType(), tf.realType())); - doubleTuples = new ITuple[doubles.length * doubles.length]; - - for (int i = 0; i < doubles.length; i++) { - for (int j = 0; j < doubles.length; j++) { - ITuple t = vf.tuple(doubles[i], doubles[j]); - doubleTuples[i * doubles.length + j] = t; - rw2.insert(t); - } - } - doubleRelation = rw2.done(); - } - - public void testIsEmpty() { - if (integerRelation.isEmpty()) { - fail("integerRelation is not empty"); - } - - if (!vf.set(tf.tupleType(tf.integerType())).isEmpty()) { - fail("this relation should be empty"); - } - - ISet emptyRel = vf.set(); - if (!emptyRel.isEmpty()) { - fail("empty relation is not empty?"); - } - if (!emptyRel.getType().isRelation()) { - fail("empty relation should have relation type"); - } - - - } - - public void testSize() { - if (integerRelation.size() != integerTuples.length) { - fail("relation size is not correct"); - } - } - - public void testArity() { - if (integerRelation.asRelation().arity() != 2) { - fail("arity should be 2"); - } - } - - public void testProductIRelation() { - ISet prod = integerRelation.product(integerRelation); - - if (prod.asRelation().arity() != 2 ) { - fail("arity of product should be 2"); - } - - if (prod.size() != integerRelation.size() * integerRelation.size()) { - fail("size of product should be square of size of integerRelation"); - } - } - - public void testProductISet() { - ISet prod = integerRelation.product(setOfIntegers); - - if (prod.asRelation().arity() != 2) { - fail("arity of product should be 2"); - } - - if (prod.size() != integerRelation.size() * setOfIntegers.size()) { - fail("size of product should be square of size of integerRelation"); - } - } - - public void testClosure() { - try { - if (!integerRelation.asRelation().closure().isEqual(integerRelation)) { - fail("closure adds extra tuples?"); - } - } catch (FactTypeUseException e) { - fail("integerRelation is reflexive, so why an error?"); - } - - try { - ISet rel = vf.set(tf.tupleType(tf.integerType(), tf.integerType())); - rel.asRelation().closure(); - } - catch (FactTypeUseException e) { - fail("reflexivity with subtyping is allowed"); - } - - - - try { - ITuple t1 = vf.tuple(integers[0], integers[1]); - ITuple t2 = vf.tuple(integers[1], integers[2]); - ITuple t3 = vf.tuple(integers[2], integers[3]); - ITuple t4 = vf.tuple(integers[0], integers[2]); - ITuple t5 = vf.tuple(integers[1], integers[3]); - ITuple t6 = vf.tuple(integers[0], integers[3]); - - ISet test = vf.set(t1, t2, t3); - ISet closed = test.asRelation().closure(); - - if (closed.asRelation().arity() != test.asRelation().arity()) { - fail("closure should produce relations of same arity"); - } - - if (closed.size() != 6) { - fail("closure contains too few elements"); - } - - if (!closed.intersect(test).isEqual(test)) { - fail("closure should contain all original elements"); - } - - if (!closed.contains(t4) || !closed.contains(t5) || !closed.contains(t6)) { - fail("closure does not contain required elements"); - } - - } catch (FactTypeUseException e) { - fail("this should all be type correct"); - } - } - - public void testCompose() { - try { - ISet comp = integerRelation.asRelation().compose(integerRelation.asRelation()); - - if (comp.asRelation().arity() != integerRelation.asRelation().arity() * 2 - 2) { - fail("composition is a product with the last column of the first relation and the first column of the last relation removed"); - } - - if (comp.size() != integerRelation.size()) { - fail("numner of expected tuples is off"); - } - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - - try { - ITuple t1 = vf.tuple(integers[0], doubles[0]); - ITuple t2 = vf.tuple(integers[1], doubles[1]); - ITuple t3 = vf.tuple(integers[2], doubles[2]); - ISet rel1 = vf.set(t1, t2, t3); - - ITuple t4 = vf.tuple(doubles[0], integers[0]); - ITuple t5 = vf.tuple(doubles[1], integers[1]); - ITuple t6 = vf.tuple(doubles[2], integers[2]); - ISet rel2 = vf.set(t4, t5, t6); - - ITuple t7 = vf.tuple(integers[0], integers[0]); - ITuple t8 = vf.tuple(integers[1], integers[1]); - ITuple t9 = vf.tuple(integers[2], integers[2]); - ISet rel3 = vf.set(t7, t8, t9); - assertTrue( - "Non-comparable types should yield empty composition result.", - vf.set(vf.tuple(doubles[0], doubles[0])).asRelation() - .compose(rel1.asRelation()).isEmpty()); - ISet comp = rel1.asRelation().compose(rel2.asRelation()); - - if (!comp.isEqual(rel3)) { - fail("composition does not produce expected result"); - } - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - } - - public void testContains() { - try { - for (ITuple t : integerTuples) { - if (!integerRelation.contains(t)) { - fail("contains returns false instead of true"); - } - } - } catch (FactTypeUseException e) { - fail("this should be type correct"); - } - } - - public void testInsert() { - try { - ISet rel = integerRelation.insert(vf.tuple(vf.integer(0),vf.integer(0))); - - if (!rel.isEqual(integerRelation)) { - fail("insert into a relation of an existing tuple should not change the relation"); - } - - ISetWriter relw3 = vf.setWriter(tf.tupleType(tf.integerType(), tf.integerType())); - relw3.insertAll(integerRelation); - ISet rel3 = relw3.done(); - - final ITuple tuple = vf.tuple(vf.integer(100), vf.integer(100)); - ISet rel4 = rel3.insert(tuple); - - if (rel4.size() != integerRelation.size() + 1) { - fail("insert failed"); - } - - if (!rel4.contains(tuple)) { - fail("insert failed"); - } - - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - } - - public void testIntersectIRelation() { - - try { - if (!integerRelation.intersect(doubleRelation).isEmpty()) { - fail("non-intersecting relations should produce empty intersections"); - } - - ISet oneTwoThree = vf.set(integerTuples[0], - integerTuples[1], integerTuples[2]); - ISet threeFourFive = vf.set(integerTuples[2], - integerTuples[3], integerTuples[4]); - ISet result = vf.set(integerTuples[2]); - - if (!oneTwoThree.intersect(threeFourFive).isEqual(result)) { - fail("intersection failed"); - } - if (!threeFourFive.intersect(oneTwoThree).isEqual(result)) { - fail("intersection should be commutative"); - } - - if (!oneTwoThree.intersect(vf.set(tf.tupleType(tf.integerType(),tf.integerType()))).isEmpty()) { - fail("intersection with empty set should produce empty"); - } - - } catch (FactTypeUseException e) { - fail("the above should all be type safe"); - } - } - - public void testIntersectISet() { - ISet empty1 = vf.set(tf.tupleType(tf.integerType())); - ISet empty2 = vf.set(tf.tupleType(tf.realType())); - - try { - final ISet intersection = empty1.intersect(empty2); - if (!intersection.isEmpty()) { - fail("empty intersection failed"); - } - - Type type = intersection.getType(); - if (!type.getFieldType(0).isSubtypeOf(tf.numberType())) { - fail("intersection should produce lub types"); - } - } catch (FactTypeUseException e) { - fail("intersecting types which have a lub should be possible"); - } - - try { - if (!integerRelation.intersect(doubleRelation).isEmpty()) { - fail("non-intersecting relations should produce empty intersections"); - } - - ISet oneTwoThree = vf.set(integerTuples[0], - integerTuples[1], integerTuples[2]); - ISet threeFourFive = vf.set(integerTuples[2], - integerTuples[3], integerTuples[4]); - ISet result = vf.set(integerTuples[2]); - - if (!oneTwoThree.intersect(threeFourFive).isEqual(result)) { - fail("intersection failed"); - } - if (!threeFourFive.intersect(oneTwoThree).isEqual(result)) { - fail("intersection should be commutative"); - } - - if (!oneTwoThree.intersect(vf.set(tf.tupleType(tf.integerType(),tf.integerType()))).isEmpty()) { - fail("intersection with empty set should produce empty"); - } - - } catch (FactTypeUseException e) { - fail("the above should all be type safe"); - } - } - - - public void testSubtractIRelation() { - ISet empty1 = vf.set(tf.tupleType(tf.integerType())); - ISet empty2 = vf.set(tf.tupleType(tf.realType())); - - try { - final ISet diff = empty1.subtract(empty2); - if (!diff.isEmpty()) { - fail("empty diff failed"); - } - - } catch (FactTypeUseException e) { - fail("subtracting types which have a lub should be possible"); - } - - try { - ISet oneTwoThree = vf.set(integerTuples[0], - integerTuples[1], integerTuples[2]); - ISet threeFourFive = vf.set(integerTuples[2], - integerTuples[3], integerTuples[4]); - ISet result1 = vf.set(integerTuples[0],integerTuples[1]); - ISet result2 = vf.set(integerTuples[3],integerTuples[4]); - - if (!oneTwoThree.subtract(threeFourFive).isEqual(result1)) { - fail("subtraction failed"); - } - if (!threeFourFive.subtract(oneTwoThree).isEqual(result2)) { - fail("subtraction failed"); - } - - ISet empty3 = vf.set(tf.tupleType(tf.integerType(),tf.integerType())); - if (!empty3.subtract(threeFourFive).isEmpty()) { - fail("subtracting from empty set should produce empty"); - } - - } catch (FactTypeUseException e) { - fail("the above should all be type safe"); - } - } - - public void testSubtractISet() { - ISet empty1 = vf.set(tf.tupleType(tf.integerType())); - ISet empty2 = vf.set(tf.tupleType(tf.realType())); - - try { - final ISet diff = empty1.subtract(empty2); - if (!diff.isEmpty()) { - fail("empty diff failed"); - } - - } catch (FactTypeUseException e) { - fail("subtracting types which have a lub should be possible"); - } - - try { - ISet oneTwoThree = vf.set(integerTuples[0], - integerTuples[1], integerTuples[2]); - ISet threeFourFive = vf.set(integerTuples[2], - integerTuples[3], integerTuples[4]); - ISet result1 = vf.set(integerTuples[0],integerTuples[1]); - - if (!oneTwoThree.subtract(threeFourFive).isEqual(result1)) { - fail("subtraction failed"); - } - - ISet empty3 = vf.set(tf.tupleType(tf.integerType(),tf.integerType())); - if (!empty3.subtract(threeFourFive).isEmpty()) { - fail("subtracting from empty set should produce empty"); - } - - } catch (FactTypeUseException e) { - fail("the above should all be type safe"); - } - } - - public void testUnionIRelation() { - try { - if (integerRelation.union(doubleRelation).size() != integerRelation.size() + doubleRelation.size()) { - fail("non-intersecting non-intersectiopn relations should produce relation that is the sum of the sizes"); - } - - ISet oneTwoThree = vf.set(integerTuples[0], - integerTuples[1], integerTuples[2]); - ISet threeFourFive = vf.set(integerTuples[2], - integerTuples[3], integerTuples[4]); - ISet result = vf.set(integerTuples[0], - integerTuples[1], integerTuples[2], integerTuples[3], integerTuples[4]); - - if (!oneTwoThree.union(threeFourFive).isEqual(result)) { - fail("union failed"); - } - if (!threeFourFive.union(oneTwoThree).isEqual(result)) { - fail("union should be commutative"); - } - - if (!oneTwoThree.union(vf.set(tf.tupleType(tf.integerType(),tf.integerType()))).isEqual(oneTwoThree)) { - fail("union with empty set should produce same set"); - } - - } catch (FactTypeUseException e) { - fail("the above should all be type safe"); - } - } - - public void testEmptySetIsARelation() { - assertTrue(vf.set().getType().isRelation()); - assertTrue(vf.set(tf.integerType()).getType().isRelation()); - - ISet r = vf.set().insert(vf.tuple(vf.integer(1), vf.integer(2))); - r = r.subtract(r); - assertTrue(r.getType().isRelation()); - - ISet s = vf.set().insert(vf.integer(1)); - s = s.subtract(s); - assertTrue(s.getType().isRelation()); // yes really! - } - - public void testUnionISet() { - try { - if (integerRelation.union(doubleRelation).size() != integerRelation.size() + doubleRelation.size()) { - fail("non-intersecting non-intersectiopn relations should produce relation that is the sum of the sizes"); - } - - ISet oneTwoThree = vf.set(integerTuples[0], - integerTuples[1], integerTuples[2]); - ISet threeFourFive = vf.set(integerTuples[2], - integerTuples[3], integerTuples[4]); - ISet result = vf.set(integerTuples[0], - integerTuples[1], integerTuples[2], integerTuples[3], integerTuples[4]); - - if (!oneTwoThree.union(threeFourFive).isEqual(result)) { - fail("union failed"); - } - if (!threeFourFive.union(oneTwoThree).isEqual(result)) { - fail("union should be commutative"); - } - - if (!oneTwoThree.union(vf.set(tf.tupleType(tf.integerType(),tf.integerType()))).isEqual(oneTwoThree)) { - fail("union with empty set should produce same set"); - } - - } catch (FactTypeUseException e) { - fail("the above should all be type safe"); - } - } - - public void testIterator() { - try { - Iterator it = integerRelation.iterator(); - - int i; - for (i = 0; it.hasNext(); i++) { - ITuple t = (ITuple) it.next(); - - if (!integerRelation.contains(t)) { - fail("iterator produces strange elements?"); - } - } - - if (i != integerRelation.size()) { - fail("iterator skipped elements"); - } - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - } - - public void testCarrier() { - ISet carrier = integerRelation.asRelation().carrier(); - - if (!carrier.isEqual(setOfIntegers)) { - fail("carrier should be equal to this set"); - } - - try { - ITuple t1 = vf.tuple(integers[0], doubles[0]); - ITuple t2 = vf.tuple(integers[1], doubles[1]); - ITuple t3 = vf.tuple(integers[2], doubles[2]); - ISet rel1 = vf.set(t1, t2, t3); - - ISet carrier1 = rel1.asRelation().carrier(); - - if (carrier1.getElementType() != tf.numberType()) { - fail("expected number type on carrier"); - } - - if (carrier1.size() != 6) { - fail("carrier does not contain all elements"); - } - - if (carrier1.intersect(setOfIntegers).size() != 3) { - fail("integers should be in there still"); - } - - if (carrier1.intersect(setOfDoubles).size() != 3) { - fail("doubles should be in there still"); - } - } catch (FactTypeUseException e) { - fail("the above should be type correct"); - } - - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/BaseTestSet.java b/value-core/src/test/java/org/rascalmpl/value/BaseTestSet.java deleted file mode 100644 index 84a9e0554..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/BaseTestSet.java +++ /dev/null @@ -1,347 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value; - -import static org.rascalmpl.value.impl.fast.RelationalFunctionsOnSet.arity; - -import java.util.Iterator; - -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.type.TypeFactory; - -import junit.framework.TestCase; - -public abstract class BaseTestSet extends TestCase { - private IValueFactory vf; - private TypeFactory tf; - private IValue[] integers; - private IValue[] doubles; - private ISet integerUniverse; - - protected void setUp(IValueFactory factory) throws Exception { - super.setUp(); - this.vf = factory; - this.tf = TypeFactory.getInstance(); - - integers = new IValue[100]; - for (int i = 0; i < integers.length; i++) { - integers[i] = vf.integer(i); - } - - doubles = new IValue[100]; - for (int i = 0; i < doubles.length; i++) { - doubles[i] = vf.real(i); - } - - ISetWriter w = vf.setWriter(tf.integerType()); - - try { - for (IValue v : integers) { - w.insert(v); - } - - integerUniverse = w.done(); - } catch (FactTypeUseException e) { - fail("this should be type correct"); - } - } - - public void testInsert() { - ISet set1 = vf.set(tf.integerType()); - ISet set2; - - try { - set2 = set1.insert(integers[0]); - - if (set2.size() != 1) { - fail("insertion failed"); - } - - if (!set2.contains(integers[0])) { - fail("insertion failed"); - } - - } catch (FactTypeUseException e1) { - fail("type checking error:" + e1); - } - - ISetWriter numberSet = vf.setWriter(tf.valueType()); - - try { - numberSet.insert(integers[0]); - numberSet.insert(doubles[0]); - } catch (FactTypeUseException e) { - fail("should be able to insert subtypes:" + e); - } - } - - public void testEmpty() { - ISet emptySet = vf.set(); - if (!emptySet.isEmpty()) { - fail("empty set is not empty?"); - } - - if (!emptySet.getType().isRelation()) { - fail("empty set should have relation type (yes really!)"); - } - } - public void testContains() { - ISet set1 = vf.set(integers[0], integers[1]); - - try { - set1.contains(integers[0]); - } catch (FactTypeUseException e) { - fail("should be able to check for containment of integers"); - } - } - - public void testIntersect() { - ISet set1 = vf.set(tf.integerType()); - ISet set2 = vf.set(tf.integerType()); - ISet set3 = vf.set(integers[0], integers[1], integers[2]); - ISet set4 = vf.set(integers[2], integers[3], integers[4]); - ISet set5 = vf.set(integers[3], integers[4], integers[5]); - - try { - if (!set1.intersect(set2).isEmpty()) { - fail("intersect of empty sets"); - } - - if (!set1.intersect(set3).isEmpty()) { - fail("intersect with empty set"); - } - - if (!set3.intersect(set1).isEmpty()) { - fail("insersect with empty set"); - } - - if (set3.intersect(set4).size() != 1) { - fail("insersect failed"); - } - - if (!set4.intersect(set3).contains(integers[2])) { - fail("intersect failed"); - } - - if (set4.intersect(set5).size() != 2) { - fail("insersect failed"); - } - - if (!set5.intersect(set4).contains(integers[3]) - || !set5.intersect(set4).contains(integers[4])) { - fail("intersect failed"); - } - - if (!set5.intersect(set3).isEmpty()) { - fail("non-intersection sets"); - } - - } catch (FactTypeUseException et) { - fail("this shouls all be typesafe"); - } - } - - public void testIsEmpty() { - if (integerUniverse.isEmpty()) { - fail("an empty universe is not so cosy"); - } - - if (!vf.set(tf.integerType()).isEmpty()) { - fail("what's in an empty set?"); - } - } - - public void testSize() { - if (vf.set(tf.integerType()).size() != 0) { - fail("empty sets have size 0"); - } - - if (vf.set(integers[0]).size() != 1) { - fail("singleton set should have size 1"); - } - - if (integerUniverse.size() != integers.length) { - fail("weird size of universe"); - } - } - - public void testSubtract() { - ISet set1 = vf.set(tf.integerType()); - ISet set2 = vf.set(tf.integerType()); - ISet set3 = vf.set(integers[0], integers[1], integers[2]); - ISet set4 = vf.set(integers[2], integers[3], integers[4]); - ISet set5 = vf.set(integers[3], integers[4], integers[5]); - - try { - if (!set1.subtract(set2).isEmpty()) { - fail("subtract of empty sets"); - } - - if (!set1.subtract(set3).isEmpty()) { - fail("subtract with empty set"); - } - - if (!set3.subtract(set1).isEqual(set3)) { - fail("subtract with empty set"); - } - - if (!set1.subtract(set3).isEqual(set1)) { - fail("subtract with empty set"); - } - - if (set3.subtract(set4).size() != 2) { - fail("subtract failed"); - } - - if (set4.subtract(set3).contains(integers[2])) { - fail("subtract failed"); - } - - if (set4.subtract(set5).size() != 1) { - fail("insersect failed"); - } - - if (set5.subtract(set4).contains(integers[3]) - || set5.subtract(set4).contains(integers[4])) { - fail("subtract failed"); - } - - } catch (FactTypeUseException et) { - fail("this shouls all be typesafe"); - } - - } - - public void testUnion() { - ISet set1 = vf.set(tf.integerType()); - ISet set2 = vf.set(tf.integerType()); - ISet set3 = vf.set(integers[0], integers[1], integers[2]); - ISet set4 = vf.set(integers[2], integers[3], integers[4]); - ISet set5 = vf.set(integers[3], integers[4], integers[5]); - - try { - if (!set1.union(set2).isEmpty()) { - fail("union of empty sets"); - } - - if (!set1.union(set3).isEqual(set3)) { - fail("union with empty set"); - } - - if (!set3.union(set1).isEqual(set3)) { - fail("union with empty set"); - } - - if (!set1.union(set3).isEqual(set3)) { - fail("union with empty set"); - } - - if (set3.union(set4).size() != 5) { - fail("union failed"); - } - - if (!set4.union(set3).contains(integers[0]) - || !set4.union(set3).contains(integers[1]) - || !set4.union(set3).contains(integers[2]) - || !set4.union(set3).contains(integers[3]) - || !set4.union(set3).contains(integers[4]) - ) { - fail("union failed"); - } - - if (set4.union(set5).size() != 4) { - fail("union failed"); - } - - } catch (FactTypeUseException et) { - fail("this shouls all be typesafe"); - } - - - } - - public void testIterator() { - try { - Iterator it = integerUniverse.iterator(); - int i; - for (i = 0; it.hasNext(); i++) { - if (!integerUniverse.contains(it.next())) { - fail("iterator produces something weird"); - } - } - if (i != integerUniverse.size()) { - fail("iterator did not iterate over everything"); - } - } catch (FactTypeUseException e) { - fail("should be type correct"); - } - } - - public void testGetElementType() { - if (!integerUniverse.getElementType().isInteger()) { - fail("elementType is broken"); - } - } - - public void testProductISet() { - ISet test = vf.set(integers[0], integers[1], integers[2],integers[3]); - ISet prod = test.product(test); - - if (arity(prod) != 2) { - fail("product's arity should be 2"); - } - - if (prod.size() != test.size() * test.size()) { - fail("product's size should be square of size"); - } - - } - - public void testProductIRelation() { - ISet test = vf.set(integers[0], integers[1], integers[2],integers[3]); - ISet prod = test.product(test); - ISet prod2 = test.product(prod); - - if (arity(prod2) != 2) { - fail("product's arity should be 3"); - } - - if (prod2.size() != test.size() * prod.size()) { - fail("product's size should be multiplication of arguments' sizes"); - } - - } - - public void testTypeDoubleInsertOneRemoveWithSet() { - ISet set1 = vf.set().insert(doubles[0]).insert(integers[0]).insert(integers[0]); - ISet set2 = set1.delete(integers[0]); - - assertEquals(tf.realType(), set2.getElementType()); - } - - public void testTypeDoubleInsertOneRemoveWithSetWriter() { - ISetWriter w = vf.setWriter(); - w.insert(doubles[0]); - w.insert(integers[0]); - w.insert(integers[0]); - ISet set1 = w.done(); - ISet set2 = set1.delete(integers[0]); - - assertEquals(tf.realType(), set2.getElementType()); - } - -} diff --git a/value-core/src/test/java/org/rascalmpl/value/BaseTestValueFactory.java b/value-core/src/test/java/org/rascalmpl/value/BaseTestValueFactory.java deleted file mode 100644 index a8fea8c69..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/BaseTestValueFactory.java +++ /dev/null @@ -1,382 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value; - -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.net.MalformedURLException; - -import org.rascalmpl.value.IList; -import org.rascalmpl.value.IMap; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.ISet; -import org.rascalmpl.value.ISetWriter; -import org.rascalmpl.value.ITuple; -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.io.StandardTextReader; -import org.rascalmpl.value.io.StandardTextWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -import junit.framework.TestCase; - -public abstract class BaseTestValueFactory extends TestCase { - private IValueFactory ff; - private TypeFactory ft = TypeFactory.getInstance(); - private IValue[] integers; - - protected void setUp(IValueFactory factory) throws Exception { - ff = factory; - - integers = new IValue[100]; - for (int i = 0; i < integers.length; i++) { - integers[i] = ff.integer(i); - } - } - - public void testRelationNamedType() { - try { - Type type = ft.aliasType(new TypeStore(), "myType2", ft.relType(ft.integerType(), ft.integerType())); - ISet r = ff.set(type.getElementType()); - - if (!r.getType().isRelation()) { - fail("relation does not have a relation type"); - } - } catch (FactTypeUseException e) { - fail("type error on the construction of a valid relation: " + e); - } - } - - public void testRealZeroDotFromString() { - assertTrue(ff.real("0.").isEqual(ff.real("0"))); - } - - public void testZeroRealRepresentation() { - IReal real = ff.real("0"); - - assertTrue(real.toString().equals("0.")); - } - - - - public void testRelationTupleType() { - ISet r = ff.relation(ft.tupleType(ft.integerType())); - - if (r.size() != 0) { - fail("empty set is not empty"); - } - - if (!r.getType().isSubtypeOf(ft.relTypeFromTuple(ft.tupleType(ft.integerType())))) { - fail("should be a rel of unary int tuples"); - } - } - - public void testRelationWith() { - ISet[] relations = new ISet[7]; - ITuple[] tuples = new ITuple[7]; - - for (int i = 0; i < 7; i++) { - tuples[i] = ff.tuple(ff.integer(i), ff.real(i)); - } - - try { - relations[0] = ff.relation(tuples[0]); - relations[1] = ff.relation(tuples[0], tuples[1]); - relations[2] = ff.relation(tuples[0], tuples[1], tuples[2]); - relations[3] = ff.relation(tuples[0], tuples[1], tuples[2], - tuples[3]); - relations[4] = ff.relation(tuples[0], tuples[1], tuples[2], - tuples[3], tuples[4]); - relations[5] = ff.relation(tuples[0], tuples[1], tuples[2], - tuples[3], tuples[4], tuples[5]); - relations[6] = ff.relation(tuples[0], tuples[1], tuples[2], - tuples[3], tuples[4], tuples[5], tuples[6]); - - for (int i = 0; i < 7; i++) { - for (int j = 0; j < i; j++) { - if (!relations[i].contains(tuples[j])) { - fail("tuple creation is weird"); - } - } - } - } catch (FactTypeUseException e) { - System.err.println(e); - fail("this should all be type correct"); - } - } - - public void testSetNamedType() { - ISet l; - try { - TypeStore typeStore = new TypeStore(); - l = ff.set(ff.integer(1)); - - if (!l.getType().isSubtypeOf(ft.aliasType(typeStore, "mySet", ft.setType(ft.integerType())))) { - fail("named types should be aliases"); - } - - if (!l.getElementType().isSubtypeOf(ft.integerType())) { - fail("elements should be integers"); - } - - if (l.size() != 1) { - fail("??"); - } - } catch (FactTypeUseException e1) { - fail("this was a correct type"); - } - } - - public void testSetType() { - ISet s = ff.set(ft.realType()); - - if (s.size() != 0) { - fail("empty set is not empty"); - } - - if (!s.getType().isSubtypeOf(ft.setType(ft.realType()))) { - fail("should be a list of reals"); - } - - if (!s.getElementType().isSubtypeOf(ft.realType())) { - fail("should be a list of reals"); - } - } - - public void testSetWith() { - ISet[] sets = new ISet[7]; - - sets[0] = ff.set(integers[0]); - sets[1] = ff.set(integers[0],integers[1]); - sets[2] = ff.set(integers[0],integers[1],integers[2]); - sets[3] = ff.set(integers[0],integers[1],integers[2],integers[3]); - sets[4] = ff.set(integers[0],integers[1],integers[2],integers[3],integers[4]); - sets[5] = ff.set(integers[0],integers[1],integers[2],integers[3],integers[4],integers[5]); - sets[6] = ff.set(integers[0],integers[1],integers[2],integers[3],integers[4],integers[5],integers[6]); - - try { - for (int i = 0; i < 7; i++) { - for (int j = 0; j <= i; j++) { - if (!sets[i].contains(integers[j])) { - fail("set creation is weird"); - } - } - for (int j = 8; j < 100; j++) { - if (sets[i].contains(integers[j])) { - fail("set creation contains weird values"); - } - } - } - } catch (FactTypeUseException e) { - System.err.println(e); - fail("this should all be type correct"); - } - } - - public void testListNamedType() { - IList l; - try { - TypeStore ts = new TypeStore(); - l = ff.list(ff.integer(1)); - - if (!l.getType().isSubtypeOf(ft.aliasType(ts, "myList", ft.listType(ft - .integerType())))) { - fail("named types should be aliases"); - } - - if (!l.getElementType().isSubtypeOf(ft.integerType())) { - fail("elements should be integers"); - } - - if (l.length() != 1) { - fail("???"); - } - } catch (FactTypeUseException e1) { - fail("this was a correct type"); - } - } - - public void testListType() { - IList l = ff.list(ft.realType()); - - if (l.length() != 0) { - fail("empty list is not empty"); - } - - if (!l.getElementType().isSubtypeOf(ft.realType())) { - fail("should be a list of reals"); - } - } - - public void testListWith() { - IList[] lists = new IList[7]; - - lists[0] = ff.list(integers[0]); - lists[1] = ff.list(integers[0],integers[1]); - lists[2] = ff.list(integers[0],integers[1],integers[2]); - lists[3] = ff.list(integers[0],integers[1],integers[2],integers[3]); - lists[4] = ff.list(integers[0],integers[1],integers[2],integers[3],integers[4]); - lists[5] = ff.list(integers[0],integers[1],integers[2],integers[3],integers[4],integers[5]); - lists[6] = ff.list(integers[0],integers[1],integers[2],integers[3],integers[4],integers[5],integers[6]); - - for (int i = 0; i < 7; i++) { - for (int j = 0; j <= i; j++) { - if (lists[i].get(j) != integers[j]) { - fail("list creation is weird"); - } - } - } - - } - - public void testTupleIValue() { - ITuple[] tuples = new ITuple[7]; - - tuples[0] = ff.tuple(integers[0]); - tuples[1] = ff.tuple(integers[0],integers[1]); - tuples[2] = ff.tuple(integers[0],integers[1],integers[2]); - tuples[3] = ff.tuple(integers[0],integers[1],integers[2],integers[3]); - tuples[4] = ff.tuple(integers[0],integers[1],integers[2],integers[3],integers[4]); - tuples[5] = ff.tuple(integers[0],integers[1],integers[2],integers[3],integers[4],integers[5]); - tuples[6] = ff.tuple(integers[0],integers[1],integers[2],integers[3],integers[4],integers[5],integers[6]); - - for (int i = 0; i < 7; i++) { - for (int j = 0; j <= i; j++) { - if (tuples[i].get(j) != integers[j]) { - fail("tuple creation is weird"); - } - } - } - } - - public void testInteger() { - assertTrue(ff.integer(42).toString().equals("42")); - } - - public void testDubble() { - assertTrue(ff.real(84.5).toString().equals("84.5")); - } - - public void testString() { - assertTrue(ff.string("hello").getValue().equals("hello")); - assertTrue(ff.string(0x1F35D).getValue().equals("🍝")); - assertTrue(ff.string(new int[] {0x1F35D,0x1F35D}).getValue().equals("🍝🍝")); - } - -// public void testSourceLocation() { -// ISourceLocation sl; -// try { -// sl = ff.sourceLocation(new URL("file:///dev/null"), 1, 2, 3, 4, 5, 6); -// if (!sl.getURL().getPath().equals("/dev/null")) { -// fail("source location creation is weird"); -// } -// -// if (sl.getStartOffset() != 1 || sl.getLength() != 2 -// || sl.getStartColumn() != 5 || sl.getStartLine() != 3 -// || sl.getEndLine() != 4 || sl.getEndColumn() != 6) { -// fail("source range creation is weird"); -// } -// } catch (MalformedURLException e) { -// fail(); -// } -// -// } - - public void testToString() { - // first we create a lot of values, and - // then we check whether toString does the same - // as StandardTextWriter - ISetWriter extended; - try { - extended = createSomeValues(); - - StandardTextWriter w = new StandardTextWriter(); - - for (IValue o : extended.done()) { - StringWriter out = new StringWriter(); - try { - w.write(o, out); - if(!out.toString().equals(o.toString())) { - fail(out.toString() + " != " + o.toString()); - } - } catch (IOException e) { - fail(e.toString()); - e.printStackTrace(); - } - } - - } catch (FactTypeUseException | MalformedURLException e1) { - fail(e1.toString()); - } - } - - public void testStandardReaderWriter() { - StandardTextWriter w = new StandardTextWriter(); - StandardTextReader r = new StandardTextReader(); - - try { - for (IValue o : createSomeValues().done()) { - StringWriter out = new StringWriter(); - w.write(o, out); - StringReader in = new StringReader(out.toString()); - IValue read = r.read(ff, in); - if (!o.isEqual(read)) { - fail(o + " != " + read); - } - } - } catch (IOException e) { - fail(); - } - } - - private ISetWriter createSomeValues() throws FactTypeUseException, MalformedURLException { - ISetWriter basicW = ff.setWriter(ft.valueType()); - - // TODO add tests for locations and constructors again - basicW.insert(ff.integer(0), - ff.real(0.0), -// ff.sourceLocation(new URL("file:///dev/null"), 0, 0, 0, 0, 0, 0), - ff.bool(true), - ff.bool(false), - ff.node("hello")); - - ISet basic = basicW.done(); - ISetWriter extended = ff.setWriter(ft.valueType()); - -// TypeStore ts = new TypeStore(); -// Type adt = ft.abstractDataType(ts, "E"); -// Type cons0 = ft.constructor(ts, adt, "cons"); -// Type cons1 = ft.constructor(ts, adt, "cons", ft.valueType(), "value"); - - extended.insertAll(basic); - for (IValue w : basic) { - extended.insert(ff.list()); - extended.insert(ff.list(w)); - extended.insert(ff.set()); - extended.insert(ff.set(w)); - IMap map = ff.map(w.getType(), w.getType()); - extended.insert(map.put(w,w)); - ITuple tuple = ff.tuple(w,w); - extended.insert(tuple); - extended.insert(ff.relation(tuple, tuple)); - extended.insert(ff.node("hi", w)); -// extended.insert(ff.constructor(cons0)); -// extended.insert(ff.constructor(cons1, w)); - } - return extended; - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/TestBigDecimalCalculations.java b/value-core/src/test/java/org/rascalmpl/value/TestBigDecimalCalculations.java deleted file mode 100644 index 24ef8b823..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/TestBigDecimalCalculations.java +++ /dev/null @@ -1,189 +0,0 @@ -package org.rascalmpl.value; - -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -import org.rascalmpl.value.IInteger; -import org.rascalmpl.value.INumber; -import org.rascalmpl.value.IReal; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.reference.ValueFactory; - -import junit.framework.TestCase; - -public class TestBigDecimalCalculations extends TestCase { - - private static IValueFactory vf = ValueFactory.getInstance(); - - private static void assertClose(INumber param, IReal actual, double expected) { - assertClose(param, actual, expected, 6); - } - - private static void assertClose(INumber param, IReal actual, double expected, int significantDigits) { - long order = 0; - - if (Math.abs(expected) > 0.00001) { - order = Math.round(Math.floor(Math.log10(Math.abs(expected)))); - } - - double maxError = Math.pow(10, order - significantDigits); - - assertTrue("failed for "+param+" real:" + actual + " double: " + expected, - Math.abs(actual.doubleValue() - expected) < maxError); - } - - public void testSinComparableToFloatingPoint() { - IReal start = vf.real(-100); - IReal stop = start.negate(); - IReal increments = vf.real("0.1"); - for (IReal param = start; !stop.less(param).getValue(); param = param.add(increments)) { - assertClose(param, param.sin(vf.getPrecision()), Math.sin(param.doubleValue())); - } - } - - public void testCosComparableToFloatingPoint() { - IReal start = vf.real(-100); - IReal stop = start.negate(); - IReal increments = vf.real("0.1"); - for (IReal param = start; !stop.less(param).getValue(); param = param.add(increments)) { - assertClose(param, param.cos(vf.getPrecision()), Math.cos(param.doubleValue())); - } - } - - public void testTanComparableToFloatingPoint() { - IReal start = vf.pi(vf.getPrecision()).divide(vf.real(2.0), vf.getPrecision()).negate(); - IReal stop = start.negate(); - IReal increments = vf.real("0.01"); - - // around pi/2 tan is undefined so we skip checking around that. - start = start.add(increments); - stop = stop.subtract(increments); - for (IReal param = start; !stop.less(param).getValue() ; param = param.add(increments)) { - assertClose(param, param.tan(vf.getPrecision()), Math.tan(param.doubleValue())); - } - } - - private static double log2(double x) { - return Math.log(x)/Math.log(2); - } - - public void testLog2ComparableToFloatingPoint() { - IReal start = vf.real(0); - IReal stop = vf.real(100); - IReal increments = vf.real("0.1"); - start = start.add(increments); - for (IReal param = start; !stop.less(param).getValue(); param = param.add(increments)) { - assertClose(param, param.log(vf.integer(2), vf.getPrecision()), log2(param.doubleValue())); - } - } - public void testLog10ComparableToFloatingPoint() { - IReal start = vf.real(0); - IReal stop = vf.real(100); - IReal increments = vf.real("0.1"); - start = start.add(increments); - for (IReal param = start; !stop.less(param).getValue(); param = param.add(increments)) { - assertClose(param, param.log(vf.integer(10), vf.getPrecision()), Math.log10(param.doubleValue())); - } - } - - public void testLnComparableToFloatingPoint() { - IReal start = vf.real(0); - IReal stop = vf.real(100); - IReal increments = vf.real("0.1"); - start = start.add(increments); - for (IReal param = start; !stop.less(param).getValue(); param = param.add(increments)) { - assertClose(param, param.ln(vf.getPrecision()), Math.log(param.doubleValue())); - } - } - - public void testPowAllNumbers() { - IReal start = vf.real(-10); - IReal stop = start.negate(); - IReal increments = vf.real("0.1"); - IReal x = vf.pi(10); - - for (IReal param = start; !stop.less(param).getValue(); param = param.add(increments)) { - assertClose(param, x.pow(param, vf.getPrecision()), Math.pow(x.doubleValue(), param.doubleValue())); - } - } - - public void testPowNaturalNumbers() { - IInteger start = vf.integer(-10); - IInteger stop = start.negate(); - IInteger increments = vf.integer(1); - IReal x = vf.pi(10); - - for (IInteger param = start; !stop.less(param).getValue(); param = param.add(increments)) { - assertClose(param, x.pow(param), Math.pow(x.doubleValue(), param.doubleValue())); - } - } - - public void testExpComparableToFloatingPoint() { - IReal start = vf.real(-100); - IReal stop = start.negate(); - IReal increments = vf.real("0.1"); - for (IReal param = start; !stop.less(param).getValue(); param = param.add(increments)) { - assertClose(param, param.exp(vf.getPrecision()), Math.exp(param.doubleValue())); - } - } - - - private void assertTakesLessThan(final int seconds, String call, final Runnable x) { - final Semaphore done = new Semaphore(0); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - x.run(); - } - finally { - done.release(); - } - } - }); - try { - t.start(); - if (!done.tryAcquire(seconds, TimeUnit.SECONDS)) { - t.interrupt(); - assertTrue(call + " took more than 2 second.", false); - } - } catch (InterruptedException e) { - } - } - - public void testExpPerformance() { - // exp(x) is small for negative x - IReal start = vf.pi(20).multiply(vf.real(10)); - IReal stop = start.subtract(start.multiply(vf.real(100))); - IReal increments = vf.real(1); - for (IReal param = start; stop.less(param).getValue(); param = param.subtract(increments)) { - final IReal currentParam = param; - assertTakesLessThan(2, "exp(" + param + ")", new Runnable() { - @Override - public void run() { - currentParam.exp(vf.getPrecision()); - } - }); - } - - } - - - public void testLnPerformance() { - // ln(x) is small for low x - IReal start = vf.pi(50).multiply(vf.real(10).pow(vf.integer(8))); - IReal stop = start.divide(vf.real(10).pow(vf.integer(30)), vf.getPrecision()); - IReal increments = vf.real(10); - for (IReal param = start; stop.less(param).getValue(); param = param.divide(increments, vf.getPrecision())) { - final IReal currentParam = param; - assertTakesLessThan(2, "ln(" + param + ")", new Runnable() { - @Override - public void run() { - currentParam.ln(vf.getPrecision()); - } - }); - } - } - - -} diff --git a/value-core/src/test/java/org/rascalmpl/value/TestBinaryIO.java b/value-core/src/test/java/org/rascalmpl/value/TestBinaryIO.java deleted file mode 100644 index ff8e0566d..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/TestBinaryIO.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.impl.fast.ValueFactory; -import org.rascalmpl.value.io.binary.BinaryReader; -import org.rascalmpl.value.io.binary.BinaryWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -import junit.framework.TestCase; - -/** - * @author Arnold Lankamp - */ -public class TestBinaryIO extends TestCase { - private static TypeStore ts = new TypeStore(); - private static TypeFactory tf = TypeFactory.getInstance(); - private static IValueFactory vf = ValueFactory.getInstance(); - private static Type Boolean = tf.abstractDataType(ts,"Boolean"); - - private static Type Name = tf.abstractDataType(ts,"Name"); - private static Type True = tf.constructor(ts,Boolean, "true"); - private static Type False= tf.constructor(ts,Boolean, "false"); - private static Type And= tf.constructor(ts,Boolean, "and", Boolean, Boolean); - private static Type Or= tf.constructor(ts,Boolean, "or", tf.listType(Boolean)); - private static Type Not= tf.constructor(ts,Boolean, "not", Boolean); - private static Type TwoTups = tf.constructor(ts,Boolean, "twotups", tf.tupleType(Boolean, Boolean), tf.tupleType(Boolean, Boolean)); - private static Type NameNode = tf.constructor(ts,Name, "name", tf.stringType()); - private static Type Friends = tf.constructor(ts,Boolean, "friends", tf.listType(Name)); - private static Type Couples = tf.constructor(ts,Boolean, "couples", tf.listType(tf.tupleType(Name, Name))); - - private IValue[] testValues = { - vf.constructor(True), - vf.constructor(And, vf.constructor(True), vf.constructor(False)), - vf.constructor(Not, vf.constructor(And, vf.constructor(True), vf.constructor(False))), - vf.constructor(TwoTups, vf.tuple(vf.constructor(True), vf.constructor(False)),vf.tuple(vf.constructor(True), vf.constructor(False))), - vf.constructor(Or, vf.list(vf.constructor(True), vf.constructor(False), vf.constructor(True))), - vf.constructor(Friends, vf.list(name("Hans"), name("Bob"))), - vf.constructor(Or, vf.list(Boolean)), - vf.constructor(Couples, vf.list(vf.tuple(name("A"), name("B")), vf.tuple(name("C"), name("D")))), - vf.integer(0), - vf.integer(1), - vf.integer(-1), - vf.string("🍝"), - vf.integer(Integer.MAX_VALUE), - vf.integer(Integer.MIN_VALUE), - vf.integer(new byte[]{(byte)0xfe, (byte)0xdc, (byte)0xba, (byte)0x98, (byte)0x76, (byte)0x54}), - vf.constructor(True).asAnnotatable().setAnnotation("test", vf.integer(1)) - }; - - private static IValue name(String n){ - return vf.constructor(NameNode, vf.string(n)); - } - - public void testBinaryIO(){ - try{ - for(int i = 0; i < testValues.length; i++){ - IValue value = testValues[i]; - - System.out.println(value); // Temp - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - BinaryWriter binaryWriter = new BinaryWriter(value, baos, ts); - binaryWriter.serialize(); - - //PBFWriter.writeValueToFile(value, new File("/tmp/testIO"+i+".pbf")); // Temp - - byte[] data = baos.toByteArray(); - ByteArrayInputStream bais = new ByteArrayInputStream(data); - BinaryReader binaryReader = new BinaryReader(vf, ts, bais); - printBytes(data); // Temp - IValue result = binaryReader.deserialize(); - - System.out.println(result); // Temp - System.out.println(); // Temp - - if(!value.isEqual(result)){ - String message = "Not equal: \n\t"+value+" : "+value.getType()+"\n\t"+result+" : "+result.getType(); - System.err.println(message); - fail(message); - } - } - }catch(IOException ioex){ - ioex.printStackTrace(); - fail(ioex.getMessage()); - } - } - - private final static String[] HEX = new String[]{"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"}; - - // May be handy when debugging. - private static void printBytes(byte[] bytes){ - for(int i = 0; i < bytes.length; i++){ - byte b = bytes[i]; - int higher = (b & 0xf0) >> 4; - int lower = b & 0xf; - System.out.print("0x"); - System.out.print(HEX[higher]); - System.out.print(HEX[lower]); - System.out.print(" "); - } - System.out.println(); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/TestIO.java b/value-core/src/test/java/org/rascalmpl/value/TestIO.java deleted file mode 100644 index c1b7c371e..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/TestIO.java +++ /dev/null @@ -1,178 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.io.StringReader; -import java.io.StringWriter; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.IValueFactory; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.impl.reference.ValueFactory; -import org.rascalmpl.value.io.SerializableValue; -import org.rascalmpl.value.io.StandardTextReader; -import org.rascalmpl.value.io.StandardTextWriter; -import org.rascalmpl.value.io.XMLReader; -import org.rascalmpl.value.io.XMLWriter; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -import junit.framework.TestCase; - -public class TestIO extends TestCase { - private static TypeStore ts = new TypeStore(); - private static TypeFactory tf = TypeFactory.getInstance(); - private static IValueFactory vf = ValueFactory.getInstance(); - private static Type Boolean = tf.abstractDataType(ts,"Boolean"); - - private static Type Name = tf.abstractDataType(ts,"Name"); - private static Type True = tf.constructor(ts,Boolean, "true"); - private static Type False= tf.constructor(ts,Boolean, "false"); - private static Type And= tf.constructor(ts,Boolean, "and", Boolean, Boolean); - private static Type Or= tf.constructor(ts,Boolean, "or", tf.listType(Boolean)); - private static Type Not= tf.constructor(ts,Boolean, "not", Boolean); - private static Type TwoTups = tf.constructor(ts,Boolean, "twotups", tf.tupleType(Boolean, Boolean), tf.tupleType(Boolean, Boolean)); - private static Type NameNode = tf.constructor(ts,Name, "name", tf.stringType()); - private static Type Friends = tf.constructor(ts,Boolean, "friends", tf.listType(Name)); - private static Type Couples = tf.constructor(ts,Boolean, "couples", tf.lrelType(Name, Name)); - - private IValue[] testValues = { - vf.constructor(True), - vf.constructor(And, vf.constructor(True), vf.constructor(False)), - vf.constructor(Not, vf.constructor(And, vf.constructor(True), vf.constructor(False))), - vf.constructor(TwoTups, vf.tuple(vf.constructor(True), vf.constructor(False)),vf.tuple(vf.constructor(True), vf.constructor(False))), - vf.constructor(Or, vf.list(vf.constructor(True), vf.constructor(False), vf.constructor(True))), - vf.constructor(Friends, vf.list(name("Hans"), name("Bob"))), - vf.constructor(Or, vf.list(Boolean)), - vf.constructor(Couples, vf.listRelation(vf.tuple(name("A"), name("B")), vf.tuple(name("C"), name("D")))) - }; - - private String[] testXML = { - "", - "", - "", - "", - "", - "HansBob", - "", - "ABCD" - }; - - public void testSerializable() { - for (IValue t : testValues) { - SerializableValue v = new SerializableValue(vf, t); - ByteArrayOutputStream buf = new ByteArrayOutputStream(); - try { - v.write(buf); - SerializableValue w = SerializableValue.read(new ByteArrayInputStream(buf.toByteArray())); - - if (!v.getValue().isEqual(w.getValue())) { - fail(); - } - } catch (IOException e) { - fail(e.getMessage()); - } - } - } - - public void testXMLWriter() { - XMLWriter testWriter = new XMLWriter(); - int i = 0; - for (IValue test : testValues) { - try { - StringWriter stream = new StringWriter(); - testWriter.write(test, stream); - System.err.println(test + " -> " + stream.toString()); - - if (!strip(stream.toString()).equals(testXML[i])) { - fail(strip(stream.toString()) + " != " + testXML[i]); - } - } catch (IOException e) { - e.printStackTrace(); - fail(e.getMessage()); - } - i++; - } - } - - private String strip(String string) { - string = string.substring(string.lastIndexOf("?>")+2); - string = string.replaceAll("\\s", ""); - return string; - } - - private static IValue name(String n) { - return vf.constructor(NameNode, vf.string(n)); - } - - public void testXMLReader() { - XMLReader testReader = new XMLReader(); - - try { - for (int i = 0; i < testXML.length; i++) { - IValue result = testReader.read(vf, ts, Boolean, new StringReader(testXML[i])); - System.err.println(testXML[i] + " -> " + result); - - if (!result.isEqual(testValues[i])) { - fail(testXML[i] + " did not parse correctly: " + result + " != " + testValues[i]); - } - } - } catch (FactTypeUseException | IOException e) { - e.printStackTrace(); - fail(); - } - } - - public void testStandardReader() { - StandardTextReader reader = new StandardTextReader(); - - try { - IValue s = reader.read(vf, new StringReader("\"a b c\"")); - assertEquals(s, vf.string("a b c")); - - IValue v = reader.read(vf, new StringReader("\"f\"(\"a b c\")")); - assertEquals(v, vf.node("f", vf.string("a b c"))); - - IValue r = reader.read(vf, new StringReader("[1.7976931348623157E+308]")); - System.err.println(r); - assertEquals(r, vf.list(vf.real("1.7976931348623157E+308"))); - - - IValue m = reader.read(vf, new StringReader("()")); - System.err.println(m); - assertEquals(m, vf.mapWriter().done()); - - IValue t = reader.read(vf, new StringReader("<()>")); - System.err.println(t); - assertEquals(t, vf.tuple(vf.mapWriter().done())); - - StringWriter w = new StringWriter(); - new StandardTextWriter().write(vf.tuple(), w); - IValue u = reader.read(vf, new StringReader(w.toString())); - System.err.println(u); - assertEquals(u, vf.tuple()); - - } catch (FactTypeUseException | IOException e) { - fail(e.getMessage()); - } - } - - -} diff --git a/value-core/src/test/java/org/rascalmpl/value/TestType.java b/value-core/src/test/java/org/rascalmpl/value/TestType.java deleted file mode 100644 index dd1f278c6..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/TestType.java +++ /dev/null @@ -1,454 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2007 IBM Corporation, 2008 CWI - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - * Jurgen Vinju (jurgen@vinju.org) - * Anya Helene Bagge - *******************************************************************************/ - -package org.rascalmpl.value; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.rascalmpl.value.exceptions.FactTypeDeclarationException; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.random.RandomTypeGenerator; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -import junit.framework.TestCase; - -public class TestType extends TestCase { - private static final int COMBINATION_UPPERBOUND = 5; - - private static TypeFactory ft = TypeFactory.getInstance(); - private static TypeStore ts = new TypeStore(); - - private static List basic = new LinkedList<>(); - private static List allTypes = new LinkedList<>(); - - static { - try { - basic.add(ft.integerType()); - basic.add(ft.realType()); - basic.add(ft.sourceLocationType()); - basic.add(ft.stringType()); - basic.add(ft.nodeType()); - - allTypes.add(ft.valueType()); - allTypes.add(ft.numberType()); - allTypes.addAll(basic); - - for (int i = 0; i < 2; i++) { - recombine(); - } - - RandomTypeGenerator rg = new RandomTypeGenerator(); - for (int i = 0; i < 1000; i++) { - allTypes.add(rg.next(10)); - } - - } catch (FactTypeUseException e) { - throw new RuntimeException("fact type error in setup", e); - } - } - - private static void recombine() throws FactTypeUseException { - List newTypes = new LinkedList<>(); - int max1 = COMBINATION_UPPERBOUND; - - for (Type t1 : allTypes) { - newTypes.add(ft.tupleType(t1)); - newTypes.add(ft.relType(t1)); - newTypes.add(ft.setType(t1)); - newTypes.add(ft.aliasType(ts, "type_" + allTypes.size() - + newTypes.size(), t1)); - Type adt = ft.abstractDataType(ts, "adt_" + newTypes.size()); - newTypes.add(ft.constructor(ts, adt, "cons_" + newTypes.size())); - newTypes.add(adt); - - int max2 = COMBINATION_UPPERBOUND; - - for (Type t2 : allTypes) { - newTypes.add(ft.tupleType(t1, t2)); - newTypes.add(ft.tupleType(t1, "a" + newTypes.size(), t2, "b" + newTypes.size())); - newTypes.add(ft.relType(t1, t2)); - newTypes.add(ft.mapType(t1, t2)); - newTypes.add(ft.mapType(t1, "a" + newTypes.size(), t2, "b" + newTypes.size())); - newTypes.add(ft.constructor(ts, adt, "cons_" + newTypes.size(), t1, "a" + newTypes.size(), t2, "b" + newTypes.size())); - int max3 = COMBINATION_UPPERBOUND; - - for (Type t3 : allTypes) { - newTypes.add(ft.tupleType(t1, t2, t3)); - newTypes.add(ft.relType(t1, t2, t3)); - newTypes.add(ft.constructor(ts, adt, "cons_" + newTypes.size(), t1, "a" + newTypes.size(), t2, "b"+ newTypes.size(), t3, "c" + newTypes.size())); - - if (max3-- == 0) { - break; - } - } - if (max2-- == 0) { - break; - } - } - - if (max1-- == 0) { - break; - } - } - - allTypes.addAll(newTypes); - } - - public void testRelations() { - for (Type t : allTypes) { - if (t.isSet() && t.getElementType().isTuple() - && !t.isRelation()) { - fail("Sets of tuples should be relations"); - } - if (t.isRelation() && !t.getElementType().isTuple()) { - fail("Relations should contain tuples"); - } - } - } - - public void testParameterizedAlias() { - Type T = ft.parameterType("T"); - TypeStore ts = new TypeStore(); - // DiGraph[&T] = rel[&T from ,&T to] - Type DiGraph = ft.aliasType(ts, "DiGraph", ft.relType(T, "from", T, "to"), - T); - Type IntInstance = ft.relType(ft.integerType(), ft.integerType()); - Type ValueInstance = ft.relType(ft.valueType(), ft.valueType()); - - // before instantiation, the parameterized type rel[&T, &T] is a - // sub-type of rel[value, value] - assertTrue(IntInstance.isSubtypeOf(DiGraph)); - assertFalse(DiGraph.isSubtypeOf(IntInstance)); - assertTrue(DiGraph.isSubtypeOf(ValueInstance)); - - Map bindings = new HashMap<>(); - DiGraph.match(IntInstance, bindings); - assertTrue(bindings.get(T) == ft.integerType()); - - // after instantiation, the parameterized type is an alias for rel[int, - // int] - Type ComputedInstance = DiGraph.instantiate(bindings); // DiGraph[int] - assertTrue(ComputedInstance.equivalent(IntInstance)); - assertFalse(ValueInstance.isSubtypeOf(ComputedInstance)); - - // and sub-typing remains co-variant: - assertTrue(IntInstance.isSubtypeOf(ValueInstance)); - assertTrue(ComputedInstance.isSubtypeOf(ValueInstance)); - - try { - ft.aliasType(ts, "DiGraph", ft.setType(T), T); - fail("should not be able to redefine alias"); - } catch (FactTypeDeclarationException e) { - // this should happen - } - } - - public void testADT() { - Type E = ft.abstractDataType(ts, "E"); - - assertTrue( - "Abstract data-types are composed of constructors which are tree nodes", - E.isSubtypeOf(ft.nodeType())); - - assertTrue(E.isSubtypeOf(ft.valueType())); - assertTrue(E.isSubtypeOf(ft.nodeType())); - assertTrue(E.lub(ft.nodeType()).isNode()); - assertTrue(ft.nodeType().lub(E).isNode()); - - Type f = ft.constructor(ts, E, "f", ft.integerType(), "i"); - Type g = ft.constructor(ts, E, "g", ft.integerType(), "j"); - - assertTrue(f.isSubtypeOf(ft.nodeType())); - - assertTrue(f.lub(ft.nodeType()).isNode()); - assertTrue(ft.nodeType().lub(f).isNode()); - - - Type a = ft.aliasType(ts, "a", ft.integerType()); - - assertFalse(f.isSubtypeOf(ft.integerType()) - || f.isSubtypeOf(ft.stringType()) || f.isSubtypeOf(a)); - assertFalse(g.isSubtypeOf(ft.integerType()) - || g.isSubtypeOf(ft.stringType()) || g.isSubtypeOf(a)); - assertFalse("constructors are subtypes of the adt", !f.isSubtypeOf(E) - || !g.isSubtypeOf(E)); - - assertFalse("alternative constructors should be incomparable", f - .isSubtypeOf(g) - || g.isSubtypeOf(f)); - - assertTrue("A constructor should be a node", f.isSubtypeOf(ft - .nodeType())); - assertTrue("A constructor should be a node", g.isSubtypeOf(ft - .nodeType())); - } - - public void testVoid() { - for (Type t : allTypes) { - if(t.isSubtypeOf(ft.voidType())) { - assertFalse(true); - } - } - } - - public void testVoidProblem1() { - assertFalse(ft.listType(ft.voidType()).isSubtypeOf(ft.voidType())); - assertFalse(ft.setType(ft.voidType()).isSubtypeOf(ft.voidType())); - assertFalse(ft.relType(ft.voidType()).isSubtypeOf(ft.voidType())); - assertFalse(ft.tupleType(ft.voidType()).isSubtypeOf(ft.voidType())); - assertFalse(ft.mapType(ft.voidType(),ft.voidType()).isSubtypeOf(ft.voidType())); - } - - public void testIsSubtypeOf() { - for (Type t : allTypes) { - if (!t.isSubtypeOf(t)) { - fail("any type should be a subtype of itself: " + t); - } - - if (t.isSet() && t.getElementType().isTuple() - && !t.isRelation()) { - fail("Sets of tuples should be relations"); - } - } - - for (Type t1 : allTypes) { - for (Type t2 : allTypes) { - assertEquals(t1.equivalent(t2), t1.isSubtypeOf(t2) && t2.isSubtypeOf(t1)); - } - } - - for (Type t1 : allTypes) { - for (Type t2 : allTypes) { - if (t1.isSubtypeOf(t2)) { - for (Type t3 : allTypes) { - if (t2.isSubtypeOf(t3)) { - if (!t1.isSubtypeOf(t3)) { - System.err.println("FAILURE"); - System.err.println("\t" + t1 + " <= " + t2 - + " <= " + t3); - System.err.println("\t" + t1 + " !<= " + t3); - fail("subtype should be transitive: " + t1 + ", " + t2 + ", " + t3); - } - } - } - } - } - } - } - - public void testEquiv() { - for (Type t : allTypes) { - if (!t.equals(t)) { - fail("any type should be equal to itself: " + t); - } - if (!t.equivalent(t)) { - fail("any type should be equivalent to itself: " + t); - } - } - - for (Type t1 : allTypes) { - for (Type t2 : allTypes) { - if (t1.equals(t2) && !t2.equals(t1)) { - fail("equals() should be symmetric: " + t1 + ", " + t2); - } - if (t1.equivalent(t2) && !t2.equivalent(t1)) { - fail("equivalent() should be symmetric: " + t1 + ", " + t2); - } - } - } - - for (Type t1 : allTypes) { - for (Type t2 : allTypes) { - if (t1.equals(t2) || t1.equivalent(t2)) { - for (Type t3 : allTypes) { - if (t1.equals(t2) && t2.equals(t3)) { - if (!t1.equals(t3)) { - fail("equals() should be transitive: " + t1 + ", " + t2 + ", " + t3); - } - } - if (t1.equivalent(t2) && t2.equivalent(t3)) { - if (!t1.equivalent(t3)) { - fail("equivalent() should be transitive: " + t1 + ", " + t2 + ", " + t3); - } - } - } - } - } - } - } - - public void testLub() { - for (Type t : allTypes) { - if (t.lub(t) != t) { - fail("lub should be idempotent: " + t + " != " + t.lub(t)); - } - } - - for (Type t1 : allTypes) { - for (Type t2 : allTypes) { - Type lub1 = t1.lub(t2); - Type lub2 = t2.lub(t1); - - if (lub1 != lub2) { - System.err.println("Failure:"); - System.err.println(t1 + ".lub(" + t2 + ") = " + lub1); - System.err.println(t2 + ".lub(" + t1 + ") = " + lub2); - fail("lub should be commutative"); - } - - if (t1.comparable(t2)) { - if (t1.isSubtypeOf(t2)) { - assertTrue(t1.lub(t2).equivalent(t2)); - } - if (t2.isSubtypeOf(t1)) { - assertTrue(t1.lub(t2).equivalent(t1)); - } - } - } - } - - for (Type t1 : allTypes) { - if (!t1.isAliased() && t1.lub(TypeFactory.getInstance().voidType()) != t1) { - System.err.println(t1 + " lub void is not " + t1 + "? its "+ t1.lub(TypeFactory.getInstance().voidType())); - fail("void should be bottom: " + t1 + ".lub = " + t1.lub(TypeFactory.getInstance().voidType())); - } - if (t1.isAliased() && t1.lub(TypeFactory.getInstance().voidType()) != t1.getAliased()) { - fail("void should be bottom:" + t1); - } - if (t1.lub(TypeFactory.getInstance().valueType()) != TypeFactory.getInstance().valueType()) { - System.err.println(t1 + " lub value is not value?"); - fail("value should be top:" + t1); - } - } - } - - public void testGlb() { - for (Type t : allTypes) { - if (t.glb(t) != t) { - fail("glb should be idempotent: " + t + " != " + t.glb(t)); - } - } - - for (Type t1 : allTypes) { - for (Type t2 : allTypes) { - Type glb1 = t1.glb(t2); - Type glb2 = t2.glb(t1); - - if (glb1 != glb2) { - System.err.println("Failure:"); - System.err.println(t1 + ".glb(" + t2 + ") = " + glb1); - System.err.println(t2 + ".glb(" + t1 + ") = " + glb2); - fail("glb should be commutative"); - } - - if (t1.comparable(t2)) { - if (t1.isSubtypeOf(t2)) { - assertTrue(t1.glb(t2).equivalent(t1)); - } - if (t2.isSubtypeOf(t1)) { - assertTrue(t1.glb(t2).equivalent(t2)); - } - } - } - } - - for (Type t1 : allTypes) { - if (!t1.isAliased() && t1.glb(TypeFactory.getInstance().valueType()) != t1) { - System.err.println(t1 + " glb value is not " + t1 + "? its "+ t1.glb(TypeFactory.getInstance().valueType())); - fail("value should be top: " + t1 + ".lub = " + t1.lub(TypeFactory.getInstance().valueType())); - } - if (t1.isAliased() && t1.glb(TypeFactory.getInstance().valueType()) != t1.getAliased()) { - fail("value should be top:" + t1); - } - if (t1.glb(TypeFactory.getInstance().voidType()) != TypeFactory.getInstance().voidType()) { - System.err.println(t1 + " glb void is not void?"); - fail("void should be bottom:" + t1); - } - } - } - public void testGetTypeDescriptor() { - int count = 0; - for (Type t1 : allTypes) { - for (Type t2 : allTypes) { - if (t1.toString().equals(t2.toString())) { - if (t1 != t2) { - System.err - .println("Type descriptors should be canonical:" - + t1.toString() - + " == " - + t2.toString()); - } - } - if (count++ > 10000) { - return; - } - } - } - } - - public void testMatchAndInstantiate() { - Type X = ft.parameterType("X"); - Map bindings = new HashMap<>(); - - Type subject = ft.integerType(); - X.match(subject, bindings); - - if (!bindings.get(X).equals(subject)) { - fail("simple match failed"); - } - - if (!X.instantiate(bindings).equals(subject)) { - fail("instantiate failed"); - } - - Type relXX = ft.relType(X, X); - bindings.clear(); - subject = ft.relType(ft.integerType(), ft.integerType()); - relXX.match(subject, bindings); - - if (!bindings.get(X).equals(ft.integerType())) { - fail("relation match failed"); - } - - if (!relXX.instantiate(bindings).equals(subject)) { - fail("instantiate failed"); - } - - bindings.clear(); - subject = ft.relType(ft.integerType(), ft.realType()); - relXX.match(subject, bindings); - - Type lub = ft.integerType().lub(ft.realType()); - if (!bindings.get(X).equals(lub)) { - fail("lubbing during matching failed"); - } - - if (!relXX.instantiate(bindings).equals(ft.relType(lub, lub))) { - fail("instantiate failed"); - } - - } - - public void testAlias() { - Type alias = ft.aliasType(new TypeStore(), "myValue", ft.valueType()); - - assertTrue(alias.isSubtypeOf(ft.valueType())); - assertTrue(ft.valueType().isSubtypeOf(alias)); - } - -} diff --git a/value-core/src/test/java/org/rascalmpl/value/TestTypeFactory.java b/value-core/src/test/java/org/rascalmpl/value/TestTypeFactory.java deleted file mode 100644 index 3159a9eac..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/TestTypeFactory.java +++ /dev/null @@ -1,407 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value; - -import java.net.URI; -import java.net.URISyntaxException; - -import org.rascalmpl.value.IValue; -import org.rascalmpl.value.exceptions.FactTypeDeclarationException; -import org.rascalmpl.value.exceptions.FactTypeUseException; -import org.rascalmpl.value.impl.reference.ValueFactory; -import org.rascalmpl.value.type.Type; -import org.rascalmpl.value.type.TypeFactory; -import org.rascalmpl.value.type.TypeStore; - -import junit.framework.TestCase; - -public class TestTypeFactory extends TestCase { - private TypeFactory ft = TypeFactory.getInstance(); - - private ValueFactory ff = ValueFactory.getInstance(); - - private Type[] types = new Type[] { ft.integerType(), ft.realType(), - ft.sourceLocationType(), ft.valueType(), - ft.listType(ft.integerType()), ft.setType(ft.realType()) }; - - public void testGetInstance() { - if (TypeFactory.getInstance() != ft) { - fail("getInstance did not return the same reference"); - } - } - - public void testGetTypeByDescriptor() { - // TODO: needs to be tested, after we've implemented it - } - - public void testValueType() { - if (ft.valueType() != ft.valueType()) { - fail("valueType should be canonical"); - } - } - - public void testIntegerType() { - if (ft.integerType() != ft.integerType()) { - fail("integerType should be canonical"); - } - } - - public void testDoubleType() { - if (ft.realType() != ft.realType()) { - fail("doubleType should be canonical"); - } - } - - public void testStringType() { - if (ft.stringType() != ft.stringType()) { - fail("stringType should be canonical"); - } - } - - public void testSourceLocationType() { - if (ft.sourceLocationType() != ft.sourceLocationType()) { - fail("sourceLocationType should be canonical"); - } - } - - public void testTupleTypeOfType() { - Type t = ft.tupleType(types[0]); - - if (t != ft.tupleType(types[0])) { - fail("tuple types should be canonical"); - } - - testTupleTypeOf(t, 1); - } - - public void testTupleTypeOfTypeType() { - Type t = ft.tupleType(types[0], types[1]); - - if (t != ft.tupleType(types[0], types[1])) { - fail("tuple types should be canonical"); - } - - testTupleTypeOf(t, 2); - } - - public void testTupleTypeOfTypeTypeType() { - Type t = ft.tupleType(types[0], types[1], types[2]); - - if (t != ft.tupleType(types[0], types[1], types[2])) { - fail("tuple types should be canonical"); - } - - testTupleTypeOf(t, 3); - } - - public void testTupleTypeOfTypeTypeTypeType() { - Type t = ft.tupleType(types[0], types[1], types[2], types[3]); - - if (t != ft.tupleType(types[0], types[1], types[2], types[3])) { - fail("tuple types should be canonical"); - } - - testTupleTypeOf(t, 4); - } - - public void testTupleTypeOfTypeTypeTypeTypeType() { - Type t = ft.tupleType(types[0], types[1], types[2], types[3], - types[4]); - - if (t != ft.tupleType(types[0], types[1], types[2], types[3], - types[4])) { - fail("tuple types should be canonical"); - } - - testTupleTypeOf(t, 5); - } - - public void testTupleTypeOfTypeTypeTypeTypeTypeType() { - Type t = ft.tupleType(types[0], types[1], types[2], types[3], - types[4], types[5]); - - if (t != ft.tupleType(types[0], types[1], types[2], types[3], - types[4], types[5])) { - fail("tuple types should be canonical"); - } - - testTupleTypeOf(t, 6); - } - - public void testTupleTypeOfTypeTypeTypeTypeTypeTypeType() { - Type t = ft.tupleType(types[0], types[1], types[2], types[3], - types[4], types[5]); - - if (t != ft.tupleType(types[0], types[1], types[2], types[3], - types[4], types[5])) { - fail("tuple types should be canonical"); - } - - testTupleTypeOf(t, 6); - } - - private void testTupleTypeOf(Type t, int width) { - - if (t.getArity() != width) { - fail("tuple arity broken"); - } - - for (int i = 0; i < t.getArity(); i++) { - if (t.getFieldType(i) != types[i % types.length]) { - fail("Tuple field type unexpected"); - } - } - } - - private void testRelationTypeOf(Type t, int width) { - - if (t.getArity() != width) { - fail("relation arity broken"); - } - - for (int i = 0; i < t.getArity(); i++) { - if (t.getFieldType(i) != types[i % types.length]) { - fail("Relation field type unexpected"); - } - } - } - - public void testTupleTypeOfIValueArray() { - // a and b shadow the 'types' field - try { - IValue[] a = new IValue[] { ff.integer(1), ff.real(1.0), - ff.sourceLocation(new URI("file://bla"), 0, 0, 0, 0, 0, 0) }; - IValue[] b = new IValue[] { ff.integer(1), ff.real(1.0), - ff.sourceLocation(new URI("file://bla"), 0, 0, 0, 0, 0, 0) }; - Type t = ft.tupleType(a); - - if (t != ft.tupleType(b)) { - fail("tuples should be canonical"); - } - - testTupleTypeOf(t, 3); - } catch (URISyntaxException e) { - fail(e.toString()); - } - } - - public void testSetTypeOf() { - Type type = ft.setType(ft.integerType()); - - if (type != ft.setType(ft.integerType())) { - fail("set should be canonical"); - } - } - - public void testRelTypeType() { - try { - TypeStore store = new TypeStore(); - Type namedType = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType())); - // note that the declared type of namedType needs to be Type - Type type = ft.relTypeFromTuple(namedType); - - Type namedType2 = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType())); - - if (type != ft.relTypeFromTuple(namedType2)) { - fail("relation types should be canonical"); - } - - if (type.getFieldType(0) != ft.integerType() && - type.getFieldType(1) != ft.integerType()) { - fail("relation should mimick tuple field types"); - } - } catch (FactTypeUseException e) { - fail("type error for correct relation"); - } - } - - public void testListRelTypeType() { - try { - TypeStore store = new TypeStore(); - Type namedType = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType())); - // note that the declared type of namedType needs to be Type - Type type = ft.lrelTypeFromTuple(namedType); - - Type namedType2 = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType())); - - if (type != ft.lrelTypeFromTuple(namedType2)) { - fail("list relation types should be canonical"); - } - - if (type.getFieldType(0) != ft.integerType() && - type.getFieldType(1) != ft.integerType()) { - fail("list relation should mimick tuple field types"); - } - } catch (FactTypeUseException e) { - fail("type error for correct list relation"); - } - } - - public void testRelTypeNamedType() { - try { - TypeStore store = new TypeStore(); - Type namedType = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType())); - // note that the declared type of namedType needs to be AliasType - Type type = ft.relTypeFromTuple(namedType); - - Type namedType2 = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType())); - - if (type != ft.relTypeFromTuple(namedType2)) { - fail("relation types should be canonical"); - } - } catch (FactTypeUseException e) { - fail("type error for correct relation"); - } - } - - public void testListRelTypeNamedType() { - try { - TypeStore store = new TypeStore(); - Type namedType = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType())); - // note that the declared type of namedType needs to be AliasType - Type type = ft.lrelTypeFromTuple(namedType); - - Type namedType2 = ft.aliasType(store, "myTuple", ft.tupleType(ft.integerType(), ft.integerType())); - - if (type != ft.lrelTypeFromTuple(namedType2)) { - fail("list relation types should be canonical"); - } - } catch (FactTypeUseException e) { - fail("type error for correct list relation"); - } - } - - public void testRelTypeTupleType() { - Type tupleType = ft - .tupleType(ft.integerType(), ft.integerType()); - // note that the declared type of tupleType needs to be TupleType - Type type = ft.relTypeFromTuple(tupleType); - - Type tupleType2 = ft.tupleType(ft.integerType(), ft - .integerType()); - - if (type != ft.relTypeFromTuple(tupleType2)) { - fail("relation types should be canonical"); - } - } - - public void testListRelTypeTupleType() { - Type tupleType = ft - .tupleType(ft.integerType(), ft.integerType()); - // note that the declared type of tupleType needs to be TupleType - Type type = ft.lrelTypeFromTuple(tupleType); - - Type tupleType2 = ft.tupleType(ft.integerType(), ft - .integerType()); - - if (type != ft.lrelTypeFromTuple(tupleType2)) { - fail("list relation types should be canonical"); - } -} - - public void testRelTypeOfType() { - Type type = ft.relType(types[0]); - - if (type != ft.relType(types[0])) { - fail("relation types should be canonical"); - } - - testRelationTypeOf(type, 1); - } - - public void testRelTypeOfTypeType() { - Type type = ft.relType(types[0], types[1]); - - if (type != ft.relType(types[0], types[1])) { - fail("relation types should be canonical"); - } - - testRelationTypeOf(type, 2); - } - - public void testRelTypeOfTypeTypeType() { - Type type = ft.relType(types[0], types[1], types[2]); - - if (type != ft.relType(types[0], types[1], types[2])) { - fail("relation types should be canonical"); - } - - testRelationTypeOf(type, 3); - } - - public void testRelTypeOfTypeTypeTypeType() { - Type type = ft.relType(types[0], types[1], types[2], types[3]); - - if (type != ft.relType(types[0], types[1], types[2], types[3])) { - fail("relation types should be canonical"); - } - testRelationTypeOf(type, 4); - } - - public void testRelTypeOfTypeTypeTypeTypeType() { - Type type = ft.relType(types[0], types[1], types[2], types[3], types[4]); - - if (type != ft.relType(types[0], types[1], types[2], types[3], types[4])) { - fail("relation types should be canonical"); - } - testRelationTypeOf(type, 5); - } - - public void testRelTypeOfTypeTypeTypeTypeTypeType() { - Type type = ft.relType(types[0], types[1], types[2], types[3], types[4], types[5]); - - if (type != ft.relType(types[0], types[1], types[2], types[3], types[4], types[5])) { - fail("relation types should be canonical"); - } - testRelationTypeOf(type, 6); - } - - public void testRelTypeOfTypeTypeTypeTypeTypeTypeType() { - Type type = ft.relType(types[0], types[1], types[2], types[3], types[4], types[5]); - - if (type != ft.relType(types[0], types[1], types[2], types[3], types[4], types[5])) { - fail("relation types should be canonical"); - } - testRelationTypeOf(type, 6); - } - - public void testNamedType() { - try { - TypeStore ts = new TypeStore(); - Type t1 = ft.aliasType(ts, "myType", ft.integerType()); - Type t2 = ft.aliasType(ts, "myType", ft.integerType()); - - if (t1 != t2) { - fail("named types should be canonical"); - } - - try { - ft.aliasType(ts, "myType", ft.realType()); - fail("Should not be allowed to redeclare a type name"); - } catch (FactTypeDeclarationException e) { - // this should happen - } - } catch (FactTypeDeclarationException e) { - fail("the above should be type correct"); - } - } - - public void testListType() { - Type t1 = ft.listType(ft.integerType()); - Type t2 = ft.listType(ft.integerType()); - - if (t1 != t2) { - fail("named types should be canonical"); - } - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/fast/TestAnnotations.java b/value-core/src/test/java/org/rascalmpl/value/fast/TestAnnotations.java deleted file mode 100644 index fc8ce3faa..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/fast/TestAnnotations.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.fast; - -import org.rascalmpl.value.BaseTestAnnotations; -import org.rascalmpl.value.impl.fast.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestAnnotations extends BaseTestAnnotations{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/fast/TestBasicValues.java b/value-core/src/test/java/org/rascalmpl/value/fast/TestBasicValues.java deleted file mode 100644 index 40fa1c79b..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/fast/TestBasicValues.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.rascalmpl.value.fast; - -import org.rascalmpl.value.BaseTestBasicValues; -import org.rascalmpl.value.impl.fast.ValueFactory; - -public class TestBasicValues extends BaseTestBasicValues { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/fast/TestEquality.java b/value-core/src/test/java/org/rascalmpl/value/fast/TestEquality.java deleted file mode 100644 index ae56d7ca4..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/fast/TestEquality.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.fast; - -import org.rascalmpl.value.BaseTestEquality; -import org.rascalmpl.value.impl.fast.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestEquality extends BaseTestEquality{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/fast/TestList.java b/value-core/src/test/java/org/rascalmpl/value/fast/TestList.java deleted file mode 100644 index 696769c93..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/fast/TestList.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.fast; - -import org.rascalmpl.value.BaseTestList; -import org.rascalmpl.value.impl.fast.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestList extends BaseTestList{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/fast/TestListRelation.java b/value-core/src/test/java/org/rascalmpl/value/fast/TestListRelation.java deleted file mode 100644 index 893fcabb7..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/fast/TestListRelation.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.fast; - -import org.rascalmpl.value.BaseTestListRelation; -import org.rascalmpl.value.impl.fast.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestListRelation extends BaseTestListRelation{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/fast/TestMap.java b/value-core/src/test/java/org/rascalmpl/value/fast/TestMap.java deleted file mode 100644 index 93b4daaea..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/fast/TestMap.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2012 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Anya Helene Bagge -*******************************************************************************/ -package org.rascalmpl.value.fast; - -import org.rascalmpl.value.BaseTestMap; -import org.rascalmpl.value.impl.fast.ValueFactory; - -public class TestMap extends BaseTestMap { - - @Override - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/fast/TestRandomValues.java b/value-core/src/test/java/org/rascalmpl/value/fast/TestRandomValues.java deleted file mode 100644 index 7429adefb..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/fast/TestRandomValues.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2011 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Anya Helene Bagge - initial implementation -*******************************************************************************/ -package org.rascalmpl.value.fast; - -import org.rascalmpl.value.BaseTestRandomValues; -import org.rascalmpl.value.impl.fast.ValueFactory; - -public class TestRandomValues extends BaseTestRandomValues { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/fast/TestRelation.java b/value-core/src/test/java/org/rascalmpl/value/fast/TestRelation.java deleted file mode 100644 index 828527e56..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/fast/TestRelation.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.fast; - -import org.rascalmpl.value.BaseTestRelation; -import org.rascalmpl.value.impl.fast.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestRelation extends BaseTestRelation{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/fast/TestSet.java b/value-core/src/test/java/org/rascalmpl/value/fast/TestSet.java deleted file mode 100644 index 97ec7edd0..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/fast/TestSet.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.fast; - -import org.rascalmpl.value.BaseTestSet; -import org.rascalmpl.value.impl.fast.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestSet extends BaseTestSet{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/fast/TestValueFactory.java b/value-core/src/test/java/org/rascalmpl/value/fast/TestValueFactory.java deleted file mode 100644 index 201b68da2..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/fast/TestValueFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.fast; - -import org.rascalmpl.value.BaseTestValueFactory; -import org.rascalmpl.value.impl.fast.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestValueFactory extends BaseTestValueFactory{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/persistent/TestAnnotations.java b/value-core/src/test/java/org/rascalmpl/value/persistent/TestAnnotations.java deleted file mode 100644 index be1a3bafa..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/persistent/TestAnnotations.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.persistent; - -import org.rascalmpl.value.BaseTestAnnotations; -import org.rascalmpl.value.impl.persistent.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestAnnotations extends BaseTestAnnotations{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/persistent/TestBasicValues.java b/value-core/src/test/java/org/rascalmpl/value/persistent/TestBasicValues.java deleted file mode 100644 index 5c98fd070..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/persistent/TestBasicValues.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.rascalmpl.value.persistent; - -import org.rascalmpl.value.BaseTestBasicValues; -import org.rascalmpl.value.impl.persistent.ValueFactory; - -public class TestBasicValues extends BaseTestBasicValues { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/persistent/TestEquality.java b/value-core/src/test/java/org/rascalmpl/value/persistent/TestEquality.java deleted file mode 100644 index f528d8e87..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/persistent/TestEquality.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.persistent; - -import org.rascalmpl.value.BaseTestEquality; -import org.rascalmpl.value.impl.persistent.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestEquality extends BaseTestEquality{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/persistent/TestList.java b/value-core/src/test/java/org/rascalmpl/value/persistent/TestList.java deleted file mode 100644 index 30b4aa25c..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/persistent/TestList.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.persistent; - -import org.rascalmpl.value.BaseTestList; -import org.rascalmpl.value.impl.persistent.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestList extends BaseTestList{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/persistent/TestListRelation.java b/value-core/src/test/java/org/rascalmpl/value/persistent/TestListRelation.java deleted file mode 100644 index 1082a457f..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/persistent/TestListRelation.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.persistent; - -import org.rascalmpl.value.BaseTestListRelation; -import org.rascalmpl.value.impl.persistent.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestListRelation extends BaseTestListRelation{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/persistent/TestMap.java b/value-core/src/test/java/org/rascalmpl/value/persistent/TestMap.java deleted file mode 100644 index a7a88026b..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/persistent/TestMap.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2012 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Anya Helene Bagge -*******************************************************************************/ -package org.rascalmpl.value.persistent; - -import org.rascalmpl.value.BaseTestMap; -import org.rascalmpl.value.impl.persistent.ValueFactory; - -public class TestMap extends BaseTestMap { - - @Override - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/persistent/TestRandomValues.java b/value-core/src/test/java/org/rascalmpl/value/persistent/TestRandomValues.java deleted file mode 100644 index acc265106..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/persistent/TestRandomValues.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2011 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Anya Helene Bagge - initial implementation -*******************************************************************************/ -package org.rascalmpl.value.persistent; - -import org.rascalmpl.value.BaseTestRandomValues; -import org.rascalmpl.value.impl.persistent.ValueFactory; - -public class TestRandomValues extends BaseTestRandomValues { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/persistent/TestRelation.java b/value-core/src/test/java/org/rascalmpl/value/persistent/TestRelation.java deleted file mode 100644 index 4a89098ca..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/persistent/TestRelation.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.persistent; - -import org.rascalmpl.value.BaseTestRelation; -import org.rascalmpl.value.impl.persistent.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestRelation extends BaseTestRelation{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/persistent/TestSet.java b/value-core/src/test/java/org/rascalmpl/value/persistent/TestSet.java deleted file mode 100644 index 42bb76cdf..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/persistent/TestSet.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.persistent; - -import org.rascalmpl.value.BaseTestSet; -import org.rascalmpl.value.impl.persistent.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestSet extends BaseTestSet{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/persistent/TestValueFactory.java b/value-core/src/test/java/org/rascalmpl/value/persistent/TestValueFactory.java deleted file mode 100644 index 5e866a058..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/persistent/TestValueFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2009 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Arnold Lankamp - interfaces and implementation -*******************************************************************************/ -package org.rascalmpl.value.persistent; - -import org.rascalmpl.value.BaseTestValueFactory; -import org.rascalmpl.value.impl.persistent.ValueFactory; - -/** - * @author Arnold Lankamp - */ -public class TestValueFactory extends BaseTestValueFactory{ - - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/reference/TestAnnotations.java b/value-core/src/test/java/org/rascalmpl/value/reference/TestAnnotations.java deleted file mode 100644 index 0372bdb3c..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/reference/TestAnnotations.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value.reference; - -import org.rascalmpl.value.BaseTestAnnotations; -import org.rascalmpl.value.impl.reference.ValueFactory; - -public class TestAnnotations extends BaseTestAnnotations { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/reference/TestBasicValues.java b/value-core/src/test/java/org/rascalmpl/value/reference/TestBasicValues.java deleted file mode 100644 index 0a640fc29..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/reference/TestBasicValues.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.rascalmpl.value.reference; - -import org.rascalmpl.value.BaseTestBasicValues; -import org.rascalmpl.value.impl.reference.ValueFactory; - -public class TestBasicValues extends BaseTestBasicValues { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/reference/TestEquality.java b/value-core/src/test/java/org/rascalmpl/value/reference/TestEquality.java deleted file mode 100644 index 15c9ffc07..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/reference/TestEquality.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value.reference; - -import org.rascalmpl.value.BaseTestEquality; -import org.rascalmpl.value.impl.reference.ValueFactory; - -public class TestEquality extends BaseTestEquality { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/reference/TestList.java b/value-core/src/test/java/org/rascalmpl/value/reference/TestList.java deleted file mode 100644 index 2c5763705..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/reference/TestList.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value.reference; - -import org.rascalmpl.value.BaseTestList; -import org.rascalmpl.value.impl.reference.ValueFactory; - -public class TestList extends BaseTestList { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/reference/TestListRelation.java b/value-core/src/test/java/org/rascalmpl/value/reference/TestListRelation.java deleted file mode 100644 index 78154feef..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/reference/TestListRelation.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value.reference; - -import org.rascalmpl.value.BaseTestListRelation; -import org.rascalmpl.value.impl.reference.ValueFactory; - -public class TestListRelation extends BaseTestListRelation { - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } - -} diff --git a/value-core/src/test/java/org/rascalmpl/value/reference/TestMap.java b/value-core/src/test/java/org/rascalmpl/value/reference/TestMap.java deleted file mode 100644 index 882aab4b3..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/reference/TestMap.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2012 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Anya Helene Bagge -*******************************************************************************/ -package org.rascalmpl.value.reference; - -import org.rascalmpl.value.BaseTestMap; -import org.rascalmpl.value.impl.reference.ValueFactory; - -public class TestMap extends BaseTestMap { - - @Override - protected void setUp() throws Exception{ - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/reference/TestRandomValues.java b/value-core/src/test/java/org/rascalmpl/value/reference/TestRandomValues.java deleted file mode 100644 index 72cde3be2..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/reference/TestRandomValues.java +++ /dev/null @@ -1,22 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2011 Centrum Wiskunde en Informatica (CWI) -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Anya Helene Bagge (anya@ii.uib.no) - initial implementation -*******************************************************************************/ -package org.rascalmpl.value.reference; - -import org.rascalmpl.value.BaseTestRandomValues; -import org.rascalmpl.value.impl.reference.ValueFactory; - -public class TestRandomValues extends BaseTestRandomValues { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/reference/TestRelation.java b/value-core/src/test/java/org/rascalmpl/value/reference/TestRelation.java deleted file mode 100644 index 56bb6ceb2..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/reference/TestRelation.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value.reference; - -import org.rascalmpl.value.BaseTestRelation; -import org.rascalmpl.value.impl.reference.ValueFactory; - -public class TestRelation extends BaseTestRelation { - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } - -} diff --git a/value-core/src/test/java/org/rascalmpl/value/reference/TestSet.java b/value-core/src/test/java/org/rascalmpl/value/reference/TestSet.java deleted file mode 100644 index 6cba797b9..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/reference/TestSet.java +++ /dev/null @@ -1,24 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value.reference; - -import org.rascalmpl.value.BaseTestSet; -import org.rascalmpl.value.impl.reference.ValueFactory; - -public class TestSet extends BaseTestSet { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/reference/TestValueFactory.java b/value-core/src/test/java/org/rascalmpl/value/reference/TestValueFactory.java deleted file mode 100644 index e57d07a84..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/reference/TestValueFactory.java +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************* -* Copyright (c) 2007 IBM Corporation. -* All rights reserved. This program and the accompanying materials -* are made available under the terms of the Eclipse Public License v1.0 -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v10.html -* -* Contributors: -* Robert Fuhrer (rfuhrer@watson.ibm.com) - initial API and implementation - -*******************************************************************************/ - -package org.rascalmpl.value.reference; - -import org.rascalmpl.value.BaseTestValueFactory; -import org.rascalmpl.value.impl.reference.ValueFactory; - - -public class TestValueFactory extends BaseTestValueFactory { - - @Override - protected void setUp() throws Exception { - super.setUp(ValueFactory.getInstance()); - } -} diff --git a/value-core/src/test/java/org/rascalmpl/value/util/MixDistribution.java b/value-core/src/test/java/org/rascalmpl/value/util/MixDistribution.java deleted file mode 100644 index 83c46a669..000000000 --- a/value-core/src/test/java/org/rascalmpl/value/util/MixDistribution.java +++ /dev/null @@ -1,524 +0,0 @@ -package org.rascalmpl.value.util; - - -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Random; -import java.util.Set; - -import javax.imageio.ImageIO; - - -public class MixDistribution { - private static final int[] BIT_OFFSET = new int[32]; - static { - for (int i=0; i < 32; i++) { - BIT_OFFSET[i] = 1 << i; - } - } - - private static void reportCollisions(String name, int[] data, Mixer mixer) { - Set used = new HashSet(); - Set seen = new HashSet(); - Set seen16 = new HashSet(); - int collisions = 0; - int collisions16 = 0; - for (int d : data) { - if (used.contains(d)) { - continue; - } - used.add(d); - int m = mixer.mix(d); - if (seen.contains(m)) { - collisions++; - continue; - } - seen.add(m); - int m16l = m & 0x0000FFFF; - int m16h = m & 0xFFFF0000; - if (seen16.contains(m16l) || seen16.contains(m16h)) { - collisions16++; - } - seen16.add(m16l); - seen16.add(m16h); - } - System.out.println(name + " full collisions: " + collisions); - System.out.println(name + " 16-bit collisions: " + collisions16); - } - - private static void reportHashDistribution(String name, int[] hashes) { - int[] counts = new int[32]; - for (int h : hashes) { - for (int bit =0; bit < 32; bit++) { - if ((h & BIT_OFFSET[bit]) != 0) { - counts[bit]++; - } - } - } - System.out.print(name); - for (int c: counts) { - System.out.print(','); - System.out.print(c); - } - System.out.println(); - Double total = 0.0; - int maxError = 0; - System.out.print(name+"-offset"); - for (int c: counts) { - System.out.print(','); - int error = c - (hashes.length / 2); - System.out.print(error); - total += (error * error); - maxError = Math.max(maxError, Math.abs(error)); - } - System.out.println(); - System.out.println(name + " max absolute offset: " + maxError); - - - System.out.println(name + " root mean error:" + Math.sqrt(total / hashes.length)); - } - - private static void createBitStatsPlot(String name, String category, int[] numbers, Mixer mixer) throws IOException { - int[][] bits = new int[32][32]; - for (int input : numbers) { - int A = mixer.mix(input); - for (int sourceBit = 0; sourceBit < 32; sourceBit++) { - int flipped = input ^ BIT_OFFSET[sourceBit]; - int B = mixer.mix(flipped); - for (int bit =0; bit < 32; bit++) { - int Abit = A & BIT_OFFSET[bit]; - int Bbit = B & BIT_OFFSET[bit]; - if (Abit != Bbit) { - bits[sourceBit][bit]++; - } - } - } - } - BufferedImage img = new BufferedImage(32, 32, BufferedImage.TYPE_INT_RGB); - for (int x = 0; x < 32; x++) { - for (int y = 0; y < 32; y++) { - img.setRGB(x, y, getColor(Math.abs((numbers.length/2)-bits[x][y])/((double)numbers.length/2))); - } - } - ImageIO.write(img, "PNG", new File("avalanche-" + category +"-"+ name + ".png")); - } - - private static int getColor(double errorRate) { - double green = 0.0; - double red = 0.0; - if (0 <= errorRate && errorRate < 0.5 ) { - green = 1.0; - red = 2 * errorRate; - } - else { - red = 1.0; - green = 1.0 - 2 * (errorRate-0.5); - } - return - (((int)Math.floor(red * 255)) << 16) - | (((int)Math.floor(green * 255)) << 8) - ; - - - } - - public static void main(String[] args) throws IOException { - Map mixers = new LinkedHashMap<>(); - mixers.put("raw", new RawMix()); - mixers.put("xxhash", new XXHashMix()); - mixers.put("xxhash2", new XXHashMix2()); - mixers.put("lookup3", new Lookup3Mix()); - mixers.put("murmur2", new MurmurHash2Mix()); - mixers.put("murmur2-2", new MurmurHash2Mix2()); - mixers.put("murmur2-3", new MurmurHash2Mix3()); - mixers.put("murmur2-4", new MurmurHash2Mix4()); - mixers.put("murmur3", new MurmurHash3Mix()); - mixers.put("murmur3-2", new MurmurHash3Mix2()); - mixers.put("crapwow", new CrapWowMix()); - mixers.put("crapwow-2", new CrapWowMix2()); - mixers.put("crapwow-3", new CrapWowMix3()); - mixers.put("encode.ru-m2-2", new EncodeRUm2Mix()); - mixers.put("superfasthash", new SuperFastHashMix()); - mixers.put("superfasthash2", new SuperFastHashMix2()); - mixers.put("hashmap", new HashMapMix()); - mixers.put("scala-hashmap", new ScalaHashMapMix()); - - int[] data = new int[10000]; - for (int i=0; i < data.length; i++) { - data[i] = i; - } - - System.out.println("Numbers from 1-10000"); - for (String m : mixers.keySet()) { - reportHashDistribution(m, mix(data, mixers.get(m))); - reportCollisions(m, data, mixers.get(m)); - } - System.out.println(""); - System.out.println(""); - System.out.println("Numbers from 1-10000 << 16"); - for (int i=0; i < data.length; i++) { - data[i] = i << 16; - } - for (String m : mixers.keySet()) { - reportHashDistribution(m, mix(data, mixers.get(m))); - reportCollisions(m, data, mixers.get(m)); - } - - - Random rand = new Random(); - for (int i=0; i < data.length; i++) { - data[i] = rand.nextInt(); - } - System.out.println(""); - System.out.println(""); - System.out.println(""); - System.out.println("Random numbers"); - for (String m : mixers.keySet()) { - reportHashDistribution(m, mix(data, mixers.get(m))); - reportCollisions(m, data, mixers.get(m)); - createBitStatsPlot(m, "random", data, mixers.get(m)); - } - - - data = new int[512]; - for (int i=0; i < data.length; i++) { - data[i] = i; - } - System.out.println(""); - System.out.println(""); - System.out.println(""); - System.out.println("Random small numbers"); - for (String m : mixers.keySet()) { - reportHashDistribution(m, mix(data, mixers.get(m))); - reportCollisions(m, data, mixers.get(m)); - } - } - - - private static int[] mix(int[] data, Mixer mixer) { - int[] result = new int[data.length]; - for (int i = 0; i < data.length; i++) { - result[i] = mixer.mix(data[i]); - } - return result; - } - - - private static interface Mixer { - int mix(int n); - } - - private static class RawMix implements Mixer { - @Override - public int mix(int n) { - return n; - } - } - - private static class XXHashMix implements Mixer { - @Override - public int mix(int n) { - int h32 = 0x165667b1; - - h32 += n * (int)3266489917L; - h32 = Integer.rotateLeft(h32, 17) * 668265263; - - h32 ^= h32 >>> 15; - h32 *= (int) 2246822519L; - h32 ^= h32 >>> 13; - h32 *= (int) 3266489917L; - h32 ^= h32 >>> 16; - - return h32; - } - } - private static class XXHashMix2 implements Mixer { - @Override - public int mix(int n) { - int h32 = n + 0x165667b1; - h32 ^= h32 >>> 15; - h32 *= (int) 2246822519L; - h32 ^= h32 >>> 13; - h32 *= (int) 3266489917L; - h32 ^= h32 >>> 16; - return h32; - } - } - private static class HashMapMix implements Mixer { - @Override - public int mix(int n) { - int h = n; - h ^= (h >>> 20) ^ (h >>> 12); - return h ^ (h >>> 7) ^ (h >>> 4); - } - } - - private static class ScalaHashMapMix implements Mixer { - @Override - public int mix(int n) { - int h = n + ~(n << 9); - h = h ^ (h >>> 14); - h = h + (h << 4); - return h ^ (h >>> 10); - } - } - - private static class MurmurHash2Mix implements Mixer { - @Override - public int mix(int n) { - int h = 1 ^ 4; - - int k = n; - k = mixK(k); - h = mixH(h, k); - - h *= m; - h ^= h >>> 13; - h *= m; - h ^= h >>> 15; - - return h; - } - - private final int m = 0x5bd1e995; - private final int r = 24; - - private int mixK(int k) { - k *= m; - k ^= k >>> r; - k *= m; - return k; - } - - private int mixH(int h, int k) { - h *= m; - h ^= k; - return h; - } - } - private static class MurmurHash2Mix2 implements Mixer { - @Override - public int mix(int n) { - int h = n; - - h *= 0x5bd1e995; - h ^= h >>> 13; - h *= 0x5bd1e995; - h ^= h >>> 15; - - return h; - } - - } - private static class MurmurHash2Mix3 implements Mixer { - @Override - public int mix(int n) { - int h = n ^ 0x85ebca6b; - - h ^= h >>> 13; - h *= 0x5bd1e995; - h ^= h >>> 15; - - return h; - } - - } - private static class MurmurHash2Mix4 implements Mixer { - @Override - public int mix(int n) { - int h = n ^ 0x85ebca6b; - - h ^= h >>> 13; - h *= 0x5bd1e995; - h ^= h >>> 15; - - h += ( h >> 22 ) ^ ( h << 4 ); - - return h; - } - - } - - private static class Lookup3Mix implements Mixer { - @Override - public int mix(int n) { - int a,b,c; - a = b = c = 0xdeadbeef + (1<<2); - a += n; - { - c ^= b; c -= (b<<14)|(b>>>-14); - a ^= c; a -= (c<<11)|(c>>>-11); - b ^= a; b -= (a<<25)|(a>>>-25); - c ^= b; c -= (b<<16)|(b>>>-16); - a ^= c; a -= (c<<4)|(c>>>-4); - b ^= a; b -= (a<<14)|(a>>>-14); - c ^= b; c -= (b<<24)|(b>>>-24); - } - return c; - } - } - - private static class MurmurHash3Mix implements Mixer{ - - @Override - public int mix(int n) { - int h = 1; - - int k = n; - k = mixK(k); - h = mixH(h, k); - - // finalizing - h ^= 1; - - h ^= h >>> 16; - h *= 0x85ebca6b; - h ^= h >>> 13; - h *= 0xc2b2ae35; - h ^= h >>> 16; - - return h; - } - - private final static int C1 = 0xcc9e2d51; - private final static int C2 = 0x1b873593; - private final static int M = 5; - private final static int N = 0xe6546b64; - - - private final static int mixK(int k) { - k *= C1; - k = Integer.rotateLeft(k, 15); - k = k * C2; - return k; - } - - private final static int mixH(int h, int k) { - h ^= k; - h = Integer.rotateLeft(h, 13); - h = h * M + N; - return h; - } - } - - private static class MurmurHash3Mix2 implements Mixer{ - - @Override - public int mix(int n) { - int h = n ^ 1; - - h ^= h >>> 16; - h *= 0x85ebca6b; - h ^= h >>> 13; - h *= 0xc2b2ae35; - h ^= h >>> 16; - - return h; - } - } - - private static class SuperFastHashMix implements Mixer { - @Override - public int mix(int n) { - int hash = 0, tmp; - - hash += n & 0xFFFF; - tmp = ((n & 0xFFFF0000) >> 5) ^ hash; - hash = (hash << 16) ^ tmp; - - hash += hash >> 11; - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - return hash; - } - } - - private static class SuperFastHashMix2 implements Mixer { - @Override - public int mix(int n) { - int hash = n; - - hash += hash >> 11; - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - return hash; - } - } - - private static class CrapWowMix implements Mixer { - - private final static int M = 0x57559429, N = 0x5052acdb; - - @Override - public int mix(int n) { - int h = 1; - int k = 1 + n + N; - - // "loop" - long p = n * (long)M; - h ^= (int)p; - k ^= (int)(p >> 32); - - // end mix - p = (h ^ (k + N)) * (long)N; - k ^= (int)p; - h ^= (int)(p >> 32); - return k ^ h; - } - - } - - private static class CrapWowMix2 implements Mixer { - - private final static int M = 0x57559429, N = 0x5052acdb; - - @Override - public int mix(int n) { - long p = n * (long)M; - p ^= (long)n + (long)N; - p *= N; - return ((int)p) ^ (int)(p >> 32); - } - } - - private static class CrapWowMix3 implements Mixer { - - private final static int M = 0x57559429, N = 0x5052acdb; - - @Override - public int mix(int n) { - long p; - p = n * (long)M; - p ^= ((long)n) << 32; - p *= (long)N; - return ((int)p) ^ (int)(p >> 32); - } - } - - private static class EncodeRUm2Mix implements Mixer { - - @Override - public int mix(int n) { - long k = n; - k ^= k >> 33; - k *= 0xff51afd7ed558ccdL; - k ^= k >> 33; - k *= 0xc4ceb9fe1a85ec53L; - k ^= k >> 33; - - return (int)k ^ (int)(k >> 32); - } - } -}