From ac849228490d5a0e2d3f048d649297d5c59b6ade Mon Sep 17 00:00:00 2001 From: Gilles Dubochet Date: Mon, 19 Dec 2005 13:49:03 +0000 Subject: Switching to the new build system and to the ne... Switching to the new build system and to the new build system. This is a MAJOR commit, so be careful when updating. --- README | 59 + VERSION | 9 - build.readme | 114 -- build.xml | 1218 +++++------- config/build.TEMPLATE.properties | 34 - config/build.base.properties | 16 - config/build.default.properties | 133 -- config/excludes/nsc.nslib.excludes | 10 - config/excludes/nsc.nstools.excludes | 7 - config/excludes/nsc.osc-nstools.excludes | 7 - config/izpack/images/Splash.png | Bin 153467 -> 0 bytes config/izpack/images/install.png | Bin 130263 -> 0 bytes config/izpack/install-nsc.xml | 111 -- config/izpack/izpack_process.xml | 44 - config/izpack/izpack_scala.xml | 96 - config/izpack/izpack_shortcut.xml | 42 - config/izpack/locales/INFO_de.html | 23 - config/izpack/locales/INFO_en.html | 23 - config/izpack/locales/INFO_fr.html | 23 - config/izpack/locales/LICENSE_de.html | 76 - config/izpack/locales/LICENSE_en.html | 68 - config/izpack/locales/LICENSE_fr.html | 82 - config/izpack/registry/bin/ICE_JNIRegistry.dll | Bin 65536 -> 0 bytes config/izpack/registry/bin/readme.txt | 50 - .../izpack/registry/bin/registry.jar.desired.sha1 | 1 - config/izpack/registry/bin/setenv.jar.desired.sha1 | 1 - config/izpack/registry/src/MANIFEST.MF | 3 - config/izpack/registry/src/Main.java | 120 -- config/izpack/targets/path_macosx.txt | 1 - config/izpack/targets/path_unix.txt | 1 - lib/fjbg.jar.desired.sha1 | 1 + lib/jaco.jar.desired.sha1 | 1 + lib/msil.jar.desired.sha1 | 1 + lib/scala-compiler.jar.desired.sha1 | 1 + lib/scala-library.jar.desired.sha1 | 1 + lib/scala.dll | Bin 0 -> 520192 bytes newsources/scala/Array.scala | 18 - newsources/scala/CaseClass.scala | 32 - newsources/scala/MatchError.scala | 40 - newsources/scala/ScalaObject.scala | 20 - sources/bin/izpack.symlink.tmpl | 11 - sources/bin/nscala-tool.win.tmpl | 47 - sources/bin/nscala.unix.tmpl | 82 - sources/bin/nscala.win.tmpl | 49 - sources/msil/AssemblyInfo.cs.tmpl | 58 - sources/msil/scala/runtime/compat/Math.scala | 36 - sources/msil/scala/runtime/compat/Platform.scala | 38 - .../msil/scala/runtime/compat/StringBuilder.scala | 22 - sources/msil/scala_part2.il.diff.tmpl | 21 - sources/scala/All$.java | 10 - sources/scala/AllRef$.java | 9 - sources/scala/AnyVal.cs | 18 - sources/scala/AnyVal.java | 14 - sources/scala/Application.scala | 51 - sources/scala/Array.cs | 35 - sources/scala/Array.java | 29 - sources/scala/Attribute.scala | 14 - sources/scala/Boolean.cs | 61 - sources/scala/Boolean.java | 53 - sources/scala/BufferedIterator.scala | 26 - sources/scala/Byte.cs | 132 -- sources/scala/Byte.java | 189 -- sources/scala/CaseClass.scala | 33 - sources/scala/Cell.scala | 20 - sources/scala/Char.cs | 128 -- sources/scala/Char.java | 187 -- sources/scala/Console.scala | 253 --- sources/scala/Double.cs | 66 - sources/scala/Double.java | 78 - sources/scala/Enumeration.scala | 140 -- sources/scala/Float.cs | 81 - sources/scala/Float.java | 93 - sources/scala/Function0.scala | 13 - sources/scala/Function1.scala | 13 - sources/scala/Function2.scala | 13 - sources/scala/Function3.scala | 13 - sources/scala/Function4.scala | 13 - sources/scala/Function5.scala | 13 - sources/scala/Function6.scala | 13 - sources/scala/Function7.scala | 13 - sources/scala/Function8.scala | 13 - sources/scala/Function9.scala | 13 - sources/scala/Int.cs | 127 -- sources/scala/Int.java | 184 -- sources/scala/Iterable.scala | 157 -- sources/scala/IterableProxy.scala | 97 - sources/scala/Iterator.scala | 429 ---- sources/scala/List.scala | 919 --------- sources/scala/Long.cs | 108 - sources/scala/Long.java | 181 -- sources/scala/MatchError.cs | 62 - sources/scala/MatchError.java | 52 - sources/scala/None.scala | 18 - sources/scala/Option.scala | 70 - sources/scala/Ordered.scala | 35 - sources/scala/PartialFunction.scala | 29 - sources/scala/PartiallyOrdered.scala | 49 - sources/scala/Predef.scala | 359 ---- sources/scala/Proxy.scala | 26 - sources/scala/Ref.cs | 31 - sources/scala/Ref.java | 27 - sources/scala/ScalaObject.cs | 24 - sources/scala/ScalaObject.java | 27 - sources/scala/Seq.scala | 194 -- sources/scala/SeqProxy.scala | 91 - sources/scala/SerialVersionUID.scala | 12 - sources/scala/Short.cs | 129 -- sources/scala/Short.java | 186 -- sources/scala/Some.scala | 19 - sources/scala/Stream.scala | 243 --- sources/scala/Symbol.scala | 30 - sources/scala/Tuple1.scala | 13 - sources/scala/Tuple2.scala | 13 - sources/scala/Tuple3.scala | 13 - sources/scala/Tuple4.scala | 13 - sources/scala/Tuple5.scala | 13 - sources/scala/Tuple6.scala | 13 - sources/scala/Tuple7.scala | 13 - sources/scala/Tuple8.scala | 13 - sources/scala/Tuple9.scala | 13 - sources/scala/Type.java | 160 -- sources/scala/Unit.cs | 45 - sources/scala/Unit.java | 37 - sources/scala/_trait_.scala | 18 - sources/scala/cloneable.scala | 12 - sources/scala/collection/BitSet.scala | 82 - sources/scala/collection/Map.scala | 180 -- sources/scala/collection/MapProxy.scala | 43 - sources/scala/collection/Set.scala | 89 - sources/scala/collection/SetProxy.scala | 37 - sources/scala/collection/immutable/BitSet.scala | 117 -- sources/scala/collection/immutable/ListMap.scala | 150 -- sources/scala/collection/immutable/ListSet.scala | 118 -- sources/scala/collection/immutable/Map.scala | 144 -- sources/scala/collection/immutable/Queue.scala | 173 -- sources/scala/collection/immutable/Set.scala | 81 - sources/scala/collection/immutable/Stack.scala | 139 -- sources/scala/collection/immutable/Tree.scala | 374 ---- sources/scala/collection/immutable/TreeMap.scala | 107 - sources/scala/collection/immutable/TreeSet.scala | 69 - sources/scala/collection/mutable/ArrayBuffer.scala | 148 -- sources/scala/collection/mutable/BitSet.scala | 87 - sources/scala/collection/mutable/Buffer.scala | 214 -- sources/scala/collection/mutable/BufferProxy.scala | 147 -- .../scala/collection/mutable/DefaultMapModel.scala | 52 - .../collection/mutable/DoubleLinkedList.scala | 49 - sources/scala/collection/mutable/HashMap.scala | 36 - sources/scala/collection/mutable/HashSet.scala | 49 - sources/scala/collection/mutable/HashTable.scala | 148 -- sources/scala/collection/mutable/History.scala | 42 - .../collection/mutable/ImmutableMapAdaptor.scala | 64 - .../collection/mutable/ImmutableSetAdaptor.scala | 50 - .../scala/collection/mutable/JavaMapAdaptor.scala | 66 - .../scala/collection/mutable/JavaSetAdaptor.scala | 44 - sources/scala/collection/mutable/LinkedList.scala | 34 - sources/scala/collection/mutable/ListBuffer.scala | 143 -- sources/scala/collection/mutable/Location.scala | 27 - sources/scala/collection/mutable/Map.scala | 169 -- sources/scala/collection/mutable/MapProxy.scala | 53 - sources/scala/collection/mutable/Message.scala | 77 - sources/scala/collection/mutable/MultiMap.scala | 38 - sources/scala/collection/mutable/MutableList.scala | 77 - .../collection/mutable/ObservableBuffer.scala | 74 - .../scala/collection/mutable/ObservableMap.scala | 48 - .../scala/collection/mutable/ObservableSet.scala | 39 - .../scala/collection/mutable/PriorityQueue.scala | 180 -- .../collection/mutable/PriorityQueueProxy.scala | 94 - sources/scala/collection/mutable/Publisher.scala | 45 - sources/scala/collection/mutable/Queue.scala | 194 -- sources/scala/collection/mutable/QueueProxy.scala | 97 - .../scala/collection/mutable/ResizableArray.scala | 64 - .../collection/mutable/RevertableHistory.scala | 31 - sources/scala/collection/mutable/Scriptable.scala | 24 - sources/scala/collection/mutable/Set.scala | 111 -- sources/scala/collection/mutable/SetProxy.scala | 51 - .../collection/mutable/SingleLinkedList.scala | 63 - sources/scala/collection/mutable/Stack.scala | 132 -- sources/scala/collection/mutable/StackProxy.scala | 108 - sources/scala/collection/mutable/Subscriber.scala | 22 - .../collection/mutable/SynchronizedBuffer.scala | 189 -- .../scala/collection/mutable/SynchronizedMap.scala | 116 -- .../mutable/SynchronizedPriorityQueue.scala | 97 - .../collection/mutable/SynchronizedQueue.scala | 93 - .../scala/collection/mutable/SynchronizedSet.scala | 104 - .../collection/mutable/SynchronizedStack.scala | 109 -- sources/scala/collection/mutable/Undoable.scala | 24 - sources/scala/concurrent/Actor.scala | 29 - sources/scala/concurrent/Channel.scala | 37 - sources/scala/concurrent/Lock.scala | 22 - sources/scala/concurrent/MailBox.scala | 170 -- sources/scala/concurrent/NameServer.scala | 35 - sources/scala/concurrent/Process.scala | 78 - sources/scala/concurrent/SyncChannel.scala | 38 - sources/scala/concurrent/SyncVar.scala | 37 - sources/scala/concurrent/TIMEOUT.scala | 12 - sources/scala/concurrent/jolib.scala | 75 - sources/scala/concurrent/ops.scala | 52 - sources/scala/concurrent/pilib.scala | 189 -- sources/scala/dbc/DataType.scala | 66 - sources/scala/dbc/Database.scala | 186 -- sources/scala/dbc/Syntax.scala | 44 - sources/scala/dbc/Utilities.scala | 25 - sources/scala/dbc/Value.scala | 24 - sources/scala/dbc/Vendor.scala | 38 - .../scala/dbc/datatype/ApproximateNumeric.scala | 53 - sources/scala/dbc/datatype/Boolean.scala | 27 - sources/scala/dbc/datatype/Character.scala | 36 - .../scala/dbc/datatype/CharacterLargeObject.scala | 27 - sources/scala/dbc/datatype/CharacterString.scala | 20 - sources/scala/dbc/datatype/CharacterVarying.scala | 37 - sources/scala/dbc/datatype/ExactNumeric.scala | 61 - sources/scala/dbc/datatype/Factory.scala | 246 --- sources/scala/dbc/datatype/Numeric.scala | 28 - sources/scala/dbc/datatype/String.scala | 20 - sources/scala/dbc/datatype/Unknown.scala | 30 - .../scala/dbc/exception/IncompatibleSchema.scala | 15 - .../scala/dbc/exception/UnsupportedFeature.scala | 12 - sources/scala/dbc/result/Field.scala | 60 - sources/scala/dbc/result/FieldMetadata.scala | 32 - sources/scala/dbc/result/Relation.scala | 68 - sources/scala/dbc/result/Status.scala | 24 - sources/scala/dbc/result/Tuple.scala | 38 - sources/scala/dbc/statement/AccessMode.scala | 22 - sources/scala/dbc/statement/DerivedColumn.scala | 32 - sources/scala/dbc/statement/Expression.scala | 25 - sources/scala/dbc/statement/Insert.scala | 32 - sources/scala/dbc/statement/InsertionData.scala | 37 - sources/scala/dbc/statement/IsolationLevel.scala | 28 - sources/scala/dbc/statement/JoinType.scala | 45 - sources/scala/dbc/statement/Jointure.scala | 43 - sources/scala/dbc/statement/Relation.scala | 53 - sources/scala/dbc/statement/Select.scala | 91 - sources/scala/dbc/statement/SetClause.scala | 18 - sources/scala/dbc/statement/SetQuantifier.scala | 30 - sources/scala/dbc/statement/Statement.scala | 14 - sources/scala/dbc/statement/Status.scala | 26 - sources/scala/dbc/statement/Table.scala | 36 - sources/scala/dbc/statement/Transaction.scala | 51 - sources/scala/dbc/statement/Update.scala | 43 - .../scala/dbc/statement/expression/Aggregate.scala | 30 - .../dbc/statement/expression/BinaryOperator.scala | 28 - .../scala/dbc/statement/expression/Constant.scala | 18 - .../scala/dbc/statement/expression/Default.scala | 17 - sources/scala/dbc/statement/expression/Field.scala | 35 - .../dbc/statement/expression/FunctionCall.scala | 28 - .../scala/dbc/statement/expression/Select.scala | 23 - .../dbc/statement/expression/SetFunction.scala | 35 - .../scala/dbc/statement/expression/TypeCast.scala | 27 - .../dbc/statement/expression/UnaryOperator.scala | 28 - sources/scala/dbc/syntax/DataTypeUtil.scala | 94 - sources/scala/dbc/syntax/Database.scala | 29 - sources/scala/dbc/syntax/Statement.scala | 270 --- sources/scala/dbc/syntax/StatementExpression.scala | 217 --- sources/scala/dbc/value/ApproximateNumeric.scala | 24 - sources/scala/dbc/value/Boolean.scala | 23 - sources/scala/dbc/value/Character.scala | 31 - sources/scala/dbc/value/CharacterLargeObject.scala | 31 - sources/scala/dbc/value/CharacterVarying.scala | 31 - sources/scala/dbc/value/Conversion.scala | 153 -- sources/scala/dbc/value/ExactNumeric.scala | 31 - sources/scala/dbc/value/Factory.scala | 91 - sources/scala/dbc/value/Unknown.scala | 23 - sources/scala/dbc/vendor/PostgreSQL.scala | 23 - sources/scala/io/Position.scala | 92 - sources/scala/io/Source.scala | 252 --- sources/scala/mobile/Code.scala | 234 --- sources/scala/mobile/Location.scala | 96 - sources/scala/reflect/Code.scala | 21 - sources/scala/reflect/Print.scala | 113 -- sources/scala/reflect/Symbol.scala | 51 - sources/scala/reflect/Type.scala | 44 - sources/scala/reflect/TypedCode.scala | 13 - sources/scala/remote.scala | 12 - sources/scala/runtime/AtomicReference.java | 54 - sources/scala/runtime/BooleanRef.java | 16 - sources/scala/runtime/BoxedAnyArray.scala | 154 -- sources/scala/runtime/BoxedArray.scala | 45 - sources/scala/runtime/BoxedBoolean.java | 49 - sources/scala/runtime/BoxedBooleanArray.scala | 33 - sources/scala/runtime/BoxedByte.java | 58 - sources/scala/runtime/BoxedByteArray.scala | 33 - sources/scala/runtime/BoxedChar.java | 59 - sources/scala/runtime/BoxedCharArray.scala | 33 - sources/scala/runtime/BoxedDouble.java | 50 - sources/scala/runtime/BoxedDoubleArray.scala | 33 - sources/scala/runtime/BoxedFloat.java | 49 - sources/scala/runtime/BoxedFloatArray.scala | 33 - sources/scala/runtime/BoxedInt.java | 59 - sources/scala/runtime/BoxedIntArray.scala | 33 - sources/scala/runtime/BoxedLong.java | 50 - sources/scala/runtime/BoxedLongArray.scala | 33 - sources/scala/runtime/BoxedNumber.java | 21 - sources/scala/runtime/BoxedObjectArray.scala | 29 - sources/scala/runtime/BoxedShort.java | 59 - sources/scala/runtime/BoxedShortArray.scala | 33 - sources/scala/runtime/BoxedUnit.java | 37 - sources/scala/runtime/ByteRef.java | 16 - sources/scala/runtime/CharRef.java | 16 - sources/scala/runtime/DoubleRef.java | 16 - sources/scala/runtime/FNV_Hash.java | 51 - sources/scala/runtime/FloatRef.java | 16 - sources/scala/runtime/IOMap.java | 171 -- sources/scala/runtime/IntRef.java | 16 - sources/scala/runtime/InterpreterSupport.java | 108 - sources/scala/runtime/LongRef.java | 16 - sources/scala/runtime/MetaAttribute.cs | 34 - sources/scala/runtime/ObjectRef.java | 16 - sources/scala/runtime/RunTime.cs | 513 ----- sources/scala/runtime/RunTime.java | 473 ----- sources/scala/runtime/ScalaRunTime.scala | 90 - sources/scala/runtime/ShortRef.java | 16 - sources/scala/runtime/SymtabAttribute.cs | 40 - sources/scala/runtime/compat/Math.scala | 36 - sources/scala/runtime/compat/Platform.scala | 35 - sources/scala/runtime/compat/StringBuilder.scala | 26 - sources/scala/runtime/matching/Address.scala | 30 - sources/scala/runtime/matching/NonTerm.scala | 52 - sources/scala/runtime/matching/PatternTests.scala | 5 - sources/scala/runtime/matching/Rule.scala | 102 - sources/scala/runtime/matching/TestAlphabet.scala | 9 - sources/scala/runtime/types/ClassType.java | 94 - sources/scala/runtime/types/CompoundType.java | 109 -- sources/scala/runtime/types/JavaClassType.java | 53 - sources/scala/runtime/types/JavaRefArrayType.java | 80 - sources/scala/runtime/types/LazyParents.java | 22 - sources/scala/runtime/types/ScalaClassType.java | 271 --- sources/scala/runtime/types/SingleType.java | 52 - sources/scala/runtime/types/SpecialType.java | 42 - sources/scala/runtime/types/Statistics.java | 155 -- sources/scala/runtime/types/TypeAll.java | 34 - sources/scala/runtime/types/TypeAllRef.java | 35 - sources/scala/runtime/types/TypeAny.java | 35 - sources/scala/runtime/types/TypeAnyVal.java | 34 - sources/scala/runtime/types/TypeBoolean.java | 37 - sources/scala/runtime/types/TypeByte.java | 50 - sources/scala/runtime/types/TypeChar.java | 50 - sources/scala/runtime/types/TypeConstructor.java | 157 -- sources/scala/runtime/types/TypeDouble.java | 49 - sources/scala/runtime/types/TypeFloat.java | 49 - sources/scala/runtime/types/TypeInt.java | 50 - sources/scala/runtime/types/TypeLong.java | 49 - sources/scala/runtime/types/TypeShort.java | 49 - sources/scala/runtime/types/TypeUnit.java | 37 - sources/scala/runtime/types/ValueType.java | 38 - sources/scala/serializable.scala | 12 - sources/scala/testing/Benchmark.scala | 74 - sources/scala/testing/SUnit.scala | 188 -- sources/scala/testing/UnitTest.scala | 58 - sources/scala/text/Document.scala | 119 -- sources/scala/tools/nsc/CompilationUnits.scala | 37 - sources/scala/tools/nsc/CompilerCommand.scala | 66 - sources/scala/tools/nsc/CompilerRun.scala | 20 - sources/scala/tools/nsc/EvalLoop.scala | 19 - sources/scala/tools/nsc/FatalError.scala | 8 - sources/scala/tools/nsc/Global.scala | 518 ----- sources/scala/tools/nsc/Interpreter.scala | 234 --- sources/scala/tools/nsc/Main.scala | 71 - sources/scala/tools/nsc/MainInterpreter.scala | 74 - sources/scala/tools/nsc/MainTokenMetric.scala | 61 - sources/scala/tools/nsc/NoPhase.scala | 11 - sources/scala/tools/nsc/Phase.scala | 35 - sources/scala/tools/nsc/Settings.scala | 166 -- sources/scala/tools/nsc/SubComponent.scala | 29 - sources/scala/tools/nsc/ant/NSC.scala | 645 ------ sources/scala/tools/nsc/ast/TreeBrowsers.scala | 631 ------ sources/scala/tools/nsc/ast/TreeGen.scala | 158 -- sources/scala/tools/nsc/ast/TreeInfo.scala | 187 -- sources/scala/tools/nsc/ast/TreePrinters.scala | 303 --- sources/scala/tools/nsc/ast/Trees.scala | 1251 ------------ .../scala/tools/nsc/ast/parser/MarkupParsers.scala | 583 ------ sources/scala/tools/nsc/ast/parser/Parsers.scala | 1808 ----------------- sources/scala/tools/nsc/ast/parser/Scanners.scala | 908 --------- .../tools/nsc/ast/parser/SymbolicXMLBuilder.scala | 349 ---- .../tools/nsc/ast/parser/SyntaxAnalyzer.scala | 25 - sources/scala/tools/nsc/ast/parser/Tokens.scala | 97 - .../scala/tools/nsc/ast/parser/TreeBuilder.scala | 289 --- .../scala/tools/nsc/backend/ScalaPrimitives.scala | 736 ------- .../tools/nsc/backend/WorklistAlgorithm.scala | 50 - .../tools/nsc/backend/icode/BasicBlocks.scala | 269 --- .../tools/nsc/backend/icode/CheckerError.scala | 11 - .../scala/tools/nsc/backend/icode/Checkers.scala | 591 ------ .../nsc/backend/icode/ExceptionHandlers.scala | 49 - .../scala/tools/nsc/backend/icode/GenICode.scala | 1672 ---------------- sources/scala/tools/nsc/backend/icode/ICodes.scala | 31 - .../tools/nsc/backend/icode/Linearizers.scala | 89 - .../scala/tools/nsc/backend/icode/Members.scala | 241 --- .../scala/tools/nsc/backend/icode/Opcodes.scala | 473 ----- .../scala/tools/nsc/backend/icode/Primitives.scala | 239 --- .../scala/tools/nsc/backend/icode/Printers.scala | 128 -- .../scala/tools/nsc/backend/icode/TypeKinds.scala | 352 ---- .../scala/tools/nsc/backend/icode/TypeStacks.scala | 96 - sources/scala/tools/nsc/backend/jvm/GenJVM.scala | 1054 ---------- .../tools/nsc/matching/AlgebraicMatchers.scala | 172 -- sources/scala/tools/nsc/matching/Autom2.scala | 196 -- sources/scala/tools/nsc/matching/BerrySethis.scala | 800 -------- sources/scala/tools/nsc/matching/CodeFactory.scala | 260 --- .../scala/tools/nsc/matching/DetWordAutoms.scala | 884 --------- sources/scala/tools/nsc/matching/LeftTracers.scala | 232 --- .../scala/tools/nsc/matching/MatcherLabels.scala | 126 -- .../tools/nsc/matching/NondetWordAutoms.scala | 522 ----- sources/scala/tools/nsc/matching/Npair.scala | 64 - .../scala/tools/nsc/matching/PatternMatchers.scala | 992 ---------- .../tools/nsc/matching/PatternNodeCreator.scala | 108 - .../scala/tools/nsc/matching/PatternNodes.scala | 371 ---- .../scala/tools/nsc/matching/RightTracers.scala | 537 ----- .../tools/nsc/matching/SequenceMatchers.scala | 173 -- .../tools/nsc/matching/StateSetComparator.scala | 34 - .../scala/tools/nsc/matching/TransMatcher.scala | 301 --- sources/scala/tools/nsc/matching/WordAutoms.scala | 146 -- sources/scala/tools/nsc/models/Models.scala.xxx | 189 -- .../scala/tools/nsc/models/SemanticTokens.scala | 513 ----- sources/scala/tools/nsc/models/Signatures.scala | 65 - .../tools/nsc/reporters/AbstractReporter.scala | 55 - .../tools/nsc/reporters/ConsoleReporter.scala | 133 -- sources/scala/tools/nsc/reporters/Reporter.scala | 46 - .../scala/tools/nsc/reporters/ReporterTimer.scala | 27 - .../scala/tools/nsc/reporters/StoreReporter.scala | 38 - sources/scala/tools/nsc/symtab/Constants.scala | 191 -- sources/scala/tools/nsc/symtab/Definitions.scala | 417 ---- sources/scala/tools/nsc/symtab/Flags.scala | 191 -- .../scala/tools/nsc/symtab/InfoTransformers.scala | 45 - sources/scala/tools/nsc/symtab/Names.scala | 332 ---- sources/scala/tools/nsc/symtab/Scopes.scala | 249 --- sources/scala/tools/nsc/symtab/StdNames.scala | 356 ---- sources/scala/tools/nsc/symtab/SymbolLoaders.scala | 192 -- sources/scala/tools/nsc/symtab/SymbolTable.scala | 50 - sources/scala/tools/nsc/symtab/Symbols.scala | 1055 ---------- sources/scala/tools/nsc/symtab/Types.scala | 2060 -------------------- .../nsc/symtab/classfile/ClassfileConstants.scala | 42 - .../nsc/symtab/classfile/ClassfileParser.scala | 402 ---- .../tools/nsc/symtab/classfile/MetaParser.scala | 153 -- .../tools/nsc/symtab/classfile/PickleBuffer.scala | 118 -- .../tools/nsc/symtab/classfile/PickleFormat.scala | 99 - .../scala/tools/nsc/symtab/classfile/Pickler.scala | 244 --- .../nsc/symtab/classfile/SymblfileParser.scala | 31 - .../tools/nsc/symtab/classfile/UnPickler.scala | 260 --- .../scala/tools/nsc/transform/AddInterfaces.scala | 258 --- .../scala/tools/nsc/transform/Constructors.scala | 163 -- sources/scala/tools/nsc/transform/Erasure.scala | 569 ------ .../scala/tools/nsc/transform/ExplicitOuter.scala | 330 ---- sources/scala/tools/nsc/transform/Flatten.scala | 112 -- .../scala/tools/nsc/transform/InfoTransform.scala | 31 - sources/scala/tools/nsc/transform/LambdaLift.scala | 352 ---- sources/scala/tools/nsc/transform/Mixin.scala | 412 ---- .../tools/nsc/transform/OverridingPairs.scala | 126 -- .../tools/nsc/transform/SampleTransform.scala | 45 - sources/scala/tools/nsc/transform/TailCalls.scala | 286 --- sources/scala/tools/nsc/transform/Transform.scala | 26 - sources/scala/tools/nsc/transform/UnCurry.scala | 365 ---- sources/scala/tools/nsc/typechecker/Analyzer.scala | 43 - .../scala/tools/nsc/typechecker/Codification.scala | 207 -- .../tools/nsc/typechecker/ConstantFolder.scala | 145 -- sources/scala/tools/nsc/typechecker/Contexts.scala | 330 ---- .../scala/tools/nsc/typechecker/EtaExpansion.scala | 73 - sources/scala/tools/nsc/typechecker/Infer.scala | 657 ------- sources/scala/tools/nsc/typechecker/Namers.scala | 576 ------ .../scala/tools/nsc/typechecker/RefChecks.scala | 589 ------ .../tools/nsc/typechecker/SuperAccessors.scala | 89 - .../tools/nsc/typechecker/SyntheticMethods.scala | 133 -- .../scala/tools/nsc/typechecker/TreeCheckers.scala | 139 -- sources/scala/tools/nsc/typechecker/Typers.scala | 1567 --------------- .../scala/tools/nsc/typechecker/Variances.scala | 83 - sources/scala/tools/nsc/util/CharArrayReader.scala | 99 - .../scala/tools/nsc/util/FreshNameCreator.scala | 33 - sources/scala/tools/nsc/util/HashSet.scala | 58 - sources/scala/tools/nsc/util/LinkedList.scala | 11 - sources/scala/tools/nsc/util/ListBuffer.scala | 58 - sources/scala/tools/nsc/util/NameTransformer.scala | 96 - sources/scala/tools/nsc/util/Position.scala | 79 - sources/scala/tools/nsc/util/Set.scala | 23 - sources/scala/tools/nsc/util/ShowPickled.scala | 161 -- sources/scala/tools/nsc/util/SourceFile.scala | 136 -- sources/scala/tools/nsc/util/Statistics.scala | 45 - sources/scala/tools/nsc/util/TreeSet.scala | 52 - sources/scala/tools/util/AbstractFile.java | 128 -- sources/scala/tools/util/AbstractFileReader.java | 111 -- sources/scala/tools/util/AbstractReporter.java | 144 -- sources/scala/tools/util/AbstractTimer.java | 49 - sources/scala/tools/util/ByteArrayFile.java | 54 - sources/scala/tools/util/CharArrayFile.java | 53 - sources/scala/tools/util/ClassPath.java | 193 -- sources/scala/tools/util/ConsoleReporter.java | 167 -- sources/scala/tools/util/DirectoryPath.java | 222 --- sources/scala/tools/util/DummyTimer.java | 44 - sources/scala/tools/util/EmptyIterator.java | 48 - sources/scala/tools/util/PlainFile.java | 149 -- sources/scala/tools/util/Position.java | 192 -- sources/scala/tools/util/Reporter.java | 62 - sources/scala/tools/util/ReporterTimer.java | 39 - sources/scala/tools/util/SourceFile.java | 122 -- sources/scala/tools/util/SourceReader.java | 155 -- sources/scala/tools/util/StringBufferWriter.java | 69 - sources/scala/tools/util/Timer.java | 27 - sources/scala/tools/util/UTF8Codec.java | 66 - sources/scala/tools/util/VirtualDirectory.java | 39 - sources/scala/tools/util/VirtualFile.java | 97 - sources/scala/tools/util/ZipArchive.java | 229 --- sources/scala/tools/util/debug/AbortError.java | 43 - sources/scala/tools/util/debug/ArrayDebugger.java | 94 - sources/scala/tools/util/debug/Debug.java | 244 --- sources/scala/tools/util/debug/Debugger.java | 34 - sources/scala/tools/util/debug/ObjectDebugger.java | 54 - .../scala/tools/util/debug/ThrowableDebugger.java | 48 - .../scala/tools/util/debug/ToStringDebugger.java | 44 - sources/scala/transient.scala | 12 - sources/scala/util/automata/BaseBerrySethi.scala | 180 -- sources/scala/util/automata/DetWordAutom.scala | 56 - sources/scala/util/automata/Inclusion.scala | 54 - sources/scala/util/automata/NondetWordAutom.scala | 101 - .../scala/util/automata/SubsetConstruction.scala | 143 -- sources/scala/util/automata/WordBerrySethi.scala | 275 --- sources/scala/util/grammar/HedgeRHS.scala | 12 - sources/scala/util/grammar/TreeRHS.scala | 9 - sources/scala/util/logging/ConsoleLogger.scala | 12 - sources/scala/util/logging/Logged.scala | 23 - .../util/parsing/CharInputStreamIterator.scala | 35 - sources/scala/util/parsing/Parsers.scala | 68 - sources/scala/util/parsing/SimpleTokenizer.scala | 46 - sources/scala/util/regexp/Base.scala | 63 - sources/scala/util/regexp/PointedHedgeExp.scala | 25 - sources/scala/util/regexp/SyntaxError.scala | 6 - sources/scala/util/regexp/WordExp.scala | 24 - sources/scala/volatile.scala | 12 - sources/scala/xml/Atom.scala | 41 - sources/scala/xml/Comment.scala | 45 - sources/scala/xml/Document.scala | 84 - sources/scala/xml/Elem.scala | 74 - sources/scala/xml/EntityRef.scala | 40 - .../scala/xml/MalformedAttributeException.scala | 3 - sources/scala/xml/MetaData.scala | 159 -- sources/scala/xml/Molecule.scala | 39 - sources/scala/xml/NamespaceBinding.scala | 70 - sources/scala/xml/Node.scala | 145 -- sources/scala/xml/NodeBuffer.scala | 55 - sources/scala/xml/NodeSeq.scala | 104 - sources/scala/xml/NodeTraverser.scala | 30 - sources/scala/xml/Null.scala | 75 - sources/scala/xml/Parsing.scala | 102 - sources/scala/xml/PrefixedAttribute.scala | 87 - sources/scala/xml/PrettyPrinter.scala | 274 --- sources/scala/xml/ProcInstr.scala | 63 - sources/scala/xml/SpecialNode.scala | 31 - sources/scala/xml/Text.scala | 32 - sources/scala/xml/TextBuffer.scala | 55 - sources/scala/xml/TopScope.scala | 28 - sources/scala/xml/TypeSymbol.scala | 11 - sources/scala/xml/UnprefixedAttribute.scala | 70 - sources/scala/xml/Utility.scala | 244 --- sources/scala/xml/XML.scala | 75 - sources/scala/xml/dtd/ContentModel.scala | 200 -- sources/scala/xml/dtd/ContentModelParser.scala | 144 -- sources/scala/xml/dtd/DTD.scala | 48 - sources/scala/xml/dtd/Decl.scala | 182 -- sources/scala/xml/dtd/DocType.scala | 44 - sources/scala/xml/dtd/DtdTypeSymbol.scala | 1 - sources/scala/xml/dtd/ElementValidator.scala | 166 -- sources/scala/xml/dtd/ExternalID.scala | 94 - sources/scala/xml/dtd/Scanner.scala | 87 - sources/scala/xml/dtd/Tokens.scala | 32 - sources/scala/xml/dtd/ValidationException.scala | 33 - sources/scala/xml/factory/Binder.scala | 43 - sources/scala/xml/factory/LoggedNodeFactory.scala | 78 - sources/scala/xml/factory/NodeFactory.scala | 77 - .../scala/xml/parsing/ConstructingHandler.scala | 24 - sources/scala/xml/parsing/ConstructingParser.scala | 61 - .../scala/xml/parsing/DefaultMarkupHandler.scala | 16 - sources/scala/xml/parsing/ExternalSources.scala | 76 - sources/scala/xml/parsing/FactoryAdapter.scala | 344 ---- sources/scala/xml/parsing/FatalError.scala | 3 - sources/scala/xml/parsing/MarkupHandler.scala | 148 -- sources/scala/xml/parsing/MarkupParser.scala | 1223 ------------ .../xml/parsing/NoBindingFactoryAdapter.scala | 53 - sources/scala/xml/parsing/TokenTests.scala | 145 -- .../xml/parsing/ValidatingMarkupHandler.scala | 104 - sources/scala/xml/path/Expression.scala | 54 - sources/scala/xml/transform/BasicTransformer.scala | 124 -- sources/scala/xml/transform/RewriteRule.scala | 13 - sources/scala/xml/transform/RuleTransformer.scala | 14 - sources/scala/xml/xsd/ContentModel.scala | 39 - sources/scala/xml/xsd/Decl.scala | 26 - sources/scala/xml/xsd/XsTypeSymbol.scala | 38 - .../scala/tools/nsc/CompilationUnits.scala | 37 + src/compiler/scala/tools/nsc/CompilerCommand.scala | 66 + src/compiler/scala/tools/nsc/CompilerRun.scala | 20 + src/compiler/scala/tools/nsc/EvalLoop.scala | 19 + src/compiler/scala/tools/nsc/FatalError.scala | 8 + src/compiler/scala/tools/nsc/Global.scala | 518 +++++ src/compiler/scala/tools/nsc/Interpreter.scala | 234 +++ src/compiler/scala/tools/nsc/Main.scala | 71 + src/compiler/scala/tools/nsc/MainInterpreter.scala | 74 + src/compiler/scala/tools/nsc/MainTokenMetric.scala | 61 + src/compiler/scala/tools/nsc/NoPhase.scala | 11 + src/compiler/scala/tools/nsc/Phase.scala | 35 + src/compiler/scala/tools/nsc/Settings.scala | 166 ++ src/compiler/scala/tools/nsc/SubComponent.scala | 29 + src/compiler/scala/tools/nsc/ant/NSC.scala | 645 ++++++ .../scala/tools/nsc/ast/TreeBrowsers.scala | 631 ++++++ src/compiler/scala/tools/nsc/ast/TreeGen.scala | 158 ++ src/compiler/scala/tools/nsc/ast/TreeInfo.scala | 187 ++ .../scala/tools/nsc/ast/TreePrinters.scala | 303 +++ src/compiler/scala/tools/nsc/ast/Trees.scala | 1251 ++++++++++++ .../scala/tools/nsc/ast/parser/MarkupParsers.scala | 583 ++++++ .../scala/tools/nsc/ast/parser/Parsers.scala | 1808 +++++++++++++++++ .../scala/tools/nsc/ast/parser/Scanners.scala | 908 +++++++++ .../tools/nsc/ast/parser/SymbolicXMLBuilder.scala | 349 ++++ .../tools/nsc/ast/parser/SyntaxAnalyzer.scala | 25 + .../scala/tools/nsc/ast/parser/Tokens.scala | 97 + .../scala/tools/nsc/ast/parser/TreeBuilder.scala | 289 +++ .../scala/tools/nsc/backend/ScalaPrimitives.scala | 736 +++++++ .../tools/nsc/backend/WorklistAlgorithm.scala | 50 + .../tools/nsc/backend/icode/BasicBlocks.scala | 269 +++ .../tools/nsc/backend/icode/CheckerError.scala | 11 + .../scala/tools/nsc/backend/icode/Checkers.scala | 591 ++++++ .../nsc/backend/icode/ExceptionHandlers.scala | 49 + .../scala/tools/nsc/backend/icode/GenICode.scala | 1672 ++++++++++++++++ .../scala/tools/nsc/backend/icode/ICodes.scala | 31 + .../tools/nsc/backend/icode/Linearizers.scala | 89 + .../scala/tools/nsc/backend/icode/Members.scala | 241 +++ .../scala/tools/nsc/backend/icode/Opcodes.scala | 473 +++++ .../scala/tools/nsc/backend/icode/Primitives.scala | 239 +++ .../scala/tools/nsc/backend/icode/Printers.scala | 128 ++ .../scala/tools/nsc/backend/icode/TypeKinds.scala | 352 ++++ .../scala/tools/nsc/backend/icode/TypeStacks.scala | 96 + .../scala/tools/nsc/backend/jvm/GenJVM.scala | 1054 ++++++++++ .../tools/nsc/matching/AlgebraicMatchers.scala | 172 ++ src/compiler/scala/tools/nsc/matching/Autom2.scala | 196 ++ .../scala/tools/nsc/matching/BerrySethis.scala | 800 ++++++++ .../scala/tools/nsc/matching/CodeFactory.scala | 260 +++ .../scala/tools/nsc/matching/DetWordAutoms.scala | 884 +++++++++ .../scala/tools/nsc/matching/LeftTracers.scala | 232 +++ .../scala/tools/nsc/matching/MatcherLabels.scala | 126 ++ .../tools/nsc/matching/NondetWordAutoms.scala | 522 +++++ src/compiler/scala/tools/nsc/matching/Npair.scala | 64 + .../scala/tools/nsc/matching/PatternMatchers.scala | 992 ++++++++++ .../tools/nsc/matching/PatternNodeCreator.scala | 108 + .../scala/tools/nsc/matching/PatternNodes.scala | 371 ++++ .../scala/tools/nsc/matching/RightTracers.scala | 537 +++++ .../tools/nsc/matching/SequenceMatchers.scala | 173 ++ .../tools/nsc/matching/StateSetComparator.scala | 34 + .../scala/tools/nsc/matching/TransMatcher.scala | 301 +++ .../scala/tools/nsc/matching/WordAutoms.scala | 146 ++ .../scala/tools/nsc/models/Models.scala.xxx | 189 ++ .../scala/tools/nsc/models/SemanticTokens.scala | 513 +++++ .../scala/tools/nsc/models/Signatures.scala | 65 + .../tools/nsc/reporters/AbstractReporter.scala | 55 + .../tools/nsc/reporters/ConsoleReporter.scala | 133 ++ .../scala/tools/nsc/reporters/Reporter.scala | 46 + .../scala/tools/nsc/reporters/ReporterTimer.scala | 27 + .../scala/tools/nsc/reporters/StoreReporter.scala | 38 + .../scala/tools/nsc/symtab/Constants.scala | 191 ++ .../scala/tools/nsc/symtab/Definitions.scala | 417 ++++ src/compiler/scala/tools/nsc/symtab/Flags.scala | 191 ++ .../scala/tools/nsc/symtab/InfoTransformers.scala | 45 + src/compiler/scala/tools/nsc/symtab/Names.scala | 332 ++++ src/compiler/scala/tools/nsc/symtab/Scopes.scala | 249 +++ src/compiler/scala/tools/nsc/symtab/StdNames.scala | 356 ++++ .../scala/tools/nsc/symtab/SymbolLoaders.scala | 192 ++ .../scala/tools/nsc/symtab/SymbolTable.scala | 50 + src/compiler/scala/tools/nsc/symtab/Symbols.scala | 1055 ++++++++++ src/compiler/scala/tools/nsc/symtab/Types.scala | 2060 ++++++++++++++++++++ .../nsc/symtab/classfile/ClassfileConstants.scala | 42 + .../nsc/symtab/classfile/ClassfileParser.scala | 402 ++++ .../tools/nsc/symtab/classfile/MetaParser.scala | 153 ++ .../tools/nsc/symtab/classfile/PickleBuffer.scala | 118 ++ .../tools/nsc/symtab/classfile/PickleFormat.scala | 99 + .../scala/tools/nsc/symtab/classfile/Pickler.scala | 244 +++ .../nsc/symtab/classfile/SymblfileParser.scala | 31 + .../tools/nsc/symtab/classfile/UnPickler.scala | 260 +++ .../scala/tools/nsc/transform/AddInterfaces.scala | 258 +++ .../scala/tools/nsc/transform/Constructors.scala | 163 ++ .../scala/tools/nsc/transform/Erasure.scala | 569 ++++++ .../scala/tools/nsc/transform/ExplicitOuter.scala | 330 ++++ .../scala/tools/nsc/transform/Flatten.scala | 112 ++ .../scala/tools/nsc/transform/InfoTransform.scala | 31 + .../scala/tools/nsc/transform/LambdaLift.scala | 352 ++++ src/compiler/scala/tools/nsc/transform/Mixin.scala | 412 ++++ .../tools/nsc/transform/OverridingPairs.scala | 126 ++ .../tools/nsc/transform/SampleTransform.scala | 45 + .../scala/tools/nsc/transform/TailCalls.scala | 286 +++ .../scala/tools/nsc/transform/Transform.scala | 26 + .../scala/tools/nsc/transform/UnCurry.scala | 365 ++++ .../scala/tools/nsc/typechecker/Analyzer.scala | 43 + .../scala/tools/nsc/typechecker/Codification.scala | 207 ++ .../tools/nsc/typechecker/ConstantFolder.scala | 145 ++ .../scala/tools/nsc/typechecker/Contexts.scala | 330 ++++ .../scala/tools/nsc/typechecker/EtaExpansion.scala | 73 + .../scala/tools/nsc/typechecker/Infer.scala | 657 +++++++ .../scala/tools/nsc/typechecker/Namers.scala | 576 ++++++ .../scala/tools/nsc/typechecker/RefChecks.scala | 589 ++++++ .../tools/nsc/typechecker/SuperAccessors.scala | 89 + .../tools/nsc/typechecker/SyntheticMethods.scala | 133 ++ .../scala/tools/nsc/typechecker/TreeCheckers.scala | 139 ++ .../scala/tools/nsc/typechecker/Typers.scala | 1567 +++++++++++++++ .../scala/tools/nsc/typechecker/Variances.scala | 83 + .../scala/tools/nsc/util/CharArrayReader.scala | 99 + .../scala/tools/nsc/util/FreshNameCreator.scala | 33 + src/compiler/scala/tools/nsc/util/HashSet.scala | 58 + src/compiler/scala/tools/nsc/util/LinkedList.scala | 11 + src/compiler/scala/tools/nsc/util/ListBuffer.scala | 58 + .../scala/tools/nsc/util/NameTransformer.scala | 96 + src/compiler/scala/tools/nsc/util/Position.scala | 79 + src/compiler/scala/tools/nsc/util/Set.scala | 23 + .../scala/tools/nsc/util/ShowPickled.scala | 161 ++ src/compiler/scala/tools/nsc/util/SourceFile.scala | 136 ++ src/compiler/scala/tools/nsc/util/Statistics.scala | 45 + src/compiler/scala/tools/nsc/util/TreeSet.scala | 52 + src/compiler/scala/tools/util/AbstractFile.java | 128 ++ .../scala/tools/util/AbstractFileReader.java | 111 ++ .../scala/tools/util/AbstractReporter.java | 144 ++ src/compiler/scala/tools/util/AbstractTimer.java | 49 + src/compiler/scala/tools/util/ByteArrayFile.java | 54 + src/compiler/scala/tools/util/CharArrayFile.java | 53 + src/compiler/scala/tools/util/ClassPath.java | 193 ++ src/compiler/scala/tools/util/ConsoleReporter.java | 167 ++ src/compiler/scala/tools/util/DirectoryPath.java | 222 +++ src/compiler/scala/tools/util/DummyTimer.java | 44 + src/compiler/scala/tools/util/EmptyIterator.java | 48 + src/compiler/scala/tools/util/PlainFile.java | 149 ++ src/compiler/scala/tools/util/Position.java | 192 ++ src/compiler/scala/tools/util/Reporter.java | 62 + src/compiler/scala/tools/util/ReporterTimer.java | 39 + src/compiler/scala/tools/util/SourceFile.java | 122 ++ src/compiler/scala/tools/util/SourceReader.java | 155 ++ .../scala/tools/util/StringBufferWriter.java | 69 + src/compiler/scala/tools/util/Timer.java | 27 + src/compiler/scala/tools/util/UTF8Codec.java | 66 + .../scala/tools/util/VirtualDirectory.java | 39 + src/compiler/scala/tools/util/VirtualFile.java | 97 + src/compiler/scala/tools/util/ZipArchive.java | 229 +++ .../scala/tools/util/debug/AbortError.java | 43 + .../scala/tools/util/debug/ArrayDebugger.java | 94 + src/compiler/scala/tools/util/debug/Debug.java | 244 +++ src/compiler/scala/tools/util/debug/Debugger.java | 34 + .../scala/tools/util/debug/ObjectDebugger.java | 54 + .../scala/tools/util/debug/ThrowableDebugger.java | 48 + .../scala/tools/util/debug/ToStringDebugger.java | 44 + src/exec/nscala-tool.win.tmpl | 47 + src/exec/nscala.unix.tmpl | 81 + src/exec/nscala.win.tmpl | 49 + src/library/scala/All$.java | 10 + src/library/scala/AllRef$.java | 9 + src/library/scala/AnyVal.cs | 18 + src/library/scala/AnyVal.java | 14 + src/library/scala/Application.scala | 51 + src/library/scala/Array.scala | 18 + src/library/scala/Attribute.scala | 14 + src/library/scala/Boolean.cs | 61 + src/library/scala/Boolean.java | 53 + src/library/scala/BufferedIterator.scala | 26 + src/library/scala/Byte.cs | 132 ++ src/library/scala/Byte.java | 189 ++ src/library/scala/CaseClass.scala | 33 + src/library/scala/Cell.scala | 20 + src/library/scala/Char.cs | 128 ++ src/library/scala/Char.java | 187 ++ src/library/scala/Console.scala | 253 +++ src/library/scala/Double.cs | 66 + src/library/scala/Double.java | 78 + src/library/scala/Enumeration.scala | 140 ++ src/library/scala/Float.cs | 81 + src/library/scala/Float.java | 93 + src/library/scala/Function0.scala | 13 + src/library/scala/Function1.scala | 13 + src/library/scala/Function2.scala | 13 + src/library/scala/Function3.scala | 13 + src/library/scala/Function4.scala | 13 + src/library/scala/Function5.scala | 13 + src/library/scala/Function6.scala | 13 + src/library/scala/Function7.scala | 13 + src/library/scala/Function8.scala | 13 + src/library/scala/Function9.scala | 13 + src/library/scala/Int.cs | 127 ++ src/library/scala/Int.java | 184 ++ src/library/scala/Iterable.scala | 157 ++ src/library/scala/IterableProxy.scala | 97 + src/library/scala/Iterator.scala | 429 ++++ src/library/scala/List.scala | 919 +++++++++ src/library/scala/Long.cs | 108 + src/library/scala/Long.java | 181 ++ src/library/scala/MatchError.scala | 40 + src/library/scala/None.scala | 18 + src/library/scala/Option.scala | 70 + src/library/scala/Ordered.scala | 35 + src/library/scala/PartialFunction.scala | 29 + src/library/scala/PartiallyOrdered.scala | 49 + src/library/scala/Predef.scala | 359 ++++ src/library/scala/Proxy.scala | 26 + src/library/scala/Ref.cs | 31 + src/library/scala/Ref.java | 27 + src/library/scala/ScalaObject.scala | 20 + src/library/scala/Seq.scala | 194 ++ src/library/scala/SeqProxy.scala | 91 + src/library/scala/SerialVersionUID.scala | 12 + src/library/scala/Short.cs | 129 ++ src/library/scala/Short.java | 186 ++ src/library/scala/Some.scala | 19 + src/library/scala/Stream.scala | 243 +++ src/library/scala/Symbol.scala | 30 + src/library/scala/Tuple1.scala | 13 + src/library/scala/Tuple2.scala | 13 + src/library/scala/Tuple3.scala | 13 + src/library/scala/Tuple4.scala | 13 + src/library/scala/Tuple5.scala | 13 + src/library/scala/Tuple6.scala | 13 + src/library/scala/Tuple7.scala | 13 + src/library/scala/Tuple8.scala | 13 + src/library/scala/Tuple9.scala | 13 + src/library/scala/Unit.cs | 45 + src/library/scala/Unit.java | 37 + src/library/scala/_trait_.scala | 18 + src/library/scala/cloneable.scala | 12 + src/library/scala/collection/BitSet.scala | 82 + src/library/scala/collection/Map.scala | 180 ++ src/library/scala/collection/MapProxy.scala | 43 + src/library/scala/collection/Set.scala | 89 + src/library/scala/collection/SetProxy.scala | 37 + .../scala/collection/immutable/BitSet.scala | 117 ++ .../scala/collection/immutable/ListMap.scala | 150 ++ .../scala/collection/immutable/ListSet.scala | 118 ++ src/library/scala/collection/immutable/Map.scala | 144 ++ src/library/scala/collection/immutable/Queue.scala | 173 ++ src/library/scala/collection/immutable/Set.scala | 81 + src/library/scala/collection/immutable/Stack.scala | 139 ++ src/library/scala/collection/immutable/Tree.scala | 374 ++++ .../scala/collection/immutable/TreeMap.scala | 107 + .../scala/collection/immutable/TreeSet.scala | 69 + .../scala/collection/mutable/ArrayBuffer.scala | 148 ++ src/library/scala/collection/mutable/BitSet.scala | 87 + src/library/scala/collection/mutable/Buffer.scala | 214 ++ .../scala/collection/mutable/BufferProxy.scala | 147 ++ .../scala/collection/mutable/DefaultMapModel.scala | 52 + .../collection/mutable/DoubleLinkedList.scala | 49 + src/library/scala/collection/mutable/HashMap.scala | 36 + src/library/scala/collection/mutable/HashSet.scala | 49 + .../scala/collection/mutable/HashTable.scala | 148 ++ src/library/scala/collection/mutable/History.scala | 42 + .../collection/mutable/ImmutableMapAdaptor.scala | 64 + .../collection/mutable/ImmutableSetAdaptor.scala | 50 + .../scala/collection/mutable/JavaMapAdaptor.scala | 66 + .../scala/collection/mutable/JavaSetAdaptor.scala | 44 + .../scala/collection/mutable/LinkedList.scala | 34 + .../scala/collection/mutable/ListBuffer.scala | 143 ++ .../scala/collection/mutable/Location.scala | 27 + src/library/scala/collection/mutable/Map.scala | 169 ++ .../scala/collection/mutable/MapProxy.scala | 53 + src/library/scala/collection/mutable/Message.scala | 77 + .../scala/collection/mutable/MultiMap.scala | 38 + .../scala/collection/mutable/MutableList.scala | 77 + .../collection/mutable/ObservableBuffer.scala | 74 + .../scala/collection/mutable/ObservableMap.scala | 48 + .../scala/collection/mutable/ObservableSet.scala | 39 + .../scala/collection/mutable/PriorityQueue.scala | 180 ++ .../collection/mutable/PriorityQueueProxy.scala | 94 + .../scala/collection/mutable/Publisher.scala | 45 + src/library/scala/collection/mutable/Queue.scala | 194 ++ .../scala/collection/mutable/QueueProxy.scala | 97 + .../scala/collection/mutable/ResizableArray.scala | 64 + .../collection/mutable/RevertableHistory.scala | 31 + .../scala/collection/mutable/Scriptable.scala | 24 + src/library/scala/collection/mutable/Set.scala | 111 ++ .../scala/collection/mutable/SetProxy.scala | 51 + .../collection/mutable/SingleLinkedList.scala | 63 + src/library/scala/collection/mutable/Stack.scala | 132 ++ .../scala/collection/mutable/StackProxy.scala | 108 + .../scala/collection/mutable/Subscriber.scala | 22 + .../collection/mutable/SynchronizedBuffer.scala | 189 ++ .../scala/collection/mutable/SynchronizedMap.scala | 116 ++ .../mutable/SynchronizedPriorityQueue.scala | 97 + .../collection/mutable/SynchronizedQueue.scala | 93 + .../scala/collection/mutable/SynchronizedSet.scala | 104 + .../collection/mutable/SynchronizedStack.scala | 109 ++ .../scala/collection/mutable/Undoable.scala | 24 + src/library/scala/concurrent/Actor.scala | 29 + src/library/scala/concurrent/Channel.scala | 37 + src/library/scala/concurrent/Lock.scala | 22 + src/library/scala/concurrent/MailBox.scala | 170 ++ src/library/scala/concurrent/NameServer.scala | 35 + src/library/scala/concurrent/Process.scala | 78 + src/library/scala/concurrent/SyncChannel.scala | 38 + src/library/scala/concurrent/SyncVar.scala | 37 + src/library/scala/concurrent/TIMEOUT.scala | 12 + src/library/scala/concurrent/jolib.scala | 75 + src/library/scala/concurrent/ops.scala | 52 + src/library/scala/concurrent/pilib.scala | 189 ++ src/library/scala/dbc/DataType.scala | 66 + src/library/scala/dbc/Database.scala | 186 ++ src/library/scala/dbc/Syntax.scala | 44 + src/library/scala/dbc/Utilities.scala | 25 + src/library/scala/dbc/Value.scala | 24 + src/library/scala/dbc/Vendor.scala | 38 + .../scala/dbc/datatype/ApproximateNumeric.scala | 53 + src/library/scala/dbc/datatype/Boolean.scala | 27 + src/library/scala/dbc/datatype/Character.scala | 36 + .../scala/dbc/datatype/CharacterLargeObject.scala | 27 + .../scala/dbc/datatype/CharacterString.scala | 20 + .../scala/dbc/datatype/CharacterVarying.scala | 37 + src/library/scala/dbc/datatype/ExactNumeric.scala | 61 + src/library/scala/dbc/datatype/Factory.scala | 246 +++ src/library/scala/dbc/datatype/Numeric.scala | 28 + src/library/scala/dbc/datatype/String.scala | 20 + src/library/scala/dbc/datatype/Unknown.scala | 30 + .../scala/dbc/exception/IncompatibleSchema.scala | 15 + .../scala/dbc/exception/UnsupportedFeature.scala | 12 + src/library/scala/dbc/result/Field.scala | 60 + src/library/scala/dbc/result/FieldMetadata.scala | 32 + src/library/scala/dbc/result/Relation.scala | 68 + src/library/scala/dbc/result/Status.scala | 24 + src/library/scala/dbc/result/Tuple.scala | 38 + src/library/scala/dbc/statement/AccessMode.scala | 22 + .../scala/dbc/statement/DerivedColumn.scala | 32 + src/library/scala/dbc/statement/Expression.scala | 25 + src/library/scala/dbc/statement/Insert.scala | 32 + .../scala/dbc/statement/InsertionData.scala | 37 + .../scala/dbc/statement/IsolationLevel.scala | 28 + src/library/scala/dbc/statement/JoinType.scala | 45 + src/library/scala/dbc/statement/Jointure.scala | 43 + src/library/scala/dbc/statement/Relation.scala | 51 + src/library/scala/dbc/statement/Select.scala | 91 + src/library/scala/dbc/statement/SetClause.scala | 18 + .../scala/dbc/statement/SetQuantifier.scala | 30 + src/library/scala/dbc/statement/Statement.scala | 14 + src/library/scala/dbc/statement/Status.scala | 26 + src/library/scala/dbc/statement/Table.scala | 36 + src/library/scala/dbc/statement/Transaction.scala | 51 + src/library/scala/dbc/statement/Update.scala | 43 + .../scala/dbc/statement/expression/Aggregate.scala | 30 + .../dbc/statement/expression/BinaryOperator.scala | 28 + .../scala/dbc/statement/expression/Constant.scala | 18 + .../scala/dbc/statement/expression/Default.scala | 17 + .../scala/dbc/statement/expression/Field.scala | 35 + .../dbc/statement/expression/FunctionCall.scala | 28 + .../scala/dbc/statement/expression/Select.scala | 23 + .../dbc/statement/expression/SetFunction.scala | 35 + .../scala/dbc/statement/expression/TypeCast.scala | 27 + .../dbc/statement/expression/UnaryOperator.scala | 28 + src/library/scala/dbc/syntax/DataTypeUtil.scala | 94 + src/library/scala/dbc/syntax/Database.scala | 29 + src/library/scala/dbc/syntax/Statement.scala | 270 +++ .../scala/dbc/syntax/StatementExpression.scala | 217 +++ .../scala/dbc/value/ApproximateNumeric.scala | 24 + src/library/scala/dbc/value/Boolean.scala | 23 + src/library/scala/dbc/value/Character.scala | 31 + .../scala/dbc/value/CharacterLargeObject.scala | 31 + src/library/scala/dbc/value/CharacterVarying.scala | 31 + src/library/scala/dbc/value/Conversion.scala | 153 ++ src/library/scala/dbc/value/ExactNumeric.scala | 31 + src/library/scala/dbc/value/Factory.scala | 91 + src/library/scala/dbc/value/Unknown.scala | 23 + src/library/scala/dbc/vendor/PostgreSQL.scala | 23 + src/library/scala/io/Position.scala | 92 + src/library/scala/io/Source.scala | 252 +++ src/library/scala/mobile/Code.scala | 234 +++ src/library/scala/mobile/Location.scala | 96 + src/library/scala/reflect/Code.scala | 21 + src/library/scala/reflect/Print.scala | 113 ++ src/library/scala/reflect/Symbol.scala | 51 + src/library/scala/reflect/Type.scala | 44 + src/library/scala/reflect/TypedCode.scala | 13 + src/library/scala/remote.scala | 12 + src/library/scala/runtime/AtomicReference.java | 54 + src/library/scala/runtime/BooleanRef.java | 16 + src/library/scala/runtime/BoxedAnyArray.scala | 154 ++ src/library/scala/runtime/BoxedArray.scala | 45 + src/library/scala/runtime/BoxedBoolean.java | 49 + src/library/scala/runtime/BoxedBooleanArray.scala | 33 + src/library/scala/runtime/BoxedByte.java | 58 + src/library/scala/runtime/BoxedByteArray.scala | 33 + src/library/scala/runtime/BoxedChar.java | 59 + src/library/scala/runtime/BoxedCharArray.scala | 33 + src/library/scala/runtime/BoxedDouble.java | 50 + src/library/scala/runtime/BoxedDoubleArray.scala | 33 + src/library/scala/runtime/BoxedFloat.java | 49 + src/library/scala/runtime/BoxedFloatArray.scala | 33 + src/library/scala/runtime/BoxedInt.java | 59 + src/library/scala/runtime/BoxedIntArray.scala | 33 + src/library/scala/runtime/BoxedLong.java | 50 + src/library/scala/runtime/BoxedLongArray.scala | 33 + src/library/scala/runtime/BoxedNumber.java | 21 + src/library/scala/runtime/BoxedObjectArray.scala | 29 + src/library/scala/runtime/BoxedShort.java | 59 + src/library/scala/runtime/BoxedShortArray.scala | 33 + src/library/scala/runtime/BoxedUnit.java | 37 + src/library/scala/runtime/ByteRef.java | 16 + src/library/scala/runtime/CharRef.java | 16 + src/library/scala/runtime/DoubleRef.java | 16 + src/library/scala/runtime/ExceptionHandling.cs | 33 + src/library/scala/runtime/ExceptionHandling.java | 24 + src/library/scala/runtime/FNV_Hash.java | 51 + src/library/scala/runtime/FloatRef.java | 16 + src/library/scala/runtime/IOMap.java | 171 ++ src/library/scala/runtime/IntRef.java | 16 + src/library/scala/runtime/InterpreterSupport.java | 108 + src/library/scala/runtime/LongRef.java | 16 + src/library/scala/runtime/MetaAttribute.cs | 34 + src/library/scala/runtime/ObjectRef.java | 16 + src/library/scala/runtime/ScalaRunTime.scala | 90 + src/library/scala/runtime/ShortRef.java | 16 + src/library/scala/runtime/SymtabAttribute.cs | 40 + src/library/scala/runtime/compat/Math.scala | 36 + src/library/scala/runtime/compat/Platform.scala | 35 + .../scala/runtime/compat/StringBuilder.scala | 26 + src/library/scala/runtime/matching/Address.scala | 30 + src/library/scala/runtime/matching/NonTerm.scala | 52 + .../scala/runtime/matching/PatternTests.scala | 5 + src/library/scala/runtime/matching/Rule.scala | 102 + .../scala/runtime/matching/TestAlphabet.scala | 9 + src/library/scala/serializable.scala | 12 + src/library/scala/testing/Benchmark.scala | 74 + src/library/scala/testing/SUnit.scala | 188 ++ src/library/scala/testing/UnitTest.scala | 58 + src/library/scala/text/Document.scala | 119 ++ src/library/scala/transient.scala | 12 + .../scala/util/automata/BaseBerrySethi.scala | 180 ++ src/library/scala/util/automata/DetWordAutom.scala | 56 + src/library/scala/util/automata/Inclusion.scala | 54 + .../scala/util/automata/NondetWordAutom.scala | 101 + .../scala/util/automata/SubsetConstruction.scala | 143 ++ .../scala/util/automata/WordBerrySethi.scala | 275 +++ src/library/scala/util/grammar/HedgeRHS.scala | 12 + src/library/scala/util/grammar/TreeRHS.scala | 9 + src/library/scala/util/logging/ConsoleLogger.scala | 12 + src/library/scala/util/logging/Logged.scala | 23 + .../util/parsing/CharInputStreamIterator.scala | 35 + src/library/scala/util/parsing/Parsers.scala | 68 + .../scala/util/parsing/SimpleTokenizer.scala | 46 + src/library/scala/util/regexp/Base.scala | 63 + .../scala/util/regexp/PointedHedgeExp.scala | 25 + src/library/scala/util/regexp/SyntaxError.scala | 6 + src/library/scala/util/regexp/WordExp.scala | 24 + src/library/scala/volatile.scala | 12 + src/library/scala/xml/Atom.scala | 41 + src/library/scala/xml/Comment.scala | 45 + src/library/scala/xml/Document.scala | 84 + src/library/scala/xml/Elem.scala | 74 + src/library/scala/xml/EntityRef.scala | 40 + .../scala/xml/MalformedAttributeException.scala | 3 + src/library/scala/xml/MetaData.scala | 159 ++ src/library/scala/xml/Molecule.scala | 39 + src/library/scala/xml/NamespaceBinding.scala | 70 + src/library/scala/xml/Node.scala | 145 ++ src/library/scala/xml/NodeBuffer.scala | 55 + src/library/scala/xml/NodeSeq.scala | 104 + src/library/scala/xml/NodeTraverser.scala | 30 + src/library/scala/xml/Null.scala | 75 + src/library/scala/xml/Parsing.scala | 102 + src/library/scala/xml/PrefixedAttribute.scala | 87 + src/library/scala/xml/PrettyPrinter.scala | 274 +++ src/library/scala/xml/ProcInstr.scala | 63 + src/library/scala/xml/SpecialNode.scala | 31 + src/library/scala/xml/Text.scala | 32 + src/library/scala/xml/TextBuffer.scala | 55 + src/library/scala/xml/TopScope.scala | 28 + src/library/scala/xml/TypeSymbol.scala | 11 + src/library/scala/xml/UnprefixedAttribute.scala | 70 + src/library/scala/xml/Utility.scala | 244 +++ src/library/scala/xml/XML.scala | 75 + src/library/scala/xml/dtd/ContentModel.scala | 200 ++ src/library/scala/xml/dtd/ContentModelParser.scala | 144 ++ src/library/scala/xml/dtd/DTD.scala | 48 + src/library/scala/xml/dtd/Decl.scala | 182 ++ src/library/scala/xml/dtd/DocType.scala | 44 + src/library/scala/xml/dtd/DtdTypeSymbol.scala | 1 + src/library/scala/xml/dtd/ElementValidator.scala | 166 ++ src/library/scala/xml/dtd/ExternalID.scala | 94 + src/library/scala/xml/dtd/Scanner.scala | 87 + src/library/scala/xml/dtd/Tokens.scala | 32 + .../scala/xml/dtd/ValidationException.scala | 33 + src/library/scala/xml/factory/Binder.scala | 43 + .../scala/xml/factory/LoggedNodeFactory.scala | 78 + src/library/scala/xml/factory/NodeFactory.scala | 77 + .../scala/xml/parsing/ConstructingHandler.scala | 24 + .../scala/xml/parsing/ConstructingParser.scala | 61 + .../scala/xml/parsing/DefaultMarkupHandler.scala | 16 + .../scala/xml/parsing/ExternalSources.scala | 76 + src/library/scala/xml/parsing/FactoryAdapter.scala | 344 ++++ src/library/scala/xml/parsing/FatalError.scala | 3 + src/library/scala/xml/parsing/MarkupHandler.scala | 148 ++ src/library/scala/xml/parsing/MarkupParser.scala | 1223 ++++++++++++ .../xml/parsing/NoBindingFactoryAdapter.scala | 53 + src/library/scala/xml/parsing/TokenTests.scala | 145 ++ .../xml/parsing/ValidatingMarkupHandler.scala | 104 + src/library/scala/xml/path/Expression.scala | 54 + .../scala/xml/transform/BasicTransformer.scala | 124 ++ src/library/scala/xml/transform/RewriteRule.scala | 13 + .../scala/xml/transform/RuleTransformer.scala | 14 + src/library/scala/xml/xsd/ContentModel.scala | 39 + src/library/scala/xml/xsd/Decl.scala | 26 + src/library/scala/xml/xsd/XsTypeSymbol.scala | 38 + src/msil-library/AssemblyInfo.cs.tmpl | 58 + src/msil-library/scala/runtime/compat/Math.scala | 36 + .../scala/runtime/compat/Platform.scala | 38 + .../scala/runtime/compat/StringBuilder.scala | 22 + 1092 files changed, 66547 insertions(+), 70844 deletions(-) create mode 100644 README delete mode 100644 VERSION delete mode 100644 build.readme delete mode 100644 config/build.TEMPLATE.properties delete mode 100644 config/build.base.properties delete mode 100644 config/build.default.properties delete mode 100644 config/excludes/nsc.nslib.excludes delete mode 100644 config/excludes/nsc.nstools.excludes delete mode 100644 config/excludes/nsc.osc-nstools.excludes delete mode 100644 config/izpack/images/Splash.png delete mode 100644 config/izpack/images/install.png delete mode 100644 config/izpack/install-nsc.xml delete mode 100644 config/izpack/izpack_process.xml delete mode 100644 config/izpack/izpack_scala.xml delete mode 100644 config/izpack/izpack_shortcut.xml delete mode 100644 config/izpack/locales/INFO_de.html delete mode 100644 config/izpack/locales/INFO_en.html delete mode 100644 config/izpack/locales/INFO_fr.html delete mode 100644 config/izpack/locales/LICENSE_de.html delete mode 100644 config/izpack/locales/LICENSE_en.html delete mode 100644 config/izpack/locales/LICENSE_fr.html delete mode 100644 config/izpack/registry/bin/ICE_JNIRegistry.dll delete mode 100644 config/izpack/registry/bin/readme.txt delete mode 100644 config/izpack/registry/bin/registry.jar.desired.sha1 delete mode 100644 config/izpack/registry/bin/setenv.jar.desired.sha1 delete mode 100644 config/izpack/registry/src/MANIFEST.MF delete mode 100644 config/izpack/registry/src/Main.java delete mode 100644 config/izpack/targets/path_macosx.txt delete mode 100644 config/izpack/targets/path_unix.txt create mode 100644 lib/fjbg.jar.desired.sha1 create mode 100644 lib/jaco.jar.desired.sha1 create mode 100644 lib/msil.jar.desired.sha1 create mode 100644 lib/scala-compiler.jar.desired.sha1 create mode 100644 lib/scala-library.jar.desired.sha1 create mode 100644 lib/scala.dll delete mode 100644 newsources/scala/Array.scala delete mode 100644 newsources/scala/CaseClass.scala delete mode 100644 newsources/scala/MatchError.scala delete mode 100644 newsources/scala/ScalaObject.scala delete mode 100644 sources/bin/izpack.symlink.tmpl delete mode 100644 sources/bin/nscala-tool.win.tmpl delete mode 100644 sources/bin/nscala.unix.tmpl delete mode 100644 sources/bin/nscala.win.tmpl delete mode 100644 sources/msil/AssemblyInfo.cs.tmpl delete mode 100644 sources/msil/scala/runtime/compat/Math.scala delete mode 100644 sources/msil/scala/runtime/compat/Platform.scala delete mode 100644 sources/msil/scala/runtime/compat/StringBuilder.scala delete mode 100644 sources/msil/scala_part2.il.diff.tmpl delete mode 100644 sources/scala/All$.java delete mode 100644 sources/scala/AllRef$.java delete mode 100644 sources/scala/AnyVal.cs delete mode 100644 sources/scala/AnyVal.java delete mode 100644 sources/scala/Application.scala delete mode 100644 sources/scala/Array.cs delete mode 100644 sources/scala/Array.java delete mode 100644 sources/scala/Attribute.scala delete mode 100644 sources/scala/Boolean.cs delete mode 100644 sources/scala/Boolean.java delete mode 100644 sources/scala/BufferedIterator.scala delete mode 100644 sources/scala/Byte.cs delete mode 100644 sources/scala/Byte.java delete mode 100644 sources/scala/CaseClass.scala delete mode 100644 sources/scala/Cell.scala delete mode 100644 sources/scala/Char.cs delete mode 100644 sources/scala/Char.java delete mode 100644 sources/scala/Console.scala delete mode 100644 sources/scala/Double.cs delete mode 100644 sources/scala/Double.java delete mode 100644 sources/scala/Enumeration.scala delete mode 100644 sources/scala/Float.cs delete mode 100644 sources/scala/Float.java delete mode 100644 sources/scala/Function0.scala delete mode 100644 sources/scala/Function1.scala delete mode 100644 sources/scala/Function2.scala delete mode 100644 sources/scala/Function3.scala delete mode 100644 sources/scala/Function4.scala delete mode 100644 sources/scala/Function5.scala delete mode 100644 sources/scala/Function6.scala delete mode 100644 sources/scala/Function7.scala delete mode 100644 sources/scala/Function8.scala delete mode 100644 sources/scala/Function9.scala delete mode 100644 sources/scala/Int.cs delete mode 100644 sources/scala/Int.java delete mode 100644 sources/scala/Iterable.scala delete mode 100644 sources/scala/IterableProxy.scala delete mode 100644 sources/scala/Iterator.scala delete mode 100644 sources/scala/List.scala delete mode 100644 sources/scala/Long.cs delete mode 100644 sources/scala/Long.java delete mode 100644 sources/scala/MatchError.cs delete mode 100644 sources/scala/MatchError.java delete mode 100644 sources/scala/None.scala delete mode 100644 sources/scala/Option.scala delete mode 100644 sources/scala/Ordered.scala delete mode 100644 sources/scala/PartialFunction.scala delete mode 100644 sources/scala/PartiallyOrdered.scala delete mode 100644 sources/scala/Predef.scala delete mode 100644 sources/scala/Proxy.scala delete mode 100644 sources/scala/Ref.cs delete mode 100644 sources/scala/Ref.java delete mode 100644 sources/scala/ScalaObject.cs delete mode 100644 sources/scala/ScalaObject.java delete mode 100644 sources/scala/Seq.scala delete mode 100644 sources/scala/SeqProxy.scala delete mode 100644 sources/scala/SerialVersionUID.scala delete mode 100644 sources/scala/Short.cs delete mode 100644 sources/scala/Short.java delete mode 100644 sources/scala/Some.scala delete mode 100644 sources/scala/Stream.scala delete mode 100644 sources/scala/Symbol.scala delete mode 100644 sources/scala/Tuple1.scala delete mode 100644 sources/scala/Tuple2.scala delete mode 100644 sources/scala/Tuple3.scala delete mode 100644 sources/scala/Tuple4.scala delete mode 100644 sources/scala/Tuple5.scala delete mode 100644 sources/scala/Tuple6.scala delete mode 100644 sources/scala/Tuple7.scala delete mode 100644 sources/scala/Tuple8.scala delete mode 100644 sources/scala/Tuple9.scala delete mode 100644 sources/scala/Type.java delete mode 100644 sources/scala/Unit.cs delete mode 100644 sources/scala/Unit.java delete mode 100644 sources/scala/_trait_.scala delete mode 100644 sources/scala/cloneable.scala delete mode 100644 sources/scala/collection/BitSet.scala delete mode 100644 sources/scala/collection/Map.scala delete mode 100644 sources/scala/collection/MapProxy.scala delete mode 100644 sources/scala/collection/Set.scala delete mode 100644 sources/scala/collection/SetProxy.scala delete mode 100644 sources/scala/collection/immutable/BitSet.scala delete mode 100644 sources/scala/collection/immutable/ListMap.scala delete mode 100644 sources/scala/collection/immutable/ListSet.scala delete mode 100644 sources/scala/collection/immutable/Map.scala delete mode 100644 sources/scala/collection/immutable/Queue.scala delete mode 100644 sources/scala/collection/immutable/Set.scala delete mode 100644 sources/scala/collection/immutable/Stack.scala delete mode 100644 sources/scala/collection/immutable/Tree.scala delete mode 100644 sources/scala/collection/immutable/TreeMap.scala delete mode 100644 sources/scala/collection/immutable/TreeSet.scala delete mode 100644 sources/scala/collection/mutable/ArrayBuffer.scala delete mode 100644 sources/scala/collection/mutable/BitSet.scala delete mode 100644 sources/scala/collection/mutable/Buffer.scala delete mode 100644 sources/scala/collection/mutable/BufferProxy.scala delete mode 100644 sources/scala/collection/mutable/DefaultMapModel.scala delete mode 100644 sources/scala/collection/mutable/DoubleLinkedList.scala delete mode 100644 sources/scala/collection/mutable/HashMap.scala delete mode 100644 sources/scala/collection/mutable/HashSet.scala delete mode 100644 sources/scala/collection/mutable/HashTable.scala delete mode 100644 sources/scala/collection/mutable/History.scala delete mode 100644 sources/scala/collection/mutable/ImmutableMapAdaptor.scala delete mode 100644 sources/scala/collection/mutable/ImmutableSetAdaptor.scala delete mode 100644 sources/scala/collection/mutable/JavaMapAdaptor.scala delete mode 100644 sources/scala/collection/mutable/JavaSetAdaptor.scala delete mode 100644 sources/scala/collection/mutable/LinkedList.scala delete mode 100644 sources/scala/collection/mutable/ListBuffer.scala delete mode 100644 sources/scala/collection/mutable/Location.scala delete mode 100644 sources/scala/collection/mutable/Map.scala delete mode 100644 sources/scala/collection/mutable/MapProxy.scala delete mode 100644 sources/scala/collection/mutable/Message.scala delete mode 100644 sources/scala/collection/mutable/MultiMap.scala delete mode 100644 sources/scala/collection/mutable/MutableList.scala delete mode 100644 sources/scala/collection/mutable/ObservableBuffer.scala delete mode 100644 sources/scala/collection/mutable/ObservableMap.scala delete mode 100644 sources/scala/collection/mutable/ObservableSet.scala delete mode 100644 sources/scala/collection/mutable/PriorityQueue.scala delete mode 100644 sources/scala/collection/mutable/PriorityQueueProxy.scala delete mode 100644 sources/scala/collection/mutable/Publisher.scala delete mode 100644 sources/scala/collection/mutable/Queue.scala delete mode 100644 sources/scala/collection/mutable/QueueProxy.scala delete mode 100644 sources/scala/collection/mutable/ResizableArray.scala delete mode 100644 sources/scala/collection/mutable/RevertableHistory.scala delete mode 100644 sources/scala/collection/mutable/Scriptable.scala delete mode 100644 sources/scala/collection/mutable/Set.scala delete mode 100644 sources/scala/collection/mutable/SetProxy.scala delete mode 100644 sources/scala/collection/mutable/SingleLinkedList.scala delete mode 100644 sources/scala/collection/mutable/Stack.scala delete mode 100644 sources/scala/collection/mutable/StackProxy.scala delete mode 100644 sources/scala/collection/mutable/Subscriber.scala delete mode 100644 sources/scala/collection/mutable/SynchronizedBuffer.scala delete mode 100644 sources/scala/collection/mutable/SynchronizedMap.scala delete mode 100644 sources/scala/collection/mutable/SynchronizedPriorityQueue.scala delete mode 100644 sources/scala/collection/mutable/SynchronizedQueue.scala delete mode 100644 sources/scala/collection/mutable/SynchronizedSet.scala delete mode 100644 sources/scala/collection/mutable/SynchronizedStack.scala delete mode 100644 sources/scala/collection/mutable/Undoable.scala delete mode 100644 sources/scala/concurrent/Actor.scala delete mode 100644 sources/scala/concurrent/Channel.scala delete mode 100644 sources/scala/concurrent/Lock.scala delete mode 100644 sources/scala/concurrent/MailBox.scala delete mode 100644 sources/scala/concurrent/NameServer.scala delete mode 100644 sources/scala/concurrent/Process.scala delete mode 100644 sources/scala/concurrent/SyncChannel.scala delete mode 100644 sources/scala/concurrent/SyncVar.scala delete mode 100644 sources/scala/concurrent/TIMEOUT.scala delete mode 100644 sources/scala/concurrent/jolib.scala delete mode 100644 sources/scala/concurrent/ops.scala delete mode 100644 sources/scala/concurrent/pilib.scala delete mode 100644 sources/scala/dbc/DataType.scala delete mode 100644 sources/scala/dbc/Database.scala delete mode 100644 sources/scala/dbc/Syntax.scala delete mode 100644 sources/scala/dbc/Utilities.scala delete mode 100644 sources/scala/dbc/Value.scala delete mode 100644 sources/scala/dbc/Vendor.scala delete mode 100644 sources/scala/dbc/datatype/ApproximateNumeric.scala delete mode 100644 sources/scala/dbc/datatype/Boolean.scala delete mode 100644 sources/scala/dbc/datatype/Character.scala delete mode 100644 sources/scala/dbc/datatype/CharacterLargeObject.scala delete mode 100644 sources/scala/dbc/datatype/CharacterString.scala delete mode 100644 sources/scala/dbc/datatype/CharacterVarying.scala delete mode 100644 sources/scala/dbc/datatype/ExactNumeric.scala delete mode 100644 sources/scala/dbc/datatype/Factory.scala delete mode 100644 sources/scala/dbc/datatype/Numeric.scala delete mode 100644 sources/scala/dbc/datatype/String.scala delete mode 100644 sources/scala/dbc/datatype/Unknown.scala delete mode 100644 sources/scala/dbc/exception/IncompatibleSchema.scala delete mode 100644 sources/scala/dbc/exception/UnsupportedFeature.scala delete mode 100644 sources/scala/dbc/result/Field.scala delete mode 100644 sources/scala/dbc/result/FieldMetadata.scala delete mode 100644 sources/scala/dbc/result/Relation.scala delete mode 100644 sources/scala/dbc/result/Status.scala delete mode 100644 sources/scala/dbc/result/Tuple.scala delete mode 100644 sources/scala/dbc/statement/AccessMode.scala delete mode 100644 sources/scala/dbc/statement/DerivedColumn.scala delete mode 100644 sources/scala/dbc/statement/Expression.scala delete mode 100644 sources/scala/dbc/statement/Insert.scala delete mode 100644 sources/scala/dbc/statement/InsertionData.scala delete mode 100644 sources/scala/dbc/statement/IsolationLevel.scala delete mode 100644 sources/scala/dbc/statement/JoinType.scala delete mode 100644 sources/scala/dbc/statement/Jointure.scala delete mode 100644 sources/scala/dbc/statement/Relation.scala delete mode 100644 sources/scala/dbc/statement/Select.scala delete mode 100644 sources/scala/dbc/statement/SetClause.scala delete mode 100644 sources/scala/dbc/statement/SetQuantifier.scala delete mode 100644 sources/scala/dbc/statement/Statement.scala delete mode 100644 sources/scala/dbc/statement/Status.scala delete mode 100644 sources/scala/dbc/statement/Table.scala delete mode 100644 sources/scala/dbc/statement/Transaction.scala delete mode 100644 sources/scala/dbc/statement/Update.scala delete mode 100644 sources/scala/dbc/statement/expression/Aggregate.scala delete mode 100644 sources/scala/dbc/statement/expression/BinaryOperator.scala delete mode 100644 sources/scala/dbc/statement/expression/Constant.scala delete mode 100644 sources/scala/dbc/statement/expression/Default.scala delete mode 100644 sources/scala/dbc/statement/expression/Field.scala delete mode 100644 sources/scala/dbc/statement/expression/FunctionCall.scala delete mode 100644 sources/scala/dbc/statement/expression/Select.scala delete mode 100644 sources/scala/dbc/statement/expression/SetFunction.scala delete mode 100644 sources/scala/dbc/statement/expression/TypeCast.scala delete mode 100644 sources/scala/dbc/statement/expression/UnaryOperator.scala delete mode 100644 sources/scala/dbc/syntax/DataTypeUtil.scala delete mode 100644 sources/scala/dbc/syntax/Database.scala delete mode 100644 sources/scala/dbc/syntax/Statement.scala delete mode 100644 sources/scala/dbc/syntax/StatementExpression.scala delete mode 100644 sources/scala/dbc/value/ApproximateNumeric.scala delete mode 100644 sources/scala/dbc/value/Boolean.scala delete mode 100644 sources/scala/dbc/value/Character.scala delete mode 100644 sources/scala/dbc/value/CharacterLargeObject.scala delete mode 100644 sources/scala/dbc/value/CharacterVarying.scala delete mode 100644 sources/scala/dbc/value/Conversion.scala delete mode 100644 sources/scala/dbc/value/ExactNumeric.scala delete mode 100644 sources/scala/dbc/value/Factory.scala delete mode 100644 sources/scala/dbc/value/Unknown.scala delete mode 100644 sources/scala/dbc/vendor/PostgreSQL.scala delete mode 100644 sources/scala/io/Position.scala delete mode 100644 sources/scala/io/Source.scala delete mode 100644 sources/scala/mobile/Code.scala delete mode 100644 sources/scala/mobile/Location.scala delete mode 100644 sources/scala/reflect/Code.scala delete mode 100644 sources/scala/reflect/Print.scala delete mode 100644 sources/scala/reflect/Symbol.scala delete mode 100644 sources/scala/reflect/Type.scala delete mode 100644 sources/scala/reflect/TypedCode.scala delete mode 100644 sources/scala/remote.scala delete mode 100644 sources/scala/runtime/AtomicReference.java delete mode 100644 sources/scala/runtime/BooleanRef.java delete mode 100644 sources/scala/runtime/BoxedAnyArray.scala delete mode 100644 sources/scala/runtime/BoxedArray.scala delete mode 100644 sources/scala/runtime/BoxedBoolean.java delete mode 100644 sources/scala/runtime/BoxedBooleanArray.scala delete mode 100644 sources/scala/runtime/BoxedByte.java delete mode 100644 sources/scala/runtime/BoxedByteArray.scala delete mode 100644 sources/scala/runtime/BoxedChar.java delete mode 100644 sources/scala/runtime/BoxedCharArray.scala delete mode 100644 sources/scala/runtime/BoxedDouble.java delete mode 100644 sources/scala/runtime/BoxedDoubleArray.scala delete mode 100644 sources/scala/runtime/BoxedFloat.java delete mode 100644 sources/scala/runtime/BoxedFloatArray.scala delete mode 100644 sources/scala/runtime/BoxedInt.java delete mode 100644 sources/scala/runtime/BoxedIntArray.scala delete mode 100644 sources/scala/runtime/BoxedLong.java delete mode 100644 sources/scala/runtime/BoxedLongArray.scala delete mode 100644 sources/scala/runtime/BoxedNumber.java delete mode 100644 sources/scala/runtime/BoxedObjectArray.scala delete mode 100644 sources/scala/runtime/BoxedShort.java delete mode 100644 sources/scala/runtime/BoxedShortArray.scala delete mode 100644 sources/scala/runtime/BoxedUnit.java delete mode 100644 sources/scala/runtime/ByteRef.java delete mode 100644 sources/scala/runtime/CharRef.java delete mode 100644 sources/scala/runtime/DoubleRef.java delete mode 100644 sources/scala/runtime/FNV_Hash.java delete mode 100644 sources/scala/runtime/FloatRef.java delete mode 100644 sources/scala/runtime/IOMap.java delete mode 100644 sources/scala/runtime/IntRef.java delete mode 100644 sources/scala/runtime/InterpreterSupport.java delete mode 100644 sources/scala/runtime/LongRef.java delete mode 100644 sources/scala/runtime/MetaAttribute.cs delete mode 100644 sources/scala/runtime/ObjectRef.java delete mode 100644 sources/scala/runtime/RunTime.cs delete mode 100644 sources/scala/runtime/RunTime.java delete mode 100644 sources/scala/runtime/ScalaRunTime.scala delete mode 100644 sources/scala/runtime/ShortRef.java delete mode 100644 sources/scala/runtime/SymtabAttribute.cs delete mode 100644 sources/scala/runtime/compat/Math.scala delete mode 100644 sources/scala/runtime/compat/Platform.scala delete mode 100644 sources/scala/runtime/compat/StringBuilder.scala delete mode 100644 sources/scala/runtime/matching/Address.scala delete mode 100644 sources/scala/runtime/matching/NonTerm.scala delete mode 100644 sources/scala/runtime/matching/PatternTests.scala delete mode 100644 sources/scala/runtime/matching/Rule.scala delete mode 100644 sources/scala/runtime/matching/TestAlphabet.scala delete mode 100644 sources/scala/runtime/types/ClassType.java delete mode 100644 sources/scala/runtime/types/CompoundType.java delete mode 100644 sources/scala/runtime/types/JavaClassType.java delete mode 100644 sources/scala/runtime/types/JavaRefArrayType.java delete mode 100644 sources/scala/runtime/types/LazyParents.java delete mode 100644 sources/scala/runtime/types/ScalaClassType.java delete mode 100644 sources/scala/runtime/types/SingleType.java delete mode 100644 sources/scala/runtime/types/SpecialType.java delete mode 100644 sources/scala/runtime/types/Statistics.java delete mode 100644 sources/scala/runtime/types/TypeAll.java delete mode 100644 sources/scala/runtime/types/TypeAllRef.java delete mode 100644 sources/scala/runtime/types/TypeAny.java delete mode 100644 sources/scala/runtime/types/TypeAnyVal.java delete mode 100644 sources/scala/runtime/types/TypeBoolean.java delete mode 100644 sources/scala/runtime/types/TypeByte.java delete mode 100644 sources/scala/runtime/types/TypeChar.java delete mode 100644 sources/scala/runtime/types/TypeConstructor.java delete mode 100644 sources/scala/runtime/types/TypeDouble.java delete mode 100644 sources/scala/runtime/types/TypeFloat.java delete mode 100644 sources/scala/runtime/types/TypeInt.java delete mode 100644 sources/scala/runtime/types/TypeLong.java delete mode 100644 sources/scala/runtime/types/TypeShort.java delete mode 100644 sources/scala/runtime/types/TypeUnit.java delete mode 100644 sources/scala/runtime/types/ValueType.java delete mode 100644 sources/scala/serializable.scala delete mode 100644 sources/scala/testing/Benchmark.scala delete mode 100644 sources/scala/testing/SUnit.scala delete mode 100644 sources/scala/testing/UnitTest.scala delete mode 100644 sources/scala/text/Document.scala delete mode 100644 sources/scala/tools/nsc/CompilationUnits.scala delete mode 100644 sources/scala/tools/nsc/CompilerCommand.scala delete mode 100644 sources/scala/tools/nsc/CompilerRun.scala delete mode 100644 sources/scala/tools/nsc/EvalLoop.scala delete mode 100644 sources/scala/tools/nsc/FatalError.scala delete mode 100644 sources/scala/tools/nsc/Global.scala delete mode 100644 sources/scala/tools/nsc/Interpreter.scala delete mode 100644 sources/scala/tools/nsc/Main.scala delete mode 100644 sources/scala/tools/nsc/MainInterpreter.scala delete mode 100644 sources/scala/tools/nsc/MainTokenMetric.scala delete mode 100644 sources/scala/tools/nsc/NoPhase.scala delete mode 100644 sources/scala/tools/nsc/Phase.scala delete mode 100644 sources/scala/tools/nsc/Settings.scala delete mode 100644 sources/scala/tools/nsc/SubComponent.scala delete mode 100644 sources/scala/tools/nsc/ant/NSC.scala delete mode 100644 sources/scala/tools/nsc/ast/TreeBrowsers.scala delete mode 100644 sources/scala/tools/nsc/ast/TreeGen.scala delete mode 100644 sources/scala/tools/nsc/ast/TreeInfo.scala delete mode 100644 sources/scala/tools/nsc/ast/TreePrinters.scala delete mode 100644 sources/scala/tools/nsc/ast/Trees.scala delete mode 100644 sources/scala/tools/nsc/ast/parser/MarkupParsers.scala delete mode 100644 sources/scala/tools/nsc/ast/parser/Parsers.scala delete mode 100644 sources/scala/tools/nsc/ast/parser/Scanners.scala delete mode 100644 sources/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala delete mode 100644 sources/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala delete mode 100644 sources/scala/tools/nsc/ast/parser/Tokens.scala delete mode 100644 sources/scala/tools/nsc/ast/parser/TreeBuilder.scala delete mode 100644 sources/scala/tools/nsc/backend/ScalaPrimitives.scala delete mode 100644 sources/scala/tools/nsc/backend/WorklistAlgorithm.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/BasicBlocks.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/CheckerError.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/Checkers.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/ExceptionHandlers.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/GenICode.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/ICodes.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/Linearizers.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/Members.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/Opcodes.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/Primitives.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/Printers.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/TypeKinds.scala delete mode 100644 sources/scala/tools/nsc/backend/icode/TypeStacks.scala delete mode 100644 sources/scala/tools/nsc/backend/jvm/GenJVM.scala delete mode 100644 sources/scala/tools/nsc/matching/AlgebraicMatchers.scala delete mode 100644 sources/scala/tools/nsc/matching/Autom2.scala delete mode 100644 sources/scala/tools/nsc/matching/BerrySethis.scala delete mode 100644 sources/scala/tools/nsc/matching/CodeFactory.scala delete mode 100644 sources/scala/tools/nsc/matching/DetWordAutoms.scala delete mode 100644 sources/scala/tools/nsc/matching/LeftTracers.scala delete mode 100644 sources/scala/tools/nsc/matching/MatcherLabels.scala delete mode 100644 sources/scala/tools/nsc/matching/NondetWordAutoms.scala delete mode 100644 sources/scala/tools/nsc/matching/Npair.scala delete mode 100644 sources/scala/tools/nsc/matching/PatternMatchers.scala delete mode 100644 sources/scala/tools/nsc/matching/PatternNodeCreator.scala delete mode 100644 sources/scala/tools/nsc/matching/PatternNodes.scala delete mode 100644 sources/scala/tools/nsc/matching/RightTracers.scala delete mode 100644 sources/scala/tools/nsc/matching/SequenceMatchers.scala delete mode 100644 sources/scala/tools/nsc/matching/StateSetComparator.scala delete mode 100644 sources/scala/tools/nsc/matching/TransMatcher.scala delete mode 100644 sources/scala/tools/nsc/matching/WordAutoms.scala delete mode 100644 sources/scala/tools/nsc/models/Models.scala.xxx delete mode 100644 sources/scala/tools/nsc/models/SemanticTokens.scala delete mode 100644 sources/scala/tools/nsc/models/Signatures.scala delete mode 100644 sources/scala/tools/nsc/reporters/AbstractReporter.scala delete mode 100644 sources/scala/tools/nsc/reporters/ConsoleReporter.scala delete mode 100644 sources/scala/tools/nsc/reporters/Reporter.scala delete mode 100644 sources/scala/tools/nsc/reporters/ReporterTimer.scala delete mode 100644 sources/scala/tools/nsc/reporters/StoreReporter.scala delete mode 100644 sources/scala/tools/nsc/symtab/Constants.scala delete mode 100644 sources/scala/tools/nsc/symtab/Definitions.scala delete mode 100644 sources/scala/tools/nsc/symtab/Flags.scala delete mode 100644 sources/scala/tools/nsc/symtab/InfoTransformers.scala delete mode 100644 sources/scala/tools/nsc/symtab/Names.scala delete mode 100644 sources/scala/tools/nsc/symtab/Scopes.scala delete mode 100644 sources/scala/tools/nsc/symtab/StdNames.scala delete mode 100644 sources/scala/tools/nsc/symtab/SymbolLoaders.scala delete mode 100644 sources/scala/tools/nsc/symtab/SymbolTable.scala delete mode 100644 sources/scala/tools/nsc/symtab/Symbols.scala delete mode 100644 sources/scala/tools/nsc/symtab/Types.scala delete mode 100644 sources/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala delete mode 100644 sources/scala/tools/nsc/symtab/classfile/ClassfileParser.scala delete mode 100644 sources/scala/tools/nsc/symtab/classfile/MetaParser.scala delete mode 100644 sources/scala/tools/nsc/symtab/classfile/PickleBuffer.scala delete mode 100644 sources/scala/tools/nsc/symtab/classfile/PickleFormat.scala delete mode 100644 sources/scala/tools/nsc/symtab/classfile/Pickler.scala delete mode 100644 sources/scala/tools/nsc/symtab/classfile/SymblfileParser.scala delete mode 100644 sources/scala/tools/nsc/symtab/classfile/UnPickler.scala delete mode 100644 sources/scala/tools/nsc/transform/AddInterfaces.scala delete mode 100644 sources/scala/tools/nsc/transform/Constructors.scala delete mode 100644 sources/scala/tools/nsc/transform/Erasure.scala delete mode 100644 sources/scala/tools/nsc/transform/ExplicitOuter.scala delete mode 100644 sources/scala/tools/nsc/transform/Flatten.scala delete mode 100644 sources/scala/tools/nsc/transform/InfoTransform.scala delete mode 100644 sources/scala/tools/nsc/transform/LambdaLift.scala delete mode 100644 sources/scala/tools/nsc/transform/Mixin.scala delete mode 100644 sources/scala/tools/nsc/transform/OverridingPairs.scala delete mode 100644 sources/scala/tools/nsc/transform/SampleTransform.scala delete mode 100644 sources/scala/tools/nsc/transform/TailCalls.scala delete mode 100644 sources/scala/tools/nsc/transform/Transform.scala delete mode 100644 sources/scala/tools/nsc/transform/UnCurry.scala delete mode 100644 sources/scala/tools/nsc/typechecker/Analyzer.scala delete mode 100644 sources/scala/tools/nsc/typechecker/Codification.scala delete mode 100644 sources/scala/tools/nsc/typechecker/ConstantFolder.scala delete mode 100644 sources/scala/tools/nsc/typechecker/Contexts.scala delete mode 100644 sources/scala/tools/nsc/typechecker/EtaExpansion.scala delete mode 100644 sources/scala/tools/nsc/typechecker/Infer.scala delete mode 100644 sources/scala/tools/nsc/typechecker/Namers.scala delete mode 100644 sources/scala/tools/nsc/typechecker/RefChecks.scala delete mode 100644 sources/scala/tools/nsc/typechecker/SuperAccessors.scala delete mode 100644 sources/scala/tools/nsc/typechecker/SyntheticMethods.scala delete mode 100644 sources/scala/tools/nsc/typechecker/TreeCheckers.scala delete mode 100644 sources/scala/tools/nsc/typechecker/Typers.scala delete mode 100644 sources/scala/tools/nsc/typechecker/Variances.scala delete mode 100644 sources/scala/tools/nsc/util/CharArrayReader.scala delete mode 100644 sources/scala/tools/nsc/util/FreshNameCreator.scala delete mode 100644 sources/scala/tools/nsc/util/HashSet.scala delete mode 100644 sources/scala/tools/nsc/util/LinkedList.scala delete mode 100644 sources/scala/tools/nsc/util/ListBuffer.scala delete mode 100644 sources/scala/tools/nsc/util/NameTransformer.scala delete mode 100644 sources/scala/tools/nsc/util/Position.scala delete mode 100644 sources/scala/tools/nsc/util/Set.scala delete mode 100644 sources/scala/tools/nsc/util/ShowPickled.scala delete mode 100644 sources/scala/tools/nsc/util/SourceFile.scala delete mode 100644 sources/scala/tools/nsc/util/Statistics.scala delete mode 100644 sources/scala/tools/nsc/util/TreeSet.scala delete mode 100644 sources/scala/tools/util/AbstractFile.java delete mode 100644 sources/scala/tools/util/AbstractFileReader.java delete mode 100644 sources/scala/tools/util/AbstractReporter.java delete mode 100644 sources/scala/tools/util/AbstractTimer.java delete mode 100644 sources/scala/tools/util/ByteArrayFile.java delete mode 100644 sources/scala/tools/util/CharArrayFile.java delete mode 100644 sources/scala/tools/util/ClassPath.java delete mode 100644 sources/scala/tools/util/ConsoleReporter.java delete mode 100644 sources/scala/tools/util/DirectoryPath.java delete mode 100644 sources/scala/tools/util/DummyTimer.java delete mode 100644 sources/scala/tools/util/EmptyIterator.java delete mode 100644 sources/scala/tools/util/PlainFile.java delete mode 100644 sources/scala/tools/util/Position.java delete mode 100644 sources/scala/tools/util/Reporter.java delete mode 100644 sources/scala/tools/util/ReporterTimer.java delete mode 100644 sources/scala/tools/util/SourceFile.java delete mode 100644 sources/scala/tools/util/SourceReader.java delete mode 100644 sources/scala/tools/util/StringBufferWriter.java delete mode 100644 sources/scala/tools/util/Timer.java delete mode 100644 sources/scala/tools/util/UTF8Codec.java delete mode 100644 sources/scala/tools/util/VirtualDirectory.java delete mode 100644 sources/scala/tools/util/VirtualFile.java delete mode 100644 sources/scala/tools/util/ZipArchive.java delete mode 100644 sources/scala/tools/util/debug/AbortError.java delete mode 100644 sources/scala/tools/util/debug/ArrayDebugger.java delete mode 100644 sources/scala/tools/util/debug/Debug.java delete mode 100644 sources/scala/tools/util/debug/Debugger.java delete mode 100644 sources/scala/tools/util/debug/ObjectDebugger.java delete mode 100644 sources/scala/tools/util/debug/ThrowableDebugger.java delete mode 100644 sources/scala/tools/util/debug/ToStringDebugger.java delete mode 100644 sources/scala/transient.scala delete mode 100644 sources/scala/util/automata/BaseBerrySethi.scala delete mode 100644 sources/scala/util/automata/DetWordAutom.scala delete mode 100644 sources/scala/util/automata/Inclusion.scala delete mode 100644 sources/scala/util/automata/NondetWordAutom.scala delete mode 100644 sources/scala/util/automata/SubsetConstruction.scala delete mode 100644 sources/scala/util/automata/WordBerrySethi.scala delete mode 100644 sources/scala/util/grammar/HedgeRHS.scala delete mode 100644 sources/scala/util/grammar/TreeRHS.scala delete mode 100644 sources/scala/util/logging/ConsoleLogger.scala delete mode 100644 sources/scala/util/logging/Logged.scala delete mode 100644 sources/scala/util/parsing/CharInputStreamIterator.scala delete mode 100644 sources/scala/util/parsing/Parsers.scala delete mode 100644 sources/scala/util/parsing/SimpleTokenizer.scala delete mode 100644 sources/scala/util/regexp/Base.scala delete mode 100644 sources/scala/util/regexp/PointedHedgeExp.scala delete mode 100644 sources/scala/util/regexp/SyntaxError.scala delete mode 100644 sources/scala/util/regexp/WordExp.scala delete mode 100644 sources/scala/volatile.scala delete mode 100644 sources/scala/xml/Atom.scala delete mode 100644 sources/scala/xml/Comment.scala delete mode 100644 sources/scala/xml/Document.scala delete mode 100644 sources/scala/xml/Elem.scala delete mode 100644 sources/scala/xml/EntityRef.scala delete mode 100644 sources/scala/xml/MalformedAttributeException.scala delete mode 100644 sources/scala/xml/MetaData.scala delete mode 100644 sources/scala/xml/Molecule.scala delete mode 100644 sources/scala/xml/NamespaceBinding.scala delete mode 100644 sources/scala/xml/Node.scala delete mode 100644 sources/scala/xml/NodeBuffer.scala delete mode 100644 sources/scala/xml/NodeSeq.scala delete mode 100644 sources/scala/xml/NodeTraverser.scala delete mode 100644 sources/scala/xml/Null.scala delete mode 100644 sources/scala/xml/Parsing.scala delete mode 100644 sources/scala/xml/PrefixedAttribute.scala delete mode 100644 sources/scala/xml/PrettyPrinter.scala delete mode 100644 sources/scala/xml/ProcInstr.scala delete mode 100644 sources/scala/xml/SpecialNode.scala delete mode 100644 sources/scala/xml/Text.scala delete mode 100644 sources/scala/xml/TextBuffer.scala delete mode 100644 sources/scala/xml/TopScope.scala delete mode 100644 sources/scala/xml/TypeSymbol.scala delete mode 100644 sources/scala/xml/UnprefixedAttribute.scala delete mode 100644 sources/scala/xml/Utility.scala delete mode 100644 sources/scala/xml/XML.scala delete mode 100644 sources/scala/xml/dtd/ContentModel.scala delete mode 100644 sources/scala/xml/dtd/ContentModelParser.scala delete mode 100644 sources/scala/xml/dtd/DTD.scala delete mode 100644 sources/scala/xml/dtd/Decl.scala delete mode 100644 sources/scala/xml/dtd/DocType.scala delete mode 100644 sources/scala/xml/dtd/DtdTypeSymbol.scala delete mode 100644 sources/scala/xml/dtd/ElementValidator.scala delete mode 100644 sources/scala/xml/dtd/ExternalID.scala delete mode 100644 sources/scala/xml/dtd/Scanner.scala delete mode 100644 sources/scala/xml/dtd/Tokens.scala delete mode 100644 sources/scala/xml/dtd/ValidationException.scala delete mode 100644 sources/scala/xml/factory/Binder.scala delete mode 100644 sources/scala/xml/factory/LoggedNodeFactory.scala delete mode 100644 sources/scala/xml/factory/NodeFactory.scala delete mode 100644 sources/scala/xml/parsing/ConstructingHandler.scala delete mode 100644 sources/scala/xml/parsing/ConstructingParser.scala delete mode 100644 sources/scala/xml/parsing/DefaultMarkupHandler.scala delete mode 100644 sources/scala/xml/parsing/ExternalSources.scala delete mode 100644 sources/scala/xml/parsing/FactoryAdapter.scala delete mode 100644 sources/scala/xml/parsing/FatalError.scala delete mode 100644 sources/scala/xml/parsing/MarkupHandler.scala delete mode 100644 sources/scala/xml/parsing/MarkupParser.scala delete mode 100644 sources/scala/xml/parsing/NoBindingFactoryAdapter.scala delete mode 100644 sources/scala/xml/parsing/TokenTests.scala delete mode 100644 sources/scala/xml/parsing/ValidatingMarkupHandler.scala delete mode 100644 sources/scala/xml/path/Expression.scala delete mode 100644 sources/scala/xml/transform/BasicTransformer.scala delete mode 100644 sources/scala/xml/transform/RewriteRule.scala delete mode 100644 sources/scala/xml/transform/RuleTransformer.scala delete mode 100644 sources/scala/xml/xsd/ContentModel.scala delete mode 100644 sources/scala/xml/xsd/Decl.scala delete mode 100644 sources/scala/xml/xsd/XsTypeSymbol.scala create mode 100644 src/compiler/scala/tools/nsc/CompilationUnits.scala create mode 100644 src/compiler/scala/tools/nsc/CompilerCommand.scala create mode 100644 src/compiler/scala/tools/nsc/CompilerRun.scala create mode 100644 src/compiler/scala/tools/nsc/EvalLoop.scala create mode 100644 src/compiler/scala/tools/nsc/FatalError.scala create mode 100644 src/compiler/scala/tools/nsc/Global.scala create mode 100644 src/compiler/scala/tools/nsc/Interpreter.scala create mode 100644 src/compiler/scala/tools/nsc/Main.scala create mode 100644 src/compiler/scala/tools/nsc/MainInterpreter.scala create mode 100644 src/compiler/scala/tools/nsc/MainTokenMetric.scala create mode 100644 src/compiler/scala/tools/nsc/NoPhase.scala create mode 100644 src/compiler/scala/tools/nsc/Phase.scala create mode 100644 src/compiler/scala/tools/nsc/Settings.scala create mode 100644 src/compiler/scala/tools/nsc/SubComponent.scala create mode 100644 src/compiler/scala/tools/nsc/ant/NSC.scala create mode 100644 src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala create mode 100644 src/compiler/scala/tools/nsc/ast/TreeGen.scala create mode 100644 src/compiler/scala/tools/nsc/ast/TreeInfo.scala create mode 100644 src/compiler/scala/tools/nsc/ast/TreePrinters.scala create mode 100644 src/compiler/scala/tools/nsc/ast/Trees.scala create mode 100644 src/compiler/scala/tools/nsc/ast/parser/MarkupParsers.scala create mode 100644 src/compiler/scala/tools/nsc/ast/parser/Parsers.scala create mode 100644 src/compiler/scala/tools/nsc/ast/parser/Scanners.scala create mode 100644 src/compiler/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala create mode 100644 src/compiler/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala create mode 100644 src/compiler/scala/tools/nsc/ast/parser/Tokens.scala create mode 100644 src/compiler/scala/tools/nsc/ast/parser/TreeBuilder.scala create mode 100644 src/compiler/scala/tools/nsc/backend/ScalaPrimitives.scala create mode 100644 src/compiler/scala/tools/nsc/backend/WorklistAlgorithm.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/BasicBlocks.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/CheckerError.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/Checkers.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/ExceptionHandlers.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/GenICode.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/ICodes.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/Linearizers.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/Members.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/Opcodes.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/Primitives.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/Printers.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/TypeKinds.scala create mode 100644 src/compiler/scala/tools/nsc/backend/icode/TypeStacks.scala create mode 100644 src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala create mode 100644 src/compiler/scala/tools/nsc/matching/AlgebraicMatchers.scala create mode 100644 src/compiler/scala/tools/nsc/matching/Autom2.scala create mode 100644 src/compiler/scala/tools/nsc/matching/BerrySethis.scala create mode 100644 src/compiler/scala/tools/nsc/matching/CodeFactory.scala create mode 100644 src/compiler/scala/tools/nsc/matching/DetWordAutoms.scala create mode 100644 src/compiler/scala/tools/nsc/matching/LeftTracers.scala create mode 100644 src/compiler/scala/tools/nsc/matching/MatcherLabels.scala create mode 100644 src/compiler/scala/tools/nsc/matching/NondetWordAutoms.scala create mode 100644 src/compiler/scala/tools/nsc/matching/Npair.scala create mode 100644 src/compiler/scala/tools/nsc/matching/PatternMatchers.scala create mode 100644 src/compiler/scala/tools/nsc/matching/PatternNodeCreator.scala create mode 100644 src/compiler/scala/tools/nsc/matching/PatternNodes.scala create mode 100644 src/compiler/scala/tools/nsc/matching/RightTracers.scala create mode 100644 src/compiler/scala/tools/nsc/matching/SequenceMatchers.scala create mode 100644 src/compiler/scala/tools/nsc/matching/StateSetComparator.scala create mode 100644 src/compiler/scala/tools/nsc/matching/TransMatcher.scala create mode 100644 src/compiler/scala/tools/nsc/matching/WordAutoms.scala create mode 100644 src/compiler/scala/tools/nsc/models/Models.scala.xxx create mode 100644 src/compiler/scala/tools/nsc/models/SemanticTokens.scala create mode 100644 src/compiler/scala/tools/nsc/models/Signatures.scala create mode 100644 src/compiler/scala/tools/nsc/reporters/AbstractReporter.scala create mode 100644 src/compiler/scala/tools/nsc/reporters/ConsoleReporter.scala create mode 100644 src/compiler/scala/tools/nsc/reporters/Reporter.scala create mode 100644 src/compiler/scala/tools/nsc/reporters/ReporterTimer.scala create mode 100644 src/compiler/scala/tools/nsc/reporters/StoreReporter.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/Constants.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/Definitions.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/Flags.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/InfoTransformers.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/Names.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/Scopes.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/StdNames.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/SymbolLoaders.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/SymbolTable.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/Symbols.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/Types.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/classfile/MetaParser.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/classfile/PickleBuffer.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/classfile/PickleFormat.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/classfile/SymblfileParser.scala create mode 100644 src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala create mode 100644 src/compiler/scala/tools/nsc/transform/AddInterfaces.scala create mode 100644 src/compiler/scala/tools/nsc/transform/Constructors.scala create mode 100644 src/compiler/scala/tools/nsc/transform/Erasure.scala create mode 100644 src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala create mode 100644 src/compiler/scala/tools/nsc/transform/Flatten.scala create mode 100644 src/compiler/scala/tools/nsc/transform/InfoTransform.scala create mode 100644 src/compiler/scala/tools/nsc/transform/LambdaLift.scala create mode 100644 src/compiler/scala/tools/nsc/transform/Mixin.scala create mode 100644 src/compiler/scala/tools/nsc/transform/OverridingPairs.scala create mode 100644 src/compiler/scala/tools/nsc/transform/SampleTransform.scala create mode 100644 src/compiler/scala/tools/nsc/transform/TailCalls.scala create mode 100644 src/compiler/scala/tools/nsc/transform/Transform.scala create mode 100644 src/compiler/scala/tools/nsc/transform/UnCurry.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/Analyzer.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/Codification.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/ConstantFolder.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/Contexts.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/EtaExpansion.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/Infer.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/Namers.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/RefChecks.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/SuperAccessors.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/SyntheticMethods.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/TreeCheckers.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/Typers.scala create mode 100644 src/compiler/scala/tools/nsc/typechecker/Variances.scala create mode 100644 src/compiler/scala/tools/nsc/util/CharArrayReader.scala create mode 100644 src/compiler/scala/tools/nsc/util/FreshNameCreator.scala create mode 100644 src/compiler/scala/tools/nsc/util/HashSet.scala create mode 100644 src/compiler/scala/tools/nsc/util/LinkedList.scala create mode 100644 src/compiler/scala/tools/nsc/util/ListBuffer.scala create mode 100644 src/compiler/scala/tools/nsc/util/NameTransformer.scala create mode 100644 src/compiler/scala/tools/nsc/util/Position.scala create mode 100644 src/compiler/scala/tools/nsc/util/Set.scala create mode 100644 src/compiler/scala/tools/nsc/util/ShowPickled.scala create mode 100644 src/compiler/scala/tools/nsc/util/SourceFile.scala create mode 100644 src/compiler/scala/tools/nsc/util/Statistics.scala create mode 100644 src/compiler/scala/tools/nsc/util/TreeSet.scala create mode 100644 src/compiler/scala/tools/util/AbstractFile.java create mode 100644 src/compiler/scala/tools/util/AbstractFileReader.java create mode 100644 src/compiler/scala/tools/util/AbstractReporter.java create mode 100644 src/compiler/scala/tools/util/AbstractTimer.java create mode 100644 src/compiler/scala/tools/util/ByteArrayFile.java create mode 100644 src/compiler/scala/tools/util/CharArrayFile.java create mode 100644 src/compiler/scala/tools/util/ClassPath.java create mode 100644 src/compiler/scala/tools/util/ConsoleReporter.java create mode 100644 src/compiler/scala/tools/util/DirectoryPath.java create mode 100644 src/compiler/scala/tools/util/DummyTimer.java create mode 100644 src/compiler/scala/tools/util/EmptyIterator.java create mode 100644 src/compiler/scala/tools/util/PlainFile.java create mode 100644 src/compiler/scala/tools/util/Position.java create mode 100644 src/compiler/scala/tools/util/Reporter.java create mode 100644 src/compiler/scala/tools/util/ReporterTimer.java create mode 100644 src/compiler/scala/tools/util/SourceFile.java create mode 100644 src/compiler/scala/tools/util/SourceReader.java create mode 100644 src/compiler/scala/tools/util/StringBufferWriter.java create mode 100644 src/compiler/scala/tools/util/Timer.java create mode 100644 src/compiler/scala/tools/util/UTF8Codec.java create mode 100644 src/compiler/scala/tools/util/VirtualDirectory.java create mode 100644 src/compiler/scala/tools/util/VirtualFile.java create mode 100644 src/compiler/scala/tools/util/ZipArchive.java create mode 100644 src/compiler/scala/tools/util/debug/AbortError.java create mode 100644 src/compiler/scala/tools/util/debug/ArrayDebugger.java create mode 100644 src/compiler/scala/tools/util/debug/Debug.java create mode 100644 src/compiler/scala/tools/util/debug/Debugger.java create mode 100644 src/compiler/scala/tools/util/debug/ObjectDebugger.java create mode 100644 src/compiler/scala/tools/util/debug/ThrowableDebugger.java create mode 100644 src/compiler/scala/tools/util/debug/ToStringDebugger.java create mode 100644 src/exec/nscala-tool.win.tmpl create mode 100644 src/exec/nscala.unix.tmpl create mode 100644 src/exec/nscala.win.tmpl create mode 100644 src/library/scala/All$.java create mode 100644 src/library/scala/AllRef$.java create mode 100644 src/library/scala/AnyVal.cs create mode 100644 src/library/scala/AnyVal.java create mode 100644 src/library/scala/Application.scala create mode 100644 src/library/scala/Array.scala create mode 100644 src/library/scala/Attribute.scala create mode 100644 src/library/scala/Boolean.cs create mode 100644 src/library/scala/Boolean.java create mode 100644 src/library/scala/BufferedIterator.scala create mode 100644 src/library/scala/Byte.cs create mode 100644 src/library/scala/Byte.java create mode 100644 src/library/scala/CaseClass.scala create mode 100644 src/library/scala/Cell.scala create mode 100644 src/library/scala/Char.cs create mode 100644 src/library/scala/Char.java create mode 100644 src/library/scala/Console.scala create mode 100644 src/library/scala/Double.cs create mode 100644 src/library/scala/Double.java create mode 100644 src/library/scala/Enumeration.scala create mode 100644 src/library/scala/Float.cs create mode 100644 src/library/scala/Float.java create mode 100644 src/library/scala/Function0.scala create mode 100644 src/library/scala/Function1.scala create mode 100644 src/library/scala/Function2.scala create mode 100644 src/library/scala/Function3.scala create mode 100644 src/library/scala/Function4.scala create mode 100644 src/library/scala/Function5.scala create mode 100644 src/library/scala/Function6.scala create mode 100644 src/library/scala/Function7.scala create mode 100644 src/library/scala/Function8.scala create mode 100644 src/library/scala/Function9.scala create mode 100644 src/library/scala/Int.cs create mode 100644 src/library/scala/Int.java create mode 100644 src/library/scala/Iterable.scala create mode 100644 src/library/scala/IterableProxy.scala create mode 100644 src/library/scala/Iterator.scala create mode 100644 src/library/scala/List.scala create mode 100644 src/library/scala/Long.cs create mode 100644 src/library/scala/Long.java create mode 100644 src/library/scala/MatchError.scala create mode 100644 src/library/scala/None.scala create mode 100644 src/library/scala/Option.scala create mode 100644 src/library/scala/Ordered.scala create mode 100644 src/library/scala/PartialFunction.scala create mode 100644 src/library/scala/PartiallyOrdered.scala create mode 100644 src/library/scala/Predef.scala create mode 100644 src/library/scala/Proxy.scala create mode 100644 src/library/scala/Ref.cs create mode 100644 src/library/scala/Ref.java create mode 100644 src/library/scala/ScalaObject.scala create mode 100644 src/library/scala/Seq.scala create mode 100644 src/library/scala/SeqProxy.scala create mode 100644 src/library/scala/SerialVersionUID.scala create mode 100644 src/library/scala/Short.cs create mode 100644 src/library/scala/Short.java create mode 100644 src/library/scala/Some.scala create mode 100644 src/library/scala/Stream.scala create mode 100644 src/library/scala/Symbol.scala create mode 100644 src/library/scala/Tuple1.scala create mode 100644 src/library/scala/Tuple2.scala create mode 100644 src/library/scala/Tuple3.scala create mode 100644 src/library/scala/Tuple4.scala create mode 100644 src/library/scala/Tuple5.scala create mode 100644 src/library/scala/Tuple6.scala create mode 100644 src/library/scala/Tuple7.scala create mode 100644 src/library/scala/Tuple8.scala create mode 100644 src/library/scala/Tuple9.scala create mode 100644 src/library/scala/Unit.cs create mode 100644 src/library/scala/Unit.java create mode 100644 src/library/scala/_trait_.scala create mode 100644 src/library/scala/cloneable.scala create mode 100644 src/library/scala/collection/BitSet.scala create mode 100644 src/library/scala/collection/Map.scala create mode 100644 src/library/scala/collection/MapProxy.scala create mode 100644 src/library/scala/collection/Set.scala create mode 100644 src/library/scala/collection/SetProxy.scala create mode 100644 src/library/scala/collection/immutable/BitSet.scala create mode 100644 src/library/scala/collection/immutable/ListMap.scala create mode 100644 src/library/scala/collection/immutable/ListSet.scala create mode 100644 src/library/scala/collection/immutable/Map.scala create mode 100644 src/library/scala/collection/immutable/Queue.scala create mode 100644 src/library/scala/collection/immutable/Set.scala create mode 100644 src/library/scala/collection/immutable/Stack.scala create mode 100644 src/library/scala/collection/immutable/Tree.scala create mode 100644 src/library/scala/collection/immutable/TreeMap.scala create mode 100644 src/library/scala/collection/immutable/TreeSet.scala create mode 100644 src/library/scala/collection/mutable/ArrayBuffer.scala create mode 100644 src/library/scala/collection/mutable/BitSet.scala create mode 100644 src/library/scala/collection/mutable/Buffer.scala create mode 100644 src/library/scala/collection/mutable/BufferProxy.scala create mode 100644 src/library/scala/collection/mutable/DefaultMapModel.scala create mode 100644 src/library/scala/collection/mutable/DoubleLinkedList.scala create mode 100644 src/library/scala/collection/mutable/HashMap.scala create mode 100644 src/library/scala/collection/mutable/HashSet.scala create mode 100644 src/library/scala/collection/mutable/HashTable.scala create mode 100644 src/library/scala/collection/mutable/History.scala create mode 100644 src/library/scala/collection/mutable/ImmutableMapAdaptor.scala create mode 100644 src/library/scala/collection/mutable/ImmutableSetAdaptor.scala create mode 100644 src/library/scala/collection/mutable/JavaMapAdaptor.scala create mode 100644 src/library/scala/collection/mutable/JavaSetAdaptor.scala create mode 100644 src/library/scala/collection/mutable/LinkedList.scala create mode 100644 src/library/scala/collection/mutable/ListBuffer.scala create mode 100644 src/library/scala/collection/mutable/Location.scala create mode 100644 src/library/scala/collection/mutable/Map.scala create mode 100644 src/library/scala/collection/mutable/MapProxy.scala create mode 100644 src/library/scala/collection/mutable/Message.scala create mode 100644 src/library/scala/collection/mutable/MultiMap.scala create mode 100644 src/library/scala/collection/mutable/MutableList.scala create mode 100644 src/library/scala/collection/mutable/ObservableBuffer.scala create mode 100644 src/library/scala/collection/mutable/ObservableMap.scala create mode 100644 src/library/scala/collection/mutable/ObservableSet.scala create mode 100644 src/library/scala/collection/mutable/PriorityQueue.scala create mode 100644 src/library/scala/collection/mutable/PriorityQueueProxy.scala create mode 100644 src/library/scala/collection/mutable/Publisher.scala create mode 100644 src/library/scala/collection/mutable/Queue.scala create mode 100644 src/library/scala/collection/mutable/QueueProxy.scala create mode 100644 src/library/scala/collection/mutable/ResizableArray.scala create mode 100644 src/library/scala/collection/mutable/RevertableHistory.scala create mode 100644 src/library/scala/collection/mutable/Scriptable.scala create mode 100644 src/library/scala/collection/mutable/Set.scala create mode 100644 src/library/scala/collection/mutable/SetProxy.scala create mode 100644 src/library/scala/collection/mutable/SingleLinkedList.scala create mode 100644 src/library/scala/collection/mutable/Stack.scala create mode 100644 src/library/scala/collection/mutable/StackProxy.scala create mode 100644 src/library/scala/collection/mutable/Subscriber.scala create mode 100644 src/library/scala/collection/mutable/SynchronizedBuffer.scala create mode 100644 src/library/scala/collection/mutable/SynchronizedMap.scala create mode 100644 src/library/scala/collection/mutable/SynchronizedPriorityQueue.scala create mode 100644 src/library/scala/collection/mutable/SynchronizedQueue.scala create mode 100644 src/library/scala/collection/mutable/SynchronizedSet.scala create mode 100644 src/library/scala/collection/mutable/SynchronizedStack.scala create mode 100644 src/library/scala/collection/mutable/Undoable.scala create mode 100644 src/library/scala/concurrent/Actor.scala create mode 100644 src/library/scala/concurrent/Channel.scala create mode 100644 src/library/scala/concurrent/Lock.scala create mode 100644 src/library/scala/concurrent/MailBox.scala create mode 100644 src/library/scala/concurrent/NameServer.scala create mode 100644 src/library/scala/concurrent/Process.scala create mode 100644 src/library/scala/concurrent/SyncChannel.scala create mode 100644 src/library/scala/concurrent/SyncVar.scala create mode 100644 src/library/scala/concurrent/TIMEOUT.scala create mode 100644 src/library/scala/concurrent/jolib.scala create mode 100644 src/library/scala/concurrent/ops.scala create mode 100644 src/library/scala/concurrent/pilib.scala create mode 100644 src/library/scala/dbc/DataType.scala create mode 100644 src/library/scala/dbc/Database.scala create mode 100644 src/library/scala/dbc/Syntax.scala create mode 100644 src/library/scala/dbc/Utilities.scala create mode 100644 src/library/scala/dbc/Value.scala create mode 100644 src/library/scala/dbc/Vendor.scala create mode 100644 src/library/scala/dbc/datatype/ApproximateNumeric.scala create mode 100644 src/library/scala/dbc/datatype/Boolean.scala create mode 100644 src/library/scala/dbc/datatype/Character.scala create mode 100644 src/library/scala/dbc/datatype/CharacterLargeObject.scala create mode 100644 src/library/scala/dbc/datatype/CharacterString.scala create mode 100644 src/library/scala/dbc/datatype/CharacterVarying.scala create mode 100644 src/library/scala/dbc/datatype/ExactNumeric.scala create mode 100644 src/library/scala/dbc/datatype/Factory.scala create mode 100644 src/library/scala/dbc/datatype/Numeric.scala create mode 100644 src/library/scala/dbc/datatype/String.scala create mode 100644 src/library/scala/dbc/datatype/Unknown.scala create mode 100644 src/library/scala/dbc/exception/IncompatibleSchema.scala create mode 100644 src/library/scala/dbc/exception/UnsupportedFeature.scala create mode 100644 src/library/scala/dbc/result/Field.scala create mode 100644 src/library/scala/dbc/result/FieldMetadata.scala create mode 100644 src/library/scala/dbc/result/Relation.scala create mode 100644 src/library/scala/dbc/result/Status.scala create mode 100644 src/library/scala/dbc/result/Tuple.scala create mode 100644 src/library/scala/dbc/statement/AccessMode.scala create mode 100644 src/library/scala/dbc/statement/DerivedColumn.scala create mode 100644 src/library/scala/dbc/statement/Expression.scala create mode 100644 src/library/scala/dbc/statement/Insert.scala create mode 100644 src/library/scala/dbc/statement/InsertionData.scala create mode 100644 src/library/scala/dbc/statement/IsolationLevel.scala create mode 100644 src/library/scala/dbc/statement/JoinType.scala create mode 100644 src/library/scala/dbc/statement/Jointure.scala create mode 100644 src/library/scala/dbc/statement/Relation.scala create mode 100644 src/library/scala/dbc/statement/Select.scala create mode 100644 src/library/scala/dbc/statement/SetClause.scala create mode 100644 src/library/scala/dbc/statement/SetQuantifier.scala create mode 100644 src/library/scala/dbc/statement/Statement.scala create mode 100644 src/library/scala/dbc/statement/Status.scala create mode 100644 src/library/scala/dbc/statement/Table.scala create mode 100644 src/library/scala/dbc/statement/Transaction.scala create mode 100644 src/library/scala/dbc/statement/Update.scala create mode 100644 src/library/scala/dbc/statement/expression/Aggregate.scala create mode 100644 src/library/scala/dbc/statement/expression/BinaryOperator.scala create mode 100644 src/library/scala/dbc/statement/expression/Constant.scala create mode 100644 src/library/scala/dbc/statement/expression/Default.scala create mode 100644 src/library/scala/dbc/statement/expression/Field.scala create mode 100644 src/library/scala/dbc/statement/expression/FunctionCall.scala create mode 100644 src/library/scala/dbc/statement/expression/Select.scala create mode 100644 src/library/scala/dbc/statement/expression/SetFunction.scala create mode 100644 src/library/scala/dbc/statement/expression/TypeCast.scala create mode 100644 src/library/scala/dbc/statement/expression/UnaryOperator.scala create mode 100644 src/library/scala/dbc/syntax/DataTypeUtil.scala create mode 100644 src/library/scala/dbc/syntax/Database.scala create mode 100644 src/library/scala/dbc/syntax/Statement.scala create mode 100644 src/library/scala/dbc/syntax/StatementExpression.scala create mode 100644 src/library/scala/dbc/value/ApproximateNumeric.scala create mode 100644 src/library/scala/dbc/value/Boolean.scala create mode 100644 src/library/scala/dbc/value/Character.scala create mode 100644 src/library/scala/dbc/value/CharacterLargeObject.scala create mode 100644 src/library/scala/dbc/value/CharacterVarying.scala create mode 100644 src/library/scala/dbc/value/Conversion.scala create mode 100644 src/library/scala/dbc/value/ExactNumeric.scala create mode 100644 src/library/scala/dbc/value/Factory.scala create mode 100644 src/library/scala/dbc/value/Unknown.scala create mode 100644 src/library/scala/dbc/vendor/PostgreSQL.scala create mode 100644 src/library/scala/io/Position.scala create mode 100644 src/library/scala/io/Source.scala create mode 100644 src/library/scala/mobile/Code.scala create mode 100644 src/library/scala/mobile/Location.scala create mode 100644 src/library/scala/reflect/Code.scala create mode 100644 src/library/scala/reflect/Print.scala create mode 100644 src/library/scala/reflect/Symbol.scala create mode 100644 src/library/scala/reflect/Type.scala create mode 100644 src/library/scala/reflect/TypedCode.scala create mode 100644 src/library/scala/remote.scala create mode 100644 src/library/scala/runtime/AtomicReference.java create mode 100644 src/library/scala/runtime/BooleanRef.java create mode 100644 src/library/scala/runtime/BoxedAnyArray.scala create mode 100644 src/library/scala/runtime/BoxedArray.scala create mode 100644 src/library/scala/runtime/BoxedBoolean.java create mode 100644 src/library/scala/runtime/BoxedBooleanArray.scala create mode 100644 src/library/scala/runtime/BoxedByte.java create mode 100644 src/library/scala/runtime/BoxedByteArray.scala create mode 100644 src/library/scala/runtime/BoxedChar.java create mode 100644 src/library/scala/runtime/BoxedCharArray.scala create mode 100644 src/library/scala/runtime/BoxedDouble.java create mode 100644 src/library/scala/runtime/BoxedDoubleArray.scala create mode 100644 src/library/scala/runtime/BoxedFloat.java create mode 100644 src/library/scala/runtime/BoxedFloatArray.scala create mode 100644 src/library/scala/runtime/BoxedInt.java create mode 100644 src/library/scala/runtime/BoxedIntArray.scala create mode 100644 src/library/scala/runtime/BoxedLong.java create mode 100644 src/library/scala/runtime/BoxedLongArray.scala create mode 100644 src/library/scala/runtime/BoxedNumber.java create mode 100644 src/library/scala/runtime/BoxedObjectArray.scala create mode 100644 src/library/scala/runtime/BoxedShort.java create mode 100644 src/library/scala/runtime/BoxedShortArray.scala create mode 100644 src/library/scala/runtime/BoxedUnit.java create mode 100644 src/library/scala/runtime/ByteRef.java create mode 100644 src/library/scala/runtime/CharRef.java create mode 100644 src/library/scala/runtime/DoubleRef.java create mode 100644 src/library/scala/runtime/ExceptionHandling.cs create mode 100644 src/library/scala/runtime/ExceptionHandling.java create mode 100644 src/library/scala/runtime/FNV_Hash.java create mode 100644 src/library/scala/runtime/FloatRef.java create mode 100644 src/library/scala/runtime/IOMap.java create mode 100644 src/library/scala/runtime/IntRef.java create mode 100644 src/library/scala/runtime/InterpreterSupport.java create mode 100644 src/library/scala/runtime/LongRef.java create mode 100644 src/library/scala/runtime/MetaAttribute.cs create mode 100644 src/library/scala/runtime/ObjectRef.java create mode 100644 src/library/scala/runtime/ScalaRunTime.scala create mode 100644 src/library/scala/runtime/ShortRef.java create mode 100644 src/library/scala/runtime/SymtabAttribute.cs create mode 100644 src/library/scala/runtime/compat/Math.scala create mode 100644 src/library/scala/runtime/compat/Platform.scala create mode 100644 src/library/scala/runtime/compat/StringBuilder.scala create mode 100644 src/library/scala/runtime/matching/Address.scala create mode 100644 src/library/scala/runtime/matching/NonTerm.scala create mode 100644 src/library/scala/runtime/matching/PatternTests.scala create mode 100644 src/library/scala/runtime/matching/Rule.scala create mode 100644 src/library/scala/runtime/matching/TestAlphabet.scala create mode 100644 src/library/scala/serializable.scala create mode 100644 src/library/scala/testing/Benchmark.scala create mode 100644 src/library/scala/testing/SUnit.scala create mode 100644 src/library/scala/testing/UnitTest.scala create mode 100644 src/library/scala/text/Document.scala create mode 100644 src/library/scala/transient.scala create mode 100644 src/library/scala/util/automata/BaseBerrySethi.scala create mode 100644 src/library/scala/util/automata/DetWordAutom.scala create mode 100644 src/library/scala/util/automata/Inclusion.scala create mode 100644 src/library/scala/util/automata/NondetWordAutom.scala create mode 100644 src/library/scala/util/automata/SubsetConstruction.scala create mode 100644 src/library/scala/util/automata/WordBerrySethi.scala create mode 100644 src/library/scala/util/grammar/HedgeRHS.scala create mode 100644 src/library/scala/util/grammar/TreeRHS.scala create mode 100644 src/library/scala/util/logging/ConsoleLogger.scala create mode 100644 src/library/scala/util/logging/Logged.scala create mode 100644 src/library/scala/util/parsing/CharInputStreamIterator.scala create mode 100644 src/library/scala/util/parsing/Parsers.scala create mode 100644 src/library/scala/util/parsing/SimpleTokenizer.scala create mode 100644 src/library/scala/util/regexp/Base.scala create mode 100644 src/library/scala/util/regexp/PointedHedgeExp.scala create mode 100644 src/library/scala/util/regexp/SyntaxError.scala create mode 100644 src/library/scala/util/regexp/WordExp.scala create mode 100644 src/library/scala/volatile.scala create mode 100644 src/library/scala/xml/Atom.scala create mode 100644 src/library/scala/xml/Comment.scala create mode 100644 src/library/scala/xml/Document.scala create mode 100644 src/library/scala/xml/Elem.scala create mode 100644 src/library/scala/xml/EntityRef.scala create mode 100644 src/library/scala/xml/MalformedAttributeException.scala create mode 100644 src/library/scala/xml/MetaData.scala create mode 100644 src/library/scala/xml/Molecule.scala create mode 100644 src/library/scala/xml/NamespaceBinding.scala create mode 100644 src/library/scala/xml/Node.scala create mode 100644 src/library/scala/xml/NodeBuffer.scala create mode 100644 src/library/scala/xml/NodeSeq.scala create mode 100644 src/library/scala/xml/NodeTraverser.scala create mode 100644 src/library/scala/xml/Null.scala create mode 100644 src/library/scala/xml/Parsing.scala create mode 100644 src/library/scala/xml/PrefixedAttribute.scala create mode 100644 src/library/scala/xml/PrettyPrinter.scala create mode 100644 src/library/scala/xml/ProcInstr.scala create mode 100644 src/library/scala/xml/SpecialNode.scala create mode 100644 src/library/scala/xml/Text.scala create mode 100644 src/library/scala/xml/TextBuffer.scala create mode 100644 src/library/scala/xml/TopScope.scala create mode 100644 src/library/scala/xml/TypeSymbol.scala create mode 100644 src/library/scala/xml/UnprefixedAttribute.scala create mode 100644 src/library/scala/xml/Utility.scala create mode 100644 src/library/scala/xml/XML.scala create mode 100644 src/library/scala/xml/dtd/ContentModel.scala create mode 100644 src/library/scala/xml/dtd/ContentModelParser.scala create mode 100644 src/library/scala/xml/dtd/DTD.scala create mode 100644 src/library/scala/xml/dtd/Decl.scala create mode 100644 src/library/scala/xml/dtd/DocType.scala create mode 100644 src/library/scala/xml/dtd/DtdTypeSymbol.scala create mode 100644 src/library/scala/xml/dtd/ElementValidator.scala create mode 100644 src/library/scala/xml/dtd/ExternalID.scala create mode 100644 src/library/scala/xml/dtd/Scanner.scala create mode 100644 src/library/scala/xml/dtd/Tokens.scala create mode 100644 src/library/scala/xml/dtd/ValidationException.scala create mode 100644 src/library/scala/xml/factory/Binder.scala create mode 100644 src/library/scala/xml/factory/LoggedNodeFactory.scala create mode 100644 src/library/scala/xml/factory/NodeFactory.scala create mode 100644 src/library/scala/xml/parsing/ConstructingHandler.scala create mode 100644 src/library/scala/xml/parsing/ConstructingParser.scala create mode 100644 src/library/scala/xml/parsing/DefaultMarkupHandler.scala create mode 100644 src/library/scala/xml/parsing/ExternalSources.scala create mode 100644 src/library/scala/xml/parsing/FactoryAdapter.scala create mode 100644 src/library/scala/xml/parsing/FatalError.scala create mode 100644 src/library/scala/xml/parsing/MarkupHandler.scala create mode 100644 src/library/scala/xml/parsing/MarkupParser.scala create mode 100644 src/library/scala/xml/parsing/NoBindingFactoryAdapter.scala create mode 100644 src/library/scala/xml/parsing/TokenTests.scala create mode 100644 src/library/scala/xml/parsing/ValidatingMarkupHandler.scala create mode 100644 src/library/scala/xml/path/Expression.scala create mode 100644 src/library/scala/xml/transform/BasicTransformer.scala create mode 100644 src/library/scala/xml/transform/RewriteRule.scala create mode 100644 src/library/scala/xml/transform/RuleTransformer.scala create mode 100644 src/library/scala/xml/xsd/ContentModel.scala create mode 100644 src/library/scala/xml/xsd/Decl.scala create mode 100644 src/library/scala/xml/xsd/XsTypeSymbol.scala create mode 100644 src/msil-library/AssemblyInfo.cs.tmpl create mode 100644 src/msil-library/scala/runtime/compat/Math.scala create mode 100644 src/msil-library/scala/runtime/compat/Platform.scala create mode 100644 src/msil-library/scala/runtime/compat/StringBuilder.scala diff --git a/README b/README new file mode 100644 index 0000000000..837d5170ae --- /dev/null +++ b/README @@ -0,0 +1,59 @@ +================================================================================ + THE SCALA REPOSITRY + Structure and build system +================================================================================ + +Part I. The repository layout +-------------------------------------------------------------------------------- + +Follows the file layout of the Scala repository. Files marked with a † are not +part of the Subversion repository but are either automatically generated by the +build script or user-created if needed. + +scala/ + build/ † Temporary staging area for build products. + build.excludes † An optional build configuration file. + build.properties † An optional build configuration file. + build.xml The main Ant build script. + dist/ † The destination folder of Scala distributions. + docs/ Documentation of Scala. More in its own module. + development/ Developer documentation. + examples/ Scala example files. + man/ UNIX manual files. + lib/ Pre-compiled libraries for the build. + fjbg.jar The Java byte-code generation library. + jaco.jar The JaCo Java compiler. + msil.jar The CLR byte-code generation library. + scala-compiler.jar The last stable version of the Scala compiler. + scala-library.jar The last stable version of the Scala library. + scala.dll The Scala library for Windows. + README The file you are currently reading. + sandbox/ † A folder to test code etc. + src/ All the source files of Scala. + compiler/ The sources of the Scala compiler. + exec/ The sources of the executable wrapper-scripts. + library/ The sources of the Scala library. + test/ The Scala test suite. + +Any change to this structure requires a modification of the 'build.xml' file. + + + +Part II. Building Scala +-------------------------------------------------------------------------------- + +The Scala build system is based on Apache Ant. Most required pre-compiled libraries are part of the repository (in 'lib/'). The following however is assumed to be installed on the build machine: + - A Java SDK 1.4 or above (1.5 not supported). + - Apache Ant version 1.6.2 or above. + +More to come ... + +Part III. Creating distributions +-------------------------------------------------------------------------------- + +More to come ... + +Part IV. Contributing to Scala +-------------------------------------------------------------------------------- + +More to come ... diff --git a/VERSION b/VERSION deleted file mode 100644 index 430aa8aa97..0000000000 --- a/VERSION +++ /dev/null @@ -1,9 +0,0 @@ -############################################################-*-Makefile-*-#### -# DO NOT EDIT. Automatically generated file! -# -# To modify the current version use the following command: -# make version-set VERSION= -# -# DO NOT EDIT. Automatically generated file! -############################################################################## -1.4.0.4 diff --git a/build.readme b/build.readme deleted file mode 100644 index 925093061b..0000000000 --- a/build.readme +++ /dev/null @@ -1,114 +0,0 @@ -BUILDING NEW SCALA WITH ANT ---------------------------- - -This is version 1.0 of the Scala Ant-based build system SABBUS. - -QUICK START ------------ - -- Copy the 'build.TEMPLATE.properties' file in 'build.support' to - 'build.USER_NAME.properties'. Set all properties in this file. - -- In a terminal window, type: - ANT_OPTS="-Xmx256M" ant distrib - -USAGE GUIDE ------------ - -PREREQUISITES - -The new Scala Ant-based build system (SABBUS) requires the following elements: - - An old Scala distribution. The Scala tools ('tools.jar' must be of a version - that does contain the improved Scalac Ant task at - 'scala.tools.scalac.ant.Scalac'. The scala library ('scala.jar') must contain - all classes required to build NSC. - - A PiCo/JaCo distribution. It must contain the improved PiCo task at - 'jaco.pizza.ant.Pico'. - - Ant version 1.6 or above. - - Java version 1.4 or above (Java 1.5 might not be supported). - -SETTING UP - -The set-up of SABBUS is done entirely in the 'build.properties' file. Make sure -that all values in this file are set and correct. - -Another configuration file exists ('build.support/build.default'). This file -should not be modified as any property declared in 'build.properties' will -override the value set in 'build.default'. - -With a normal Java distribution, the standard memory allocated to the JVM in -insufficient for Scala compilation. The ANT_OPTS environment variable needs to -be set to increase the memory size (either each time as in the quick start -example above, or once and for all in the default shell environment). - -Skipping parts of the build - -In some cases, parts of the build process should be disabled for debug reasons: - - skip.doc will not build the LaTeX documentation. - - skip.nsc will not build anything with NSC. This will create a non-working - distribution. - -BUILDING NEW SCALA - -The 'build' target builds all the Scala library and tools. It is composed of the -following sub-targets: - - 'build.pico.nslib': - Builds the Java files in Scala (runtime, tools and scala root) with PiCo. - When both a Java file in sources and a Scala file in newsources exist, the - Java file is not compiled (it is considered to have been superseeded by the - Scala file). - - 'build.osc.nstools': - Builds NSC with an existing Scalac (found in path of property - 'ostools.jar'). - - 'build.nsc.nslib': - Builds the new Scala library with the compiler built at target - 'build.osc.nstools'. Depends on 'build.osc.nstools' & 'build.pico.nslib'. - If files should not be compiled at that stage, they can be specified in the - 'build.support/nsc.nslib.excludes' - - 'build.nsc.nstools': - Builds NSC with the compiler built at target 'build.osc.nstools'. Depends - on 'build.osc.nstools' & 'build.pico.nslib'. If files should not be - compiled at that stage, they can be specified in the - 'build.support/nsc.nstools.excludes' - -CONSTRUCTING A DISTRIBUTION - -The 'distrib' target constructs a simple distribution of new Scala from the -latest build. The following steps will be done: - - Creates a standard distribution folder hierarchy. - - Create JAR packages for the library ('nslib.jar'), and the tools, both - compiled with Scalac ('osc-nstools.jar') and with NSC ('nstools.jar'). - - Create script files (bash and bat) to execute the new Scala compiler. - - Adds man files and the documentation to the distribution. - - Generates some symbolic links to simplify navigation (only on UNIX). Amongst - other, a 'latest' link in the 'dist' folder will point to the latest - distribution folder (useful to refer in a permanent way to the latest - distribution on your system). - -CLEANING - -The 'clean' target removes all build and distribution files. - - 'clean.build' only removes build files and does not touch distribution files. - - 'clean.distrib' only removes distribution files. - -DOCUMENTING - -Not implemented yet - -TESTING - -Not implemented yet - -KNOWN BUGS, LIMITATIONS AND PLANNED IMPROVEMENTS ------------------------------------------------- - -- Create NSC executable scripts for UNIX and Windows. -- Create Windows build system. -- Create documentation. -- Support testing. - -HISTORY -------- - -1.0 - First functioning version. Supports clean, build and a limited distrib. diff --git a/build.xml b/build.xml index 4fc5401fc7..e570ccd1cc 100644 --- a/build.xml +++ b/build.xml @@ -1,744 +1,494 @@ - - - - This is SABBUS, the system to build the Scala NSC compiler as well as - various related tools. The 'build.TEMPLATE.properties' file must be - customised for your own particular system, no other customisation should - be required. The build file expects the file structure of a Scala CVS - distribution. - - - This is SABBUS, your helpful build script for new Scala. - - - - - - SABBUS requires additional memory. Please set the 'ANT_OPTS' environment property to '-Xmx256M' or more. - - - - - + + + + I am Sabbus for Scala-core, the build system for the Scala compiler and core + library. Please check the 'docs/README' file for more information about me. + + + Running Sabbus for Scala-core + + + + + + + + + Sabbus requires additional memory. Please set the 'ANT_OPTS' environment + property to '-Xmx256M' or more. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + starr.lib.jar=${starr.lib.jar} + + + + + + + + starr.comp.jar=${starr.comp.jar} + + + + + + fjbg.jar=${fjbg.jar} + + + + + + msil.jar=${msil.jar} + + + + + + jaco.jar=${jaco.jar} + + + + + + ant.jar=${ant.jar} + + + + + + + + + + - SABBUS is too unstable when used with a non-empty classpath. Unset your classpath environment variable. - - - - - - Loading properties from '${basedir}/config/build.base.properties' - - - - Loading properties from '${config.dir}/build.${user.name}.properties' - - Loading properties from '${build.support.dir}/build.${user.name}.properties' - - Loading properties from '${config.dir}/build.default.properties' - - - - - - - - - + + + + - - - - + + + + - - - - - - - - + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - oslib.jar=${oslib.jar} - oslib.src=${oslib.src} - ostools.jar=${ostools.jar} - fjbg.jar=${fjbg.jar} - msil.jar=${msil.jar} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jaco.jar=${jaco.jar} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - scala.dll=${scala.dll} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - A full distribution cannot be build when skipping NSC. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + - - - - - izpack.home=${izpack.home} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Windows-specific IzPack installer is not generated yet. - - - - - - - - - - - - - oslib.jar=${oslib.jar} - oslib.src=${oslib.src} - ostools.jar=${ostools.jar} - - - - - - - - - - - - - - Generating API documentation to ${build.dir}/doc/api - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Execute 'ant -projecthelp' for build file help. - Execute 'ant -help' for Ant help. - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Build is stable + + + + + + Docs is not available yet. + + + + + + Dist is not available yet. + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/build.TEMPLATE.properties b/config/build.TEMPLATE.properties deleted file mode 100644 index 2606ac4625..0000000000 --- a/config/build.TEMPLATE.properties +++ /dev/null @@ -1,34 +0,0 @@ -############################################################################## -# USER PROPERTIES FOR SABBUS # -############################################################################## -# These are user-specific properties for SABBUS. Any property that has not -# been set here will take the value defined in 'build.default.properties' -# or 'build.base.properties'. Properties in the latter of these files can -# be refered to from within this file. -# $Id$ -############################################################################## - -# The path to the old Scala library JAR package and source directory. -oslib.jar= -oslib.src= - -# The path to the old Scala tools. -ostools.jar= - -# The path to the Jaco/Pico compiler. -jaco.jar= - -# The path to the FJBG byte-code generation library. -fjbg.jar= - -# The path to the MSIL byte-code generation library. -msil.jar= - -# The path to the MSIL DLL library. -scala.dll= - -# The path to the IzPack tool. -izpack.jar= - -# Other custom properties come here -nsc.skip= diff --git a/config/build.base.properties b/config/build.base.properties deleted file mode 100644 index 25ef7417eb..0000000000 --- a/config/build.base.properties +++ /dev/null @@ -1,16 +0,0 @@ -############################################################################## -# BASE PROPERTIES FOR SABBUS # -############################################################################## -# These are properties specific to the layout of the Scala distribution. -# DO NOT CHANGE them unless one of the mentioned directory is changed. -# $Id$ -############################################################################## - -bin.dir=${basedir}/bin -build.support.dir=${basedir}/build.support -config.dir=${basedir}/config -doc.dir=${basedir}/doc -newsources.dir=${basedir}/newsources -sources.dir=${basedir}/sources -support.dir=${basedir}/support -test.dir=${basedir}/test diff --git a/config/build.default.properties b/config/build.default.properties deleted file mode 100644 index 8f9788f4dc..0000000000 --- a/config/build.default.properties +++ /dev/null @@ -1,133 +0,0 @@ -############################################################################## -# DEFAULT PROPERTIES FOR SABBUS # -############################################################################## -# These are default values for all properties used by SABBUS. DO NOT CHANGE -# them in this file. All properties can be overriden in the -# build.USER_NAME.properties file. -# $Id$ -############################################################################## - -# CONFIGURATION OF NSC -############################################################################## - -copyright.notice=(C) 2002-06 LAMP/EPFL - -# What NSC should output during compilation. Either 'none', 'verbose', 'debug'. -nsc.logging=none - -# After which compile phase NSC should stop. This will induce build errors. -nsc.stop= - -# A comma-separated list of compile phases that NSC should skip. -nsc.skip= - -# A comma-separated list of compile phases that NSC should log. -nsc.log= - -# A comma-separated list of compile phases which result should be checked for -# consistency. -nsc.check= - -# A comma-separated list of compile phases that NSC should print. -nsc.print= - -# The name of a file that lists files that should be excluded when building -# the new Scala library. This file MUST EXIST. -nsc.nslib.excludes=${config.dir}/excludes/nsc.nslib.excludes - -# The name of a file that lists files that should be excluded when building -# the new Scala tools. This file MUST EXIST. -nsc.nstools.excludes=${config.dir}/excludes/nsc.nstools.excludes - -# The name of a file that lists files that should be excluded when building -# the new Scala tools. This file MUST EXIST. -nsc.osc-nstools.excludes=${config.dir}/excludes/nsc.osc-nstools.excludes - -# Boolean flag that controls whether the NSC compiler will generate -# debug information in class files -nsc.debuginfo=true - - -# LOCATION OF PRE-COMPILED LIBRARIES -############################################################################## - -# The path to the old Scala library ('scala.jar'). -oslib.jar=/usr/local/lib/scala.jar - -# The path to the old Scala library sources. -oslib.src=/usr/local/share/scala/src - -# The path to the old Scala tools ('tools.jar'). -ostools.jar=/usr/local/lib/tools.jar - -# The path to the JaCo compiler ('jaco.jar'). -jaco.jar=/usr/local/lib/jaco.jar - -# The path to the FJBG byte-code generation library ('fjbg.jar'). -fjbg.jar=/usr/local/lib/fjbg.jar - -# The path to the MSIL byte-code generation library ('fjbg.jar'). -msil.jar=/usr/local/lib/msil.jar - -# The path to the MSIL DLL library ('scala.dll'). -scala.dll=/usr/local/lib/scala.dll - -# The path to the Java base classes ('rt.jar' or 'classes.jar'). -java.jar=${java.home}/jre/lib/rt.jar - -# The path to the Ant base classes ('ant.jar'). -ant.jar=${ant.home}/lib/ant.jar - -# The path to the IzPack tools ('standalone-compiler.jar'). -izpack.home=/usr/local/ - -# LOCATION OF BUILD PRODUCTS -############################################################################## - -# The directory in which all build products live. -build.dir=${basedir}/build - -# The directory to which the new Scala library is compiled. -build.nslib.dir=${build.dir}/nslib - -# The directory to which the part of the new Scala library built with PiCo -# is compiled. This should be different from ${build.nslib.dir}. -build.pico-nslib.dir=${build.dir}/pico-nslib - -# The directory to which the new Scala tools (built with OSC) are compiled. -build.osc-nstools.dir=${build.dir}/osc-nstools - -# The directory to which the new Scala tools are compiled. -build.nstools.dir=${build.dir}/nstools - -# LOCATION AND STRUCTURE OF THE DISTRIBUTION -# Overriding these properties will produce a non-standard distribution that -# might not be useable. -############################################################################## - -# The directory to which a new distribution will be added, both for UNIX and -# Windows. These directories MUST BE SEPARATE! -distrib.unix.dir=${basedir}/distribs/unix -distrib.win.dir=${basedir}/distribs/windows - -# The name of the product to build. -distrib.name=nscala - -# The name of the JAR file in which the new Scala library should be archived. -nslib.jar.name=nslib.jar - -# The name of the JAR file in which the new Scala tools should be archived. -nstools.jar.name=nstools.jar - -# The name of the JAR file in which the new Scala tools (built with OSC) -# should be archived. -osc-nstools.jar.name=osc-nstools.jar - -# The name of the Scala executables -scala.exec.name=ns -scalac.exec.name=nsc -scalai.exec.name=nsi -scalap.exec.name=nsp -scalatok.exec.name=nsctok - -############################################################################## diff --git a/config/excludes/nsc.nslib.excludes b/config/excludes/nsc.nslib.excludes deleted file mode 100644 index 7dd733694c..0000000000 --- a/config/excludes/nsc.nslib.excludes +++ /dev/null @@ -1,10 +0,0 @@ -################################################################################ -# NSLIB EXCLUDED FILES # -################################################################################ -# A list of files to exclude when compiling the Scala library with NSC. All -# files can be defined using Ant's fileset wildcard notation; one statement per -# line. -# $Id$ -################################################################################ - -scala/dbc/** diff --git a/config/excludes/nsc.nstools.excludes b/config/excludes/nsc.nstools.excludes deleted file mode 100644 index a02527bf19..0000000000 --- a/config/excludes/nsc.nstools.excludes +++ /dev/null @@ -1,7 +0,0 @@ -################################################################################ -# NSTOOLS EXCLUDED FILES # -################################################################################ -# A list of files to exclude when compiling the Scala tools with NSC. All files -# can be defined using Ant's fileset wildcard notation; one statement per line. -# $Id$ -################################################################################ diff --git a/config/excludes/nsc.osc-nstools.excludes b/config/excludes/nsc.osc-nstools.excludes deleted file mode 100644 index 3ef12c77d6..0000000000 --- a/config/excludes/nsc.osc-nstools.excludes +++ /dev/null @@ -1,7 +0,0 @@ -################################################################################ -# OSC-NSTOOLS EXCLUDED FILES # -################################################################################ -# A list of files to exclude when compiling the Scala tools with NSC. All files -# can be defined using Ant's fileset wildcard notation; one statement per line. -# $Id$ -################################################################################ diff --git a/config/izpack/images/Splash.png b/config/izpack/images/Splash.png deleted file mode 100644 index 8d0e8389cc..0000000000 Binary files a/config/izpack/images/Splash.png and /dev/null differ diff --git a/config/izpack/images/install.png b/config/izpack/images/install.png deleted file mode 100644 index f75b7fb2c1..0000000000 Binary files a/config/izpack/images/install.png and /dev/null differ diff --git a/config/izpack/install-nsc.xml b/config/izpack/install-nsc.xml deleted file mode 100644 index 08737a42fe..0000000000 --- a/config/izpack/install-nsc.xml +++ /dev/null @@ -1,111 +0,0 @@ - - - - - - - Scala - @VERSION@ - @URL@ - 1.4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Installing the Scala software. - - - - - - - - - - - - - - - - - - - - - -Djava.library.path=$INSTALL_PATH\Uninstaller - -cp - $INSTALL_PATH\Uninstaller\registry.jar;$INSTALL_PATH\Uninstaller\setenv.jar - Main - @VERSION@ - - - - - diff --git a/config/izpack/izpack_process.xml b/config/izpack/izpack_process.xml deleted file mode 100644 index ed5982707a..0000000000 --- a/config/izpack/izpack_process.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - $INSTALL_PATH/Uninstaller - - - - - Create symbolic links - - - ../share/@PREFIX@/bin/.scala_wrapper - - - .scala_wrapper - - - - Clean up - - - -f - $INSTALL_PATH/bin/.nsc_symlink - $INSTALL_PATH/share/@PREFIX@/bin/.nsc_symlink - - - - - - - Add the SCALA_HOME variable to the user environment - - - -Djava.library.path=$INSTALL_PATH\Uninstaller - -cp - $INSTALL_PATH\Uninstaller\registry.jar;$INSTALL_PATH\Uninstaller\setenv.jar - Main - @VERSION@ - $INSTALL_PATH - - - - diff --git a/config/izpack/izpack_scala.xml b/config/izpack/izpack_scala.xml deleted file mode 100644 index 282ed59e39..0000000000 --- a/config/izpack/izpack_scala.xml +++ /dev/null @@ -1,96 +0,0 @@ - - - - - Scala - 1.4.0.1 - - http://scala.epfl.ch/ - 1.4 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Installing the Scala software. - - - - - - - - - - - - - diff --git a/config/izpack/izpack_shortcut.xml b/config/izpack/izpack_shortcut.xml deleted file mode 100644 index 4d396dea1d..0000000000 --- a/config/izpack/izpack_shortcut.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/config/izpack/locales/INFO_de.html b/config/izpack/locales/INFO_de.html deleted file mode 100644 index 8ca5c531cf..0000000000 --- a/config/izpack/locales/INFO_de.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - -

- IzPack führt Sie durch - die Installation von Scala @VERSION@. -

-

- Scala erfordert Sun JDK/JRE - version 1.4 oder neuer. -

-

- Sie können die Installation jederzeit abbrechen, indem - Sie auf 'Beenden' klicken. -

- - diff --git a/config/izpack/locales/INFO_en.html b/config/izpack/locales/INFO_en.html deleted file mode 100644 index 3112960fe3..0000000000 --- a/config/izpack/locales/INFO_en.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - -

- IzPack will guide you through - the installation of Scala @VERSION@. -

-

- Scala requires Sun JDK/JRE - version 1.4 or newer. -

-

- You may cancel this installation at any time by clicking the - 'Quit' button. -

- - diff --git a/config/izpack/locales/INFO_fr.html b/config/izpack/locales/INFO_fr.html deleted file mode 100644 index 9edfe4455e..0000000000 --- a/config/izpack/locales/INFO_fr.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - -

- IzPack will guide you through - the installation of Scala @VERSION@. -

-

- Scala requiert Sun JDK/JRE - version 1.4 ou plus récent. -

-

- Vous pouvez abandonner l'installation à tout moment - en cliquant sur 'Quitter'. -

- - diff --git a/config/izpack/locales/LICENSE_de.html b/config/izpack/locales/LICENSE_de.html deleted file mode 100644 index 90b5da193e..0000000000 --- a/config/izpack/locales/LICENSE_de.html +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - -
-SCALA LIZENZ -
- -

-Copyright © 2002-05 EPFL, Lausanne. -Alle Rechte vorbehalten. -

- -

-Diese Software wurde von der Gruppe Methoden der Programmierung an -der Eidgenössiche Technische Hochschule von Lausanne, Schweiz, -entwickelt. -

- -

-Die Genehmigung zum Verwenden, Kopieren, Ändern and Weitervertreiben -dieser Software im Quell- und Binärformat zu einem beliebigen Zweck -wird hiermit ohne Gebühr erteilt, sofern folgende Konditionen -erfüllt sind: -

- -
    -
  1. - Bei Weitervertrieb des Quellcodes müssen vorstehender - Urheberrechtshinweis, diese Liste der Konditionen und die folgende - Verzichtserklärung beibehalten werden. -
  2. -
  3. - Bei Weitervertrieb im Binärformat müssen in der Dokumentation - und/oder anderen Materialien, die vertrieben werden, vorstehender - Urheberrechtshinweis, diese Liste der Konditionen und die folgende - Verzichtserklärung reproduziert werden. -
  4. -
  5. - Neither the name of the EPFL nor the names of its contributors - may be used to endorse or promote products derived from this - software without specific prior written permission. -
  6. -
- -

-DIESE SOFTWARE WIRD VON DEN AUTOREN WIE BESEHEN UND UNTER AUSSCHLUSS ALLER -AUSDRÜCKLICHEN ODER KONKLUDENTEN GARANTIEN ZUR VERFÃœGUNG GESTELLT, -EINSCHLIESSLICH, ABER NICHT BESCHRÄNKT AUF KONKLUDENTE GARANTIEN DER -HANDELSÜBLICHKEIT UND/ODER EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. -UNTER KEINEN UMSTÄNDEN KÖNNEN DIE AUTOREN FÜR DIREKTE, INDIREKTE, -ZUFÄLLIGE, BESONDERE, EXEMPLARISCHE ODER FOLGESCHÄDEN (EINSCHLIESSLICH -VON, ABER NICHT BESCHRÄNKT AUF, BESCHAFFUNG VON ERSATZWAREN ODER -ERSATZLEISTUNGEN, ENTGANGENEM NUTZEN, VERLUST VON DATEN, ENTGANGENEM GEWINN -ODER GESCHÄFTSAUSFALL) HAFTBAR GEMACHT WERDEN, DIE AUS EINER BELIEBIGEN -URSACHE UND AUF GRUNDLAGE IRGENDEINES HAFTBARKEITSVERSTÄNDNISSES ENTSTEHEN, -UNABHÄNGIG VON VERTRÄGEN, DER GEFÄHRDUNGSHAFTUNG ODER UNERLAUBTEN -HANDLUNGEN (EINSCHLIESSLICH FAHRLÄSSIGKEIT ODER ANDERWEITIG), DIE IN -IRGENDEINER WEISE DURCH DIE VERWENDUNG DIESER SOFTWARE ENTSTEHEN, AUCH DANN, -WENN DIE AUTOREN ÜBER DIE MÖGLICHKEIT SOLCHER SCHÄDEN UNTERRICHTET WURDEN. -

- - - - diff --git a/config/izpack/locales/LICENSE_en.html b/config/izpack/locales/LICENSE_en.html deleted file mode 100644 index 59ef4cc4e0..0000000000 --- a/config/izpack/locales/LICENSE_en.html +++ /dev/null @@ -1,68 +0,0 @@ - - - - - - - - -
-SCALA LICENSE -
- -

-Copyright © 2002-05 EPFL, Lausanne. -All rights reserved. -

- -

-This software was developed by the Programming Methods Laboratory of -the Swiss Federal Institute of Technology, Lausanne, Switzerland. -

- -

-Permission to use, copy, modify, and distribute this software in source -or binary form for any purpose with or without fee is hereby granted, -provided that the following conditions are met: -

- -
    -
  1. - Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -
  2. -
  3. - Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -
  4. -
  5. - Neither the name of the EPFL nor the names of its contributors - may be used to endorse or promote products derived from this - software without specific prior written permission. -
  6. -
- -

-THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 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 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -SUCH DAMAGE. -

- - - diff --git a/config/izpack/locales/LICENSE_fr.html b/config/izpack/locales/LICENSE_fr.html deleted file mode 100644 index dab0ccd677..0000000000 --- a/config/izpack/locales/LICENSE_fr.html +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - -
-LICENCE SCALA -
- -

-Copyright © 2002-05 EPFL, Lausanne. -Tous droits réservés. -

- -

-Ce logiciel a été développé par le Laboratoire -des Méthodes de Programmation de l'Ecole Polytechnique -Fédérale de Lausanne (EPFL), Suisse. -

- -

-L'utilisation, la modification et la redistribution de ce logiciel sous forme -de code source et/ou binaire, dans un but commercial ou non, sont permis -étant entendu que les conditions suivantes sont satisfaites: -

- -
    -
  1. - Toute redistribution du code source doit contenir la notice de droits - d'auteur ci-dessus, la présente liste des conditions - d'utilisation et l'avis de non-responsabilité mentionné - plus bas. -
  2. -
  3. - Toute redistribution du code binaire doit contenir la notice de droits - d'auteur ci-dessus, la présente liste des conditions d'utilisation - et l'avis de non-responsabilité mentionné plus bas dans - la documentation et/ou tout autre support fourni dans la distribution. -
  4. -
  5. - Ni le nom de l'EPFL, ni celui des personnes qui ont - contribué au développement de ce logiciel ne peuvent - être utilisés dans le but de promouvoir des produits - dérivés de ce logiciel sans permission écrite - préalable. -
  6. -
- -

-CE LOGICIEL EST FOURNI "EN L'ÉTAT" SANS GARANTIE AUCUNE QUANT -À SON UTILISATION, Y COMPRIS, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. EN AUCUN CAS L'UNIVERSITÉ OU QUICONQUE AYANT -CONTRIBUÉ AU DÉVELOPPEMENT DU LOGICIEL NE SAURAIT ÊTRE -TENU RESPONSABLE DE TOUS DOMMAGES DIRECTS OU INDIRECTS, CONSÉCUTIFS -À L'UTILISATION DU LOGICIEL ET, NOTAMMENT DE TOUTES PERTES DE PROFITS -OU MANQUES À GAGNER, PERTE D'INFORMATION, DÉFAILLANCE -D'ORDINATEUR, INTERRUPTION DE TRAVAIL OU AUTRES DÉGÂTS, ET -CELA QUAND BIEN MÊME UN REPRÉSENTANT DE L'UNIVERSITÉ -AURAIT ÉTÉ INFORMÉ DE LA POSSIBILITÉ DE TELS -DOMMAGES. -

- -

-Seule la version anglaise de ce contrat fait foi juridiquement. -Les traductions en d'autres langues sont fournies aux usagers à -titre indicatif, mais elles ne sont pas nécessairement exactes -d'un point de vue juridique. -

- - - diff --git a/config/izpack/registry/bin/ICE_JNIRegistry.dll b/config/izpack/registry/bin/ICE_JNIRegistry.dll deleted file mode 100644 index 5463a70a40..0000000000 Binary files a/config/izpack/registry/bin/ICE_JNIRegistry.dll and /dev/null differ diff --git a/config/izpack/registry/bin/readme.txt b/config/izpack/registry/bin/readme.txt deleted file mode 100644 index 19b8731936..0000000000 --- a/config/izpack/registry/bin/readme.txt +++ /dev/null @@ -1,50 +0,0 @@ - - Windows Registry API Native Interface - -*Release 3.1.3, September 11, 2003* - -The com.ice.jni.registry package is a Java native interface for the -Windows Registry API. This allows Java program to access, modify, and -export Windows Registry resources. - -The com.ice.jni.registry package has been placed into the public domain. -Thus, you have absolutely no licensing issues to consider. You may do -anything you wish with the code. Of course, I always appreciate it when -you properly credit my work. - -The package will work only with Java 1.1 and greater, and uses the -Javasoft native interface, not the Netscape interface. The package also -includes a DLL that implements the interface. The package has been used -with JDK1.2, and JDK1.3, JDK1.4, as well as JDK1.1.8. - -The package includes the pre-built DLL (debug and release), source code -(both the Java and the DLL's C code), as well as the compiled Java classes. - -The original release was posted on November 17, 1997. The current -release is 3.1.3, which was posted on September 11, 2003. - -Email me if you have questions. - - - View The Source Code - -You can now directly view the JNIRegistry source code - and -source code documentation - -online via the Giant Java Tree. - - - Downloads - -Download the WinZip-ed package. (FTP) - - -Download the WinZip-ed package. (HTTP) - - - ------------------------------------------------------------------------- -* All contents are copyrighted (c) by ICE Engineering, Inc. * -http://www.trustice.com/ --- http://www.icetoo.com/ - diff --git a/config/izpack/registry/bin/registry.jar.desired.sha1 b/config/izpack/registry/bin/registry.jar.desired.sha1 deleted file mode 100644 index 634c7ec706..0000000000 --- a/config/izpack/registry/bin/registry.jar.desired.sha1 +++ /dev/null @@ -1 +0,0 @@ -54ed7dd49e6370b92f67acc20b43a32f4373343f ?registry.jar diff --git a/config/izpack/registry/bin/setenv.jar.desired.sha1 b/config/izpack/registry/bin/setenv.jar.desired.sha1 deleted file mode 100644 index 30ace1f6cc..0000000000 --- a/config/izpack/registry/bin/setenv.jar.desired.sha1 +++ /dev/null @@ -1 +0,0 @@ -6cd4b4e5799e861e00d1307f4e0ecd16ee3188cd ?setenv.jar diff --git a/config/izpack/registry/src/MANIFEST.MF b/config/izpack/registry/src/MANIFEST.MF deleted file mode 100644 index a99365f10a..0000000000 --- a/config/izpack/registry/src/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Created-By: 1.4.2_09 (Sun Microsystems Inc.) -Main-Class: Main diff --git a/config/izpack/registry/src/Main.java b/config/izpack/registry/src/Main.java deleted file mode 100644 index 6f5ee96bfd..0000000000 --- a/config/izpack/registry/src/Main.java +++ /dev/null @@ -1,120 +0,0 @@ -// File : Main.java -// Project : Scala -// Author(s) : Stephane Micheloud (mics) -// Environment: JNI Registry 3.1.3, Sun JDK 1.4.2_09 -// Version : 01 -// Created : 25.09.2005/mics -// Modified : - - - -import com.ice.jni.registry.NoSuchKeyException; -import com.ice.jni.registry.NoSuchValueException; -import com.ice.jni.registry.Registry; -import com.ice.jni.registry.RegistryException; -import com.ice.jni.registry.RegistryKey; -import com.ice.jni.registry.RegistryValue; -import com.ice.jni.registry.RegMultiStringValue; -import com.ice.jni.registry.RegStringValue; - -public class Main { - - private static final String PATH = "PATH"; - private static final String SCALA_HOME = "SCALA_HOME"; - private static final String SCALA_BIN = "%" + SCALA_HOME + "%\\bin"; - - private static void updateRegistry(String homePath, String fullName) throws RegistryException { - // HKEY_CURRENT_USER\Environment - RegistryKey envKey = Registry.openSubkey( - Registry.HKEY_CURRENT_USER, - "Environment", - RegistryKey.ACCESS_ALL); - if (homePath != null) { - // set home directory - RegStringValue data = new RegStringValue(envKey, SCALA_HOME, homePath); - envKey.setValue(data); - // update user path - String path = envKey.getStringValue(PATH); - if (path.indexOf(SCALA_BIN) < 0) { - int inx = path.lastIndexOf(";"); - StringBuffer buf = new StringBuffer(path); - if (0 < inx && inx < path.length()-1) - buf.append(";"); - buf.append(SCALA_BIN); - data = new RegStringValue(envKey, PATH, buf.toString()); - envKey.setValue(data); - } - } - else { // uninstall - // remove home directory - try { - envKey.deleteValue(SCALA_HOME); - } - catch (NoSuchValueException e) { - // do nothing - } - String path = envKey.getStringValue(PATH); - int inx1 = path.indexOf(SCALA_BIN); - if (inx1 >= 0) { - int inx2 = path.indexOf(";", inx1); - StringBuffer buf = new StringBuffer(path.substring(0, inx1)); - if (inx2 >= 0) - buf.append(path.substring(inx2)); - RegStringValue data = new RegStringValue(envKey, PATH, buf.toString()); - envKey.setValue(data); - } - } - - // HKEY_CURRENT_USER\Software - RegistryKey softwareKey = Registry.openSubkey( - Registry.HKEY_CURRENT_USER, - "Software", - RegistryKey.ACCESS_WRITE); - if (homePath != null) { - RegistryKey productKey = softwareKey.createSubKey( - fullName, - "java.lang.String", - RegistryKey.ACCESS_WRITE); - RegStringValue data = new RegStringValue(productKey, "Location", homePath); - productKey.setValue(data); - } - else { // uninstall - try { - softwareKey.deleteSubKey(fullName); - String name = fullName; - int inx = name.lastIndexOf("\\"); - while (inx != -1) { - String parentName = name.substring(0, inx); - RegistryKey key = softwareKey.openSubKey(parentName, RegistryKey.ACCESS_READ); - int n = key.getNumberSubkeys(); - if (n == 0) softwareKey.deleteSubKey(parentName); - name = parentName; - inx = name.lastIndexOf("\\"); - } - } - catch (NoSuchKeyException e) { - // do nothing - } - } - } - - public static void main(String[] args) { - int argc = args.length; - if (argc != 1 && argc != 2) { - System.out.println("Usage: java Main [ ]\n"); - System.out.println("\tversion number (e.g. 1.4.0.1)"); - System.out.println("\tinstall path (e.g. c:\\\\Program Files\\\\Scala)"); - System.out.println(); - System.exit((argc > 0) ? 1 : 0); - } - String homePath = (argc == 2) ? args[1] : null; // e.g. "C:\\Program Files\\Scala" - String fullName = "EPFL\\Scala\\" + args[0]; // e.g. "EPFL\\Scala\\1.4.0.1" - try { - updateRegistry(homePath, fullName); - } - catch (RegistryException e) { - System.out.println(e.getMessage()); - System.exit(1); - } - } - -} diff --git a/config/izpack/targets/path_macosx.txt b/config/izpack/targets/path_macosx.txt deleted file mode 100644 index bbae42e6bc..0000000000 --- a/config/izpack/targets/path_macosx.txt +++ /dev/null @@ -1 +0,0 @@ -/usr/local/ diff --git a/config/izpack/targets/path_unix.txt b/config/izpack/targets/path_unix.txt deleted file mode 100644 index bbae42e6bc..0000000000 --- a/config/izpack/targets/path_unix.txt +++ /dev/null @@ -1 +0,0 @@ -/usr/local/ diff --git a/lib/fjbg.jar.desired.sha1 b/lib/fjbg.jar.desired.sha1 new file mode 100644 index 0000000000..ed3c414956 --- /dev/null +++ b/lib/fjbg.jar.desired.sha1 @@ -0,0 +1 @@ +0b8a2e9257039ac9a7ba02720e3497655aa2015b ?fjbg.jar diff --git a/lib/jaco.jar.desired.sha1 b/lib/jaco.jar.desired.sha1 new file mode 100644 index 0000000000..cfd3e09ca8 --- /dev/null +++ b/lib/jaco.jar.desired.sha1 @@ -0,0 +1 @@ +d7d547efe60ae6f398183bd04074723e480dc39d ?jaco.jar diff --git a/lib/msil.jar.desired.sha1 b/lib/msil.jar.desired.sha1 new file mode 100644 index 0000000000..90c937b347 --- /dev/null +++ b/lib/msil.jar.desired.sha1 @@ -0,0 +1 @@ +eee44b93d8b1936061e55ec9207e8c4151198e08 ?msil.jar diff --git a/lib/scala-compiler.jar.desired.sha1 b/lib/scala-compiler.jar.desired.sha1 new file mode 100644 index 0000000000..306cc36177 --- /dev/null +++ b/lib/scala-compiler.jar.desired.sha1 @@ -0,0 +1 @@ +050578dd01ce7a0189f9a703bc3862296818ca36 ?scala-compiler.jar diff --git a/lib/scala-library.jar.desired.sha1 b/lib/scala-library.jar.desired.sha1 new file mode 100644 index 0000000000..444d9bcb44 --- /dev/null +++ b/lib/scala-library.jar.desired.sha1 @@ -0,0 +1 @@ +2a39d9395a726506fe3978133e0a4ae2119993c4 ?scala-library.jar diff --git a/lib/scala.dll b/lib/scala.dll new file mode 100644 index 0000000000..22c2e372e9 Binary files /dev/null and b/lib/scala.dll differ diff --git a/newsources/scala/Array.scala b/newsources/scala/Array.scala deleted file mode 100644 index b1f15e1b6d..0000000000 --- a/newsources/scala/Array.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -final class Array[A](_length: Int) extends Cloneable with java.io.Serializable with Seq[A] { - def length: Int = throw new Error(); - def apply(i: Int): A = throw new Error(); - def update(i: Int, x: A): Unit = throw new Error(); - def elements: Iterator[A] = throw new Error(); -} diff --git a/newsources/scala/CaseClass.scala b/newsources/scala/CaseClass.scala deleted file mode 100644 index e644a03750..0000000000 --- a/newsources/scala/CaseClass.scala +++ /dev/null @@ -1,32 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - -/** defines an access function for instances of case classes - * - * @author Burak Emir - */ -trait CaseClass extends AnyRef { - - /** for a case class A(x_0,...,x_(k-1)), returns x_i for 0 <= i < k, - ** null otherwise - */ - def caseElement(n: Int): Any ; - - /** need also, for reflection - def setCaseElement(n: Int, v: Any): unit - */ - - /** for a case class A(x_0,...,x_(k-1)), returns k - */ - def caseArity: Int; - - def caseName: String; -} diff --git a/newsources/scala/MatchError.scala b/newsources/scala/MatchError.scala deleted file mode 100644 index 4979df8717..0000000000 --- a/newsources/scala/MatchError.scala +++ /dev/null @@ -1,40 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** ** -** $Id$ -\* */ -package scala; - - -/** This class implements errors which are thrown whenever an - * object doesn't match any pattern of a pattern matching - * expression. - * - * @author Matthias Zenger - * @author Martin Odersky - * @version 1.1, 05/03/2004 - */ -object MatchError { - - // todo: change pattern matcher so that dummy type parameter T can be removed. - def fail[T](source: String, line: Int): All = throw new MatchError(source, line); - - def report(source: String, line: Int, obj: Any) = - try { - throw new MatchError(source, line, obj.toString()) - } catch { - case e: MatchError => throw e - case e: Throwable => throw new MatchError(source, line) - } -} - -final class MatchError(msg: String) extends Error(msg) { - def this(source: String, line: Int) = - this(" in '" + source + "' at line " + line); - def this(source: String, line: Int, obj: String) = - this("for object " + obj + " in '" + source + "' at line " + line); -} diff --git a/newsources/scala/ScalaObject.scala b/newsources/scala/ScalaObject.scala deleted file mode 100644 index 21c1fdbfba..0000000000 --- a/newsources/scala/ScalaObject.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -trait ScalaObject extends AnyRef { - - /** This method is needed for optimizing pattern matching expressions - * which match on constructors of case classes. - */ - def $tag(): Int = 0; - -} diff --git a/sources/bin/izpack.symlink.tmpl b/sources/bin/izpack.symlink.tmpl deleted file mode 100644 index 009f8b6eec..0000000000 --- a/sources/bin/izpack.symlink.tmpl +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh - -DIRNAME="dirname" -LN="/bin/ln -sf" - -COMMANDS="scala scalac scaladoc scalap" - -cd `$DIRNAME $0` && \ -for cmd in $COMMANDS; do $LN $1 $cmd; done - -# $Id$ diff --git a/sources/bin/nscala-tool.win.tmpl b/sources/bin/nscala-tool.win.tmpl deleted file mode 100644 index ff9f7475c5..0000000000 --- a/sources/bin/nscala-tool.win.tmpl +++ /dev/null @@ -1,47 +0,0 @@ -@echo off - -rem ########################################################################## -rem # Copyright @COPYRIGHT@ -rem # -rem # This is free software; see the distribution for copying conditions. -rem # There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A -rem # PARTICULAR PURPOSE. -rem ########################################################################## - -if "%OS%"=="Windows_NT" @setlocal -if "%OS%"=="Windows_NT" @set SCALA_HOME=%~dp0 - -if "%SCALA_HOME%" == "" goto error1 -if not exist "%SCALA_HOME%\VERSION-@VERSION@" goto error2 - -set _ARGS= -:loop -if '%1' == '' goto exec -set _ARGS=%_ARGS% %1 -shift -goto loop - -:exec -set _JAVACMD=java -set _PROPS=-Dscala.product=@PRODUCT@ -Dscala.version=@VERSION@ -set _MAIN=@MAIN@ -set _TOOLS_CPATH=@TOOLS_CPATH@ -set _LIB_CPATH=@LIB_CPATH@ - -rem echo %_JAVACMD% %_PROPS% -cp %_CPATH% %_MAIN% %_ARGS% -%_JAVACMD% %_PROPS% -cp %_TOOLS_CPATH% %_MAIN% -sourcepath %_LIB_CPATH% %_ARGS% -goto end - -rem ########################################################################## -rem # errors - -:error1 -echo ERROR: environment variable SCALA_HOME is undefined. It should point to the directory containing the file "VERSION-@VERSION@". -goto end - -:error2 -echo ERROR: environment variable SCALA_HOME points to the wrong directory "%SCALA_HOME%". It should point to the directory containing the file "VERSION-@VERSION@". -goto end - -:end -if "%OS%"=="Windows_NT" @endlocal diff --git a/sources/bin/nscala.unix.tmpl b/sources/bin/nscala.unix.tmpl deleted file mode 100644 index 8288bde383..0000000000 --- a/sources/bin/nscala.unix.tmpl +++ /dev/null @@ -1,82 +0,0 @@ -#!/bin/bash - -############################################################################## -# Copyright @COPYRIGHT@ -# -# This is free software; see the distribution for copying conditions. -# There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A -# PARTICULAR PURPOSE. -############################################################################## - -cygwin=false; -darwin=false; -case "`uname`" in - CYGWIN*) cygwin=true ;; - Darwin*) darwin=true ;; -esac - -SOURCE=$0; -SCRIPT=`basename "$SOURCE"`; -while [ -h "$SOURCE" ]; do - SCRIPT=`basename "$SOURCE"`; - LOOKUP=`ls -ld "$SOURCE"`; - TARGET=`expr "$LOOKUP" : '.*-> \(.*\)$'`; - if expr "${TARGET:-.}/" : '/.*/$' > /dev/null; then - SOURCE=${TARGET:-.}; - else - SOURCE=`dirname "$SOURCE"`/${TARGET:-.}; - fi; -done; -PREFIX=`dirname "$SOURCE"`/..; -prefix=$PREFIX; -PREFIX=`cd "$PREFIX"; pwd`; - -if [ -z "$SCRIPT" ]; then - abort "Illegal direct invocation; invoke me through a symbolic link."; -fi; - -_JAVACMD=java -_TOOLS_CPATH=@TOOLS_CPATH@ -_LIB_CPATH=@LIB_CPATH@ - -# For Cygwin, switch paths to appropriate format before running java -if $cygwin; then - if [ "$OS" = "Windows_NT" ] && cygpath -m .>/dev/null 2>/dev/null ; then - format=mixed - else - format=windows - fi - _TOOLS_CPATH=`cygpath --path --$format "$_TOOLS_CPATH"` - _LIB_CPATH=`cygpath --path --$format "$_LIB_CPATH"` -fi - -main= -case "$SCRIPT" in - @SCALA@ ) ;; - @SCALAC@ ) main=scala.tools.nsc.Main;; - @SCALAI@ ) main=scala.tools.nsc.MainInterpreter;; - @SCALAP@ ) main=scala.tools.scalap.Main;; - @SCALATOK@ ) main=scala.tools.nsc.MainTokenMetric;; - * ) abort "Don't know what to do for $SCRIPT.";; -esac; - -if [ -z "$main" ]; then - for arg in "" "$@"; do - [ -z "$arg" ] && continue; - if [ "$arg" = "-version" ]; then - echo "$SCRIPT @VERSION@ -- @COPYRIGHT@"; - exit 0 - fi - done; - $_JAVACMD \ - -Xbootclasspath/a:"$_LIB_CPATH" \ - "$@" -else - $_JAVACMD \ - -Xms16M -Xmx256M \ - -Dscala.product="$SCRIPT" \ - -Dscala.version="@VERSION@" \ - -Dscala.home="$PREFIX" \ - -cp "$_TOOLS_CPATH" \ - $main -sourcepath "$_LIB_CPATH" "$@" -fi diff --git a/sources/bin/nscala.win.tmpl b/sources/bin/nscala.win.tmpl deleted file mode 100644 index feb4655e0f..0000000000 --- a/sources/bin/nscala.win.tmpl +++ /dev/null @@ -1,49 +0,0 @@ -@echo off - -rem ########################################################################## -rem # Copyright @COPYRIGHT@ -rem # -rem # This is free software; see the distribution for copying conditions. -rem # There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A -rem # PARTICULAR PURPOSE. -rem ########################################################################## - -if "%OS%"=="Windows_NT" @setlocal -if "%OS%"=="Windows_NT" @set SCALA_HOME=%~dp0 - -if "%SCALA_HOME%" == "" goto error1 -if not exist "%SCALA_HOME%\VERSION-@VERSION@" goto error2 - -set _ARGS= -:loop -if '%1' == '' goto exec -if '%1' == '-version' goto version -set _ARGS=%_ARGS% %1 -shift -goto loop - -:exec -set _JAVACMD=java -set _JAVAOPT=-Xbootclasspath/a:@BOOTCPATH@ - -rem echo %_JAVACMD% %_JAVAOPT% %_ARGS% -%_JAVACMD% %_JAVAOPT% %_ARGS% -goto end - -:version -echo @PRODUCT@ @VERSION@ -- @COPYRIGHT@ -goto end - -rem ########################################################################## -rem # errors - -:error1 -echo ERROR: environment variable SCALA_HOME is undefined. It should point to the directory containing the file "VERSION-@VERSION@". -goto end - -:error2 -echo ERROR: environment variable SCALA_HOME points to the wrong directory "%SCALA_HOME%". It should point to the directory containing the file "VERSION-@VERSION@". -goto end - -:end -if "%OS%"=="Windows_NT" @endlocal diff --git a/sources/msil/AssemblyInfo.cs.tmpl b/sources/msil/AssemblyInfo.cs.tmpl deleted file mode 100644 index c32f40ff11..0000000000 --- a/sources/msil/AssemblyInfo.cs.tmpl +++ /dev/null @@ -1,58 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; - -// -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -// -[assembly: AssemblyTitle("scala")] -[assembly: AssemblyDescription("Scala Runtime Library")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("EPFL-LAMP")] -[assembly: AssemblyProduct("Scala Language Distribution")] -[assembly: AssemblyCopyright("2002-2005 EPFL-LAMP")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly: AssemblyVersion("SCALA_VERSION")] - -// -// In order to sign your assembly you must specify a key to use. Refer to the -// Microsoft .NET Framework documentation for more information on assembly signing. -// -// Use the attributes below to control which key is used for signing. -// -// Notes: -// (*) If no key is specified, the assembly is not signed. -// (*) KeyName refers to a key that has been installed in the Crypto Service -// Provider (CSP) on your machine. KeyFile refers to a file which contains -// a key. -// (*) If the KeyFile and the KeyName values are both specified, the -// following processing occurs: -// (1) If the KeyName can be found in the CSP, that key is used. -// (2) If the KeyName does not exist and the KeyFile does exist, the key -// in the KeyFile is installed into the CSP and used. -// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. -// When specifying the KeyFile, the location of the KeyFile should be -// relative to the project output directory which is -// %Project Directory%\obj\. For example, if your KeyFile is -// located in the project directory, you would specify the AssemblyKeyFile -// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] -// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework -// documentation for more information on this. -// -[assembly: AssemblyDelaySign(true)] -[assembly: AssemblyKeyFile("lamp.key")] -[assembly: AssemblyKeyName("")] diff --git a/sources/msil/scala/runtime/compat/Math.scala b/sources/msil/scala/runtime/compat/Math.scala deleted file mode 100644 index 5b9853e953..0000000000 --- a/sources/msil/scala/runtime/compat/Math.scala +++ /dev/null @@ -1,36 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime.compat; - -object Math { - val MIN_BYTE = System.SByte.MinValue; - val MAX_BYTE = System.SByte.MaxValue; - val MIN_SHORT = System.Int16.MinValue; - val MAX_SHORT = System.Int16.MaxValue; - val MIN_CHAR = System.Char.MinValue; - val MAX_CHAR = System.Char.MaxValue; - val MIN_INT = System.Int32.MinValue; - val MAX_INT = System.Int32.MaxValue; - val MIN_LONG = System.Int64.MinValue; - val MAX_LONG = System.Int64.MaxValue; - val MIN_FLOAT = System.Single.MinValue; - val MAX_FLOAT = System.Single.MaxValue; - val MIN_DOUBLE = System.Double.MinValue; - val MAX_DOUBLE = System.Double.MaxValue; - - def max(x: Int, y: Int): Int = System.Math.Max(x, y); - - def ceil (x: Double): Double = System.Math.Ceiling(x); - def floor(x: Double): Double = System.Math.Floor(x); - def log (x: Double): Double = System.Math.Log(x); - def sqrt (x: Double): Double = System.Math.Sqrt(x); -} diff --git a/sources/msil/scala/runtime/compat/Platform.scala b/sources/msil/scala/runtime/compat/Platform.scala deleted file mode 100644 index fcdaa54e22..0000000000 --- a/sources/msil/scala/runtime/compat/Platform.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime.compat; - -object Platform { - def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: int): Unit = - System.Array.Copy(src.asInstanceOf[System.Array], srcPos, dest.asInstanceOf[System.Array], destPos, length); - def getClass(obj: AnyRef) = obj.GetType(); - def getClassName(obj: AnyRef) = obj.GetType().FullName; - def printStackTrace(exc: System.Exception) = - System.Console.WriteLine(exc.StackTrace); - def getMessage(exc: System.Exception) = exc.Message; - def split(str: String, separator: Char): Array[String] = { - val sep = new Array[Char](1); - sep(0) = separator; - str.Split(sep); - } - - def currentThread = System.Threading.Thread.CurrentThread; - - def parseByte(s: String) : Byte = System.Byte.Parse(s); - def parseShort(s: String) : Short = System.Int16.Parse(s); - def parseInt(s: String) : Int = System.Int32.Parse(s); - def parseLong(s: String) : Long = System.Int64.Parse(s); - def parseFloat(s: String) : Float = System.Single.Parse(s); - def parseDouble(s: String): Double = System.Double.Parse(s); - - def isDigit(c: Char): Boolean = System.Char.IsDigit(c); -} diff --git a/sources/msil/scala/runtime/compat/StringBuilder.scala b/sources/msil/scala/runtime/compat/StringBuilder.scala deleted file mode 100644 index 4154c0fb3a..0000000000 --- a/sources/msil/scala/runtime/compat/StringBuilder.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime.compat; - -class StringBuilder { - val str = new System.Text.StringBuilder(); - def append(x: Any): StringBuilder = { - str.Append(x); - this - } - def length(): Int = str.Length; - override def toString() = str.toString(); -} diff --git a/sources/msil/scala_part2.il.diff.tmpl b/sources/msil/scala_part2.il.diff.tmpl deleted file mode 100644 index 8f63867b2b..0000000000 --- a/sources/msil/scala_part2.il.diff.tmpl +++ /dev/null @@ -1,21 +0,0 @@ ---- scala_part2.il 2005-09-21 16:19:30.676754000 +0200 -+++ scala_part2.il.new 2005-09-21 16:21:58.522947000 +0200 -@@ -1,18 +1,3 @@ --.assembly extern 'mscorlib' --{ -- .ver 1:0:3300:0 -- .publickeytoken = (b7 7a 5c 56 19 34 e0 89) --} --.assembly extern 'scala_part1' --{ -- .ver SCALA_VERSION -- .publickeytoken = (80 07 fc 78 8a 2e 53 08) --} --.assembly 'scala_part2' --{ --} --.module 'scala_part2.dll' -- - .namespace 'scala' - { - .class public auto ansi interface 'Tuple1' diff --git a/sources/scala/All$.java b/sources/scala/All$.java deleted file mode 100644 index e220b26ac7..0000000000 --- a/sources/scala/All$.java +++ /dev/null @@ -1,10 +0,0 @@ -package scala; - -/** - * Dummy class which exist only to satisfy the JVM. It corresponds - * to scala.AllRef. If such type appears in method - * signatures, it is erased to this one. - */ - -public class All$ {} - diff --git a/sources/scala/AllRef$.java b/sources/scala/AllRef$.java deleted file mode 100644 index e8c7e77aa9..0000000000 --- a/sources/scala/AllRef$.java +++ /dev/null @@ -1,9 +0,0 @@ -package scala; - -/** - * Dummy class which exist only to satisfy the JVM. It corresponds - * to scala.AllRef. If such type appears in method - * signatures, it is erased to this one. - */ - -public class AllRef$ {} diff --git a/sources/scala/AnyVal.cs b/sources/scala/AnyVal.cs deleted file mode 100644 index 2178416e4e..0000000000 --- a/sources/scala/AnyVal.cs +++ /dev/null @@ -1,18 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using scala.runtime; - -namespace scala -{ - - [Meta("class extends scala.Any;")] - public abstract class AnyVal {} -} diff --git a/sources/scala/AnyVal.java b/sources/scala/AnyVal.java deleted file mode 100644 index a7a96d0a6d..0000000000 --- a/sources/scala/AnyVal.java +++ /dev/null @@ -1,14 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -/** @meta class extends scala.Any; */ -public abstract class AnyVal {} diff --git a/sources/scala/Application.scala b/sources/scala/Application.scala deleted file mode 100644 index 80fc41acbd..0000000000 --- a/sources/scala/Application.scala +++ /dev/null @@ -1,51 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** The Application class can be used to quickly turn objects - * into executable programs. Here is an example: - *
- *  object Main with Application {
- *    Console.println("Hello World!");
- *  }
- *  
- * Here, object Main inherits the main method - * of Application. The body of the Main object - * defines the main program. This technique does not work if the main - * program depends on command-line arguments (which are not accessible - * with the technique presented here). - * - * It is possible to time the execution of objects that inherit from - * class Application by setting the global scala.time property. - * Here is an example for benchmarking object Main: - *
- *  java -Dscala.time Main
- *  
- * - * @author Matthias Zenger - * @version 1.0, 10/09/03 - */ - -[_trait_] class Application { - - /** The time when execution of this program started. - */ - val executionStart: Long = java.lang.System.currentTimeMillis(); - - /** The default main method. - */ - def main(args: Array[String]) = { - if (java.lang.System.getProperty("scala.time") != null) - java.lang.System.out.println("[total " + - (java.lang.System.currentTimeMillis() - - executionStart) + "ms]"); - } -} diff --git a/sources/scala/Array.cs b/sources/scala/Array.cs deleted file mode 100644 index f48f18d5e4..0000000000 --- a/sources/scala/Array.cs +++ /dev/null @@ -1,35 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - [Meta("class [?T] extends scala.AnyRef;")] - [Serializable] - public abstract class Array /*: Cloneable*/ - { - - [Meta("constr (scala.Int);")] - public Array() {} - - [Meta("method []scala.Array[?T];")] - public abstract object value(); - - [Meta("method []scala.Int;")] - public abstract int length(); - [Meta("method (scala.Int)?T;")] - public abstract object apply(int i); - [Meta("method (scala.Int,?T)scala.Unit;")] - public abstract void update(int i, object x); - } -} diff --git a/sources/scala/Array.java b/sources/scala/Array.java deleted file mode 100644 index df85888513..0000000000 --- a/sources/scala/Array.java +++ /dev/null @@ -1,29 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -/** @meta class [?T] extends scala.AnyRef with java.lang.Cloneable with java.io.Serializable; */ -public abstract class Array implements Cloneable, java.io.Serializable { - - /** @meta constr (scala.Int); */ - public Array() {} - - /** @meta method []scala.Array[?T]; */ - public abstract Object value(); - - /** @meta method []scala.Int; */ - public abstract int length(); - /** @meta method (scala.Int)?T; */ - public abstract Object apply(int i); - /** @meta method (scala.Int,?T)scala.Unit; */ - public abstract void update(int i, Object x); - -} diff --git a/sources/scala/Attribute.scala b/sources/scala/Attribute.scala deleted file mode 100644 index 263d1cfbb5..0000000000 --- a/sources/scala/Attribute.scala +++ /dev/null @@ -1,14 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - -/** A base class for attributes -*/ -class Attribute {} diff --git a/sources/scala/Boolean.cs b/sources/scala/Boolean.cs deleted file mode 100644 index add1f882f1..0000000000 --- a/sources/scala/Boolean.cs +++ /dev/null @@ -1,61 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - [Meta("class extends scala.AnyVal;")] - [Serializable] - public abstract class Boolean : AnyVal - { - - public readonly bool value; - - public Boolean(bool value) - { - this.value = value; - } - - public override bool Equals(object other) - { - return other is Boolean && value == ((Boolean)other).value; - } - public override int GetHashCode() - { - return value ? 1231 : 1237; - } - public override string ToString() - { - return value.ToString(); - } - - [Meta("method (scala.Any)scala.Boolean;")] - public bool __eq__eq (object other) { return Equals(other); } - [Meta("method (scala.Any)scala.Boolean;")] - public bool __bang__eq(object other) { return !Equals(other); } - - [Meta("method []scala.Boolean;")] - public bool __bang ( ) { return !value ; } - - public string __plus (string that) { return value + that; } - - public bool __eq__eq (bool that) { return value == that; } - public bool __bang__eq (bool that) { return value != that; } - public bool __bar__bar (bool that) { return value || that; } - public bool __amp__amp (bool that) { return value && that; } - public bool __bar (bool that) { return value | that; } - public bool __amp (bool that) { return value & that; } - public bool __up (bool that) { return value ^ that; } - - } -} \ No newline at end of file diff --git a/sources/scala/Boolean.java b/sources/scala/Boolean.java deleted file mode 100644 index 960595f5a5..0000000000 --- a/sources/scala/Boolean.java +++ /dev/null @@ -1,53 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -/** @meta class extends scala.AnyVal; */ -public abstract class Boolean extends AnyVal implements java.io.Serializable { - - public final boolean value; - - public Boolean(boolean value) { - this.value = value; - } - - public boolean equals(java.lang.Object other) { - return other instanceof Boolean && value == ((Boolean)other).value; - } - public int hashCode() { - int bits = value ? 1231 : 1237; - return bits; - } - public String toString() { - return String.valueOf(value); - } - - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $eq$eq (java.lang.Object other) { return equals(other); } - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $bang$eq(java.lang.Object other) { return !equals(other); } - - /** @meta method []scala.Boolean; */ - public boolean $bang ( ) { return !value ; } - - - - public String $plus (String that) { return value + that; } - - public boolean $eq$eq (boolean that) { return value == that; } - public boolean $bang$eq (boolean that) { return value != that; } - public boolean $bar$bar (boolean that) { return value || that; } - public boolean $amp$amp (boolean that) { return value && that; } - public boolean $bar (boolean that) { return value | that; } - public boolean $amp (boolean that) { return value & that; } - public boolean $up (boolean that) { return value ^ that; } - -} diff --git a/sources/scala/BufferedIterator.scala b/sources/scala/BufferedIterator.scala deleted file mode 100644 index e17093e1d2..0000000000 --- a/sources/scala/BufferedIterator.scala +++ /dev/null @@ -1,26 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** Buffered iterators are iterators which allow to inspect the next - * element without discarding it. - * - * @author Martin Odersky - * @version 1.0, 16/07/2003 - */ -trait BufferedIterator[+A] extends Iterator[A] { - - /** Checks what the next available element is. - * - * @return the current element - */ - def head: A; -} diff --git a/sources/scala/Byte.cs b/sources/scala/Byte.cs deleted file mode 100644 index 4fd6493458..0000000000 --- a/sources/scala/Byte.cs +++ /dev/null @@ -1,132 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - [Meta("class extends scala.AnyVal;")] - [Serializable] - public abstract class Byte : AnyVal { - - public readonly sbyte value; - - public Byte(sbyte value) - { - this.value = value; - } - - public override bool Equals(object other) - { - return (other is Byte) && (value == ((Byte)other).value); - } - public override int GetHashCode() - { - return value; - } - public override string ToString() - { - return value.ToString(); - } - - [Meta("method (scala.Any)scala.Boolean;")] - public bool __eq__eq (object other) { return Equals(other); } - [Meta("method (scala.Any)scala.Boolean;")] - public bool __bang__eq(object other) { return !Equals(other); } - - [Meta("method []scala.Int;")] - public int __plus ( ) { return +value ; } - [Meta("method []scala.Int;")] - public int __minus ( ) { return -value ; } - - public string __plus (string that) { return value + that; } - - public bool __eq__eq (double that) { return value == that; } - public bool __bang__eq (double that) { return value != that; } - public bool __less (double that) { return value < that; } - public bool __greater (double that) { return value > that; } - public bool __less__eq (double that) { return value <= that; } - public bool __greater__eq(double that) { return value >= that; } - public double __plus (double that) { return value + that; } - public double __minus (double that) { return value - that; } - public double __times (double that) { return value * that; } - public double __div (double that) { return value / that; } - public double __percent (double that) { return value % that; } - - [Meta("method []scala.Double;")] - public double coerce ( ) { return value ; } - - public bool __eq__eq (float that) { return value == that; } - public bool __bang__eq (float that) { return value != that; } - public bool __less (float that) { return value < that; } - public bool __greater (float that) { return value > that; } - public bool __less__eq (float that) { return value <= that; } - public bool __greater__eq(float that) { return value >= that; } - public float __plus (float that) { return value + that; } - public float __minus (float that) { return value - that; } - public float __times (float that) { return value * that; } - public float __div (float that) { return value / that; } - public float __percent (float that) { return value % that; } - - [Meta("method []scala.Float;")] - public float coerce (float dummy) { return value ; } - [Meta("method []scala.Int;")] - public int __tilde ( ) { return ~value ; } - - public int __less__less (int that) { return value << that; } - public int __less__less (long that) { return value << (int)that; } - public int __greater__greater(int that) { return value >> that; } - public int __greater__greater(long that) { return value >> (int)that; } - public int __greater__greater__greater(int that) { return (int)((uint)value >>that); } - public int __greater__greater__greater(long that) { return (int)((uint)value >>(int)that); } - - public bool __eq__eq (long that) { return value == that; } - public bool __bang__eq (long that) { return value != that; } - public bool __less (long that) { return value < that; } - public bool __greater (long that) { return value > that; } - public bool __less__eq (long that) { return value <= that; } - public bool __greater__eq(long that) { return value >= that; } - public long __plus (long that) { return value + that; } - public long __minus (long that) { return value - that; } - public long __times (long that) { return value * that; } - public long __div (long that) { return value / that; } - public long __percent (long that) { return value % that; } - public long __bar (long that) { return value | that; } - public long __amp (long that) { return value & that; } - public long __up (long that) { return value ^ that; } - - [Meta("method []scala.Long;")] - public long coerce (long dummy) { return value ; } - - public bool __eq__eq (int that) { return value == that; } - public bool __bang__eq (int that) { return value != that; } - public bool __less (int that) { return value < that; } - public bool __greater (int that) { return value > that; } - public bool __less__eq (int that) { return value <= that; } - public bool __greater__eq(int that) { return value >= that; } - public int __plus (int that) { return value + that; } - public int __minus (int that) { return value - that; } - public int __times (int that) { return value * that; } - public int __div (int that) { return value / that; } - public int __percent (int that) { return value % that; } - public int __bar (int that) { return value | that; } - public int __amp (int that) { return value & that; } - public int __up (int that) { return value ^ that; } - - [Meta("method []scala.Int;")] - public int coerce (int dummy) { return value ; } - - [Meta("method []scala.Short;")] - public short coerce (short dummy) { return value ; } - - } -} \ No newline at end of file diff --git a/sources/scala/Byte.java b/sources/scala/Byte.java deleted file mode 100644 index 2a841225dc..0000000000 --- a/sources/scala/Byte.java +++ /dev/null @@ -1,189 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -/** @meta class extends scala.AnyVal; */ -public abstract class Byte extends AnyVal implements java.io.Serializable { - - public final byte value; - - public Byte (byte value) { - this.value = value; - } - - public boolean equals(java.lang.Object other) { - return other instanceof Byte && value == ((Byte )other).value; - } - public int hashCode() { - int bits = value; - return bits; - } - public String toString() { - return String.valueOf(value); - } - - /** @meta method []scala.Byte; */ - public byte toByte() { return (byte)value; } - - /** @meta method []scala.Short; */ - public short toShort() { return (short)value; } - - /** @meta method []scala.Char; */ - public char toChar() { return (char)value; } - - /** @meta method []scala.Int; */ - public int toInt() { return (int)value; } - - /** @meta method []scala.Long; */ - public long toLong() { return (long)value; } - - /** @meta method []scala.Float; */ - public float toFloat() { return (float)value; } - - /** @meta method []scala.Double; */ - public double toDouble() { return (double)value; } - - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $eq$eq (java.lang.Object other) { return equals(other); } - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $bang$eq(java.lang.Object other) { return !equals(other); } - - /** @meta method []scala.Int ; */ - public int $plus ( ) { return +value ; } - /** @meta method []scala.Int ; */ - public int $minus ( ) { return -value ; } - - public String $plus (String that) { return value + that; } - - public boolean $eq$eq (double that) { return value == that; } - public boolean $bang$eq (double that) { return value != that; } - public boolean $less (double that) { return value < that; } - public boolean $greater (double that) { return value > that; } - public boolean $less$eq (double that) { return value <= that; } - public boolean $greater$eq(double that) { return value >= that; } - public double $plus (double that) { return value + that; } - public double $minus (double that) { return value - that; } - public double $times (double that) { return value * that; } - public double $div (double that) { return value / that; } - public double $percent (double that) { return value % that; } - - /** @meta method []scala.Double ; */ - public double coerce ( ) { return value ; } - - public boolean $eq$eq (float that) { return value == that; } - public boolean $bang$eq (float that) { return value != that; } - public boolean $less (float that) { return value < that; } - public boolean $greater (float that) { return value > that; } - public boolean $less$eq (float that) { return value <= that; } - public boolean $greater$eq(float that) { return value >= that; } - public float $plus (float that) { return value + that; } - public float $minus (float that) { return value - that; } - public float $times (float that) { return value * that; } - public float $div (float that) { return value / that; } - public float $percent (float that) { return value % that; } - - /** @meta method []scala.Float ; */ - public float coerce ( ) { return value ; } - /** @meta method []scala.Int ; */ - public int $tilde ( ) { return ~value ; } - - public int $less$less (int that) { return value << that; } - public int $less$less (long that) { return value << that; } - public int $greater$greater(int that) { return value >> that; } - public int $greater$greater(long that) { return value >> that; } - public int $greater$greater$greater(int that) { return value >>>that; } - public int $greater$greater$greater(long that) { return value >>>that; } - - public boolean $eq$eq (long that) { return value == that; } - public boolean $bang$eq (long that) { return value != that; } - public boolean $less (long that) { return value < that; } - public boolean $greater (long that) { return value > that; } - public boolean $less$eq (long that) { return value <= that; } - public boolean $greater$eq(long that) { return value >= that; } - public long $plus (long that) { return value + that; } - public long $minus (long that) { return value - that; } - public long $times (long that) { return value * that; } - public long $div (long that) { return value / that; } - public long $percent (long that) { return value % that; } - public long $bar (long that) { return value | that; } - public long $amp (long that) { return value & that; } - public long $up (long that) { return value ^ that; } - - /** @meta method []scala.Long ; */ - public long coerce ( ) { return value ; } - - public boolean $eq$eq (int that) { return value == that; } - public boolean $bang$eq (int that) { return value != that; } - public boolean $less (int that) { return value < that; } - public boolean $greater (int that) { return value > that; } - public boolean $less$eq (int that) { return value <= that; } - public boolean $greater$eq(int that) { return value >= that; } - public int $plus (int that) { return value + that; } - public int $minus (int that) { return value - that; } - public int $times (int that) { return value * that; } - public int $div (int that) { return value / that; } - public int $percent (int that) { return value % that; } - public int $bar (int that) { return value | that; } - public int $amp (int that) { return value & that; } - public int $up (int that) { return value ^ that; } - - /** @meta method []scala.Int ; */ - public int coerce ( ) { return value ; } - - /** @meta method []scala.Short ; */ - public short coerce ( ) { return value ; } - - - public boolean $eq$eq (char that) { return value == that; } - public boolean $bang$eq (char that) { return value != that; } - public boolean $less (char that) { return value < that; } - public boolean $greater (char that) { return value > that; } - public boolean $less$eq (char that) { return value <= that; } - public boolean $greater$eq(char that) { return value >= that; } - public int $plus (char that) { return value + that; } - public int $minus (char that) { return value - that; } - public int $times (char that) { return value * that; } - public int $div (char that) { return value / that; } - public int $percent (char that) { return value % that; } - public int $bar (char that) { return value | that; } - public int $amp (char that) { return value & that; } - public int $up (char that) { return value ^ that; } - - public boolean $eq$eq (short that) { return value == that; } - public boolean $bang$eq (short that) { return value != that; } - public boolean $less (short that) { return value < that; } - public boolean $greater (short that) { return value > that; } - public boolean $less$eq (short that) { return value <= that; } - public boolean $greater$eq(short that) { return value >= that; } - public int $plus (short that) { return value + that; } - public int $minus (short that) { return value - that; } - public int $times (short that) { return value * that; } - public int $div (short that) { return value / that; } - public int $percent (short that) { return value % that; } - public int $bar (short that) { return value | that; } - public int $amp (short that) { return value & that; } - public int $up (short that) { return value ^ that; } - - public boolean $eq$eq (byte that) { return value == that; } - public boolean $bang$eq (byte that) { return value != that; } - public boolean $less (byte that) { return value < that; } - public boolean $greater (byte that) { return value > that; } - public boolean $less$eq (byte that) { return value <= that; } - public boolean $greater$eq(byte that) { return value >= that; } - public int $plus (byte that) { return value + that; } - public int $minus (byte that) { return value - that; } - public int $times (byte that) { return value * that; } - public int $div (byte that) { return value / that; } - public int $percent (byte that) { return value % that; } - public int $bar (byte that) { return value | that; } - public int $amp (byte that) { return value & that; } - public int $up (byte that) { return value ^ that; } -} diff --git a/sources/scala/CaseClass.scala b/sources/scala/CaseClass.scala deleted file mode 100644 index 0180efe267..0000000000 --- a/sources/scala/CaseClass.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - -/** defines an access function for instances of case classes - * - * @author Burak Emir - */ -trait CaseClass extends AnyRef { - - /** for a case class A(x_0,...,x_(k-1)), returns x_i for 0 <= i < k, - ** null otherwise - */ - def caseElement(n: Int): Any ; - - /** need also, for reflection - def setCaseElement(n: Int, v: Any): unit - */ - - /** for a case class A(x_0,...,x_(k-1)), returns k - */ - def caseArity: Int ; - - def caseName: String = ""; // for now - -} diff --git a/sources/scala/Cell.scala b/sources/scala/Cell.scala deleted file mode 100644 index 8a5146a3a3..0000000000 --- a/sources/scala/Cell.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** A Cell is a generic wrapper which completely - * hides the functionality of the wrapped object. The wrapped - * object is accessible via the elem accessor method. - * - * @author Martin Odersky - * @version 1.0, 08/08/2003 - */ -case class Cell[+T](elem: T); diff --git a/sources/scala/Char.cs b/sources/scala/Char.cs deleted file mode 100644 index b3e28a454b..0000000000 --- a/sources/scala/Char.cs +++ /dev/null @@ -1,128 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - [Meta("class extends scala.AnyVal;")] - public abstract class Char : AnyVal { - - public readonly char value; - - public Char(char value) - { - this.value = value; - } - - public override bool Equals(object other) - { - return other is Char && value == ((Char)other).value; - } - public override int GetHashCode() - { - return value; - } - public override string ToString() - { - return value.ToString(); - } - - [Meta("method (scala.Any)scala.Boolean;")] - public bool __eq__eq (object other) { return Equals(other); } - [Meta("method (scala.Any)scala.Boolean;")] - public bool __bang__eq(object other) { return !Equals(other); } - - [Meta("method []scala.Int;")] - public int __plus ( ) { return +value ; } - [Meta("method []scala.Int;")] - public int __minus ( ) { return -value ; } - - public string __plus (string that) { return value + that; } - - public bool __eq__eq (double that) { return value == that; } - public bool __bang__eq (double that) { return value != that; } - public bool __less (double that) { return value < that; } - public bool __greater (double that) { return value > that; } - public bool __less__eq (double that) { return value <= that; } - public bool __greater__eq(double that) { return value >= that; } - public double __plus (double that) { return value + that; } - public double __minus (double that) { return value - that; } - public double __times (double that) { return value * that; } - public double __div (double that) { return value / that; } - public double __percent (double that) { return value % that; } - - [Meta("method []scala.Double;")] - public double coerce ( ) { return value ; } - - public bool __eq__eq (float that) { return value == that; } - public bool __bang__eq (float that) { return value != that; } - public bool __less (float that) { return value < that; } - public bool __greater (float that) { return value > that; } - public bool __less__eq (float that) { return value <= that; } - public bool __greater__eq(float that) { return value >= that; } - public float __plus (float that) { return value + that; } - public float __minus (float that) { return value - that; } - public float __times (float that) { return value * that; } - public float __div (float that) { return value / that; } - public float __percent (float that) { return value % that; } - - [Meta("method []scala.Float;")] - public float coerce (float dummy) { return value; } - [Meta("method []scala.Int;")] - public int __tilde ( ) { return ~value; } - - public int __less__less (int that) { return value << that; } - public int __less__less (long that) { return value << (int)that; } - public int __greater__greater(int that) { return value >> that; } - public int __greater__greater(long that) { return value >> (int)that; } - public int __greater__greater__greater(int that) { return (int)((uint)value >>that); } - public int __greater__greater__greater(long that) { return (int)((uint)value >>(int)that); } - - public bool __eq__eq (long that) { return value == that; } - public bool __bang__eq (long that) { return value != that; } - public bool __less (long that) { return value < that; } - public bool __greater (long that) { return value > that; } - public bool __less__eq (long that) { return value <= that; } - public bool __greater__eq(long that) { return value >= that; } - public long __plus (long that) { return value + that; } - public long __minus (long that) { return value - that; } - public long __times (long that) { return value * that; } - public long __div (long that) { return value / that; } - public long __percent (long that) { return value % that; } - public long __bar (long that) { return value | that; } - public long __amp (long that) { return value & that; } - public long __up (long that) { return value ^ that; } - - [Meta("method []scala.Long;")] - public long coerce (long dummy) { return value ; } - - public bool __eq__eq (int that) { return value == that; } - public bool __bang__eq (int that) { return value != that; } - public bool __less (int that) { return value < that; } - public bool __greater (int that) { return value > that; } - public bool __less__eq (int that) { return value <= that; } - public bool __greater__eq(int that) { return value >= that; } - public int __plus (int that) { return value + that; } - public int __minus (int that) { return value - that; } - public int __times (int that) { return value * that; } - public int __div (int that) { return value / that; } - public int __percent (int that) { return value % that; } - public int __bar (int that) { return value | that; } - public int __amp (int that) { return value & that; } - public int __up (int that) { return value ^ that; } - - [Meta("method []scala.Int;")] - public int coerce (int dummy) { return value ; } - - } -} \ No newline at end of file diff --git a/sources/scala/Char.java b/sources/scala/Char.java deleted file mode 100644 index a875e717df..0000000000 --- a/sources/scala/Char.java +++ /dev/null @@ -1,187 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -/** @meta class extends scala.AnyVal; */ -public abstract class Char extends AnyVal implements java.io.Serializable { - - public final char value; - - public Char (char value) { - this.value = value; - } - - public boolean equals(java.lang.Object other) { - return other instanceof Char && value == ((Char )other).value; - } - public int hashCode() { - int bits = value; - return bits; - } - public String toString() { - return String.valueOf(value); - } - - /** @meta method []scala.Byte; */ - public byte toByte() { return (byte)value; } - - /** @meta method []scala.Short; */ - public short toShort() { return (short)value; } - - /** @meta method []scala.Char; */ - public char toChar() { return (char)value; } - - /** @meta method []scala.Int; */ - public int toInt() { return (int)value; } - - /** @meta method []scala.Long; */ - public long toLong() { return (long)value; } - - /** @meta method []scala.Float; */ - public float toFloat() { return (float)value; } - - /** @meta method []scala.Double; */ - public double toDouble() { return (double)value; } - - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $eq$eq (java.lang.Object other) { return equals(other); } - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $bang$eq(java.lang.Object other) { return !equals(other); } - - /** @meta method []scala.Int ; */ - public int $plus ( ) { return +value ; } - /** @meta method []scala.Int ; */ - public int $minus ( ) { return -value ; } - - public String $plus (String that) { return value + that; } - - public boolean $eq$eq (double that) { return value == that; } - public boolean $bang$eq (double that) { return value != that; } - public boolean $less (double that) { return value < that; } - public boolean $greater (double that) { return value > that; } - public boolean $less$eq (double that) { return value <= that; } - public boolean $greater$eq(double that) { return value >= that; } - public double $plus (double that) { return value + that; } - public double $minus (double that) { return value - that; } - public double $times (double that) { return value * that; } - public double $div (double that) { return value / that; } - public double $percent (double that) { return value % that; } - - /** @meta method []scala.Double ; */ - public double coerce ( ) { return value ; } - - public boolean $eq$eq (float that) { return value == that; } - public boolean $bang$eq (float that) { return value != that; } - public boolean $less (float that) { return value < that; } - public boolean $greater (float that) { return value > that; } - public boolean $less$eq (float that) { return value <= that; } - public boolean $greater$eq(float that) { return value >= that; } - public float $plus (float that) { return value + that; } - public float $minus (float that) { return value - that; } - public float $times (float that) { return value * that; } - public float $div (float that) { return value / that; } - public float $percent (float that) { return value % that; } - - /** @meta method []scala.Float ; */ - public float coerce ( ) { return value ; } - /** @meta method []scala.Int ; */ - public int $tilde ( ) { return ~value ; } - - public int $less$less (int that) { return value << that; } - public int $less$less (long that) { return value << that; } - public int $greater$greater(int that) { return value >> that; } - public int $greater$greater(long that) { return value >> that; } - public int $greater$greater$greater(int that) { return value >>>that; } - public int $greater$greater$greater(long that) { return value >>>that; } - - public boolean $eq$eq (long that) { return value == that; } - public boolean $bang$eq (long that) { return value != that; } - public boolean $less (long that) { return value < that; } - public boolean $greater (long that) { return value > that; } - public boolean $less$eq (long that) { return value <= that; } - public boolean $greater$eq(long that) { return value >= that; } - public long $plus (long that) { return value + that; } - public long $minus (long that) { return value - that; } - public long $times (long that) { return value * that; } - public long $div (long that) { return value / that; } - public long $percent (long that) { return value % that; } - public long $bar (long that) { return value | that; } - public long $amp (long that) { return value & that; } - public long $up (long that) { return value ^ that; } - - /** @meta method []scala.Long ; */ - public long coerce ( ) { return value ; } - - public boolean $eq$eq (int that) { return value == that; } - public boolean $bang$eq (int that) { return value != that; } - public boolean $less (int that) { return value < that; } - public boolean $greater (int that) { return value > that; } - public boolean $less$eq (int that) { return value <= that; } - public boolean $greater$eq(int that) { return value >= that; } - public int $plus (int that) { return value + that; } - public int $minus (int that) { return value - that; } - public int $times (int that) { return value * that; } - public int $div (int that) { return value / that; } - public int $percent (int that) { return value % that; } - public int $bar (int that) { return value | that; } - public int $amp (int that) { return value & that; } - public int $up (int that) { return value ^ that; } - - public boolean $eq$eq (char that) { return value == that; } - public boolean $bang$eq (char that) { return value != that; } - public boolean $less (char that) { return value < that; } - public boolean $greater (char that) { return value > that; } - public boolean $less$eq (char that) { return value <= that; } - public boolean $greater$eq(char that) { return value >= that; } - public int $plus (char that) { return value + that; } - public int $minus (char that) { return value - that; } - public int $times (char that) { return value * that; } - public int $div (char that) { return value / that; } - public int $percent (char that) { return value % that; } - public int $bar (char that) { return value | that; } - public int $amp (char that) { return value & that; } - public int $up (char that) { return value ^ that; } - - public boolean $eq$eq (short that) { return value == that; } - public boolean $bang$eq (short that) { return value != that; } - public boolean $less (short that) { return value < that; } - public boolean $greater (short that) { return value > that; } - public boolean $less$eq (short that) { return value <= that; } - public boolean $greater$eq(short that) { return value >= that; } - public int $plus (short that) { return value + that; } - public int $minus (short that) { return value - that; } - public int $times (short that) { return value * that; } - public int $div (short that) { return value / that; } - public int $percent (short that) { return value % that; } - public int $bar (short that) { return value | that; } - public int $amp (short that) { return value & that; } - public int $up (short that) { return value ^ that; } - - public boolean $eq$eq (byte that) { return value == that; } - public boolean $bang$eq (byte that) { return value != that; } - public boolean $less (byte that) { return value < that; } - public boolean $greater (byte that) { return value > that; } - public boolean $less$eq (byte that) { return value <= that; } - public boolean $greater$eq(byte that) { return value >= that; } - public int $plus (byte that) { return value + that; } - public int $minus (byte that) { return value - that; } - public int $times (byte that) { return value * that; } - public int $div (byte that) { return value / that; } - public int $percent (byte that) { return value % that; } - public int $bar (byte that) { return value | that; } - public int $amp (byte that) { return value & that; } - public int $up (byte that) { return value ^ that; } - - - /** @meta method []scala.Int ; */ - public int coerce ( ) { return value ; } - -} diff --git a/sources/scala/Console.scala b/sources/scala/Console.scala deleted file mode 100644 index f9ec8fc490..0000000000 --- a/sources/scala/Console.scala +++ /dev/null @@ -1,253 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - -import Predef._; - -/** The Console object implements functionality for - * printing Scala values on the terminal. There are also functions - * for reading specific values. Console also defines - * constants for marking up text on ANSI terminals. - * - * @author Matthias Zenger - * @version 1.0, 03/09/2003 - */ -object Console { - import java.io._; - import java.text._; - - // ANSI colors foreground - final val BLACK = "\033[30m"; - final val RED = "\033[31m"; - final val GREEN = "\033[32m"; - final val YELLOW = "\033[33m"; - final val BLUE = "\033[34m"; - final val MAGENTA = "\033[35m"; - final val CYAN = "\033[36m"; - final val WHITE = "\033[37m"; - - // ANSI colors background - final val BLACK_B = "\033[40m"; - final val RED_B = "\033[41m"; - final val GREEN_B = "\033[42m"; - final val YELLOW_B = "\033[43m"; - final val BLUE_B = "\033[44m"; - final val MAGENTA_B = "\033[45m"; - final val CYAN_B = "\033[46m"; - final val WHITE_B = "\033[47m"; - - // ANSI styles - final val RESET = "\033[0m"; - final val BOLD = "\033[1m"; - final val UNDERLINED = "\033[4m"; - final val BLINK = "\033[5m"; - final val REVERSED = "\033[7m"; - final val INVISIBLE = "\033[8m"; - - private var out: PrintStream = java.lang.System.out; - private var in: BufferedReader = - new BufferedReader(new InputStreamReader(java.lang.System.in)); - - /** Set the default output stream. - * - * @param out the new output stream. - */ - def setOut(out: PrintStream): Unit = { - this.out = out; - } - - /** Set the default input stream. - * - * @param in the new input stream. - */ - def setIn(in: InputStream): Unit = { - this.in = new BufferedReader(new InputStreamReader(in)); - } - - /** Set the default input stream. - * - * @param reader specifies the new input stream. - */ - def setIn(reader: Reader): Unit = { - this.in = new BufferedReader(reader); - } - - /** Print an object on the terminal. - * - * @param obj the object to print. - */ - def print(obj: Any): Unit = { - if (obj == null) - out.print("null"); - else - out.print(obj.toString()); - } - - /** Flush the output stream. This function is required when partial - * output (i.e. output not terminated by a new line character) has - * to be made visible on the terminal. - */ - def flush: Unit = out.flush(); - - /** Print a new line character on the terminal. - */ - def println: Unit = { - out.println(); - } - - /** Print out an object followed by a new line character. - * - * @param x the object to print. - */ - def println(x: Any): Unit = { - out.println(x); - } - - /** Format and print out some text (in a fashion similar to printf in C). - * The format of the text to print is specified by the parameter - * text. The arguments that are inserted into specific - * locations in text are provided with parameter - * args. See class java.text.MessageFormat - * for a full specification of the format syntax. - * - * @param text the format of the text to print out. - * @param args the parameters used to instantiate the format. - */ - def printf(text: String)(args: Any*): Unit = { - // todo: Uncurry - if (text == null) - out.print("null"); - else - out.print(MessageFormat.format(text, textParams(args))); - } - - /** Read a full line from the terminal. - * - * @return the string read from the terminal. - */ - def readLine: String = in.readLine(); - - /** Read a boolean value from the terminal. - * - * @return the boolean value read from the terminal. - */ - def readBoolean: Boolean = in.readLine().toLowerCase() match { - case "true" => true - case "t" => true - case "yes" => true - case "y" => true - case _ => false - } - - /** Read a byte value from the terminal. - */ - def readByte: Byte = java.lang.Byte.decode(in.readLine()).byteValue(); - - /** Read a short value from the terminal. - */ - def readShort: Short = java.lang.Short.decode(in.readLine()).shortValue(); - - /** Read a char value from the terminal. - */ - def readChar: Char = in.readLine().charAt(0); - - /** Read an int value from the terminal. - */ - def readInt: Int = java.lang.Integer.decode(in.readLine()).intValue(); - - /** Read a float value from the terminal. - */ - def readFloat: Float = - scala.runtime.compat.Platform.parseFloat(in.readLine()); - - /** Read a double value from the terminal. - */ - def readDouble: Double = - scala.runtime.compat.Platform.parseDouble(in.readLine()); - - /** Read in some structured input, specified by a format specifier. - * See class java.text.MessageFormat for details of - * the format specification. - * - * @param format the format of the input. - * @return a list of all extracted values. - */ - def readf(format: String): List[Any] = - textComponents(new MessageFormat(format).parse(in.readLine())); - - /** Read in some structured input, specified by a format specifier. - * Opposed to readf, this function only returns the - * first value extracted from the input according to the format - * specification. - */ - def readf1(format: String): Any = readf(format).head; - - /** Read in some structured input, specified by a format specifier. - * Opposed to readf, this function only returns the - * first two values extracted from the input according to the format - * specification. - */ - def readf2(format: String): Pair[Any, Any] = { - val res = readf(format); - Pair(res.head, res.tail.head) - } - - /** Read in some structured input, specified by a format specifier. - * Opposed to readf, this function only returns the - * first three values extracted from the input according to the format - * specification. - */ - def readf3(format: String): Triple[Any, Any, Any] = { - val res = readf(format); - Triple(res.head, res.tail.head, res.tail.tail.head) - } - - private def textComponents(a: Array[AnyRef]): List[Any] = { - var i: Int = a.length - 1; - var res: List[Any] = Nil; - while (i >= 0) { - res = (a(i) match { - case x: java.lang.Boolean => x.booleanValue() - case x: java.lang.Byte => x.byteValue() - case x: java.lang.Short => x.shortValue() - case x: java.lang.Character => x.charValue() - case x: java.lang.Integer => x.intValue() - case x: java.lang.Long => x.longValue() - case x: java.lang.Float => x.floatValue() - case x: java.lang.Double => x.doubleValue() - case x => x - }) :: res; - i = i - 1; - } - res - } - - private def textParams(s: Seq[Any]): Array[AnyRef] = { - val res = new Array[AnyRef](s.length); - var i: Int = 0; - val iter = s.elements; - while (iter.hasNext) { - res(i) = iter.next match { - case x: Boolean => new java.lang.Boolean(x); - case x: Byte => new java.lang.Byte(x); - case x: Short => new java.lang.Short(x); - case x: Char => new java.lang.Character(x); - case x: Int => new java.lang.Integer(x); - case x: Long => new java.lang.Long(x); - case x: Float => new java.lang.Float(x); - case x: Double => new java.lang.Double(x); - case x: Unit => "()"; - case x: AnyRef => x; - } - i = i + 1; - } - res - } -} diff --git a/sources/scala/Double.cs b/sources/scala/Double.cs deleted file mode 100644 index 59da220403..0000000000 --- a/sources/scala/Double.cs +++ /dev/null @@ -1,66 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - [Meta("class extends scala.AnyVal;")] - [Serializable] - public abstract class Double : AnyVal { - - public readonly double value; - - public Double (double value) - { - this.value = value; - } - - public override bool Equals(object other) - { - return other is Double && value == ((Double )other).value; - } - public override int GetHashCode() - { - return value.GetHashCode(); - } - public override string ToString() - { - return value.ToString(); - } - - [Meta("method (scala.Any)scala.Boolean;")] - public bool __eq__eq (object other) { return Equals(other); } - [Meta("method (scala.Any)scala.Boolean;")] - public bool __bang__eq(object other) { return !Equals(other); } - - [Meta("method []scala.Double;")] - public double __plus (object dummy) { return +value; } - [Meta("method []scala.Double;")] - public double __minus ( ) { return -value; } - - public string __plus (string that) { return value + that; } - - public bool __eq__eq (double that) { return value == that; } - public bool __bang__eq (double that) { return value != that; } - public bool __less (double that) { return value < that; } - public bool __greater (double that) { return value > that; } - public bool __less__eq (double that) { return value <= that; } - public bool __greater__eq(double that) { return value >= that; } - public double __plus (double that) { return value + that; } - public double __minus (double that) { return value - that; } - public double __times (double that) { return value * that; } - public double __div (double that) { return value / that; } - public double __percent (double that) { return value % that; } - - } -} \ No newline at end of file diff --git a/sources/scala/Double.java b/sources/scala/Double.java deleted file mode 100644 index 77f44fd10e..0000000000 --- a/sources/scala/Double.java +++ /dev/null @@ -1,78 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -/** @meta class extends scala.AnyVal; */ -public abstract class Double extends AnyVal implements java.io.Serializable { - - public final double value; - - public Double (double value) { - this.value = value; - } - - public boolean equals(java.lang.Object other) { - return other instanceof Double && value == ((Double )other).value; - } - public int hashCode() { - long bits = java.lang.Double.doubleToLongBits(value); - return (int)(bits ^ (bits >>> 32)); - } - public String toString() { - return String.valueOf(value); - } - - /** @meta method []scala.Byte; */ - public byte toByte() { return (byte)value; } - - /** @meta method []scala.Short; */ - public short toShort() { return (short)value; } - - /** @meta method []scala.Char; */ - public char toChar() { return (char)value; } - - /** @meta method []scala.Int; */ - public int toInt() { return (int)value; } - - /** @meta method []scala.Long; */ - public long toLong() { return (long)value; } - - /** @meta method []scala.Float; */ - public float toFloat() { return (float)value; } - - /** @meta method []scala.Double; */ - public double toDouble() { return (double)value; } - - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $eq$eq (java.lang.Object other) { return equals(other); } - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $bang$eq(java.lang.Object other) { return !equals(other); } - - /** @meta method []scala.Double ; */ - public double $plus ( ) { return +value ; } - /** @meta method []scala.Double ; */ - public double $minus ( ) { return -value ; } - - public String $plus (String that) { return value + that; } - - public boolean $eq$eq (double that) { return value == that; } - public boolean $bang$eq (double that) { return value != that; } - public boolean $less (double that) { return value < that; } - public boolean $greater (double that) { return value > that; } - public boolean $less$eq (double that) { return value <= that; } - public boolean $greater$eq(double that) { return value >= that; } - public double $plus (double that) { return value + that; } - public double $minus (double that) { return value - that; } - public double $times (double that) { return value * that; } - public double $div (double that) { return value / that; } - public double $percent (double that) { return value % that; } - -} diff --git a/sources/scala/Enumeration.scala b/sources/scala/Enumeration.scala deleted file mode 100644 index 4515a8c4bf..0000000000 --- a/sources/scala/Enumeration.scala +++ /dev/null @@ -1,140 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - -import scala.collection.mutable._; -import Predef._; - -/** - *

The class Enumeration provides the same functionality as the - * enum construct found in C-like languages like C++ or Java. - * Here is an example:

- *
- * object Main with Application {
- *
- *   object WeekDays extends Enumeration  {
- *     val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
- *   }
- *
- *   def isWorkingDay(d: WeekDays.Value) =
- *     ! (d == WeekDays.Sat || d == WeekDays.Sun);
- *
- *   WeekDays filter (isWorkingDay) foreach { d => System.out.println(d) }
- * }
- * 
- * - * @param initial the initial integer value associated with the first element - * @param names the sequence of element names of the enumeration - * - * @author Matthias Zenger - * @version 1.0, 10/02/04 - */ -abstract class Enumeration(initial: Int, names: String*) { - - def this() = this(0, null); - - def this(names: String*) = this(0, names: _*); - - def name = { - val cname = scala.runtime.compat.Platform.getClassName(this); - if (cname.endsWith("$")) - cname.substring(0, cname.length() - 1); - else if (cname.endsWith("$class")) - cname.substring(0, cname.length() - 6); - else - cname; - } - - /** - * A mapping between the enumeration value id and the enumeration - * object. - */ - private var values: Map[Int, Value] = new HashMap; - - /** - * A cache listing all values of this enumeration. - */ - private var vcache: List[Value] = null; - - private def updateCache: List[Value] = - if (vcache == null) { - vcache = values.values.toList.sort((p1, p2) => p1.id < p2.id); - vcache - } else - vcache; - - protected var nextId = initial; - - protected var nextName = names.elements; - - private var topId = initial; - - final def maxId = topId; - - /** - * Returns the enumeration value for the given id. - */ - final def apply(x: Int): Value = values(x); - - /** - * Returns all values of this enumeration. - */ - final def elements: Iterator[Value] = updateCache.elements; - - def foreach(f: Value => Unit): Unit = elements foreach f; - - def forall(p: Value => Boolean): Boolean = elements forall p; - - def exists(p: Value => Boolean): Boolean = elements exists p; - - def map[b](f: Value => b): Iterator[b] = elements map f; - - def flatMap[b](f: Value => Iterator[b]): Iterator[b] = elements flatMap f; - - def filter(p: Value => Boolean): Iterator[Value] = elements filter p; - - override def toString(): String = updateCache.mkString("{", ", ", "}"); - - protected final def Value: Value = - new Val(nextId, if (nextName.hasNext) nextName.next else null); - - protected final def Value(i: Int): Value = - new Val(i, if (nextName.hasNext) nextName.next else null); - - protected final def Value(name: String): Value = new Val(nextId, name); - - protected final def Value(i: Int, name: String): Value = new Val(i, name); - - trait Value extends Ordered[Value] { - def id: Int; - override def compareTo[S >: Value <% Ordered[S]](that: S): Int = that match { - case that1: Value => id - that1.id - case _ => -(that compareTo this) - } - } - - protected class Val(i: Int, name: String) extends Value { - def this(i: Int) = - this(i, if (nextName.hasNext) nextName.next else i.toString()); - def this(name: String) = this(nextId, name); - def this() = - this(nextId, if (nextName.hasNext) nextName.next else nextId.toString()); - assert(!values.isDefinedAt(i)); - values(i) = this; - nextId = i + 1; - if (nextId > topId) - topId = nextId; - def id = i; - override def toString() = if (name == null) - Enumeration.this.name + "(" + i + ")"; - else - name; - } -} diff --git a/sources/scala/Float.cs b/sources/scala/Float.cs deleted file mode 100644 index 13832f3f1b..0000000000 --- a/sources/scala/Float.cs +++ /dev/null @@ -1,81 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - [Meta("class extends scala.AnyVal;")] - [Serializable] - public abstract class Float : AnyVal { - - public readonly float value; - - public Float(float value) - { - this.value = value; - } - - public override bool Equals(object other) - { - return (other is Float) && (value == ((Float)other).value); - } - public override int GetHashCode() - { - return value.GetHashCode(); - } - public override string ToString() - { - return value.ToString(); - } - - [Meta("method (scala.Any)scala.Boolean;")] - public bool __eq__eq(object other) { return Equals(other); } - [Meta("method (scala.Any)scala.Boolean;")] - public bool __bang__eq(object other) { return !Equals(other); } - - [Meta("method []scala.Float;")] - public float __plus ( ) { return +value ; } - [Meta("method []scala.Float;")] - public float __minus ( ) { return -value ; } - - public string __plus (string that) { return value + that; } - - public bool __eq__eq (double that) { return value == that; } - public bool __bang__eq (double that) { return value != that; } - public bool __less (double that) { return value < that; } - public bool __greater (double that) { return value > that; } - public bool __less__eq (double that) { return value <= that; } - public bool __greater__eq(double that) { return value >= that; } - public double __plus (double that) { return value + that; } - public double __minus (double that) { return value - that; } - public double __times (double that) { return value * that; } - public double __div (double that) { return value / that; } - public double __percent (double that) { return value % that; } - - [Meta("method []scala.Double;")] - public double coerce ( ) { return value; } - - public bool __eq__eq (float that) { return value == that; } - public bool __bang__eq (float that) { return value != that; } - public bool __less (float that) { return value < that; } - public bool __greater (float that) { return value > that; } - public bool __less__eq (float that) { return value <= that; } - public bool __greater__eq(float that) { return value >= that; } - public float __plus (float that) { return value + that; } - public float __minus (float that) { return value - that; } - public float __times (float that) { return value * that; } - public float __div (float that) { return value / that; } - public float __percent (float that) { return value % that; } - - } -} \ No newline at end of file diff --git a/sources/scala/Float.java b/sources/scala/Float.java deleted file mode 100644 index a4a35f575e..0000000000 --- a/sources/scala/Float.java +++ /dev/null @@ -1,93 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -/** @meta class extends scala.AnyVal; */ -public abstract class Float extends AnyVal implements java.io.Serializable { - - public final float value; - - public Float (float value) { - this.value = value; - } - - public boolean equals(java.lang.Object other) { - return other instanceof Float && value == ((Float )other).value; - } - public int hashCode() { - int bits = java.lang.Float.floatToIntBits(value); - return bits; - } - public String toString() { - return String.valueOf(value); - } - - /** @meta method []scala.Byte; */ - public byte toByte() { return (byte)value; } - - /** @meta method []scala.Short; */ - public short toShort() { return (short)value; } - - /** @meta method []scala.Char; */ - public char toChar() { return (char)value; } - - /** @meta method []scala.Int; */ - public int toInt() { return (int)value; } - - /** @meta method []scala.Long; */ - public long toLong() { return (long)value; } - - /** @meta method []scala.Float; */ - public float toFloat() { return (float)value; } - - /** @meta method []scala.Double; */ - public double toDouble() { return (double)value; } - - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $eq$eq (java.lang.Object other) { return equals(other); } - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $bang$eq(java.lang.Object other) { return !equals(other); } - - /** @meta method []scala.Float ; */ - public float $plus ( ) { return +value ; } - /** @meta method []scala.Float ; */ - public float $minus ( ) { return -value ; } - - public String $plus (String that) { return value + that; } - - public boolean $eq$eq (double that) { return value == that; } - public boolean $bang$eq (double that) { return value != that; } - public boolean $less (double that) { return value < that; } - public boolean $greater (double that) { return value > that; } - public boolean $less$eq (double that) { return value <= that; } - public boolean $greater$eq(double that) { return value >= that; } - public double $plus (double that) { return value + that; } - public double $minus (double that) { return value - that; } - public double $times (double that) { return value * that; } - public double $div (double that) { return value / that; } - public double $percent (double that) { return value % that; } - - /** @meta method []scala.Double ; */ - public double coerce ( ) { return value ; } - - public boolean $eq$eq (float that) { return value == that; } - public boolean $bang$eq (float that) { return value != that; } - public boolean $less (float that) { return value < that; } - public boolean $greater (float that) { return value > that; } - public boolean $less$eq (float that) { return value <= that; } - public boolean $greater$eq(float that) { return value >= that; } - public float $plus (float that) { return value + that; } - public float $minus (float that) { return value - that; } - public float $times (float that) { return value * that; } - public float $div (float that) { return value / that; } - public float $percent (float that) { return value % that; } - -} diff --git a/sources/scala/Function0.scala b/sources/scala/Function0.scala deleted file mode 100644 index f689152741..0000000000 --- a/sources/scala/Function0.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -trait Function0[+R] extends AnyRef { - def apply(): R; -} diff --git a/sources/scala/Function1.scala b/sources/scala/Function1.scala deleted file mode 100644 index cfb5897a2c..0000000000 --- a/sources/scala/Function1.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -trait Function1[-T0, +R] extends AnyRef { - def apply(v0: T0): R; -} diff --git a/sources/scala/Function2.scala b/sources/scala/Function2.scala deleted file mode 100644 index fd5eedc497..0000000000 --- a/sources/scala/Function2.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -trait Function2[-T0, -T1, +R] extends AnyRef { - def apply(v0: T0, v1: T1): R; -} diff --git a/sources/scala/Function3.scala b/sources/scala/Function3.scala deleted file mode 100644 index 9212945a4e..0000000000 --- a/sources/scala/Function3.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -trait Function3[-T0, -T1, -T2, +R] extends AnyRef { - def apply(v0: T0, v1: T1, v2: T2): R; -} diff --git a/sources/scala/Function4.scala b/sources/scala/Function4.scala deleted file mode 100644 index 4731986c30..0000000000 --- a/sources/scala/Function4.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -trait Function4[-T0, -T1, -T2, -T3, +R] extends AnyRef { - def apply(v0: T0, v1: T1, v2: T2, v3: T3): R; -} diff --git a/sources/scala/Function5.scala b/sources/scala/Function5.scala deleted file mode 100644 index 17abc7eb7f..0000000000 --- a/sources/scala/Function5.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -trait Function5[-T0, -T1, -T2, -T3, -T4, +R] extends AnyRef { - def apply(v0: T0, v1: T1, v2: T2, v3: T3, v4: T4): R; -} diff --git a/sources/scala/Function6.scala b/sources/scala/Function6.scala deleted file mode 100644 index 02f6c94af2..0000000000 --- a/sources/scala/Function6.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -trait Function6[-T0, -T1, -T2, -T3, -T4, -T5, +R] extends AnyRef { - def apply(v0: T0, v1: T1, v2: T2, v3: T3, v4: T4, v5: T5): R; -} diff --git a/sources/scala/Function7.scala b/sources/scala/Function7.scala deleted file mode 100644 index e97dc787ec..0000000000 --- a/sources/scala/Function7.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -trait Function7[-T0, -T1, -T2, -T3, -T4, -T5, -T6, +R] extends AnyRef { - def apply(v0: T0, v1: T1, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6): R; -} diff --git a/sources/scala/Function8.scala b/sources/scala/Function8.scala deleted file mode 100644 index f905cae58d..0000000000 --- a/sources/scala/Function8.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -trait Function8[-T0, -T1, -T2, -T3, -T4, -T5, -T6, -T7, +R] extends AnyRef { - def apply(v0: T0, v1: T1, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6, v7: T7): R; -} diff --git a/sources/scala/Function9.scala b/sources/scala/Function9.scala deleted file mode 100644 index 8ae0a5d658..0000000000 --- a/sources/scala/Function9.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -trait Function9[-T0, -T1, -T2, -T3, -T4, -T5, -T6, -T7, -T8, +R] extends AnyRef { - def apply(v0: T0, v1: T1, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6, v7: T7, v8: T8): R; -} diff --git a/sources/scala/Int.cs b/sources/scala/Int.cs deleted file mode 100644 index 001ee900d5..0000000000 --- a/sources/scala/Int.cs +++ /dev/null @@ -1,127 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - [Meta("class extends scala.AnyVal;")] - [Serializable] - public abstract class Int : AnyVal { - - public readonly int value; - - public Int(int value) - { - this.value = value; - } - - public override bool Equals(object other) - { - return (other is Int) && (value == ((Int)other).value); - } - public override int GetHashCode() - { - return value; - } - public override string ToString() - { - return value.ToString(); - } - - [Meta("method (scala.Any)scala.Boolean;")] - public bool __eq__eq (object other) { return Equals(other); } - [Meta("method (scala.Any)scala.Boolean;")] - public bool __bang__eq(object other) { return !Equals(other); } - - [Meta("method []scala.Int;")] - public int __plus ( ) { return +value ; } - - [Meta("method []scala.Int;")] - public int __minus ( ) { return -value ; } - - public string __plus (string that) { return value + that; } - - public bool __eq__eq (double that) { return value == that; } - public bool __bang__eq (double that) { return value != that; } - public bool __less (double that) { return value < that; } - public bool __greater (double that) { return value > that; } - public bool __less__eq (double that) { return value <= that; } - public bool __greater__eq(double that) { return value >= that; } - public double __plus (double that) { return value + that; } - public double __minus (double that) { return value - that; } - public double __times (double that) { return value * that; } - public double __div (double that) { return value / that; } - public double __percent (double that) { return value % that; } - - [Meta("method []scala.Double;")] - public double coerce (double dummy) { return value; } - - public bool __eq__eq (float that) { return value == that; } - public bool __bang__eq (float that) { return value != that; } - public bool __less (float that) { return value < that; } - public bool __greater (float that) { return value > that; } - public bool __less__eq (float that) { return value <= that; } - public bool __greater__eq(float that) { return value >= that; } - public float __plus (float that) { return value + that; } - public float __minus (float that) { return value - that; } - public float __times (float that) { return value * that; } - public float __div (float that) { return value / that; } - public float __percent (float that) { return value % that; } - - [Meta("method []scala.Float;")] - public float coerce (float dummy) { return value; } - [Meta("method []scala.Int;")] - public int __tilde ( ) { return ~value; } - - public int __less__less (int that) { return value << that; } - public int __less__less (long that) { return value << (int)that; } - public int __greater__greater(int that) { return value >> that; } - public int __greater__greater(long that) { return value >> (int)that; } - public int __greater__greater__greater(int that) { return (int)((uint)value >>that); } - public int __greater__greater__greater(long that) { return (int)((uint)value >>(int)that); } - - public bool __eq__eq (long that) { return value == that; } - public bool __bang__eq (long that) { return value != that; } - public bool __less (long that) { return value < that; } - public bool __greater (long that) { return value > that; } - public bool __less__eq (long that) { return value <= that; } - public bool __greater__eq(long that) { return value >= that; } - public long __plus (long that) { return value + that; } - public long __minus (long that) { return value - that; } - public long __times (long that) { return value * that; } - public long __div (long that) { return value / that; } - public long __percent (long that) { return value % that; } - public long __bar (long that) { return value | that; } - public long __amp (long that) { return value & that; } - public long __up (long that) { return value ^ that; } - - [Meta("method []scala.Long;")] - public long coerce (object dummy) { return value ; } - - public bool __eq__eq (int that) { return value == that; } - public bool __bang__eq (int that) { return value != that; } - public bool __less (int that) { return value < that; } - public bool __greater (int that) { return value > that; } - public bool __less__eq (int that) { return value <= that; } - public bool __greater__eq(int that) { return value >= that; } - public int __plus (int that) { return value + that; } - public int __minus (int that) { return value - that; } - public int __times (int that) { return value * that; } - public int __div (int that) { return value / that; } - public int __percent (int that) { return value % that; } - public int __bar (int that) { return value | that; } - public int __amp (int that) { return value & that; } - public int __up (int that) { return value ^ that; } - - } -} \ No newline at end of file diff --git a/sources/scala/Int.java b/sources/scala/Int.java deleted file mode 100644 index 5c5d95a63e..0000000000 --- a/sources/scala/Int.java +++ /dev/null @@ -1,184 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -/** @meta class extends scala.AnyVal; */ -public abstract class Int extends AnyVal implements java.io.Serializable { - - public final int value; - - public Int (int value) { - this.value = value; - } - - public boolean equals(java.lang.Object other) { - return other instanceof Int && value == ((Int )other).value; - } - public int hashCode() { - int bits = value; - return bits; - } - public String toString() { - return String.valueOf(value); - } - - /** @meta method []scala.Byte; */ - public byte toByte() { return (byte)value; } - - /** @meta method []scala.Short; */ - public short toShort() { return (short)value; } - - /** @meta method []scala.Char; */ - public char toChar() { return (char)value; } - - /** @meta method []scala.Int; */ - public int toInt() { return (int)value; } - - /** @meta method []scala.Long; */ - public long toLong() { return (long)value; } - - /** @meta method []scala.Float; */ - public float toFloat() { return (float)value; } - - /** @meta method []scala.Double; */ - public double toDouble() { return (double)value; } - - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $eq$eq (java.lang.Object other) { return equals(other); } - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $bang$eq(java.lang.Object other) { return !equals(other); } - - /** @meta method []scala.Int ; */ - public int $plus ( ) { return +value ; } - - /** @meta method []scala.Int ; */ - public int $minus ( ) { return -value ; } - - public String $plus (String that) { return value + that; } - - public boolean $eq$eq (double that) { return value == that; } - public boolean $bang$eq (double that) { return value != that; } - public boolean $less (double that) { return value < that; } - public boolean $greater (double that) { return value > that; } - public boolean $less$eq (double that) { return value <= that; } - public boolean $greater$eq(double that) { return value >= that; } - public double $plus (double that) { return value + that; } - public double $minus (double that) { return value - that; } - public double $times (double that) { return value * that; } - public double $div (double that) { return value / that; } - public double $percent (double that) { return value % that; } - - /** @meta method []scala.Double ; */ - public double coerce ( ) { return value ; } - - public boolean $eq$eq (float that) { return value == that; } - public boolean $bang$eq (float that) { return value != that; } - public boolean $less (float that) { return value < that; } - public boolean $greater (float that) { return value > that; } - public boolean $less$eq (float that) { return value <= that; } - public boolean $greater$eq(float that) { return value >= that; } - public float $plus (float that) { return value + that; } - public float $minus (float that) { return value - that; } - public float $times (float that) { return value * that; } - public float $div (float that) { return value / that; } - public float $percent (float that) { return value % that; } - - /** @meta method []scala.Float ; */ - public float coerce ( ) { return value ; } - /** @meta method []scala.Int ; */ - public int $tilde ( ) { return ~value ; } - - public int $less$less (int that) { return value << that; } - public int $less$less (long that) { return value << that; } - public int $greater$greater(int that) { return value >> that; } - public int $greater$greater(long that) { return value >> that; } - public int $greater$greater$greater(int that) { return value >>>that; } - public int $greater$greater$greater(long that) { return value >>>that; } - - public boolean $eq$eq (long that) { return value == that; } - public boolean $bang$eq (long that) { return value != that; } - public boolean $less (long that) { return value < that; } - public boolean $greater (long that) { return value > that; } - public boolean $less$eq (long that) { return value <= that; } - public boolean $greater$eq(long that) { return value >= that; } - public long $plus (long that) { return value + that; } - public long $minus (long that) { return value - that; } - public long $times (long that) { return value * that; } - public long $div (long that) { return value / that; } - public long $percent (long that) { return value % that; } - public long $bar (long that) { return value | that; } - public long $amp (long that) { return value & that; } - public long $up (long that) { return value ^ that; } - - /** @meta method []scala.Long ; */ - public long coerce ( ) { return value ; } - - public boolean $eq$eq (int that) { return value == that; } - public boolean $bang$eq (int that) { return value != that; } - public boolean $less (int that) { return value < that; } - public boolean $greater (int that) { return value > that; } - public boolean $less$eq (int that) { return value <= that; } - public boolean $greater$eq(int that) { return value >= that; } - public int $plus (int that) { return value + that; } - public int $minus (int that) { return value - that; } - public int $times (int that) { return value * that; } - public int $div (int that) { return value / that; } - public int $percent (int that) { return value % that; } - public int $bar (int that) { return value | that; } - public int $amp (int that) { return value & that; } - public int $up (int that) { return value ^ that; } - - - public boolean $eq$eq (char that) { return value == that; } - public boolean $bang$eq (char that) { return value != that; } - public boolean $less (char that) { return value < that; } - public boolean $greater (char that) { return value > that; } - public boolean $less$eq (char that) { return value <= that; } - public boolean $greater$eq(char that) { return value >= that; } - public int $plus (char that) { return value + that; } - public int $minus (char that) { return value - that; } - public int $times (char that) { return value * that; } - public int $div (char that) { return value / that; } - public int $percent (char that) { return value % that; } - public int $bar (char that) { return value | that; } - public int $amp (char that) { return value & that; } - public int $up (char that) { return value ^ that; } - - public boolean $eq$eq (short that) { return value == that; } - public boolean $bang$eq (short that) { return value != that; } - public boolean $less (short that) { return value < that; } - public boolean $greater (short that) { return value > that; } - public boolean $less$eq (short that) { return value <= that; } - public boolean $greater$eq(short that) { return value >= that; } - public int $plus (short that) { return value + that; } - public int $minus (short that) { return value - that; } - public int $times (short that) { return value * that; } - public int $div (short that) { return value / that; } - public int $percent (short that) { return value % that; } - public int $bar (short that) { return value | that; } - public int $amp (short that) { return value & that; } - public int $up (short that) { return value ^ that; } - - public boolean $eq$eq (byte that) { return value == that; } - public boolean $bang$eq (byte that) { return value != that; } - public boolean $less (byte that) { return value < that; } - public boolean $greater (byte that) { return value > that; } - public boolean $less$eq (byte that) { return value <= that; } - public boolean $greater$eq(byte that) { return value >= that; } - public int $plus (byte that) { return value + that; } - public int $minus (byte that) { return value - that; } - public int $times (byte that) { return value * that; } - public int $div (byte that) { return value / that; } - public int $percent (byte that) { return value % that; } - public int $bar (byte that) { return value | that; } - public int $amp (byte that) { return value & that; } - public int $up (byte that) { return value ^ that; } -} diff --git a/sources/scala/Iterable.scala b/sources/scala/Iterable.scala deleted file mode 100644 index 035da41067..0000000000 --- a/sources/scala/Iterable.scala +++ /dev/null @@ -1,157 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - -import Predef._; - -object Iterable { - def view[A <% Ordered[A]](x: Iterable[A]): Ordered[Iterable[A]] = new Ordered[Iterable[A]] { - def compareTo[B >: Iterable[A] <% Ordered[B]](that: B): Int = that match { - case y: Iterable[A] => - val xs = x.elements; - val ys = y.elements; - var res = 0; - while (xs.hasNext && ys.hasNext && (res == 0)) { - res = xs.next compareTo ys.next; - } - if (xs.hasNext) 1 - else if (ys.hasNext) -1 - else res; - case _ => - -(that compareTo x) - } - } - - /** The minimum element of a non-empty sequence of ordered elements */ - def min[A <% Ordered[A]](seq: Iterable[A]): A = { - val xs = seq.elements; - if (!xs.hasNext) error("min()"); - var min = xs.next; - while (xs.hasNext) { - val x = xs.next; - if (x < min) min = x; - } - min - } - - /** The maximum element of a non-empty sequence of ordered elements */ - def max[A <% Ordered[A]](seq: Iterable[A]): A = { - val xs = seq.elements; - if (!xs.hasNext) error("max()"); - var max = xs.next; - while (xs.hasNext) { - val x = xs.next; - if (max < x) max = x; - } - max - } -} - -/** Collection classes supporting this trait provide a method - * elements which returns an iterator over all the - * elements contained in the collection. - * - * @author Matthias Zenger - * @version 1.1, 04/02/2004 - */ -trait Iterable[+A] { - - /** Creates a new iterator over all elements contained in this - * object. - * - * @return the new iterator - */ - def elements: Iterator[A]; - - /** Concatenates two iterable objects - * - * @return the new iterable object - * @author buraq - */ - def concat[B >: A](that:Iterable[B]): Iterable[B] = new Iterable[B] { - def elements: Iterator[B] = Iterable.this.elements.append(that.elements); - } - - /** Apply a function f to all elements of this - * iterable object. - * - * @param f a function that is applied to every element. - */ - def foreach(f: A => Unit): Unit = elements.foreach(f); - - /** Apply a predicate p to all elements of this - * iterable object and return true, iff the predicate yields - * true for all elements. - * - * @param p the predicate - * @returns true, iff the predicate yields true for all elements. - */ - def forall(p: A => Boolean): Boolean = elements.forall(p); - - /** Apply a predicate p to all elements of this - * iterable object and return true, iff there is at least one - * element for which p yields true. - * - * @param p the predicate - * @returns true, iff the predicate yields true for at least one element. - */ - def exists(p: A => Boolean): Boolean = elements.exists(p); - - /** Find and return the first element of the iterable object satisfying a - * predicate, if any. - * - * @param p the predicate - * @return the first element in the iterable object satisfying p, - * or None if none exists. - */ - def find(p: A => Boolean): Option[A] = elements.find(p); - - /** Combines the elements of this list together using the binary - * operator op, from left to right, and starting with - * the value z. - * @return op(... (op(op(z,a0),a1) ...), an) if the list - * is List(a0, a1, ..., an). - */ - def foldLeft[B](z: B)(op: (B, A) => B): B = elements.foldLeft(z)(op); - - /** Combines the elements of this list together using the binary - * operator op, from rigth to left, and starting with - * the value z. - * @return a0 op (... op (an op z)...) if the list - * is [a0, a1, ..., an]. - */ - def foldRight[B](z: B)(op: (A, B) => B): B = elements.foldRight(z)(op); - - /** Similar to foldLeft but can be used as - * an operator with the order of list and zero arguments reversed. - * That is, z /: xs is the same as xs foldLeft z - */ - def /:[B](z: B)(f: (B, A) => B): B = foldLeft(z)(f); - - /** An alias for foldRight. - * That is, xs :\ z is the same as xs foldRight z - */ - def :\[B](z: B)(f: (A, B) => B): B = foldRight(z)(f); - - /** Checks if the other iterable object contains the same elements. - * - * @param that the other iterable object - * @return true, iff both iterable objects contain the same elements. - */ - def sameElements[B >: A](that: Iterable[B]): Boolean = { - val ita = this.elements; - val itb = that.elements; - var res = true; - while (res && ita.hasNext && itb.hasNext) { - res = (ita.next == itb.next); - } - !ita.hasNext && !itb.hasNext && res - } -} diff --git a/sources/scala/IterableProxy.scala b/sources/scala/IterableProxy.scala deleted file mode 100644 index 19bae8825d..0000000000 --- a/sources/scala/IterableProxy.scala +++ /dev/null @@ -1,97 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** This class implements a proxy for iterable objects. It forwards - * all calls to a different iterable object. - * - * @author Matthias Zenger - * @version 1.0, 26/04/2004 - */ -trait IterableProxy[+A] extends Iterable[A] with Proxy { - - def self: Iterable[A]; - - /** Creates a new iterator over all elements contained in this - * object. - * - * @return the new iterator - */ - def elements: Iterator[A] = self.elements; - - /** Apply a function f to all elements of this - * iterable object. - * - * @param f a function that is applied to every element. - */ - override def foreach(f: A => Unit): Unit = self.foreach(f); - - /** Apply a predicate p to all elements of this - * iterable object and return true, iff the predicate yields - * true for all elements. - * - * @param p the predicate - * @returns true, iff the predicate yields true for all elements. - */ - override def forall(p: A => Boolean): Boolean = self.forall(p); - - /** Apply a predicate p to all elements of this - * iterable object and return true, iff there is at least one - * element for which p yields true. - * - * @param p the predicate - * @returns true, iff the predicate yields true for at least one element. - */ - override def exists(p: A => Boolean): Boolean = self.exists(p); - - /** Find and return the first element of the iterable object satisfying a - * predicate, if any. - * - * @param p the predicate - * @return the first element in the iterable object satisfying p, - * or None if none exists. - */ - override def find(p: A => Boolean): Option[A] = self.find(p); - - /** Combines the elements of this list together using the binary - * operator op, from left to right, and starting with - * the value z. - * @return op(... (op(op(z,a0),a1) ...), an) if the list - * is List(a0, a1, ..., an). - */ - override def foldLeft[B](z: B)(op: (B, A) => B): B = self.foldLeft(z)(op); - - /** Combines the elements of this list together using the binary - * operator op, from rigth to left, and starting with - * the value z. - * @return a0 op (... op (an op z)...) if the list - * is [a0, a1, ..., an]. - */ - override def foldRight[B](z: B)(op: (A, B) => B): B = self.foldRight(z)(op); - - /** Similar to foldLeft but can be used as - * an operator with the order of list and zero arguments reversed. - * That is, z /: xs is the same as xs foldLeft z - */ - override def /:[B](z: B)(f: (B, A) => B): B = self./:(z)(f); - - /** An alias for foldRight. - * That is, xs :\ z is the same as xs foldRight z - */ - override def :\[B](z: B)(f: (A, B) => B): B = self.:\(z)(f); - - /** Checks if the other iterable object contains the same elements. - * - * @param that the other iterable object - * @return true, iff both iterable objects contain the same elements. - */ - override def sameElements[B >: A](that: Iterable[B]): Boolean = self.sameElements(that); -} diff --git a/sources/scala/Iterator.scala b/sources/scala/Iterator.scala deleted file mode 100644 index 5a60a198ca..0000000000 --- a/sources/scala/Iterator.scala +++ /dev/null @@ -1,429 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -import Predef._; - -/** The Iterator object provides various functions for - * creating specialized iterators. - * - * @author Martin Odersky - * @author Matthias Zenger - * @version 1.1, 04/02/2004 - */ -object Iterator { - - def empty[a] = new Iterator[a] { - def hasNext: Boolean = false; - def next: a = Predef.error("next on empty iterator"); - } - - def single[a](x: a) = new Iterator[a] { - private var hasnext = true; - def hasNext: Boolean = hasnext; - def next: a = if (hasnext) { hasnext = false; x } else Predef.error("next on empty iterator"); - } - - def fromValues[a](xs: a*) = xs.elements; - - def fromArray[a](xs: Array[a]) = new Iterator[a] { - private var i = 0; - def hasNext: Boolean = i < xs.length; - def next: a = - if (i < xs.length) { val x = xs(i) ; i = i + 1 ; x } - else Predef.error("next on empty iterator"); - } - - def fromString(str: String): Iterator[Char] = new Iterator[Char] { - private var i = 0; - private val len = str.length(); - def hasNext = i < len; - def next = { val c = str charAt i; i = i + 1; c }; - } - - def fromCaseClass(n:CaseClass): Iterator[Any] = new Iterator[Any] { - private var c:Int = 0; - private val cmax = n.caseArity; - def hasNext = c < cmax; - def next = { val a = n caseElement c; c = c + 1; a } - } - - /** Create an iterator with elements - * en+1 = en + 1 - * where e0 = lo - * and ei < end. - * - * @param lo the start value of the iterator - * @param end the end value of the iterator - * @return the iterator with values in range [lo;end). - */ - def range(lo: Int, end: Int): Iterator[Int] = - range(lo, end, 1); - - /** Create an iterator with elements - * en+1 = en + step - * where e0 = lo - * and ei < end. - * - * @param lo the start value of the iterator - * @param end the end value of the iterator - * @param step the increment value of the iterator (must be positive or negative) - * @return the iterator with values in range [lo;end). - */ - def range(lo: Int, end: Int, step: Int): Iterator[Int] = { - assert(step != 0); - new Iterator[Int] { - private var i = lo; - def hasNext: Boolean = if (step > 0) i < end else i > end; - def next: Int = - if (hasNext) { val j = i; i = i + step; j } else Predef.error("next on empty iterator"); - def head: Int = - if (hasNext) i else Predef.error("head on empty iterator"); - } - } - - /** Create an iterator with elements - * en+1 = step(en) - * where e0 = lo - * and ei < end. - * - * @param lo the start value of the iterator - * @param end the end value of the iterator - * @param step the increment function of the iterator - * @return the iterator with values in range [lo;end). - */ - def range(lo: Int, end: Int, step: Int => Int): Iterator[Int] = new Iterator[Int] { - private var i = lo; - def hasNext: Boolean = i < end; - def next: Int = - if (i < end) { val j = i; i = step(i); j } else Predef.error("next on empty iterator"); - def head: Int = - if (i < end) i else Predef.error("head on empty iterator"); - } - - /** Create an iterator with elements - * en+1 = en + 1 - * where e0 = lo. - * - * @param lo the start value of the iterator - * @return the iterator starting at value lo. - */ - def from(lo: Int): Iterator[Int] = - from(lo, 1); - - /** Create an iterator with elements - * en+1 = en + step - * where e0 = lo. - * - * @param lo the start value of the iterator - * @param step the increment value of the iterator - * @return the iterator starting at value lo. - */ - def from(lo: Int, step: Int) = new Iterator[Int] { - private var i = lo; - def hasNext: Boolean = true; - def next: Int = { val j = i; i = i + step; j } - } - - /** Create an iterator with elements - * en+1 = step(en) - * where e0 = lo. - * - * @param lo the start value of the iterator - * @param step the increment function of the iterator - * @return the iterator starting at value lo. - */ - def from(lo: Int, step: Int => Int) = new Iterator[Int] { - private var i = lo; - def hasNext: Boolean = true; - def next: Int = { val j = i; i = step(i); j } - } - -} - -/** Iterators are data structures that allow to iterate over a sequence - * of elements. They have a hasNext method for checking - * if there is a next element available, and a next method - * which returns the next element and discards it from the iterator. - * - * @author Martin Odersky - * @author Matthias Zenger - * @version 1.2, 15/03/2004 - */ -trait Iterator[+A] { - - /** Does this iterator provide another element? - */ - def hasNext: Boolean; - - /** Returns the next element. - */ - def next: A; - - /** Returns a new iterator that iterates only over the first n - * elements. - */ - def take(n: Int) = new Iterator[A] { - var remaining = n; - def hasNext = remaining > 0 && Iterator.this.hasNext; - def next: A = - if (hasNext) { remaining = remaining - 1; Iterator.this.next } - else Predef.error("next on empty iterator"); - } - - /** Removes the first n elements from this iterator. - */ - def drop(n: Int): Iterator[A] = - if (n > 0) { next; drop(n - 1) } else this; - - /** Returns a new iterator that maps all elements of this iterator - * to new elements using function f. - */ - def map[B](f: A => B): Iterator[B] = new Iterator[B] { - def hasNext = Iterator.this.hasNext; - def next = f(Iterator.this.next) - } - - /** Returns a new iterator that first yields the elements of this - * iterator followed by the elements provided by iterator that. - */ - def append[B >: A](that: Iterator[B]) = new Iterator[B] { - def hasNext = Iterator.this.hasNext || that.hasNext; - def next = if (Iterator.this.hasNext) Iterator.this.next else that.next; - } - - /** Applies the given function f to each element of - * this iterator, then concatenates the results. - * - * @param f the function to apply on each element. - * @return an iterator over f(a0), ... , f(an) if this iterator - * yields the elements a0, ..., an. - */ - def flatMap[B](f: A => Iterator[B]): Iterator[B] = new Iterator[B] { - private var cur: Iterator[B] = Iterator.empty; - def hasNext: Boolean = - if (cur.hasNext) true - else if (Iterator.this.hasNext) { - cur = f(Iterator.this.next); - hasNext - } else false; - def next: B = - if (cur.hasNext) cur.next - else if (Iterator.this.hasNext) { - cur = f(Iterator.this.next); - next - } else Predef.error("next on empty iterator"); - } - - /** Returns an iterator over all the elements of this iterator that - * satisfy the predicate p. The order of the elements - * is preserved. - * - * @param p the redicate used to filter the iterator. - * @return the elements of this iterator satisfying p. - */ - def filter(p: A => Boolean): Iterator[A] = new BufferedIterator[A] { - private val source = Iterator.this.buffered; - private def skip: Unit = - while (source.hasNext && !p(source.head)) { source.next; () } - def hasNext: Boolean = { skip; source.hasNext } - def next: A = { skip; source.next } - def head: A = { skip; source.head; } - } - - /** Return an iterator formed from this iterator and the specified iterator - * that by associating each element of the former with - * the element at the same position in the latter. - * - * @param that must have the same number of elements as this - * iterator. - * @return an iterator yielding (a0,b0), ..., (an,bn) where - * ai are the elements from this iterator and - * bi are the elements from iterator that. - */ - def zip[B](that: Iterator[B]) = new Iterator[Pair[A, B]] { - def hasNext = Iterator.this.hasNext && that.hasNext; - def next = Pair(Iterator.this.next, that.next); - } - - /** Apply a function f to all elements of this - * iterable object. - * - * @param f a function that is applied to every element. - */ - def foreach(f: A => Unit): Unit = while (hasNext) { f(next) }; - - /** Apply a predicate p to all elements of this - * iterable object and return true, iff the predicate yields - * true for all elements. - * - * @param p the predicate - * @returns true, iff the predicate yields true for all elements. - */ - def forall(p: A => Boolean): Boolean = { - var res = true; - while (res && hasNext) { res = p(next) } - res - } - - /** Apply a predicate p to all elements of this - * iterable object and return true, iff there is at least one - * element for which p yields true. - * - * @param p the predicate - * @returns true, iff the predicate yields true for at least one element. - */ - def exists(p: A => Boolean): Boolean = { - var res = false; - while (!res && hasNext) { res = p(next) } - res - } - - /** Tests if the given value elem is a member of this list. - * - * @param elem element whose membership has to be tested. - * @return True iff there is an element of this list which is - * equal (w.r.t. ==) to elem. - */ - def contains(elem: Any): Boolean = exists { x => x == elem }; - - /** Find and return the first element of the iterable object satisfying a - * predicate, if any. - * - * @param p the predicate - * @return the first element in the iterable object satisfying p, - * or None if none exists. - */ - def find(p: A => Boolean): Option[A] = { - var res: Option[A] = None; - while (res.isEmpty && hasNext) { - val e = next; - if (p(e)) res = Some(e); - } - res - } - - /** Combines the elements of this list together using the binary - * operator op, from left to right, and starting with - * the value z. - * @return op(... (op(op(z,a0),a1) ...), an) if the list - * is List(a0, a1, ..., an). - */ - def foldLeft[B](z: B)(op: (B, A) => B): B = { - var acc = z; - while (hasNext) { acc = op(acc, next) } - acc - } - - /** Combines the elements of this list together using the binary - * operator op, from rigth to left, and starting with - * the value z. - * @return a0 op (... op (an op z)...) if the list - * is [a0, a1, ..., an]. - */ - def foldRight[B](z: B)(op: (A, B) => B): B = { - def fold(z: B): B = - if (hasNext) op(next, fold(z)) else z; - fold(z) - } - - /** Similar to foldLeft but can be used as - * an operator with the order of list and zero arguments reversed. - * That is, z /: xs is the same as xs foldLeft z - */ - def /:[B](z: B)(f: (B, A) => B): B = foldLeft(z)(f); - - /** An alias for foldRight. - * That is, xs :\ z is the same as xs foldRight z - */ - def :\[B](z: B)(f: (A, B) => B): B = foldRight(z)(f); - - /** Returns a buffered iterator from this iterator. - */ - def buffered: BufferedIterator[A] = new BufferedIterator[A] { - private var hd: A = _; - private var ahead: Boolean = false; - def head: A = { - if (!ahead) { - hd = Iterator.this.next; - ahead = true - } - hd - } - def next: A = - if (ahead) { ahead = false; hd } else head; - def hasNext: Boolean = ahead || Iterator.this.hasNext; - override def buffered: BufferedIterator[A] = this; - } - - /** Creates two new iterators that both iterate over the same elements - * than this iterator (in the same order). - */ - def duplicate: Pair[Iterator[A], Iterator[A]] = { - var xs: List[A] = Nil; - var ahead: Iterator[A] = null; - class Partner extends Iterator[A] { - var ys: List[A] = Nil; - def hasNext: Boolean = Iterator.this.synchronized ( - ((this == ahead) && Iterator.this.hasNext) || - ((this != ahead) && (!xs.isEmpty || !ys.isEmpty || Iterator.this.hasNext)) - ); - def next: A = Iterator.this.synchronized { - if (this == ahead) { - val e = Iterator.this.next; - xs = e :: xs; e - } else { - if (ys.isEmpty) { - ys = xs.reverse; - xs = Nil; - } - ys match { - case Nil => val e = Iterator.this.next; - ahead = this; - xs = e :: xs; e - case z :: zs => ys = zs; z - } - } - } - } - ahead = new Partner; - Pair(ahead, new Partner) - } - - /** Fills the given array xs with the elements of - * this sequence starting at position start. - * - * @param xs the array to fill. - * @param start starting index. - * @return the given array xs filled with this list. - */ - def copyToArray[B >: A](xs: Array[B], start: Int): Array[B] = { - var i = start; - while (hasNext) { - xs(i) = next; - i = i + 1; - } - xs - } - - /** Transform this iterator into a list of all elements. - * - * @return a list which enumerates all elements of this iterator. - */ - def toList: List[A] = { - var res: List[A] = Nil; - while (hasNext) { - res = next :: res; - } - res.reverse - } - -} diff --git a/sources/scala/List.scala b/sources/scala/List.scala deleted file mode 100644 index f71a09e110..0000000000 --- a/sources/scala/List.scala +++ /dev/null @@ -1,919 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - -import Predef._; - -/** This object provides methods for creating specialized lists, and for - * transforming special kinds of lists (e.g. lists of lists). - * - * @author Martin Odersky and others - * @version 1.0, 15/07/2003 - */ -object List { - - /** Create a list with given elements. - * - * @param xs the elements to put in the list - * @return the list containing elements xs. - */ - def apply[A](xs: A*): List[A] = - // TODO: remove the type test once nsc becomes standard - if (xs.isInstanceOf$erased[List[A]]) - xs.asInstanceOf$erased[List[A]]; - else - fromArray(xs.asInstanceOf$erased[Array[A]]); - - /** Create a sorted list of all integers in a range. - * - * @param from the start value of the list - * @param end the end value of the list - * @return the sorted list of all integers in range [from;end). - */ - def range(from: Int, end: Int): List[Int] = - range(from, end, 1); - - /** Create a sorted list of all integers in a range. - * - * @param from the start value of the list - * @param end the end value of the list - * @param step the increment value of the list - * @return the sorted list of all integers in range [from;end). - */ - def range(from: Int, end: Int, step: Int): List[Int] = - if (from >= end) Nil - else from :: range(from + step, end, step); - - /** Create a sorted list of all integers in a range. - * - * @param from the start value of the list - * @param end the end value of the list - * @param step the increment function of the list - * @return the sorted list of all integers in range [from;end). - */ - def range(from: Int, end: Int, step: Int => Int): List[Int] = - if (from >= end) Nil - else from :: range(step(from), end, step); - - /** Create a list containing several copies of an element. - * - * @param n the length of the resulting list - * @param elem the element composing the resulting list - * @return a list composed of n elements all equal to elem - */ - def make[a](n: int, elem: a): List[a] = - if (n == 0) Nil - else elem :: make(n - 1, elem); - - /** Create a list by applying a function to successive integers. - * - * @param n the length of the resulting list - * @param maker the procedure which, given an integer n, returns the - * nth element of the resulting list, where n is in [0;n). - * @return the list obtained by applying the maker function to successive - * integers from 0 to n (exclusive). - */ - def tabulate[a](n: int, maker: int => a): List[a] = { - def loop(i: int): List[a] = - if (i == n) Nil - else maker(i) :: loop(i + 1); - loop(0) - } - - /** Concatenate all the elements of a given list of lists. - * @param l the list of lists that are to be concatenated - * @return the concatenation of all the lists - */ - def flatten[a](l: List[List[a]]): List[a] = l match { - case Nil => Nil - case head :: tail => head ::: flatten(tail) - } - - /** Transforms a list of pair into a pair of lists. - * - * @param l the list of pairs to unzip - * @return a pair of lists: the first list in the pair contains the list - */ - def unzip[a,b](l: List[Pair[a,b]]): Pair[List[a], List[b]] = l match { - case Nil => new Pair(Nil, Nil) - case Pair(f, s) :: tail => - val Pair(fs, ss) = unzip(tail); - Pair(f :: fs, s :: ss) - } - - /** Converts an iterator to a list - * - * @param it the iterator to convert - * @return a list that contains the elements returned by successive - * calls to it.next - */ - def fromIterator[a](it: Iterator[a]): List[a] = - if (it.hasNext) it.next :: fromIterator(it); - else Nil; - - /** Converts an array into a list. - * - * @param arr the array to convert - * @return a list that contains the same elements than arr - * in the same order - */ - def fromArray[a](arr: Array[a]): List[a] = fromArray(arr, 0, arr.length); - - /** Converts a range of an array into a list. - * - * @param arr the array to convert - * @param start the first index to consider - * @param len the lenght of the range to convert - * @return a list that contains the same elements than arr - * in the same order - */ - def fromArray[a](arr: Array[a], start: Int, len: Int): List[a] = { - var res: List[a] = Nil; - var i = start + len; - while (i > start) { - i = i - 1; - res = arr(i) :: res; - } - res - } - - /** Parses a string which contains substrings separated by a - * - * separator character and returns a list of all substrings. - * @param str the string to parse - * @param separator the separator character - * @return the list of substrings - */ - def fromString(str: String, separator: Char): List[String] = { - var words: List[String] = List(); - var pos = str.length(); - while (pos > 0) { - val pos1 = str.lastIndexOf(separator, pos - 1); - if (pos1 + 1 < pos) - words = str.substring(pos1 + 1, pos) :: words; - pos = pos1 - } - words - } -/* - var res: List[String] = Nil; - var start = 0; - var end = str.indexOf(separator); - while (end >= 0) { - if (end > start) - res = str.substring(start, end) :: res; - end = end + 1; - start = end; - end = str.indexOf(separator, end); - } - res.reverse - } -*/ - /** Returns the given string as a list of characters. - * - * @param str the string to convert. - * @return the string as a list of characters. - */ - def fromString(str: String): List[Char] = { - var res: List[Char] = Nil; - var i = str.length(); - while (i > 0) { - i = i - 1; - res = str.charAt(i) :: res; - } - res - } - - /** Returns the given list of characters as a string. - * - * @param xs the list to convert. - * @return the list in form of a string. - */ - def toString(xs: List[Char]): String = { - val sb = new StringBuffer(); - var ys = xs; - while (!ys.isEmpty) { - sb.append(ys.head); - ys = ys.tail; - } - sb.toString() - } - - /** Returns the list resulting from applying the given function f to - * corresponding elements of the argument lists. - * - * @param f function to apply to each pair of elements. - * @return [f(a0,b0), ..., f(an,bn)] if the lists are - * [a0, ..., ak], [b0, ..., bl] and - * n = min(k,l) - */ - def map2[a,b,c](xs: List[a], ys: List[b])(f: (a, b) => c): List[c] = - if (xs.isEmpty || ys.isEmpty) Nil - else f(xs.head, ys.head) :: map2(xs.tail, ys.tail)(f); - - /** Like xs map f, but returns xs unchanged if function `f' maps all elements to themselves - */ - def mapConserve[a <: AnyRef](xs: List[a])(f: a => a): List[a] = { - if (xs.isEmpty) xs - else { - val head = xs.head; - val head1 = f(head); - val tail = xs.tail; - val tail1 = mapConserve(tail)(f); - if ((head1 eq head) && (tail1 eq tail)) xs else head1 :: tail1 - } - } - - /** Returns the list resulting from applying the given function f to - * corresponding elements of the argument lists. - * - * @param f function to apply to each pair of elements. - * @return [f(a0,b0,c0), ..., f(an,bn,cn)] if the lists are - * [a0, ..., ak], [b0, ..., bl], [c0, ..., cm] and - * n = min(k,l,m) - */ - def map3[a,b,c, d](xs: List[a], ys: List[b], zs: List[c])(f: (a, b, c) => d): List[d] = - if (xs.isEmpty || ys.isEmpty || zs.isEmpty) Nil - else f(xs.head, ys.head, zs.head) :: map3(xs.tail, ys.tail, zs.tail)(f); - - /** Tests whether the given predicate p holds - * for all corresponding elements of the argument lists. - * - * @param p function to apply to each pair of elements. - * @return n == 0 || (p(a0,b0) && ... && p(an,bn))] if the lists are - * [a0, ..., ak], [b0, ..., bl] and - * m = min(k,l) - */ - def forall2[a,b](xs: List[a], ys: List[b])(f: (a, b) => boolean): boolean = - if (xs.isEmpty || ys.isEmpty) true - else f(xs.head, ys.head) && forall2(xs.tail, ys.tail)(f); - - /** Tests whether the given predicate p holds - * for some corresponding elements of the argument lists. - * - * @param p function to apply to each pair of elements. - * @return n != 0 && (p(a0,b0) || ... || p(an,bn))] if the lists are - * [a0, ..., ak], [b0, ..., bl] and - * m = min(k,l) - */ - def exists2[a,b](xs: List[a], ys: List[b])(f: (a, b) => boolean): boolean = - if (xs.isEmpty || ys.isEmpty) false - else f(xs.head, ys.head) || exists2(xs.tail, ys.tail)(f); - - /** Transposes a list of lists. - * pre: All element lists have the same length. - */ - def transpose[a](xss: List[List[a]]): List[List[a]] = - if (xss.head.isEmpty) List() - else (xss map (xs => xs.head)) :: transpose(xss map (xs => xs.tail)); - - /** Lists with ordered elements are ordered - */ - implicit def list2ordered[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = new Ordered[List[a]] { - def compareTo [b >: List[a] <% Ordered[b]](y: b): int = y match { - case y1: List[a] => compareLists(x, y1); - case _ => -(y compareTo x) - } - private def compareLists(xs: List[a], ys: List[a]): int = { - if (xs.isEmpty && ys.isEmpty) 0 - else if (xs.isEmpty) -1 - else if (ys.isEmpty) 1 - else { - val s = xs.head compareTo ys.head; - if (s != 0) s - else compareLists(xs.tail, ys.tail) - } - } - } - def view[a <% Ordered[a]](x: List[a]): Ordered[List[a]] = list2ordered(x); -} - -/** A trait representing an ordered collection of elements of type - * a. This class comes with two implementing case - * classes scala.Nil and scala.:: that - * implement the abstract members isEmpty, - * head and tail. - * - * @author Martin Odersky and others - * @version 1.0, 16/07/2003 - */ -sealed abstract class List[+a] extends Seq[a] { - - /** Returns true if the list does not contain any elements. - * @return true, iff the list is empty. - */ - def isEmpty: Boolean; - - /** Returns this first element of the list. - * @return the first element of this list. - * @throws java.lang.RuntimeException if the list is empty. - */ - def head: a; - - /** Returns this list without its first element. - * @return this list without its first element. - * @throws java.lang.RuntimeException if the list is empty. - */ - def tail: List[a]; - - /** Add an element x at the beginning of this list. - *

- * Ex:
- * 1 :: [2, 3] = [2, 3].::(1) = [1, 2, 3]. - * @param x the element to append. - * @return the list with x appended at the beginning. - */ - def ::[b >: a](x: b): List[b] = - new scala.::(x, this); - - /** Returns a list resulting from the concatenation of the given - * list prefix and this list. - *

- * Ex:
- * [1, 2] ::: [3, 4] = [3, 4].:::([1, 2]) = [1, 2, 3, 4]. - * @param prefix the list to concatenate at the beginning of this list. - * @return the concatenation of the two lists. - */ - def :::[b >: a](prefix: List[b]): List[b] = prefix match { - case Nil => this - case head :: tail => head :: (tail ::: this); - } - - /** Reverse the given prefix and append the current list to that. - * This function is equivalent to an application of reverse - * on the prefix followed by a call to :::, but more - * efficient (and tail recursive). - * @param prefix the prefix to reverse and then prepend - * @return the concatenation of the reversed prefix and the current list. - */ - def reverse_:::[b >: a](prefix: List[b]): List[b] = prefix match { - case Nil => this - case head :: tail => tail.reverse_:::(head :: this)//todo: remove type annotation - } - - /** Returns the number of elements in the list. - * - * @return the number of elements in the list. - */ - def length: Int = { - var xs = this; - var len = 0; - while (!xs.isEmpty) { - len = len + 1; - xs = xs.tail - } - len - } - - /** Creates a list with all indices in the list. This is - * equivalent to a call to List.range(0, xs.length). - * - * @return a list of all indices in the list. - */ - def indices: List[Int] = { - def loop(i: Int, xs: List[a]): List[Int] = xs match { - case Nil => Nil - case _ :: ys => i :: loop(i + 1, ys) - } - loop(0, this) - } - - /** Returns the elements in the list as an iterator - * - * @return an iterator on the list elements. - */ - def elements: Iterator[a] = new Iterator[a] { - var current = List.this; - def hasNext: Boolean = !current.isEmpty; - def next: a = - if (!hasNext) - error("next on empty Iterator") - else { - val result = current.head; current = current.tail; result - } - } - - /** Transform this sequence into a list of all elements. - * - * @return a list which enumerates all elements of this sequence. - */ - override def toList: List[a] = this; - - /** Returns the list without its last element. - * - * @return the list without its last element. - * @throws java.lang.RuntimeException if the list is empty. - */ - def init: List[a] = this match { - case Nil => error("Nil.init") - case _ :: Nil => Nil - case head :: tail => head :: tail.init - } - - /** Returns the last element of this list. - * - * @return the last element of the list. - * @throws java.lang.RuntimeException if the list is empty. - */ - def last: a = this match { - case Nil => error("Nil.last") - case last :: Nil => last - case _ :: tail => tail.last - } - - /** Returns the n first elements of this list. - * - * @param n the number of elements to take. - * @return the n first elements of this list. - */ - override def take(n: Int): List[a] = - if (n == 0 || isEmpty) Nil - else head :: (tail take (n-1)); - - /** Returns the list without its n first elements. - * - * @param n the number of elements to drop. - * @return the list without its n first elements. - */ - override def drop(n: Int): List[a] = - if (n == 0 || isEmpty) this - else (tail drop (n-1)); - - /** Returns the rightmost n elements from this list. - * - * @param n the number of elements to take - * @return the suffix of length n of the list - * @throws java.lang.RuntimeException if the list is too short. - */ - def takeRight(n: Int): List[a] = { - def loop(lead: List[a], lag: List[a]): List[a] = lead match { - case Nil => lag - case _ :: tail => loop(tail, lag.tail) - } - loop(drop(n), this) - } - - /** Returns the list wihout its rightmost n elements. - * - * @param n the number of elements to take - * @return the suffix of length n of the list - * @throws java.lang.RuntimeException if the list is too short. - */ - def dropRight(n: Int): List[a] = { - def loop(lead: List[a], lag: List[a]): List[a] = lead match { - case Nil => Nil - case _ :: tail => lag.head :: loop(tail, lag.tail) - } - loop(drop(n), this) - } - - /** Split the list at a given point and return the two parts thus - * created. - * - * @param n the position at which to split - * @return a pair of lists composed of the first n - * elements, and the other elements. - */ - def splitAt(n: Int): Pair[List[a], List[a]] = - if (n == 0) Pair(Nil, this) - else { - val Pair(tail1, tail2) = tail splitAt (n-1); - Pair(head :: tail1, tail2) - } - - /** Returns the longest prefix of this list whose elements satisfy - * the predicate p. - * - * @param p the test predicate. - * @return the longest prefix of this list whose elements satisfy - * the predicate p. - */ - def takeWhile(p: a => Boolean): List[a] = - if (isEmpty || !p(head)) Nil - else head :: (tail takeWhile p); - - /** Returns the longest suffix of this list whose first element - * does not satisfy the predicate p. - * - * @param p the test predicate. - * @return the longest suffix of the list whose first element - * does not satisfy the predicate p. - */ - def dropWhile(p: a => Boolean): List[a] = - if (isEmpty || !p(head)) this - else tail dropWhile p; - - /** Returns the longest prefix of the list whose elements all satisfy - * the given predicate, and the rest of the list. - * - * @param p the test predicate - * @return a pair consisting of the longest prefix of the list whose - * elements all satisfy p, and the rest of the list. - */ - def span(p: a => Boolean): Pair[List[a], List[a]] = this match { - case Nil => Pair(Nil, Nil) - case head :: tail => - if (p(head)) { - val Pair(tail1, tail2) = tail span p; - Pair(head :: tail1, tail2) - } else - Pair(Nil, this) - } - - /** Like span but with the predicate inverted. - */ - def break(p: a => Boolean): Pair[List[a], List[a]] = span { x => !p(x) } - - /** Returns the n-th element of this list. The first element - * (head of the list) is at position 0. - * - * @param n index of the element to return - * @return the element at position n in this list. - * @throws java.lang.RuntimeException if the list is too short. - */ - def apply(n: Int): a = drop(n).head; - - /** Returns the list resulting from applying the given function f to each - * element of this list. - * - * @param f function to apply to each element. - * @return [f(a0), ..., f(an)] if this list is [a0, ..., an]. - */ - def map[b](f: a => b): List[b] = this match { - case Nil => Nil - case head :: tail => f(head) :: (tail map f) - } - - /** Apply a function to all the elements of the list, and return the - * reversed list of results. This is equivalent to a call to map - * followed by a call to reverse, but more efficient. - * - * @param f the function to apply to each elements. - * @return the reversed list of results. - */ - def reverseMap[b](f: a => b): List[b] = { - def loop(l: List[a], res: List[b]): List[b] = l match { - case Nil => res - case head :: tail => loop(tail, f(head) :: res) - } - loop(this, Nil) - } - - /** Apply the given function f to each element of this list - * (while respecting the order of the elements). - * - * @param f the treatment to apply to each element. - */ - override def foreach(f: a => Unit): Unit = { - def loop(xs: List[a]): Unit = xs match { - case Nil => () - case head :: tail => f(head); loop(tail) - } - loop(this) - } - - /** Returns all the elements of this list that satisfy the - * predicate p. The order of the elements is preserved. - * - * @param p the redicate used to filter the list. - * @return the elements of this list satisfying p. - */ - def filter(p: a => Boolean): List[a] = this match { - case Nil => this - case head :: tail => - if (p(head)) { - val tail1 = tail filter p; - if (tail eq tail1) this else head :: tail1 - } else tail filter p - } - - /** Removes all elements of the list which satisfy the predicate - * p. This is like filter with the - * predicate inversed. - * - * @param p the predicate to use to test elements - * @return the list without all elements which satisfy p - */ - def remove(p: a => Boolean): List[a] = this match { - case Nil => this - case head :: tail => - if (p(head)) tail remove p else head :: (tail remove p) - } - - /** Partition the list in two sub-lists according to a predicate. - * - * @param p the predicate on which to partition - * @return a pair of lists: the list of all elements which satisfy - * p and the list of all elements which do not. The - * relative order of the elements in the sub-lists is the same as in - * the original list. - */ - def partition(p: a => Boolean): Pair[List[a], List[a]] = this match { - case Nil => Pair(Nil, Nil) - case head :: tail => - val Pair(taily, tailn) = tail partition p; - if (p(head)) Pair(head :: taily, tailn) - else Pair(taily, head :: tailn) - } - - /** Sort the list according to the comparison function - * <(e1: a, e2: a) => Boolean, - * which should be true iff e1 is smaller than e2. - * Note: The current implementation is inefficent for - * already sorted lists. - * - * @param lt the comparison function - * @return a list sorted according to the comparison function - * <(e1: a, e2: a) => Boolean. - */ - def sort(lt : (a,a) => Boolean): List[a] = { - def sort_1(smaller: List[a], acc: List[a]): List[a] = - smaller match { - case Nil => - acc - case List(x) => - x::acc - case List(x, y) => - if (lt(x, y)) x::(y::acc) else y::x::acc - case List(x, y, z) => - if (lt(x, y)) { - if (lt(y, z)) x::y::z::acc - else if (lt(x, z)) x::z::y::acc - else z::x::y::acc - } else if (lt(x, z)) y::x::z::acc - else if (lt(z, y)) z::y::x::acc - else y::z::x::acc - case hd1::hd2::hd3::tail => { - val List(x, y, z) = sort_1(hd1::hd2::hd3::Nil, Nil); - val Pair(small, large) = tail.partition((e2) => lt(e2, y)); - sort_1(x::small, y::sort_1(z::large, acc)) - } - } - this match { - case Nil => - this - case List(x) => - this - case List(x, y) => - if (lt(x, y)) this else y::x::Nil - case List(x, y, z) => - if (lt(x, y)) { - if (lt(y, z)) this - else if (lt(x, z)) x::z::y::Nil - else z::x::y::Nil - } else if (lt(x, z)) y::x::z::Nil - else if (lt(z, y)) z::y::x::Nil - else y::z::x::Nil - case hd1::hd2::hd3::tail => { - val List(x, y, z) = sort_1(hd1::hd2::hd3::Nil, Nil); - val Pair(small,large) = tail.partition((e2) => lt(e2, y)); - sort_1(x::small, y::sort_1(z::large, Nil)); - } - } - } - - - /** Count the number of elements in the list which satisfy a predicate. - * - * @param p the predicate for which to count - * @return the number of elements satisfying the predicate p. - */ - def count(p: a => Boolean): Int = this match { - case Nil => 0 - case head :: tail => if (p(head)) 1 + (tail count p) else (tail count p) - } - - /** Tests if the predicate p is satisfied by all elements - * in this list. - * - * @param p the test predicate. - * @return True iff all elements of this list satisfy the predicate p. - */ - override def forall(p: a => Boolean): Boolean = - isEmpty || (p(head) && (tail forall p)); - - /** Tests the existence in this list of an element that satisfies the predicate - * p. - * - * @param p the test predicate. - * @return true iff there exists an element in this list that satisfies - * the predicate p. - */ - override def exists(p: a => Boolean): Boolean = - !isEmpty && (p(head) || (tail exists p)); - - /** Tests if the given value elem is a member of this - * iterable object. - * - * @param elem element whose membership has to be tested. - * @return True iff there is an element of this list which is - * equal (w.r.t. ==) to elem. - */ - def contains(elem: Any): boolean = exists { x => x == elem } - - /** Find and return the first element of the list satisfying a - * predicate, if any. - * - * @param p the predicate - * @return the first element in the list satisfying p, - * or None if none exists. - */ - override def find(p: a => Boolean): Option[a] = this match { - case Nil => None - case head :: tail => if (p(head)) Some(head) else tail find p - } - - /** Combines the elements of this list together using the binary - * operator op, from left to right, and starting with - * the value z. - * - * @return op(... (op(op(z,a0),a1) ...), an) if the list - * is [a0, a1, ..., an]. - */ - override def foldLeft[b](z: b)(f: (b, a) => b): b = this match { - case Nil => z - case x :: xs => xs.foldLeft[b](f(z, x))(f) - } - - /** Combines the elements of this list together using the binary - * operator op, from rigth to left, and starting with - * the value z. - * - * @return a0 op (... op (an op z)...) if the list - * is [a0, a1, ..., an]. - */ - override def foldRight[b](z: b)(f: (a, b) => b): b = this match { - case Nil => z - case x :: xs => f(x, xs.foldRight(z)(f)) - } - - def reduceLeft[b >: a](f: (b, b) => b): b = this match { - case Nil => error("Nil.reduceLeft") - case x :: xs => ((xs: List[b]) foldLeft (x: b))(f) - } - - def reduceRight[b >: a](f: (b, b) => b): b = this match { - case Nil => error("Nil.reduceRight") - case x :: Nil => x: b - case x :: xs => f(x, xs reduceRight f) - } - - /** Applies the given function f to each element of - * this list, then concatenates the results. - * - * @param f the function to apply on each element. - * @return f(a0) ::: ... ::: f(an) if this list is - * [a0, ..., an]. - */ - def flatMap[b](f: a => List[b]): List[b] = this match { - case Nil => Nil - case head :: tail => f(head) ::: (tail flatMap f) - } - - /** Reverses the elements of this list. - *

- * Ex:
- * [1, 2, 3] reverse = [3, 2, 1]. - * - * @return the elements of this list in reverse order. - */ - def reverse: List[a] = - foldLeft(Nil : List[a])((xs, x) => x :: xs); - - /** Returns a string representation of this list. The resulting string - * begins with the string start and is finished by the string - * end. Inside, the string representations of elements (w.r.t. - * the method toString()) are separated by the string - * sep. - *

- * Ex:
- * List(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)" - * - * @param start starting string. - * @param sep separator string. - * @param end ending string. - * @return a string representation of this list. - */ - def mkString(start: String, sep: String, end: String): String = this match { - case Nil => start + end - case last :: Nil => start + last + end - case fst :: tail => start + fst + sep + tail.mkString("", sep, end) - } - - override def toString() = mkString("List(", ",", ")"); - - /** Returns a list formed from this list and the specified list - * that by associating each element of the former with - * the element at the same position in the latter. - * - * @param that must have the same length as the self list. - * @return [(a0,b0), ..., (an,bn)] when - * [a0, ..., an] zip [b0, ..., bn] is invoked. - */ - def zip[b](that: List[b]): List[Pair[a,b]] = - if (this.isEmpty || that.isEmpty) Nil - else Pair(this.head, that.head) :: this.tail.zip(that.tail); - - /** Returns a list formed from this list and the specified list - * that by associating each element of the former with - * the element at the same position in the latter. - * - * @param that may have a different length as the self list. - * @param thisElem is used to fill up the resulting list if - * the self list is shorter than that - * @param thatElem is used to fill up the resulting list if - * that is shorter than the self list - * @return [(a0,b0), ..., (an,bn), (elem,bn+1), ..., (elem,bm)] - * when [a0, ..., an] zip [b0, ..., bm] is invoked where - * m > n. - */ - def zipAll[c >: a, b](that: List[b], thisElem: c, thatElem: b): List[Pair[c,b]] = - if (this.isEmpty && that.isEmpty) - Nil - else if (this.isEmpty) - List.make(that.length, thisElem) zip that - else if (that.isEmpty) - this zip List.make(this.length, thatElem) - else - Pair(this.head, that.head) :: this.tail.zipAll(that.tail, thisElem, thatElem); - - /** Computes the union of this list and the given list - * that. - * - * @param that the list of elements to add to the list. - * @return a list without doubles containing the elements of this - * list and those of the given list that. - */ - def union[b >: a](that: List[b]): List[b] = this match { - case Nil => that - case head :: tail => - if (that contains head) tail union that - else head :: (tail union that) - } - - /** Computes the difference between this list and the given list - * that. - * - * @param that the list of elements to remove from this list. - * @return this list without the elements of the given list that. - */ - def diff[b >: a](that: List[b]): List[b] = this match { - case Nil => Nil - case head :: tail => - if (that contains head) tail diff that - else head :: (tail diff that) - } - - /** Computes the intersection between this list and the given list - * that. - * - * @param that the list to intersect. - * @return the list of elements contained both in this list and - * in the given list that. - */ - def intersect[b >: a](that: List[b]): List[b] = filter(x => that contains x); - - /** Removes redundant elements from the list. Uses the method == - * to decide if two elements are identical. - * - * @return the list without doubles. - */ - def removeDuplicates: List[a] = this match { - case Nil => this - case head :: tail => - if (tail contains head) tail.removeDuplicates - else head :: tail.removeDuplicates - } -} - -/** The empty list. - * - * @author Martin Odersky - * @version 1.0, 15/07/2003 - */ -[SerialVersionUID(0 - 8256821097970055419L)] -case object Nil extends List[All] { - def isEmpty = true; - def head: All = error("head of empty list"); - def tail: List[All] = error("tail of empty list"); -} - -/** A non empty list characterized by a head and a tail. - * - * @author Martin Odersky - * @version 1.0, 15/07/2003 - */ -[SerialVersionUID(0L - 8476791151983527571L)] -final case class ::[+b](hd: b, tl: List[b]) extends List[b] { - def isEmpty: boolean = false; - def head: b = hd; - def tail: List[b] = tl; -} - diff --git a/sources/scala/Long.cs b/sources/scala/Long.cs deleted file mode 100644 index 01995f7d04..0000000000 --- a/sources/scala/Long.cs +++ /dev/null @@ -1,108 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - [Meta("class extends scala.AnyVal;")] - [Serializable] - public abstract class Long : AnyVal { - - public readonly long value; - - public Long (long value) - { - this.value = value; - } - - public override bool Equals(object other) - { - return (other is Long) && value == ((Long)other).value; - } - public override int GetHashCode() - { - return value.GetHashCode(); - } - public override string ToString() - { - return value.ToString(); - } - - [Meta("method (scala.Any)scala.Boolean;")] - public bool __eq__eq (object other) { return Equals(other); } - [Meta("method (scala.Any)scala.Boolean;")] - public bool __bang__eq(object other) { return !Equals(other); } - - [Meta("method []scala.Long;")] - public long __plus ( ) { return +value ; } - [Meta("method []scala.Long;")] - public long __minus ( ) { return -value ; } - - public string __plus (string that) { return value + that; } - - public bool __eq__eq (double that) { return value == that; } - public bool __bang__eq (double that) { return value != that; } - public bool __less (double that) { return value < that; } - public bool __greater (double that) { return value > that; } - public bool __less__eq (double that) { return value <= that; } - public bool __greater__eq(double that) { return value >= that; } - public double __plus (double that) { return value + that; } - public double __minus (double that) { return value - that; } - public double __times (double that) { return value * that; } - public double __div (double that) { return value / that; } - public double __percent (double that) { return value % that; } - - [Meta("method []scala.Double;")] - public double coerce ( ) { return value ; } - - public bool __eq__eq (float that) { return value == that; } - public bool __bang__eq (float that) { return value != that; } - public bool __less (float that) { return value < that; } - public bool __greater (float that) { return value > that; } - public bool __less__eq (float that) { return value <= that; } - public bool __greater__eq(float that) { return value >= that; } - public float __plus (float that) { return value + that; } - public float __minus (float that) { return value - that; } - public float __times (float that) { return value * that; } - public float __div (float that) { return value / that; } - public float __percent (float that) { return value % that; } - - [Meta("method []scala.Float;")] - public float coerce (object dummy) { return value ; } - [Meta("method []scala.Long;")] - public long __tilde ( ) { return ~value ; } - - public long __less__less (int that) { return value << that; } - public long __less__less (long that) { return value << (int)that; } - public long __greater__greater(int that) { return value >> that; } - public long __greater__greater(long that) { return value >> (int)that; } - public long __greater__greater__greater(int that) { return (int)((ulong)value >>that); } - public long __greater__greater__greater(long that) { return (int)((ulong)value >>(int)that); } - - public bool __eq__eq (long that) { return value == that; } - public bool __bang__eq (long that) { return value != that; } - public bool __less (long that) { return value < that; } - public bool __greater (long that) { return value > that; } - public bool __less__eq (long that) { return value <= that; } - public bool __greater__eq(long that) { return value >= that; } - public long __plus (long that) { return value + that; } - public long __minus (long that) { return value - that; } - public long __times (long that) { return value * that; } - public long __div (long that) { return value / that; } - public long __percent (long that) { return value % that; } - public long __bar (long that) { return value | that; } - public long __amp (long that) { return value & that; } - public long __up (long that) { return value ^ that; } - - } -} \ No newline at end of file diff --git a/sources/scala/Long.java b/sources/scala/Long.java deleted file mode 100644 index bcaf38eb36..0000000000 --- a/sources/scala/Long.java +++ /dev/null @@ -1,181 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -/** @meta class extends scala.AnyVal; */ -public abstract class Long extends AnyVal implements java.io.Serializable { - - public final long value; - - public Long (long value) { - this.value = value; - } - - public boolean equals(java.lang.Object other) { - return other instanceof Long && value == ((Long )other).value; - } - public int hashCode() { - long bits = value; - return (int)(bits ^ (bits >>> 32)); - } - public String toString() { - return String.valueOf(value); - } - - /** @meta method []scala.Byte; */ - public byte toByte() { return (byte)value; } - - /** @meta method []scala.Short; */ - public short toShort() { return (short)value; } - - /** @meta method []scala.Char; */ - public char toChar() { return (char)value; } - - /** @meta method []scala.Int; */ - public int toInt() { return (int)value; } - - /** @meta method []scala.Long; */ - public long toLong() { return (long)value; } - - /** @meta method []scala.Float; */ - public float toFloat() { return (float)value; } - - /** @meta method []scala.Double; */ - public double toDouble() { return (double)value; } - - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $eq$eq (java.lang.Object other) { return equals(other); } - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $bang$eq(java.lang.Object other) { return !equals(other); } - - /** @meta method []scala.Long ; */ - public long $plus ( ) { return +value ; } - /** @meta method []scala.Long ; */ - public long $minus ( ) { return -value ; } - - public String $plus (String that) { return value + that; } - - public boolean $eq$eq (double that) { return value == that; } - public boolean $bang$eq (double that) { return value != that; } - public boolean $less (double that) { return value < that; } - public boolean $greater (double that) { return value > that; } - public boolean $less$eq (double that) { return value <= that; } - public boolean $greater$eq(double that) { return value >= that; } - public double $plus (double that) { return value + that; } - public double $minus (double that) { return value - that; } - public double $times (double that) { return value * that; } - public double $div (double that) { return value / that; } - public double $percent (double that) { return value % that; } - - /** @meta method []scala.Double ; */ - public double coerce ( ) { return value ; } - - public boolean $eq$eq (float that) { return value == that; } - public boolean $bang$eq (float that) { return value != that; } - public boolean $less (float that) { return value < that; } - public boolean $greater (float that) { return value > that; } - public boolean $less$eq (float that) { return value <= that; } - public boolean $greater$eq(float that) { return value >= that; } - public float $plus (float that) { return value + that; } - public float $minus (float that) { return value - that; } - public float $times (float that) { return value * that; } - public float $div (float that) { return value / that; } - public float $percent (float that) { return value % that; } - - /** @meta method []scala.Float ; */ - public float coerce ( ) { return value ; } - /** @meta method []scala.Long ; */ - public long $tilde ( ) { return ~value ; } - - public long $less$less (int that) { return value << that; } - public long $less$less (long that) { return value << that; } - public long $greater$greater(int that) { return value >> that; } - public long $greater$greater(long that) { return value >> that; } - public long $greater$greater$greater(int that) { return value >>>that; } - public long $greater$greater$greater(long that) { return value >>>that; } - - public boolean $eq$eq (long that) { return value == that; } - public boolean $bang$eq (long that) { return value != that; } - public boolean $less (long that) { return value < that; } - public boolean $greater (long that) { return value > that; } - public boolean $less$eq (long that) { return value <= that; } - public boolean $greater$eq(long that) { return value >= that; } - public long $plus (long that) { return value + that; } - public long $minus (long that) { return value - that; } - public long $times (long that) { return value * that; } - public long $div (long that) { return value / that; } - public long $percent (long that) { return value % that; } - public long $bar (long that) { return value | that; } - public long $amp (long that) { return value & that; } - public long $up (long that) { return value ^ that; } -/* - - public boolean $eq$eq (int that) { return value == that; } - public boolean $bang$eq (int that) { return value != that; } - public boolean $less (int that) { return value < that; } - public boolean $greater (int that) { return value > that; } - public boolean $less$eq (int that) { return value <= that; } - public boolean $greater$eq(int that) { return value >= that; } - public long $plus (int that) { return value + that; } - public long $minus (int that) { return value - that; } - public long $times (int that) { return value * that; } - public long $div (int that) { return value / that; } - public long $percent (int that) { return value % that; } - public long $bar (int that) { return value | that; } - public long $amp (int that) { return value & that; } - public long $up (int that) { return value ^ that; } - - public boolean $eq$eq (short that) { return value == that; } - public boolean $bang$eq (short that) { return value != that; } - public boolean $less (short that) { return value < that; } - public boolean $greater (short that) { return value > that; } - public boolean $less$eq (short that) { return value <= that; } - public boolean $greater$eq(short that) { return value >= that; } - public long $plus (short that) { return value + that; } - public long $minus (short that) { return value - that; } - public long $times (short that) { return value * that; } - public long $div (short that) { return value / that; } - public long $percent (short that) { return value % that; } - public long $bar (short that) { return value | that; } - public long $amp (short that) { return value & that; } - public long $up (short that) { return value ^ that; } - - public boolean $eq$eq (char that) { return value == that; } - public boolean $bang$eq (char that) { return value != that; } - public boolean $less (char that) { return value < that; } - public boolean $greater (char that) { return value > that; } - public boolean $less$eq (char that) { return value <= that; } - public boolean $greater$eq(char that) { return value >= that; } - public long $plus (char that) { return value + that; } - public long $minus (char that) { return value - that; } - public long $times (char that) { return value * that; } - public long $div (char that) { return value / that; } - public long $percent (char that) { return value % that; } - public long $bar (char that) { return value | that; } - public long $amp (char that) { return value & that; } - public long $up (char that) { return value ^ that; } - - public boolean $eq$eq (byte that) { return value == that; } - public boolean $bang$eq (byte that) { return value != that; } - public boolean $less (byte that) { return value < that; } - public boolean $greater (byte that) { return value > that; } - public boolean $less$eq (byte that) { return value <= that; } - public boolean $greater$eq(byte that) { return value >= that; } - public long $plus (byte that) { return value + that; } - public long $minus (byte that) { return value - that; } - public long $times (byte that) { return value * that; } - public long $div (byte that) { return value / that; } - public long $percent (byte that) { return value % that; } - public long $bar (byte that) { return value | that; } - public long $amp (byte that) { return value & that; } - public long $up (byte that) { return value ^ that; } -*/ -} diff --git a/sources/scala/MatchError.cs b/sources/scala/MatchError.cs deleted file mode 100644 index 1ce0b37b09..0000000000 --- a/sources/scala/MatchError.cs +++ /dev/null @@ -1,62 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** ** -** $Id$ -\* */ -using System; -using scala.runtime; - -namespace scala -{ - - - /** This class implements errors which are thrown whenever an - * object doesn't match any pattern of a pattern matching - * expression. - * - * @author Matthias Zenger - * @version 1.1, 05/03/2004 - */ - public sealed class MatchError : ApplicationException - { - - [Meta("constr (System.String, scala.Int);")] - private MatchError(string source, int line) : - base(" in '" + source + "' at line " + line) - { - } - - [Meta("constr (System.String, scala.Int, System.String);")] - private MatchError(string source, int line, string obj) : - base("for object " + obj + " in '" + source + "' at line " + line) - { - } - - [Meta("method [?T](System.String, scala.Int) ?T;")] - public static object fail(string source, int line) - { - throw new MatchError(source, line); - } - - [Meta("method [?T](System.String, scala.Int, scala.Any) ?T;")] - public static object report(string source, int line, object obj) - { - try - { - throw new MatchError(source, line, obj.ToString()); - } - catch (MatchError e) - { - throw e; - } - catch (Exception e) - { - throw new MatchError(source, line); - } - } - } -} \ No newline at end of file diff --git a/sources/scala/MatchError.java b/sources/scala/MatchError.java deleted file mode 100644 index 0668f5a1d6..0000000000 --- a/sources/scala/MatchError.java +++ /dev/null @@ -1,52 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** ** -** $Id$ -\* */ - -package scala; - - -/** This class implements errors which are thrown whenever an - * object doesn't match any pattern of a pattern matching - * expression. - * - * @author Matthias Zenger - * @version 1.1, 05/03/2004 - */ -public final class MatchError extends Error { - - /** @meta constr (java.lang.String, scala.Int); - */ - private MatchError(java.lang.String source, int line) { - super(" in '" + source + "' at line " + line); - } - - /** @meta constr (java.lang.String, scala.Int, java.lang.String); - */ - private MatchError(java.lang.String source, int line, String obj) { - super("for object " + obj + " in '" + source + "' at line " + line); - } - - /** @meta method [?T](java.lang.String, scala.Int) ?T; - */ - public static java.lang.Object fail(java.lang.String source, int line) { - throw new MatchError(source, line); - } - - /** @meta method [?T](java.lang.String, scala.Int, scala.Any) ?T; - */ - public static java.lang.Object report(java.lang.String source, int line, java.lang.Object obj) { - try { - throw new MatchError(source, line, obj.toString()); - } catch (MatchError e) { - throw e; - } catch (Throwable e) { - throw new MatchError(source, line); - } - } -} diff --git a/sources/scala/None.scala b/sources/scala/None.scala deleted file mode 100644 index 9905889ac1..0000000000 --- a/sources/scala/None.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** This case object represents non-existent values. - * - * @author Martin Odersky - * @version 1.0, 16/07/2003 - */ -case object None extends Option[All]; diff --git a/sources/scala/Option.scala b/sources/scala/Option.scala deleted file mode 100644 index 7d9dbce459..0000000000 --- a/sources/scala/Option.scala +++ /dev/null @@ -1,70 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - -import Predef._; - - -/** This class represents optional values. Instances of Option - * are either instances of case class Some or it is case - * object None. - * - * @author Martin Odersky - * @author Matthias Zenger - * @version 1.0, 16/07/2003 - */ -trait Option[+A] extends Iterable[A] { - - def isEmpty: Boolean = this match { - case None => true - case _ => false - } - - def get: A = this match { - case None => error("None.get") - case Some(x) => x - } - - def get[B >: A](default: B): B = this match { - case None => default - case Some(x) => x - } - - def map[B](f: A => B): Option[B] = this match { - case None => None - case Some(x) => Some(f(x)) - } - - def flatMap[B](f: A => Option[B]): Option[B] = this match { - case None => None - case Some(x) => f(x) - } - - def filter(p: A => Boolean): Option[A] = this match { - case None => None - case Some(x) => if (p(x)) Some(x) else None - } - - override def foreach(f: A => Unit): Unit = this match { - case None => () - case Some(x) => f(x) - } - - def elements: Iterator[A] = this match { - case None => Iterator.empty - case Some(x) => Iterator.fromValues(x) - } - - def toList: List[A] = this match { - case None => List() - case Some(x) => List(x) - } - -} diff --git a/sources/scala/Ordered.scala b/sources/scala/Ordered.scala deleted file mode 100644 index dc2bed7784..0000000000 --- a/sources/scala/Ordered.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** A trait for totally ordered data. - * - * @author Martin Odersky - * @version 1.0, 23/04/2004 - */ -trait Ordered[+a] { - - /** Result of comparing `this' with operand `that'. - * returns `x' where - * x < 0 iff this < that - * x == 0 iff this == that - * x > 0 iff this > that - */ - def compareTo [b >: a <% Ordered[b]](that: b): Int; - - def < [b >: a <% Ordered[b]](that: b): Boolean = (this compareTo that) < 0; - - def > [b >: a <% Ordered[b]](that: b): Boolean = (this compareTo that) > 0; - - def <= [b >: a <% Ordered[b]](that: b): Boolean = (this compareTo that) <= 0; - - def >= [b >: a <% Ordered[b]](that: b): Boolean = (this compareTo that) >= 0; -} diff --git a/sources/scala/PartialFunction.scala b/sources/scala/PartialFunction.scala deleted file mode 100644 index 470f9c5718..0000000000 --- a/sources/scala/PartialFunction.scala +++ /dev/null @@ -1,29 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** A partial function of type PartialFunction[A, B] is a - * unary function where the domain does not include all values of type - * A. The function isDefinedAt allows to - * test dynamically, if a value is in the domain of the function. - * - * @author Martin Odersky - * @version 1.0, 16/07/2003 - */ -trait PartialFunction[-A, +B] extends AnyRef with Function1[A, B] { - - /** Checks if a value is contained in the functions domain. - * - * @param x the value to test - * @return true, iff x is in the domain of this function. - */ - def isDefinedAt(x: A): Boolean; -} diff --git a/sources/scala/PartiallyOrdered.scala b/sources/scala/PartiallyOrdered.scala deleted file mode 100644 index fba76066e0..0000000000 --- a/sources/scala/PartiallyOrdered.scala +++ /dev/null @@ -1,49 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** A trait for partially ordered data. - * - * @author Martin Odersky - * @version 1.0, 23/04/2004 - */ -trait PartiallyOrdered[+a] { - - /** Result of comparing `this' with operand `that'. - * Returns `None' if operands are not comparable. - * If operands are comparable, returns `Some(x)' where - * x < 0 iff this < that - * x == 0 iff this == that - * x > 0 iff this > that - */ - def tryCompareTo [b >: a <% PartiallyOrdered[b]](that: b): Option[int]; - - def < [b >: a <% PartiallyOrdered[b]](that: b): boolean = - (this tryCompareTo that) match { - case Some(x) if x < 0 => true - case _ => false - } - def > [b >: a <% PartiallyOrdered[b]](that: b): boolean = - (this tryCompareTo that) match { - case Some(x) if x > 0 => true - case _ => false - } - def <= [b >: a <% PartiallyOrdered[b]](that: b): boolean = - (this tryCompareTo that) match { - case Some(x) if x <= 0 => true - case _ => false - } - def >= [b >: a <% PartiallyOrdered[b]](that: b): boolean = - (this tryCompareTo that) match { - case Some(x) if x >= 0 => true - case _ => false - } -} diff --git a/sources/scala/Predef.scala b/sources/scala/Predef.scala deleted file mode 100644 index 5005e3df3e..0000000000 --- a/sources/scala/Predef.scala +++ /dev/null @@ -1,359 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** The Predef object provides definitions that are - * accessible in all Scala compilation units without explicit - * qualification. - */ -object Predef { - - // aliases ------------------------------------------------------- - - type byte = scala.Byte; - type short = scala.Short; - type char = scala.Char; - type int = scala.Int; - type long = scala.Long; - type float = scala.Float; - type double = scala.Double; - type boolean = scala.Boolean; - type unit = scala.Unit; - - type String = java.lang.String; - type NullPointerException = java.lang.NullPointerException; - type Throwable = java.lang.Throwable; - - type Pair[+p, +q] = Tuple2[p, q]; - def Pair[a, b](x: a, y: b) = Tuple2(x, y); - - type Triple[+a, +b, +c] = Tuple3[a, b, c]; - def Triple[a, b, c](x: a, y: b, z: c) = Tuple3(x, y, z); - - def id[a](x: a): a = x; - def fst[a](x: a, y: Any): a = x; - def scd[a](x: Any, y: a): a = y; - - val namespace$default = ""; - val $scope = scala.xml.TopScope; - - type Function[-a,+b] = Function1[a,b]; - - // arrays ----------------------------------------------------------- - - /** Create an array with given elements. - * - * @param xs the elements to put in the array - * @return the array containing elements xs. - */ -/* - def Array[A](xs: A*): Array[A] = { - val array = new Array[A](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } -*/ - def Array[A <: AnyRef](xs: A*): Array[A] = { - val array = new Array[A](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } - def Array(xs: boolean*): Array[boolean] = { - val array = new Array[boolean](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } - def Array(xs: byte*): Array[byte] = { - val array = new Array[byte](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } - def Array(xs: short*): Array[short] = { - val array = new Array[short](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } - def Array(xs: char*): Array[char] = { - val array = new Array[char](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } - def Array(xs: int*): Array[int] = { - val array = new Array[int](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } - def Array(xs: long*): Array[long] = { - val array = new Array[long](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } - def Array(xs: float*): Array[float] = { - val array = new Array[float](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } - def Array(xs: double*): Array[double] = { - val array = new Array[double](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } - def Array(xs: unit*): Array[unit] = { - val array = new Array[unit](xs.length); - var i = 0; - for (val x <- xs.elements) { array(i) = x; i = i + 1; } - array; - } - - // errors and asserts ------------------------------------------------- - - def error(message: String): All = throw new Error(message); - - def exit: All = exit(0); - - def exit(status: Int): All = { - java.lang.System.exit(status); - throw new Throwable() - } - - def assert(assertion: Boolean): Unit = { - if (!assertion) - throw new Error("assertion failed"); - } - - def assert(assertion: Boolean, message: Any): Unit = { - if (!assertion) - throw new Error("assertion failed: " + message); - } - - def assume(assumption: Boolean): Unit = { - if (!assumption) - throw new Error("assumption failed"); - } - - def assume(assumption: Boolean, message: Any): Unit = { - if (!assumption) - throw new Error("assumption failed: " + message); - } - - // views ------------------------------------------------------------- - - implicit def identity[a](x: a): a = x; - - implicit def int2ordered(x: int): Ordered[int] = new Ordered[int] with Proxy { - def self: Any = x; - def compareTo [b >: int <% Ordered[b]](y: b): int = y match { - case y1: int => - if (x < y1) -1 - else if (x > y1) 1 - else 0 - case _ => -(y compareTo x) - } - } - def view(x: int): Ordered[int] = int2ordered(x); - - implicit def char2ordered(x: char): Ordered[char] = new Ordered[char] with Proxy { - def self: Any = x; - def compareTo [b >: char <% Ordered[b]](y: b): int = y match { - case y1: char => - if (x < y1) -1 - else if (x > y1) 1 - else 0 - case _ => -(y compareTo x) - } - } - def view(x: char): Ordered[char] = char2ordered(x); - - implicit def long2ordered(x: long): Ordered[long] = new Ordered[long] with Proxy { - def self: Any = x; - def compareTo [b >: long <% Ordered[b]](y: b): int = y match { - case y1: long => - if (x < y1) -1 - else if (x > y1) 1 - else 0 - case _ => -(y compareTo x) - } - } - def view(x: long): Ordered[long] = long2ordered(x); - - implicit def float2ordered(x: float): Ordered[float] = new Ordered[float] with Proxy { - def self: Any = x; - def compareTo [b >: float <% Ordered[b]](y: b): int = y match { - case y1: float => - if (x < y1) -1 - else if (x > y1) 1 - else 0 - case _ => -(y compareTo x) - } - } - def view(x: float): Ordered[float] = float2ordered(x); - - implicit def double2ordered(x: double): Ordered[double] = new Ordered[double] with Proxy { - def self: Any = x; - def compareTo [b >: double <% Ordered[b]](y: b): int = y match { - case y1: double => - if (x < y1) -1 - else if (x > y1) 1 - else 0 - case _ => -(y compareTo x) - } - } - def view(x: double): Ordered[double] = double2ordered(x); - - implicit def boolean2ordered(x: boolean): Ordered[boolean] = new Ordered[boolean] with Proxy { - def self: Any = x; - def compareTo [b >: boolean <% Ordered[b]](y: b): int = y match { - case y1: boolean => - if (x == y1) 0 - else if (x) 1 - else -1 - case _ => -(y compareTo x) - } - } - def view(x: boolean): Ordered[boolean] = boolean2ordered(x); - - implicit def array2ordered[A <% Ordered[A]](xs: Array[A]): Ordered[Array[A]] = new Ordered[Array[A]] with Proxy { - def self: Any = xs; - def compareTo[B >: Array[A] <% Ordered[B]](that: B): Int = that match { - case ys: Array[A] => - var i, res = 0; - while ((i < xs.length) && (i < ys.length) && (res == 0)) { - res = xs(i) compareTo ys(i); - i = i + 1; - } - if (res != 0) res - else if (i < xs.length) 1 - else if (i < ys.length) -1 - else 0 - case _ => - -(that compareTo xs) - } - } - def view[A <% Ordered[A]](xs: Array[A]): Ordered[Array[A]] = array2ordered(xs); - - private def first(xs: Int*): Int = xs.elements.find(x => x != 0) match { - case Some(r) => r - case _ => 0 - } - - /* We can't bootstrap currently with the following views included. We have to - * wait for the next release... - * - implicit def view[A <% Ordered[A], B <% Ordered[B]](x: Tuple2[A, B]): Ordered[Tuple2[A, B]] = - new Ordered[Tuple2[A, B]] with Proxy(x) { - def compareTo[T >: Tuple2[A, B] <% Ordered[T]](y: T): Int = y match { - case y1: Tuple2[A, B] => first(x._1.compareTo(y1._1), - x._2.compareTo(y1._2)); - case _ => -(y compareTo x) - } - } - - implicit def view[A <% Ordered[A], B <% Ordered[B], C <% Ordered[C]] - (x: Tuple3[A, B, C]): Ordered[Tuple3[A, B, C]] = - new Ordered[Tuple3[A, B, C]] with Proxy(x) { - def compareTo[T >: Tuple3[A, B, C] <% Ordered[T]](y: T): Int = y match { - case y1: Tuple3[A, B, C] => first(x._1.compareTo(y1._1), - x._2.compareTo(y1._2), - x._3.compareTo(y1._3)); - case _ => -(y compareTo x) - } - } - - implicit def view[A <% Ordered[A], B <% Ordered[B], C <% Ordered[C], D <% Ordered[D]] - (x: Tuple4[A, B, C, D]): Ordered[Tuple4[A, B, C, D]] = - new Ordered[Tuple4[A, B, C, D]] with Proxy(x) { - def compareTo[T >: Tuple4[A, B, C, D] <% Ordered[T]](y: T): Int = y match { - case y1: Tuple4[A, B, C, D] => first(x._1.compareTo(y1._1), - x._2.compareTo(y1._2), - x._3.compareTo(y1._3), - x._4.compareTo(y1._4)); - case _ => -(y compareTo x) - } - } - - implicit def view[A <% Ordered[A], B <% Ordered[B], C <% Ordered[C], D <% Ordered[D], E <% Ordered[E]] - (x: Tuple5[A, B, C, D, E]): Ordered[Tuple5[A, B, C, D, E]] = - new Ordered[Tuple5[A, B, C, D, E]] with Proxy(x) { - def compareTo[T >: Tuple5[A, B, C, D, E] <% Ordered[T]](y: T): Int = y match { - case y1: Tuple5[A, B, C, D, E] => first(x._1.compareTo(y1._1), - x._2.compareTo(y1._2), - x._3.compareTo(y1._3), - x._4.compareTo(y1._4), - x._5.compareTo(y1._5)); - case _ => -(y compareTo x) - } - } - */ - - implicit def string2ordered(x: String): Ordered[String] = new Ordered[String] with Proxy { - def self: Any = x; - def compareTo [b >: String <% Ordered[b]](y: b): int = y match { - case y1: String => x compareTo y1; - case _ => -(y compareTo x) - } - } - def view(x: String): Ordered[String] = string2ordered(x); - - implicit def array2seq[A](xs: Array[A]): Seq[A] = new Seq[A] { - def length = xs.length; - def elements = Iterator.fromArray(xs); - def apply(n: Int) = xs(n); - override def hashCode(): Int = xs.hashCode(); - override def equals(y: Any): Boolean = (xs == y); - override protected def stringPrefix: String = "Array"; - } - def view[A](xs: Array[A]): Seq[A] = array2seq(xs); - - implicit def string2seq(str: String): Seq[Char] = new Seq[Char] { - def length = str.length(); - def elements = Iterator.fromString(str); - def apply(n: Int) = str.charAt(n); - override def hashCode(): Int = str.hashCode(); - override def equals(y: Any): Boolean = (str == y); - override protected def stringPrefix: String = "String"; - } - def view(x: String): Seq[Char] = string2seq(x); - - implicit def byte2short(x: byte): short = x.toShort; - implicit def byte2int(x: byte): int = x.toInt; - implicit def byte2long(x: byte): long = x.toLong; - implicit def byte2float(x: byte): float = x.toFloat; - implicit def byte2double(x: byte): double = x.toDouble; - - implicit def short2int(x: short): int = x.toInt; - implicit def short2long(x: short): long = x.toLong; - implicit def short2float(x: short): float = x.toFloat; - implicit def short2double(x: short): double = x.toDouble; - - implicit def char2int(x: char): int = x.toInt; - implicit def char2long(x: char): long = x.toLong; - implicit def char2float(x: char): float = x.toFloat; - implicit def char2double(x: char): double = x.toDouble; - - implicit def int2long(x: int): long = x.toLong; - implicit def int2float(x: int): float = x.toFloat; - implicit def int2double(x: int): double = x.toDouble; - - implicit def long2float(x: long): float = x.toFloat; - implicit def long2double(x: long): double = x.toDouble; - - implicit def float2double(x: float): double = x.toDouble; -} diff --git a/sources/scala/Proxy.scala b/sources/scala/Proxy.scala deleted file mode 100644 index 5129f0eb00..0000000000 --- a/sources/scala/Proxy.scala +++ /dev/null @@ -1,26 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** This class implements a simple proxy that forwards all calls to - * methods of class Any to another object self. - * Please note that only those methods can be forwarded that are - * overridable and public. - * - * @author Matthias Zenger - * @version 1.0, 26/04/2004 - */ -trait Proxy { - def self: Any; - override def hashCode(): Int = self.hashCode(); - override def equals(y: Any): Boolean = self.equals(y); - override def toString(): String = self.toString(); -} diff --git a/sources/scala/Ref.cs b/sources/scala/Ref.cs deleted file mode 100644 index 3a10a7c648..0000000000 --- a/sources/scala/Ref.cs +++ /dev/null @@ -1,31 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $OldId: Ref.java,v 1.2 2002/03/12 13:16:04 zenger Exp $ -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - [Meta("class [?T] extends scala.AnyRef;")] - [Serializable] - public class Ref : object { - - [Meta("field ?T;")] - public object elem = null; - - [Meta("constr (?T);")] - public Ref(object x) - { - elem = x; - } - } -} \ No newline at end of file diff --git a/sources/scala/Ref.java b/sources/scala/Ref.java deleted file mode 100644 index 3c47ae5573..0000000000 --- a/sources/scala/Ref.java +++ /dev/null @@ -1,27 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $OldId: Ref.java,v 1.2 2002/03/12 13:16:04 zenger Exp $ -// $Id$ - -package scala; - -/** @meta class [?T] extends java.lang.Object with java.io.Serializable; - */ -public class Ref extends java.lang.Object implements java.io.Serializable { - - /** @meta field ?T; - */ - public java.lang.Object elem = null; - - /** @meta constr (?T); - */ - public Ref(java.lang.Object x) { - elem = x; - } -} diff --git a/sources/scala/ScalaObject.cs b/sources/scala/ScalaObject.cs deleted file mode 100644 index 7f2b7f693b..0000000000 --- a/sources/scala/ScalaObject.cs +++ /dev/null @@ -1,24 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - [Meta("class extends scala.AnyRef;")] - public interface ScalaObject - { - /** This method is needed for optimizing pattern matching expressions - * which match on constructors of case classes. - */ - int __tag(); - } -} \ No newline at end of file diff --git a/sources/scala/ScalaObject.java b/sources/scala/ScalaObject.java deleted file mode 100644 index c958960a02..0000000000 --- a/sources/scala/ScalaObject.java +++ /dev/null @@ -1,27 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -import scala.runtime.types.ClassType; - -/** @meta class extends scala.AnyRef; - */ -public interface ScalaObject { - /** - * Return the Scala type of the object. - */ - public ClassType getScalaType(); - - /** This method is needed for optimizing pattern matching expressions - * which match on constructors of case classes. - */ - public int $tag(); -} diff --git a/sources/scala/Seq.scala b/sources/scala/Seq.scala deleted file mode 100644 index efc3996333..0000000000 --- a/sources/scala/Seq.scala +++ /dev/null @@ -1,194 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - -import Predef._; - -object Seq { - - /** builds a singleton sequence - * @author buraq - */ - def single[A](x:A) = new Seq[A] { - def length = 1; - def elements = Iterator.single(x); - override def isDefinedAt(x: Int): Boolean = (x == 0); - def apply(i:Int) = x; // caller's responsibility to check isDefinedAt - } - - def view[A <% Ordered[A]](xs: Seq[A]): Ordered[Seq[A]] = new Ordered[Seq[A]] with Proxy { - def self: Any = xs; - def compareTo[B >: Seq[A] <% Ordered[B]](that: B): Int = that match { - case ys: Seq[A] => - var res = 0; - val xsit = xs.elements; - val ysit = ys.elements; - while (xsit.hasNext && ysit.hasNext && (res == 0)) { - res = xsit.next compareTo ysit.next; - } - if (res != 0) res else if (xsit.hasNext) 1 else -1 - case _ => - -(that compareTo xs) - } - } -} - - -/** Class Seq[A] represents finite sequences of elements - * of type A. - * - * @author Martin Odersky - * @author Matthias Zenger - * @version 1.0, 16/07/2003 - */ -[serializable] -trait Seq[+A] extends AnyRef with PartialFunction[Int, A] with Iterable[A] { - - /** Returns the length of the sequence. - * - * @return the sequence length. - */ - def length: Int; - - /** Returns the concatenation of two sequences. - * - * @return concatenation of this sequence with argument - * @author buraq - */ - def concat[B >: A](that:Seq[B]): Seq[B] = new Seq[B] { - def length = Seq.this.length + that.length; - def elements: Iterator[B] = Seq.this.elements.append(that.elements); - def apply(i:Int) = { - if(Seq.this.isDefinedAt(i)) - Seq.this.apply(i) - else - that.apply(i - Seq.this.length); - } - } - - /** Is this partial function defined for the index x? - * - * @return true, iff x is a legal sequence index. - */ - def isDefinedAt(x: Int): Boolean = (x >= 0) && (x < length); - - /** Returns the index of the first occurence of the specified - * object in this sequence. - * - * @param elem element to search for. - * @return the index in this sequence of the first occurence of the specified - * element, or -1 if the sequence does not contain this element. - */ - def indexOf[B >: A](elem: B): Int = { - val it = elements; - var i = 0; - var found = false; - while (!found && it.hasNext) { - if (it.next == elem) { - found = true; - } else { - i = i + 1 - } - } - if (found) i else -1; - } - - /** Returns the index of the last occurence of the specified - * element in this sequence, or -1 if the sequence does not - * contain this element. - * - * @param elem element to search for. - * @return the index in this sequence of the last occurence of the - * specified element, or -1 if the sequence does not contain - * this element. - */ - def lastIndexOf[B >: A](elem: B): Int = { - var i = length; - var found = false; - while (!found && (i > 0)) { - i = i - 1; - if (this(i) == elem) { - found = true; - } - } - if (found) i else -1; - } - - /** Returns the sub-sequence starting from index n. - */ - def take(n: Int): Seq[A] = subseq(0, n); - - /** Returns a new sub-sequence that drops the first n - * elements of this sequence. - */ - def drop(n: Int): Seq[A] = subseq(n, length - n); - - /** Returns a subsequence starting from index from - * consisting of len elements. - */ - def subseq(from: Int, len: Int): Seq[A] = - if ((from + len) <= length) new Seq[A] { - def apply(n: Int): A = Seq.this.apply(n + from); - def length: Int = len; - def elements: Iterator[A] = new Iterator[A] { - var i = from; - def hasNext = (i < (from + len)); - def next = { - val res = Seq.this.apply(i); - i = i + 1; - res - } - } - } else - error("cannot create subsequence"); - - /** Fills the given array xs with the elements of - * this sequence starting at position start. - * - * @param xs the array to fill. - * @param start starting index. - * @return the given array xs filled with this list. - */ - def copyToArray[B >: A](xs: Array[B], start: Int): Array[B] = { - val it = elements; - var i = start; - while (it.hasNext) { - xs(i) = it.next; - i = i + 1; - } - xs - } - - /** Transform this sequence into a list of all elements. - * - * @return a list which enumerates all elements of this sequence. - */ - def toList: List[A] = elements.toList; - - /** Customizes the toString method. - * - * @return a string representation of this sequence. - */ - override def toString() = { - val iter = elements; - var res = stringPrefix + "("; - if (iter.hasNext) { - res = res + iter.next; - while (iter.hasNext) - res = res + ", " + iter.next; - } - res + ")" - } - - /** Defines the prefix of the string representation. - */ - protected def stringPrefix: String = "Seq"; -} - diff --git a/sources/scala/SeqProxy.scala b/sources/scala/SeqProxy.scala deleted file mode 100644 index 03f6031312..0000000000 --- a/sources/scala/SeqProxy.scala +++ /dev/null @@ -1,91 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** Class Seq[A] represents finite sequences of elements - * of type A. - * - * @author Martin Odersky - * @author Matthias Zenger - * @version 1.0, 16/07/2003 - */ -trait SeqProxy[+A] extends Seq[A] with IterableProxy[A] { - - def self: Seq[A]; - - /** Returns the length of the sequence. - * - * @return the sequence length. - */ - def length: Int = self.length; - - /** Access element number n. - * - * @return the element at index n. - */ - def apply(n: Int): A = self.apply(n); - - /** Is this partial function defined for the index x? - * - * @return true, iff x is a legal sequence index. - */ - override def isDefinedAt(y: Int): Boolean = self.isDefinedAt(y); - - /** Returns the index of the first occurence of the specified - * object in this sequence. - * - * @param elem element to search for. - * @return the index in this sequence of the first occurence of the specified - * element, or -1 if the sequence does not contain this element. - */ - override def indexOf[B >: A](elem: B): Int = self.indexOf(elem); - - /** Returns the index of the last occurence of the specified - * element in this sequence, or -1 if the sequence does not - * contain this element. - * - * @param elem element to search for. - * @return the index in this sequence of the last occurence of the - * specified element, or -1 if the sequence does not contain - * this element. - */ - override def lastIndexOf[B >: A](elem: B): Int = self.lastIndexOf(elem); - - /** Returns the sub-sequence starting from index n. - */ - override def take(n: Int): Seq[A] = self.take(n); - - /** Returns a new sub-sequence that drops the first n - * elements of this sequence. - */ - override def drop(n: Int): Seq[A] = self.drop(n); - - /** Returns a subsequence starting from index from - * consisting of len elements. - */ - override def subseq(from: Int, len: Int): Seq[A] = self.subseq(from, len); - - /** Fills the given array xs with the elements of - * this sequence starting at position start. - * - * @param xs the array to fill. - * @param start starting index. - * @return the given array xs filled with the elements - * of this sequence. - */ - override def copyToArray[B >: A](xs: Array[B], start: Int): Array[B] = self.copyToArray(xs, start); - - /** Transform this sequence into a list of all elements. - * - * @return a list which enumerates all elements of this sequence. - */ - override def toList: List[A] = self.toList; -} diff --git a/sources/scala/SerialVersionUID.scala b/sources/scala/SerialVersionUID.scala deleted file mode 100644 index c86da7b66c..0000000000 --- a/sources/scala/SerialVersionUID.scala +++ /dev/null @@ -1,12 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -*/ - -package scala; - -case class SerialVersionUID(uid: Long) extends Attribute {} diff --git a/sources/scala/Short.cs b/sources/scala/Short.cs deleted file mode 100644 index 0e03090d59..0000000000 --- a/sources/scala/Short.cs +++ /dev/null @@ -1,129 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - [Meta("class extends scala.AnyVal;")] - [Serializable] - public abstract class Short : AnyVal { - - public readonly short value; - - public Short(short value) - { - this.value = value; - } - - public override bool Equals(object other) - { - return (other is Short) && value == ((Short)other).value; - } - public override int GetHashCode() - { - return value; - } - public override string ToString() - { - return value.ToString(); - } - - [Meta("method (scala.Any)scala.Boolean;")] - public bool __eq__eq (object other) { return Equals(other); } - [Meta("method (scala.Any)scala.Boolean;")] - public bool __bang__eq(object other) { return !Equals(other); } - - [Meta("method []scala.Int;")] - public int __plus () { return +value; } - [Meta("method []scala.Int;")] - public int __minus () { return -value; } - - public string __plus (string that) { return value + that; } - - public bool __eq__eq (double that) { return value == that; } - public bool __bang__eq (double that) { return value != that; } - public bool __less (double that) { return value < that; } - public bool __greater (double that) { return value > that; } - public bool __less__eq (double that) { return value <= that; } - public bool __greater__eq(double that) { return value >= that; } - public double __plus (double that) { return value + that; } - public double __minus (double that) { return value - that; } - public double __times (double that) { return value * that; } - public double __div (double that) { return value / that; } - public double __percent (double that) { return value % that; } - - [Meta("method []scala.Double;")] - public double coerce ( ) { return value; } - - public bool __eq__eq (float that) { return value == that; } - public bool __bang__eq (float that) { return value != that; } - public bool __less (float that) { return value < that; } - public bool __greater (float that) { return value > that; } - public bool __less__eq (float that) { return value <= that; } - public bool __greater__eq(float that) { return value >= that; } - public float __plus (float that) { return value + that; } - public float __minus (float that) { return value - that; } - public float __times (float that) { return value * that; } - public float __div (float that) { return value / that; } - public float __percent (float that) { return value % that; } - - [Meta("method []scala.Float;")] - public float coerce (float dummy) { return value ; } - [Meta("method []scala.Int;")] - public int __tilde ( ) { return ~value ; } - - public int __less__less (int that) { return value << that; } - public int __less__less (long that) { return value << (int)that; } - public int __greater__greater(int that) { return value >> that; } - public int __greater__greater(long that) { return value >> (int)that; } - public int __greater__greater__greater(int that) { return (int)((uint)value >>that); } - public int __greater__greater__greater(long that) { return (int)((uint)value >>(int)that); } - - public bool __eq__eq (long that) { return value == that; } - public bool __bang__eq (long that) { return value != that; } - public bool __less (long that) { return value < that; } - public bool __greater (long that) { return value > that; } - public bool __less__eq (long that) { return value <= that; } - public bool __greater__eq(long that) { return value >= that; } - public long __plus (long that) { return value + that; } - public long __minus (long that) { return value - that; } - public long __times (long that) { return value * that; } - public long __div (long that) { return value / that; } - public long __percent (long that) { return value % that; } - public long __bar (long that) { return value | that; } - public long __amp (long that) { return value & that; } - public long __up (long that) { return value ^ that; } - - [Meta("method []scala.Long;")] - public long coerce (long dummy) { return value ; } - - public bool __eq__eq (int that) { return value == that; } - public bool __bang__eq (int that) { return value != that; } - public bool __less (int that) { return value < that; } - public bool __greater (int that) { return value > that; } - public bool __less__eq (int that) { return value <= that; } - public bool __greater__eq(int that) { return value >= that; } - public int __plus (int that) { return value + that; } - public int __minus (int that) { return value - that; } - public int __times (int that) { return value * that; } - public int __div (int that) { return value / that; } - public int __percent (int that) { return value % that; } - public int __bar (int that) { return value | that; } - public int __amp (int that) { return value & that; } - public int __up (int that) { return value ^ that; } - - [Meta("method []scala.Int;")] - public int coerce (int dummy) { return value ; } - - } -} \ No newline at end of file diff --git a/sources/scala/Short.java b/sources/scala/Short.java deleted file mode 100644 index e800678202..0000000000 --- a/sources/scala/Short.java +++ /dev/null @@ -1,186 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -/** @meta class extends scala.AnyVal; */ -public abstract class Short extends AnyVal implements java.io.Serializable { - - public final short value; - - public Short (short value) { - this.value = value; - } - - public boolean equals(java.lang.Object other) { - return other instanceof Short && value == ((Short )other).value; - } - public int hashCode() { - int bits = value; - return bits; - } - public String toString() { - return String.valueOf(value); - } - - /** @meta method []scala.Byte; */ - public byte toByte() { return (byte)value; } - - /** @meta method []scala.Short; */ - public short toShort() { return (short)value; } - - /** @meta method []scala.Char; */ - public char toChar() { return (char)value; } - - /** @meta method []scala.Int; */ - public int toInt() { return (int)value; } - - /** @meta method []scala.Long; */ - public long toLong() { return (long)value; } - - /** @meta method []scala.Float; */ - public float toFloat() { return (float)value; } - - /** @meta method []scala.Double; */ - public double toDouble() { return (double)value; } - - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $eq$eq (java.lang.Object other) { return equals(other); } - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $bang$eq(java.lang.Object other) { return !equals(other); } - - /** @meta method []scala.Int ; */ - public int $plus ( ) { return +value ; } - /** @meta method []scala.Int ; */ - public int $minus ( ) { return -value ; } - - public String $plus (String that) { return value + that; } - - public boolean $eq$eq (double that) { return value == that; } - public boolean $bang$eq (double that) { return value != that; } - public boolean $less (double that) { return value < that; } - public boolean $greater (double that) { return value > that; } - public boolean $less$eq (double that) { return value <= that; } - public boolean $greater$eq(double that) { return value >= that; } - public double $plus (double that) { return value + that; } - public double $minus (double that) { return value - that; } - public double $times (double that) { return value * that; } - public double $div (double that) { return value / that; } - public double $percent (double that) { return value % that; } - - /** @meta method []scala.Double ; */ - public double coerce ( ) { return value ; } - - public boolean $eq$eq (float that) { return value == that; } - public boolean $bang$eq (float that) { return value != that; } - public boolean $less (float that) { return value < that; } - public boolean $greater (float that) { return value > that; } - public boolean $less$eq (float that) { return value <= that; } - public boolean $greater$eq(float that) { return value >= that; } - public float $plus (float that) { return value + that; } - public float $minus (float that) { return value - that; } - public float $times (float that) { return value * that; } - public float $div (float that) { return value / that; } - public float $percent (float that) { return value % that; } - - /** @meta method []scala.Float ; */ - public float coerce ( ) { return value ; } - /** @meta method []scala.Int ; */ - public int $tilde ( ) { return ~value ; } - - public int $less$less (int that) { return value << that; } - public int $less$less (long that) { return value << that; } - public int $greater$greater(int that) { return value >> that; } - public int $greater$greater(long that) { return value >> that; } - public int $greater$greater$greater(int that) { return value >>>that; } - public int $greater$greater$greater(long that) { return value >>>that; } - - public boolean $eq$eq (long that) { return value == that; } - public boolean $bang$eq (long that) { return value != that; } - public boolean $less (long that) { return value < that; } - public boolean $greater (long that) { return value > that; } - public boolean $less$eq (long that) { return value <= that; } - public boolean $greater$eq(long that) { return value >= that; } - public long $plus (long that) { return value + that; } - public long $minus (long that) { return value - that; } - public long $times (long that) { return value * that; } - public long $div (long that) { return value / that; } - public long $percent (long that) { return value % that; } - public long $bar (long that) { return value | that; } - public long $amp (long that) { return value & that; } - public long $up (long that) { return value ^ that; } - - /** @meta method []scala.Long ; */ - public long coerce ( ) { return value ; } - - public boolean $eq$eq (int that) { return value == that; } - public boolean $bang$eq (int that) { return value != that; } - public boolean $less (int that) { return value < that; } - public boolean $greater (int that) { return value > that; } - public boolean $less$eq (int that) { return value <= that; } - public boolean $greater$eq(int that) { return value >= that; } - public int $plus (int that) { return value + that; } - public int $minus (int that) { return value - that; } - public int $times (int that) { return value * that; } - public int $div (int that) { return value / that; } - public int $percent (int that) { return value % that; } - public int $bar (int that) { return value | that; } - public int $amp (int that) { return value & that; } - public int $up (int that) { return value ^ that; } - - /** @meta method []scala.Int ; */ - public int coerce ( ) { return value ; } - - - public boolean $eq$eq (char that) { return value == that; } - public boolean $bang$eq (char that) { return value != that; } - public boolean $less (char that) { return value < that; } - public boolean $greater (char that) { return value > that; } - public boolean $less$eq (char that) { return value <= that; } - public boolean $greater$eq(char that) { return value >= that; } - public int $plus (char that) { return value + that; } - public int $minus (char that) { return value - that; } - public int $times (char that) { return value * that; } - public int $div (char that) { return value / that; } - public int $percent (char that) { return value % that; } - public int $bar (char that) { return value | that; } - public int $amp (char that) { return value & that; } - public int $up (char that) { return value ^ that; } - - public boolean $eq$eq (short that) { return value == that; } - public boolean $bang$eq (short that) { return value != that; } - public boolean $less (short that) { return value < that; } - public boolean $greater (short that) { return value > that; } - public boolean $less$eq (short that) { return value <= that; } - public boolean $greater$eq(short that) { return value >= that; } - public int $plus (short that) { return value + that; } - public int $minus (short that) { return value - that; } - public int $times (short that) { return value * that; } - public int $div (short that) { return value / that; } - public int $percent (short that) { return value % that; } - public int $bar (short that) { return value | that; } - public int $amp (short that) { return value & that; } - public int $up (short that) { return value ^ that; } - - public boolean $eq$eq (byte that) { return value == that; } - public boolean $bang$eq (byte that) { return value != that; } - public boolean $less (byte that) { return value < that; } - public boolean $greater (byte that) { return value > that; } - public boolean $less$eq (byte that) { return value <= that; } - public boolean $greater$eq(byte that) { return value >= that; } - public int $plus (byte that) { return value + that; } - public int $minus (byte that) { return value - that; } - public int $times (byte that) { return value * that; } - public int $div (byte that) { return value / that; } - public int $percent (byte that) { return value % that; } - public int $bar (byte that) { return value | that; } - public int $amp (byte that) { return value & that; } - public int $up (byte that) { return value ^ that; } -} diff --git a/sources/scala/Some.scala b/sources/scala/Some.scala deleted file mode 100644 index 4f0bd7ea3c..0000000000 --- a/sources/scala/Some.scala +++ /dev/null @@ -1,19 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** Class Option[A] represents existing values of type - * A. - * - * @author Martin Odersky - * @version 1.0, 16/07/2003 - */ -final case class Some[+A1](x: A1) extends Option[A1]; diff --git a/sources/scala/Stream.scala b/sources/scala/Stream.scala deleted file mode 100644 index bd0501b4fb..0000000000 --- a/sources/scala/Stream.scala +++ /dev/null @@ -1,243 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - -/** - * The object Stream provides helper functions - * to manipulate streams. - * - * @author Martin Odersky, Matthias Zenger - * @version 1.1 08/08/03 - */ -object Stream { - - val empty: Stream[All] = new Stream[All] { - def isEmpty = true; - def head: All = error("head of empty stream"); - def tail: Stream[All] = error("tail of empty stream"); - def printElems(buf: StringBuffer, prefix: String): StringBuffer = buf; - } - - def cons[a](hd: a, tl: => Stream[a]) = new Stream[a] { - def isEmpty = false; - def head = hd; - private var tlVal: Stream[a] = _; - private var tlDefined = false; - def tail: Stream[a] = { - if (!tlDefined) { tlVal = tl; tlDefined = true; } - tlVal - } - def printElems(buf: StringBuffer, prefix: String): StringBuffer = { - val buf1 = buf.append(prefix).append(hd); - if (tlDefined) printElems(buf1, ", ") else buf1 append ", ?"; - } - } - - def fromIterator[a](it: Iterator[a]): Stream[a] = - if (it.hasNext) cons(it.next, fromIterator(it)) else empty; - - def concat[a](xs: Seq[Stream[a]]): Stream[a] = concat(xs.elements); - - def concat[a](xs: Iterator[Stream[a]]): Stream[a] = { - if (xs.hasNext) xs.next append concat(xs) - else empty; - } - - /** - * Create a stream with element values - * vn+1 = vn + 1 - * where v0 = start - * and vi < end. - * - * @param start the start value of the stream - * @param end the end value of the stream - * @return the stream starting at value start. - */ - def range(start: Int, end: Int): Stream[Int] = - range(start, end, 1); - - /** - * Create a stream with element values - * vn+1 = vn + step - * where v0 = start - * and vi < end. - * - * @param start the start value of the stream - * @param end the end value of the stream - * @param step the increment value of the stream - * @return the stream starting at value start. - */ - def range(start: Int, end: Int, step: Int): Stream[Int] = { - def loop(lo: Int): Stream[Int] = - if (lo >= end) empty - else cons(lo, loop(lo + step)); - loop(start) - } - - /** - * Create a stream with element values - * vn+1 = step(vn) - * where v0 = start - * and vi < end. - * - * @param start the start value of the stream - * @param end the end value of the stream - * @param step the increment function of the stream - * @return the stream starting at value start. - */ - def range(start: Int, end: Int, step: Int => Int): Stream[Int] = { - def loop(lo: Int): Stream[Int] = - if (lo >= end) empty - else cons(lo, loop(step(lo))); - loop(start) - } -} - -/** - *

The class Stream implements lazy lists where elements - * are only evaluated when they are needed. Here is an example:

- *
- * object Main with Application {
- *
- *   def from(n: Int): Stream[Int] =
- *     Stream.cons(n, from(n + 1));
- *
- *   def sieve(s: Stream[Int]): Stream[Int] =
- *     Stream.cons(s.head, sieve(s.tail filter { x => x % s.head != 0 }));
- *
- *   def primes = sieve(from(2));
- *
- *   primes take 10 print
- * }
- * 
- * - * @author Martin Odersky, Matthias Zenger - * @version 1.1 08/08/03 - */ -trait Stream[+a] extends Seq[a] { - - def isEmpty: Boolean; - def head: a; - def tail: Stream[a]; - - def length: int = if (isEmpty) 0 else tail.length + 1; - - def append[b >: a](rest: => Stream[b]): Stream[b] = - if (isEmpty) rest - else Stream.cons(head, tail.append(rest)); - - def elements: Iterator[a] = new Iterator[a] { - var current = Stream.this; - def hasNext: boolean = !current.isEmpty; - def next: a = { val result = current.head; current = current.tail; result } - } - - def init: Stream[a] = - if (isEmpty) error("Stream.empty.init") - else if (tail.isEmpty) Stream.empty - else Stream.cons(head, tail.init); - - def last: a = - if (isEmpty) error("Stream.empty.last") - else if (tail.isEmpty) head - else tail.last; - - override def take(n: int): Stream[a] = - if (n == 0) Stream.empty - else Stream.cons(head, tail.take(n-1)); - - override def drop(n: int): Stream[a] = - if (n == 0) this - else tail.drop(n-1); - - def apply(n: int) = drop(n).head; - def at(n: int) = drop(n).head; - - def takeWhile(p: a => Boolean): Stream[a] = - if (isEmpty || !p(head)) Stream.empty - else Stream.cons(head, tail.takeWhile(p)); - - def dropWhile(p: a => Boolean): Stream[a] = - if (isEmpty || !p(head)) this - else tail.dropWhile(p); - - def map[b](f: a => b): Stream[b] = - if (isEmpty) Stream.empty - else Stream.cons(f(head), tail.map(f)); - - override def foreach(f: a => unit): unit = - if (isEmpty) {} - else { f(head); tail.foreach(f) } - - def filter(p: a => Boolean): Stream[a] = - if (isEmpty) this - else if (p(head)) Stream.cons(head, tail.filter(p)) - else tail.filter(p); - - override def forall(p: a => Boolean): Boolean = - isEmpty || (p(head) && tail.forall(p)); - - override def exists(p: a => Boolean): Boolean = - !isEmpty && (p(head) || tail.exists(p)); - - override def foldLeft[b](z: b)(f: (b, a) => b): b = - if (isEmpty) z - else tail.foldLeft[b](f(z, head))(f); - - override def foldRight[b](z: b)(f: (a, b) => b): b = - if (isEmpty) z - else f(head, tail.foldRight(z)(f)); - - def reduceLeft[b >: a](f: (b, b) => b): b = - if (isEmpty) error("Stream.empty.reduceLeft") - else ((tail: Stream[b]) foldLeft (head: b))(f); - - def reduceRight[b >: a](f: (b, b) => b): b = - if (isEmpty) error("Stream.empty.reduceRight") - else if (tail.isEmpty) head: b - else f(head, tail.reduceRight(f)); - - def flatMap[b](f: a => Stream[b]): Stream[b] = - if (isEmpty) Stream.empty - else f(head).append(tail.flatMap(f)); - - def reverse: Stream[a] = - foldLeft(Stream.empty: Stream[a])((xs, x) => Stream.cons(x, xs)); - - // The following method is not compilable without run-time type - // information. It should therefore be left commented-out for - // now. - // def toArray: Array[a] = { - // val xs = new Array[a](length); - // copyToArray(xs, 0); - // xs - // } - - override def copyToArray[b >: a](xs: Array[b], start: int): Array[b] = - if (isEmpty) xs - else { xs(start) = head; tail.copyToArray(xs, start + 1) } - - def zip[b](that: Stream[b]): Stream[Tuple2[a, b]] = - if (this.isEmpty || that.isEmpty) Stream.empty - else Stream.cons(Tuple2(this.head, that.head), this.tail.zip(that.tail)); - - def print: unit = - if (isEmpty) Console.println("Stream.empty") - else { - Console.print(head); - Console.print(", "); - tail.print - } - - override def toString() = - "Stream(" + printElems(new StringBuffer(), "") + ")"; - - def printElems(buf: StringBuffer, prefix: String): StringBuffer; -} diff --git a/sources/scala/Symbol.scala b/sources/scala/Symbol.scala deleted file mode 100644 index 2e1ab3a724..0000000000 --- a/sources/scala/Symbol.scala +++ /dev/null @@ -1,30 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala; - - -/** Instances of Symbol can be created easily with - * Scala's built-in quote mechanism. For instance, the Scala term - * 'mysym will invoke the constructor of the - * Symbol class in the following way: - * new Symbol("mysym"). . - * - * @author Martin Odersky - * @version 1.7, 08/12/2003 - */ -final case class Symbol(name: String) { - - /** Converts this symbol to a string. - */ - override def toString(): String = { - "'" + name - } - -} diff --git a/sources/scala/Tuple1.scala b/sources/scala/Tuple1.scala deleted file mode 100644 index 620ad276bc..0000000000 --- a/sources/scala/Tuple1.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -case class Tuple1[+T1](_1: T1) { - override def toString(): String = "(" + _1 + ")"; -} diff --git a/sources/scala/Tuple2.scala b/sources/scala/Tuple2.scala deleted file mode 100644 index e830a4f769..0000000000 --- a/sources/scala/Tuple2.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -case class Tuple2[+T1, +T2](_1: T1, _2: T2) { - override def toString(): String = "(" + _1 + "," + _2 + ")"; -} diff --git a/sources/scala/Tuple3.scala b/sources/scala/Tuple3.scala deleted file mode 100644 index 53ce97a5b1..0000000000 --- a/sources/scala/Tuple3.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -case class Tuple3[+T1, +T2, +T3](_1: T1, _2: T2, _3: T3) { - override def toString(): String = "(" + _1 + "," + _2 + "," + _3 + ")"; -} diff --git a/sources/scala/Tuple4.scala b/sources/scala/Tuple4.scala deleted file mode 100644 index 419afd7eb1..0000000000 --- a/sources/scala/Tuple4.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -case class Tuple4[+T1, +T2, +T3, +T4](_1: T1, _2: T2, _3: T3, _4: T4) { - override def toString(): String = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + ")"; -} diff --git a/sources/scala/Tuple5.scala b/sources/scala/Tuple5.scala deleted file mode 100644 index 24bca2d443..0000000000 --- a/sources/scala/Tuple5.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -case class Tuple5[+T1, +T2, +T3, +T4, +T5](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5) { - override def toString(): String = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + ")"; -} diff --git a/sources/scala/Tuple6.scala b/sources/scala/Tuple6.scala deleted file mode 100644 index 205afce10d..0000000000 --- a/sources/scala/Tuple6.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -case class Tuple6[+T1, +T2, +T3, +T4, +T5, +T6](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6) { - override def toString(): String = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + ")"; -} diff --git a/sources/scala/Tuple7.scala b/sources/scala/Tuple7.scala deleted file mode 100644 index 61dcac85b5..0000000000 --- a/sources/scala/Tuple7.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -case class Tuple7[+T1, +T2, +T3, +T4, +T5, +T6, +T7](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7) { - override def toString(): String = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + ")"; -} diff --git a/sources/scala/Tuple8.scala b/sources/scala/Tuple8.scala deleted file mode 100644 index 6857e876d3..0000000000 --- a/sources/scala/Tuple8.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -case class Tuple8[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8) { - override def toString(): String = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + ")"; -} diff --git a/sources/scala/Tuple9.scala b/sources/scala/Tuple9.scala deleted file mode 100644 index 50b3c66b40..0000000000 --- a/sources/scala/Tuple9.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala; - -case class Tuple9[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9](_1: T1, _2: T2, _3: T3, _4: T4, _5: T5, _6: T6, _7: T7, _8: T8, _9: T9) { - override def toString(): String = "(" + _1 + "," + _2 + "," + _3 + "," + _4 + "," + _5 + "," + _6 + "," + _7 + "," + _8 + "," + _9 + ")"; -} diff --git a/sources/scala/Type.java b/sources/scala/Type.java deleted file mode 100644 index 288bb634f5..0000000000 --- a/sources/scala/Type.java +++ /dev/null @@ -1,160 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -import scala.runtime.RunTime; -import scala.runtime.types.ScalaClassType; -import scala.runtime.types.JavaClassType; -import scala.runtime.types.TypeBoolean; -import scala.runtime.types.TypeByte; -import scala.runtime.types.TypeChar; -import scala.runtime.types.TypeDouble; -import scala.runtime.types.TypeFloat; -import scala.runtime.types.TypeInt; -import scala.runtime.types.TypeLong; -import scala.runtime.types.TypeShort; -import scala.runtime.types.TypeUnit; -import scala.runtime.types.TypeAll; -import scala.runtime.types.TypeAllRef; -import scala.runtime.types.TypeAny; -import scala.runtime.types.TypeAnyVal; -import scala.runtime.types.Statistics; - -import scala.runtime.FNV_Hash; - -/** - * Run-time types for Scala. - * - * @author Michel Schinz - * @version 1.0 - */ - -abstract public class Type implements java.io.Serializable { - public Type() { - assert Statistics.incInstances(getClass().getName(), this); - } - - protected static ThreadLocal unsafeArraysAllowed = new BooleanThreadLocal(); - - /* - * Allow (or not) the creation of "unsafe" arrays for the current - * thread. - */ - public static void allowUnsafeArrays(boolean allow) { - unsafeArraysAllowed.set(allow - ? java.lang.Boolean.TRUE - : java.lang.Boolean.FALSE); - } - - /** @meta method [?T](scala.Int) scala.Array[?T]; */ - abstract public Array newArray(int size); - - /** Return the default value for the type (_ in Scala) */ - abstract public Object defaultValue(); - - /** - * Return true iff the given object is an instance of a subtype of - * this type (implement Scala's isInstanceOf operation). - */ - abstract public boolean isInstance(Object o); - - abstract public boolean isSameType(Type that); - abstract public boolean isSubType(Type that); - - public boolean isSameAsJavaType(Class that) { - throw new Error("cannot compare Scala type " + this - + " with Java type " + that); - } - - public boolean equals(Object that) { - return (that instanceof Type) && this.isSameType((Type)that); - } - - public int hashCode() { - throw new Error("missing hashCode implementation in class " - + this.getClass()); - } - - /** - * Check that the given object can be cast to this type, and throw - * an exception if this is not possible (implement Scala's - * asInstanceOf operation). - */ - public Object cast(Object o) { - assert Statistics.incTypeCast(); - if (o == null) { - if (this.isSubType(JavaLangObject)) - return null; - else - throw new ClassCastException(); - } else { - assert Statistics.decInstanceOf(); - if (isInstance(o)) - return o; - else - throw new ClassCastException("\n" + ((ScalaObject)o).getScalaType() - + "\n" + this.toString()); - } - } - - // Value types - public static final TypeDouble Double = TypeDouble.INSTANCE; - public static final TypeFloat Float = TypeFloat.INSTANCE; - public static final TypeLong Long = TypeLong.INSTANCE; - public static final TypeInt Int = TypeInt.INSTANCE; - public static final TypeShort Short = TypeShort.INSTANCE; - public static final TypeChar Char = TypeChar.INSTANCE; - public static final TypeByte Byte = TypeByte.INSTANCE; - public static final TypeBoolean Boolean = TypeBoolean.INSTANCE; - public static final TypeUnit Unit = TypeUnit.INSTANCE; - - // "Special" types - public static final TypeAny Any = TypeAny.INSTANCE; - public static final TypeAnyVal AnyVal = TypeAnyVal.INSTANCE; - public static final TypeAllRef AllRef = TypeAllRef.INSTANCE; - public static final TypeAll All = TypeAll.INSTANCE; - - private static JavaClassType JavaLangObject; - - static { - try { - JavaLangObject = new JavaClassType("java.lang.Object"); - } catch (ClassNotFoundException e) { - throw new Error(e); - } - } - - public static boolean isSameType(Type[] these, Type[] those) { - if (these.length != those.length) - return false; - for (int i = 0; i < these.length; ++i) { - if (!these[i].isSameType(those[i])) - return false; - } - return true; - } - - public static int hashCode(Type[] types) { - final int len = types.length; - - int h = FNV_Hash.INIT; - for (int i = 0; i < len; ++i) - h = FNV_Hash.hashStep32(h, types[i].hashCode()); - - return h; - } -} - -class BooleanThreadLocal extends ThreadLocal { - protected Object initialValue() { - return java.lang.Boolean.TRUE; - } -} diff --git a/sources/scala/Unit.cs b/sources/scala/Unit.cs deleted file mode 100644 index 0acb8db74b..0000000000 --- a/sources/scala/Unit.cs +++ /dev/null @@ -1,45 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; -using scala.runtime; - -namespace scala -{ - - public abstract class Unit : AnyVal { - - public void value() {} - - public Unit() {} - - public override bool Equals(object other) - { - return other is Unit; - } - public override int GetHashCode() - { - int bits = 4041; - return bits; - } - public override string ToString() - { - return "()"; - } - - [Meta("method (scala.Any)scala.Boolean;")] - public bool __eq__eq (object other) { return Equals(other); } - [Meta("method (scala.Any)scala.Boolean;")] - public bool __bang__eq(object other) { return !Equals(other); } - - public string __plus (string that) { return this + that; } - - } -} \ No newline at end of file diff --git a/sources/scala/Unit.java b/sources/scala/Unit.java deleted file mode 100644 index dd50889c10..0000000000 --- a/sources/scala/Unit.java +++ /dev/null @@ -1,37 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala; - -public abstract class Unit extends AnyVal { - - public final void value() {} - - public Unit ( ) { - - } - - public boolean equals(java.lang.Object other) { - return other instanceof Unit; - } - public int hashCode() { - int bits = 4041; - return bits; - } - public String toString() { - return "()"; - } - - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $eq$eq (java.lang.Object other) { return equals(other); } - /** @meta method (scala.Any)scala.Boolean; */ - public boolean $bang$eq(java.lang.Object other) { return !equals(other); } - -} diff --git a/sources/scala/_trait_.scala b/sources/scala/_trait_.scala deleted file mode 100644 index 61928d4284..0000000000 --- a/sources/scala/_trait_.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -*/ - -// $Id$ - -package scala; - -/** Temporary class. - * When this appears in the attribute list of an abstract class, the class - * is assumed to be a trait. Used to ensure that code that compiles under - * (old) scalac can also compile under nsc. - */ -class _trait_ extends Attribute {} diff --git a/sources/scala/cloneable.scala b/sources/scala/cloneable.scala deleted file mode 100644 index 8369799be0..0000000000 --- a/sources/scala/cloneable.scala +++ /dev/null @@ -1,12 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -*/ - -package scala; - -class cloneable extends Attribute {} diff --git a/sources/scala/collection/BitSet.scala b/sources/scala/collection/BitSet.scala deleted file mode 100644 index bd5855c1de..0000000000 --- a/sources/scala/collection/BitSet.scala +++ /dev/null @@ -1,82 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection; - -/** The class BitSet ... - * - * @author Burak Emir, Stephane Micheloud - * @version 1.0 - */ -[_trait_] abstract class BitSet extends AnyRef with Function1[Int,Boolean] { - - /** number of bits in this bitset */ - def size: Int; - - /** returns true if bit i is set */ - def apply(i: Int): Boolean; - - /** returns an iterator over the truth values of all bits */ - final def booleanElements: Iterator[Boolean] = new Iterator[Boolean] { - var i = 0; - def hasNext: Boolean = i < size; - def next: Boolean = { i = i + 1; apply(i-1) } - } - - /** - * Returns the subset of [0..size] whose elements are - * indices of bits set to v. - * - * @param v - */ - final def toSet(v: Boolean) = { - var res = new immutable.TreeSet[Int](); - var j = 0; - while (j < size) { - if (v == apply(j)) - res = res + j; - j = j + 1; - } - res - } - - /** - * Checks if two bitsets are structurally identical. - * - * @return true, iff both bitsets contain the same sequence of elements. - */ - override def equals(that: Any): Boolean = ( - that.isInstanceOf[BitSet] && - { val other = that.asInstanceOf[BitSet]; - ( size == other.size) && ( - Iterator.range(0, size) forall { i => apply(i) == other.apply(i)} - ) - } - ); - - /** - * applies f to any index which is set to true. - */ - def foreach(f: Int => Unit): Unit = toSet(true).foreach(f); - - /** - * Returns a string representation of this bitset in hexadecimal form, - * e.g. the bitset 001100000001 (12 bits) is represented as "{0, 8, 9}". - * - * @return the string representation for this bitset - */ - override def toString() = - toSet(true).toString(); - - /** returns number of Int cells needed to store n bits */ - protected def memsize(n:Int) = (n >>> 5) + { - if((n & 0x1F) != 0) 1 else 0 - }; - -} diff --git a/sources/scala/collection/Map.scala b/sources/scala/collection/Map.scala deleted file mode 100644 index 14546e9e71..0000000000 --- a/sources/scala/collection/Map.scala +++ /dev/null @@ -1,180 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection; - -/** This trait defines the interface of collections that unambiguously map - * keys to values (i.e. a key is mapped to at least one value). - * Trait Map may only be used for - * accessing elements from map implementations. Two different extensions - * of trait Map in the package scala.collections.mutable - * and scala.collections.immutable provide functionality for - * adding new key/value mappings to a map. The trait in the first package is - * implemented by maps that are modified destructively, whereas the trait in - * the second package is used by functional map implementations that rely on - * immutable data structures. - * - * @author Matthias Zenger - * @version 1.1, 02/05/2004 - */ -trait Map[A, +B] extends AnyRef with PartialFunction[A, B] with Iterable[Pair[A, B]] { - - /** Compute the number of key-to-value mappings. - * - * @return the number of mappings - */ - def size: Int; - - /** Check if this map maps key to a value and return the - * value if it exists. - * - * @param key the key of the mapping of interest - * @return the value of the mapping, if it exists - */ - def get(key: A): Option[B]; - - /** Is this an empty map? - * - * @return true, iff the map is empty. - */ - def isEmpty: Boolean = (size == 0); - - /** Retrieve the value which is associated with the given key. This - * method throws an exception if there is no mapping from the given - * key to a value. - * - * @param key the key - * @return the value associated with the given key. - */ - def apply(key: A): B = get(key) match { - case None => default - case Some(value) => value - } - - /** Is the given key mapped to a value by this map? - * - * @param key the key - * @return true, iff there is a mapping for key in this map - */ - def contains(key: A): Boolean = get(key) match { - case None => false - case Some(_) => true - } - - /** Does this map contain a mapping from the given key to a value? - * - * @param key the key - * @return true, iff there is a mapping for key in this map - */ - def isDefinedAt(key: A) = contains(key); - - /** Creates an iterator for all keys. - * - * @return an iterator over all keys. - */ - def keys: Iterator[A] = new Iterator[A] { - val iter = Map.this.elements; - def hasNext = iter.hasNext; - def next = iter.next._1; - } - - /** Creates an iterator for a contained values. - * - * @return an iterator over all values. - */ - def values: Iterator[B] = new Iterator[B] { - val iter = Map.this.elements; - def hasNext = iter.hasNext; - def next = iter.next._2; - } - - /** Executes the given function for all (key, value) pairs - * contained in this map. - * - * @param f the function to execute. - */ - def foreach(f: (A, B) => Unit) = { - val iter = elements; - while (iter.hasNext) { - val Pair(key, value) = iter.next; - f(key, value); - } - } - - /** Applies the given predicate to all (key, value) mappings - * contained in this map and returns true if this predicate - * yields true for all mappings. - * - * @param p the predicate - * @return true, iff p yields true for all mappings. - */ - def forall(p: (A, B) => Boolean): Boolean = elements.forall { - case Pair(key, value) => p(key, value) - } - - /** Applies the given predicate to all (key, value) mappings - * contained in this map and returns true if there is at least - * one mapping for which this predicate yields true. - * - * @param p the predicate - * @return true, iff there is at least one mapping for which - * p yields true. - */ - def exists(p: (A, B) => Boolean): Boolean = elements.exists { - case Pair(key, value) => p(key, value) - } - - /** Compares two maps structurally; i.e. checks if all mappings - * contained in this map are also contained in the other map, - * and vice versa. - * - * @return true, iff both maps contain exactly the same mappings. - */ - override def equals(that: Any): Boolean = that match { - case other: Map[A, B] => - this.size == other.size && this.elements.forall { - case Pair(key, value) => other.get(key) match { - case None => false; - case Some(otherval) => value == otherval; - } - } - case _ => false - } - - /** Returns the mappings of this map as a list. - * - * @return a list containing all mappings - */ - def toList: List[Pair[A, B]] = elements.toList; - - /** Creates a string representation for this map. - * - * @return a string showing all mappings - */ - override def toString() = - if (size == 0) - "{}" - else - "{" + { - val iter = elements; - var res = iter.next.toString(); - while (iter.hasNext) { - res = res + ", " + iter.next; - } - res; - } + "}"; - - /** The default value for the map, returned when a key is not found - * The method implemented here yields an error, - * but it might be overridden in subclasses. - */ - def default: B = - error("key not found") -} - diff --git a/sources/scala/collection/MapProxy.scala b/sources/scala/collection/MapProxy.scala deleted file mode 100644 index 8284a628d2..0000000000 --- a/sources/scala/collection/MapProxy.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection; - - -/** This is a simple wrapper class for scala.collection.Map. - * It is most useful for assembling customized map abstractions - * dynamically using object composition and forwarding. - * - * @author Matthias Zenger - * @version 1.0, 21/07/2003 - */ -trait MapProxy[A, +B] extends Map[A, B] with IterableProxy[Pair[A, B]] { - - def self: Map[A, B]; - - def size: Int = self.size; - - def get(key: A): Option[B] = self.get(key); - - override def isEmpty: Boolean = self.isEmpty; - - override def apply(key: A): B = self.apply(key); - - override def contains(key: A): Boolean = self.contains(key); - - override def isDefinedAt(key: A) = self.isDefinedAt(key); - - override def keys: Iterator[A] = self.keys; - - override def values: Iterator[B] = self.values; - - override def foreach(f: (A, B) => Unit) = self.foreach(f); - - override def toList: List[Pair[A, B]] = self.toList; -} diff --git a/sources/scala/collection/Set.scala b/sources/scala/collection/Set.scala deleted file mode 100644 index 00ac17f6df..0000000000 --- a/sources/scala/collection/Set.scala +++ /dev/null @@ -1,89 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection; - - -/** This trait defines the interface of collections that do not contain - * duplicate elements. Trait Set may only be used for - * accessing elements from set implementations. Two different extensions - * of trait Set in the package scala.collections.mutable - * and scala.collections.immutable provide functionality for - * adding new elements to a set. The trait in the first package is implemented - * by sets the are modified destructively, whereas the trait in the second - * package is used by functional set implementations that rely on immutable - * data structures. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -trait Set[A] extends AnyRef with Function1[A, Boolean] with Iterable[A] { - - /** Returns the number of elements in this set. - * - * @return number of set elements. - */ - def size: Int; - - /** Checks if this set contains element elem. - * - * @param elem the element to check for membership. - * @return true, iff elem is contained in this set. - */ - def contains(elem: A): Boolean; - - /** This method allows sets to be interpreted as predicates. - * It returns true, iff this set contains element elem. - * - * @param elem the element to check for membership. - * @return true, iff elem is contained in this set. - */ - def apply(elem: A): Boolean = contains(elem); - - /** Checks if this set is empty. - * - * @return true, iff there is no element in the set. - */ - def isEmpty: Boolean = (size == 0); - - /** Checks if this set is a subset of set that. - * - * @param that another set. - * @return true, iff the other set is a superset of this set. - */ - def subsetOf(that: Set[A]): Boolean = forall(that.contains); - - /** Compares this set with another object and returns true, iff the - * other object is also a set which contains the same elements as - * this set. - * - * @param that the other object - * @return true, iff this set and the other set contain the same - * elements. - */ - override def equals(that: Any): Boolean = that match { - case other: Set[A] => - this.size == other.size && this.elements.forall(other.contains) - case _ => - false - } - - /** Returns the elements of this set as a list. - * - * @return a list containing all set elements. - */ - def toList: List[A] = elements.toList; - - /** Returns a string representation of this set. - * - * @return a string showing all elements of this set. - */ - override def toString(): String = - if (size == 0) "{}" else elements.toList.mkString("{", ", ", "}"); -} diff --git a/sources/scala/collection/SetProxy.scala b/sources/scala/collection/SetProxy.scala deleted file mode 100644 index 0fc1931385..0000000000 --- a/sources/scala/collection/SetProxy.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection; - - -/** This is a simple wrapper class for scala.collection.Set. - * It is most useful for assembling customized set abstractions - * dynamically using object composition and forwarding. - * - * @author Matthias Zenger - * @version 1.0, 21/07/2003 - */ -trait SetProxy[A] extends Set[A] with IterableProxy[A] { - - def self: Set[A]; - - def size: Int = self.size; - - override def isEmpty: Boolean = self.isEmpty; - - def contains(elem: A): Boolean = self.contains(elem); - - override def subsetOf(that: Set[A]): Boolean = self.subsetOf(that); - - override def foreach(f: A => Unit): Unit = self.foreach(f); - - override def exists(p: A => Boolean): Boolean = self.exists(p); - - override def toList: List[A] = self.toList; -} diff --git a/sources/scala/collection/immutable/BitSet.scala b/sources/scala/collection/immutable/BitSet.scala deleted file mode 100644 index 61299bf069..0000000000 --- a/sources/scala/collection/immutable/BitSet.scala +++ /dev/null @@ -1,117 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.immutable; - -/** The class BitSetprovides an immutable bitset view on an - * int array. Instances can conveniently be created from instances of - * mutable.ResizableBitSet. Bit indices are between 0..(size-1) inclusive - * - * @param n represents the number of relevant bits - * @param ba: array of ints of length n>>>5 - * @param copy: if yes, then ba is copied and updates will - * not affect this bitset - * - * @author Burak Emir - * @version 1.0 - */ -[serializable] -class BitSet(n:Int, ba: Array[Int], copy: Boolean) extends collection.BitSet with Ordered[BitSet] { - import scala.runtime.compat.Platform.arraycopy; - /** lexicographic ordering */ - def compareTo [b >: BitSet <% Ordered[b]](other: b): int = other match { - case that:BitSet => - val it1 = this.toSet(true).elements; - val it2 = that.toSet(true).elements; - var res = 0; - while((0==res) && it1.hasNext) { - while((0==res) && it2.hasNext) { - if(!it1.hasNext) - res = -1 - else { - val i1 = it1.next; - val i2 = it2.next; - if(i1i2) - res = 1 - } - } - if(it1.hasNext) - res = 1 - } - if(it2.hasNext) - res = -1; - res - - case _ => -(other.compareTo(this)) - } - - - final def size = n; - - protected val array: Array[Int] = - if (copy) { - val arr = new Array[Int](ba.length); - arraycopy(ba, 0, arr, 0, ba.length); - arr - } - else - ba; - - /** - * Checks if two bitsets are structurally identical. - * - * @return true, iff both bitsets contain the same sequence of elements. - */ - override def equals(that: Any): Boolean = ( - that.isInstanceOf[BitSet] && - { val other = that.asInstanceOf[BitSet]; - (size == other.size) && ( size == 0 || { - var len = memsize( size ); - var i = 0; - var res=true; - while(( i< len ) && res ) { // 32 x faster equality check - res = array(i) == other.array(i); - i = i + 1; - } - res - }) - } || super.equals(that) - ); - - def this(rbs: mutable.BitSet) = { - this(rbs.size, rbs.toArray, false); - } - - /** returns true if bit i is set - * - * @param i - */ - def apply(i: Int):Boolean = { - val j = (i >>> 5); - val mask = (1 << (i & 0x1F)); - (array(j) & mask) != 0; - } - - def makeMutable = { - val rbs = new mutable.BitSet(size) ; - val it = this.toSet(true).elements; - while(it.hasNext) { - rbs.set(it.next) - } - rbs - } - - def toArray: Array[Int] = { - val arr = new Array[Int](array.length); - arraycopy(arr, 0, array, 0, array.length); - arr - } -} diff --git a/sources/scala/collection/immutable/ListMap.scala b/sources/scala/collection/immutable/ListMap.scala deleted file mode 100644 index b6c9989531..0000000000 --- a/sources/scala/collection/immutable/ListMap.scala +++ /dev/null @@ -1,150 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.immutable; - - -object ListMap { - def Empty[A, B] = new ListMap[A, B]; -} - -/** This class implements immutable maps using a list-based data - * structure. Instances of ListMap represent - * empty maps; they can be either created by calling the constructor - * directly, or by applying the function ListMap.Empty. - * - * @author Matthias Zenger - * @version 1.0, 09/07/2003 - */ -[serializable] -class ListMap[A, B] extends AnyRef with Map[A, B] { - - /** This method returns a new ListMap instance mapping keys of the - * same type to values of type C. - */ - def empty[C] = new ListMap[A, C]; - - /** Returns the number of mappings in this map. - * - * @return number of mappings. - */ - def size: Int = 0; - - /** Check if this map maps key to a value and return the - * value if it exists. - * - * @param key the key of the mapping of interest - * @return the value of the mapping, if it exists - */ - def get(key: A): Option[B] = None; - - /** This method allows one to create a new map with an - * additional mapping from key - * to value. If the map contains already a - * mapping for key, it will be overridden by this - * function. - */ - def update(key: A, value: B): ListMap[A, B] = new Node(key, value); - - /** This creates a new mapping without the given key. - * If the map does not contain a mapping for the given key, the - * method returns the same map. - */ - def -(key: A): ListMap[A, B] = this; - - /** This returns an iterator over key-value pairs. - */ - def elements: Iterator[Pair[A, B]] = toList.elements; - - /** This return a list of key-value pairs. - */ - override def toList: List[Pair[A, B]] = Nil; - - /** Compares two maps for equality. - * Two maps are equal iff they contain exactly the - * same key-value pairs. - */ - override def equals(obj: Any): Boolean = - if (obj.isInstanceOf[scala.collection.Map[A, B]]) { - val that = obj.asInstanceOf[scala.collection.Map[A, B]]; - if (size != that.size) false else toList.forall { - case Pair(key, value) => that.get(key) match { - case None => false; - case Some(v) => v == value; - } - }; - } else - false; - - override def hashCode(): Int = 0; - - protected class Node(key: A, value: B) extends ListMap[A, B] { - /** Returns the number of mappings in this map. - * - * @return number of mappings. - */ - override def size: Int = ListMap.this.size + 1; - - /** Is this an empty map? - * - * @return true, iff the map is empty. - */ - override def isEmpty: Boolean = false; - - /** Retrieve the value which is associated with the given key. This - * method throws an exception if there is no mapping from the given - * key to a value. - * - * @param key the key - * @return the value associated with the given key. - */ - override def apply(k: A): B = if (k == key) value else ListMap.this(k); - - /** Check if this map maps key to a value and return the - * value if it exists. - * - * @param key the key of the mapping of interest - * @return the value of the mapping, if it exists - */ - override def get(k: A): Option[B] = - if (k == key) Some(value) else ListMap.this.get(k); - - /** This method allows one to create a new map with an - * additional mapping from key - * to value. If the map contains already a - * mapping for key, it will be overridden by this - * function. - */ - override def update(k: A, v: B): ListMap[A, B] = - if (k == key) { - new ListMap.this.Node(k, v); - } else { - val tail = ListMap.this.update(k,v); new tail.Node(key, value) - } - - /** This creates a new mapping without the given key. - * If the map does not contain a mapping for the given key, the - * method returns the same map. - */ - override def -(k: A): ListMap[A, B] = - if (k == key) - ListMap.this - else { - val tail = ListMap.this - k; new tail.Node(key, value) - } - - /** This return a list of key-value pairs. - */ - override def toList: List[Pair[A, B]] = Pair(key, value) :: ListMap.this.toList; - - override def hashCode(): Int = - (key.hashCode() ^ value.hashCode()) + ListMap.this.hashCode(); - } -} - diff --git a/sources/scala/collection/immutable/ListSet.scala b/sources/scala/collection/immutable/ListSet.scala deleted file mode 100644 index 305e54cb90..0000000000 --- a/sources/scala/collection/immutable/ListSet.scala +++ /dev/null @@ -1,118 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.collection.immutable; - - -object ListSet { - /** constructs an empty ListSet - */ - def Empty[A] = new ListSet[A]; -} - - -/** This class implements immutable sets using a list-based data - * structure. Instances of ListSet represent - * empty sets; they can be either created by calling the constructor - * directly, or by applying the function ListSet.Empty. - * - * @author Matthias Zenger - * @version 1.0, 09/07/2003 - */ -[serializable] -class ListSet[A] extends AnyRef with Set[A] { - - /** Returns the number of elements in this set. - * - * @return number of set elements. - */ - def size: Int = 0; - - /** Checks if this set contains element elem. - * - * @param elem the element to check for membership. - * @return true, iff elem is contained in this set. - */ - def contains(elem: A): Boolean = false; - - /** This method creates a new set with an additional element. - */ - def +(elem: A): ListSet[A] = new Node(elem); - - /** - can be used to remove a single element from - * a set. - */ - def -(elem: A): ListSet[A] = this; - - /** Creates a new iterator over all elements contained in this - * object. - * - * @return the new iterator - */ - def elements: Iterator[A] = toList.elements; - - /** Transform this set into a list of all elements. - * - * @return a list which enumerates all elements of this set. - */ - override def toList: List[A] = Nil; - - /** Compares two sets for equality. - * Two set are equal iff they contain the same elements. - */ - override def equals(obj: Any): Boolean = - if (obj.isInstanceOf[scala.collection.Set[A]]) { - val that = obj.asInstanceOf[scala.collection.Set[A]]; - if (size != that.size) false else toList.forall(that.contains); - } else - false; - - override def hashCode(): Int = 0; - - protected class Node(elem: A) extends ListSet[A] { - /** Returns the number of elements in this set. - * - * @return number of set elements. - */ - override def size = ListSet.this.size + 1; - - /** Checks if this set is empty. - * - * @return true, iff there is no element in the set. - */ - override def isEmpty: Boolean = false; - - /** Checks if this set contains element elem. - * - * @param elem the element to check for membership. - * @return true, iff elem is contained in this set. - */ - override def contains(e: A) = (e == elem) || ListSet.this.contains(e); - - /** This method creates a new set with an additional element. - */ - override def +(e: A): ListSet[A] = if (contains(e)) this else new Node(e); - - /** - can be used to remove a single element from - * a set. - */ - override def -(e: A): ListSet[A] = if (e == elem) ListSet.this else { - val tail = ListSet.this - e; new tail.Node(elem) - } - - /** Transform this set into a list of all elements. - * - * @return a list which enumerates all elements of this set. - */ - override def toList: List[A] = elem :: ListSet.this.toList; - - override def hashCode(): Int = elem.hashCode() + ListSet.this.hashCode(); - } -} diff --git a/sources/scala/collection/immutable/Map.scala b/sources/scala/collection/immutable/Map.scala deleted file mode 100644 index b737f48886..0000000000 --- a/sources/scala/collection/immutable/Map.scala +++ /dev/null @@ -1,144 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.immutable; - - -/** This trait extends the Map interface of collections that unambiguously map - * keys to values (i.e. a key is mapped to at least one value). - * This trait defines the interface for functional map implementations - * relying on immutable data structures. - * Concrete map implementations have to provide functionality for the - * abstract methods in scala.collection.Map as well as for - * factory, update, and -. - * - * @author Matthias Zenger - * @author Erik Stenman - * @version 1.1, 22/03/2004 - */ -trait Map[A, B] extends AnyRef with scala.collection.Map[A, B] { - - /** This method returns a new map instance of the same class - * mapping keys of the same type to values of type C. - */ - def empty[C]: Map[A, C]; - - /** This method allows one to create a new map with an - * additional mapping from key - * to value. If the map contains already a - * mapping for key, it will be overridden by this - * function. - */ - def update(key: A, value: B): Map[A, B]; - - /** This creates a new mapping without the given key. - * If the map does not contain a mapping for the given key, the - * method returns the same map. - */ - def -(key: A): Map[A, B]; - - /** This method defines syntactic sugar for adding a - * mapping. It is typically used in the following way: - *
-     *  map + key -> value;
-     *  
- */ - def +(key: A): MapTo = new MapTo(key); - - /** incl can be used to add many mappings at the same time - * to the map. The method assumes that a mapping is represented - * by a Pair object who's first component denotes the - * key, and who's second component refers to the value. - */ - def incl(mappings: Pair[A, B]*): Map[A, B] = incl(mappings); - - /** incl can be used to add many mappings at the same time - * to the map. The method assumes that each mapping is represented - * by an Iterator over Pair objects who's first component - * denotes the key, and who's second component refers to the value. - */ - def incl(map: Iterable[Pair[A, B]]): Map[A, B] = { - val iter = map.elements; - var res = this; - while (iter.hasNext) { - val Pair(key, value) = iter.next; - res = res.update(key, value); - } - res - } - - /** This method will return a map where all the mappings - * for the given sequence of keys are removed from the map. - */ - def excl(keys: A*): Map[A, B] = excl(keys); - - /** This method removes all the mappings for keys provided by an - * iterator over the elements of the keys object. - */ - def excl(keys: Iterable[A]): Map[A, B] = { - val iter = keys.elements; - var res = this; - while (iter.hasNext) { - res = res - iter.next; - } - res; - } - - /** This function transforms all the values of mappings contained - * in this map with function f. - */ - def map[C](f: (A, B) => C): Map[A, C] = { - var res = empty[C]; - elements foreach { - case Pair(key, value) => res = res.update(key, f(key, value)); - } - res; - } - - /** This method removes all the mappings for which the predicate - * p returns false. - */ - def filter(p: (A, B) => Boolean): Map[A, B] = { - var res = this; - toList foreach { - case Pair(key, value) => if (!p(key, value)) { res = res.excl(key); } - } - res; - } - - /** Returns a string representation of this map which shows - * all the mappings. - */ - override def toString() = - if (size == 0) - "{}" - else - "{" + { - val iter = elements; - var res = mappingToString(iter.next); - while (iter.hasNext) { - res = res + ", " + mappingToString(iter.next); - } - res; - } + "}"; - - override def hashCode() = { - elements.foldLeft(0)((hash:Int,pair:AnyRef) => hash + pair.hashCode()); - } - - /** This method controls how a mapping is represented in the string - * representation provided by method toString. - */ - def mappingToString(p: Pair[A, B]) = p._1.toString() + " -> " + p._2; - - class MapTo(key: A) { - def ->(value: B) = update(key, value); - } -} - diff --git a/sources/scala/collection/immutable/Queue.scala b/sources/scala/collection/immutable/Queue.scala deleted file mode 100644 index cb005d3b5e..0000000000 --- a/sources/scala/collection/immutable/Queue.scala +++ /dev/null @@ -1,173 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.immutable; - - -object Queue { - val Empty: Queue[All] = new Queue(); -} - -/** Queue objects implement data structures that allow to - * insert and retrieve elements in a first-in-first-out (FIFO) manner. - * - * @author Erik Stenman - * @version 1.0, 08/07/2003 - */ -[serializable] -class Queue[+A](elem: A*) extends Seq[A] { - protected val in: List[A] = Nil; - protected val out: List[A] = itToList(elem.elements); - - protected def itToList[B >: A](elems: Iterator[B]): List[B] = - if (elems.hasNext) { - val hd = elems.next; - hd :: itToList(elems) - } - else - Nil; - - protected def mkQueue[A](i: List[A], o: List[A]): Queue[A] = - new Queue[A]() { - override protected val in = i; - override protected val out = o - }; - - /** Returns the n-th element of this queue. - * The first element is at position 0. - * - * @param n index of the element to return - * @return the element at position n in this list. - * @throws java.lang.RuntimeException if the list is too short. - */ - def apply(n: Int): A = - if (n < out.length) out.apply(n) - else in.reverse.apply(n - out.length); - - /** Returns the elements in the list as an iterator - */ - def elements: Iterator[A] = (out ::: in.reverse).elements; - - /** Checks if the queue is empty. - * - * @return true, iff there is no element in the queue. - */ - def isEmpty: Boolean = in.isEmpty && out.isEmpty; - - /** Returns the length of the queue. - */ - def length = in.length + out.length; - - /** Creates a new queue with element added at the end - * of the old queue. - * - * @param elem the element to insert - */ - def +[B >: A](elem: B) = mkQueue(elem :: in, out); - - /** Returns a new queue with all all elements provided by - * an Iterable object added at the end of - * the queue. - * The elements are prepended in the order they - * are given out by the iterator. - * - * @param iter an iterable object - */ - def +[B >: A](iter: Iterable[B]) = { - var q: List[B] = in; - iter.elements.foreach(e => q = e :: q); - mkQueue(q, out); - } - - /** Returns a new queue with all elements added. - * - * @param elems the elements to add. - */ - def enqueue [B >: A](elems: B*) = this + elems; - - /** Returns a tuple with the first element in the queue, - * and a new queue with this element removed. - * - * @return the first element of the queue. - */ - def dequeue: Pair[A, Queue[A]] = { - val Pair(newOut, newIn) = - if (out.isEmpty) Pair(in.reverse, Nil) - else Pair(out, in); - if (newOut.isEmpty) error("queue empty"); - else Pair(newOut.head, mkQueue(newIn, newOut.tail)); - } - - /** Returns the first element in the queue, or throws an error if there - * is no element contained in the queue. - * - * @return the first element. - */ - def front: A = - if (out.isEmpty) { - if (in.isEmpty) error("queue empty") else in.last; - } else - out.head; - - /** Returns a string representation of this queue. The resulting string - * begins with the string start and is finished by the string - * end. Inside, the string representations of elements (w.r.t. - * the method toString()) are separated by the string - * sep. - *

- * Ex:
- * Queue(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)" - * - * @param start starting string. - * @param sep separator string. - * @param end ending string. - * @return a string representation of this list. - */ - def mkString(start: String, sep: String, end: String): String = - (out ::: in.reverse).mkString(start, sep, end); - - /** Returns a string representation of this queue. - */ - override def toString() = (out ::: in.reverse).mkString("Queue(", ",", ")"); - - /** Compares two queues for equality by comparing - * each element in the queues. - * - * @return true, iff the two queues are structurally equal. - */ - override def equals(o: Any): Boolean = o match { - case q: Queue[Any] => - /* A function that compares the element at - position index in q with the element at - the same position in this (queue). - If they are equal the next element is - compared. */ - def eqe(index: Int): Boolean = ( - /* If all elements are compared - the queues are equal. */ - index >= this.length || - /* Otherwise: compare the elements */ - (q.apply(index) == this.apply(index) && - /* if they are equal compare the rest. */ - eqe(index + 1)) - ); - /* If the length of the ques are the same, - compare each element, starting at index 0. */ - (q.length == this.length) && eqe(0); - - case _ => false; /* o is not a queue: not equal to this. */ - } - - override def hashCode(): Int = - if (isEmpty) 0 - else { - val q: Pair[A,Queue[A]] = dequeue; - q._1.hashCode() + q._2.hashCode(); - } -} diff --git a/sources/scala/collection/immutable/Set.scala b/sources/scala/collection/immutable/Set.scala deleted file mode 100644 index af3340e8f1..0000000000 --- a/sources/scala/collection/immutable/Set.scala +++ /dev/null @@ -1,81 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.immutable; - - -/** This trait represents immutable sets. Concrete set implementations - * just have to provide functionality for the abstract methods in - * scala.collection.Set as well as for + and - * -. - * - * @author Matthias Zenger - * @version 1.1, 03/05/2004 - */ -trait Set[A] extends AnyRef with scala.collection.Set[A] { - - /** This method creates a new set with an additional element. - */ - def +(elem: A): Set[A]; - - /** incl can be used to add many elements to the set - * at the same time. - */ - def incl(elems: A*): Set[A] = incl(elems); - - /** This method will add all the elements provided by an iterator - * of the iterable object that to the set. - */ - def incl(that: Iterable[A]): Set[A] = { - var res = this; - that.elements.foreach(elem => res = res + elem); - res; - } - - /** - can be used to remove a single element from - * a set. - */ - def -(elem: A): Set[A]; - - /** excl removes many elements from the set. - */ - def excl(elems: A*): Set[A] = excl(elems); - - /** This method removes all the elements provided by an iterator - * of the iterable object that from the set. - */ - def excl(that: Iterable[A]): Set[A] = { - var res = this; - that.elements.foreach(elem => res = res - elem); - res; - } - - /** This method computes an intersection with set that. - * It removes all the elements that are not present in that. - */ - def intersect(that: scala.collection.Set[A]): Set[A] = filter(that.contains); - - /** Method filter removes all elements from the set for - * which the predicate p yields the value false. - */ - def filter(p: A => Boolean): Set[A] = { - var res = this; - toList foreach { - elem => if (!p(elem)) { res = res - elem; } - } - res; - } - - /** hashcode for this set */ - override def hashCode() = { - elements.foldLeft(0)((hash: Int, e: A) => hash + e.hashCode()); - } - -} - diff --git a/sources/scala/collection/immutable/Stack.scala b/sources/scala/collection/immutable/Stack.scala deleted file mode 100644 index 46b15794a3..0000000000 --- a/sources/scala/collection/immutable/Stack.scala +++ /dev/null @@ -1,139 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.immutable; - - -object Stack { - def Empty[A] = new Stack[A]; -} - -/** This class implements immutable stacks using a list-based data - * structure. Instances of Stack represent - * empty stacks; they can be either created by calling the constructor - * directly, or by applying the function Stack.Empty. - * - * @author Matthias Zenger - * @version 1.0, 10/07/2003 - */ -[serializable] -class Stack[+A] extends Seq[A] { - - /** Checks if this stack is empty. - * - * @return true, iff there is no element on the stack. - */ - def isEmpty: Boolean = true; - - /** Returns the size of this stack. - * - * @return the stack size. - */ - def length: Int = 0; - - /** Push an element on the stack. - * - * @param elem the element to push on the stack. - * @return the stack with the new element on top. - */ - def +[B >: A](elem: B): Stack[B] = new Node(elem); - - /** Push all elements provided by the given iterable object onto - * the stack. The last element returned by the iterable object - * will be on top of the new stack. - * - * @param elems the iterable object. - * @return the stack with the new elements on top. - */ - def +[B >: A](elems: Iterable[B]): Stack[B] = { - var res: Stack[B] = this; - elems.elements.foreach { elem => res = res + elem; } - res - } - - /** Push a sequence of elements onto the stack. The last element - * of the sequence will be on top of the new stack. - * - * @param elems the element sequence. - * @return the stack with the new elements on top. - */ - def push[B >: A](elems: B*): Stack[B] = this + elems; - - /** Returns the top element of the stack. An error is signaled if - * there is no element on the stack. - * - * @return the top element. - */ - def top: A = error("no element on stack"); - - /** Removes the top element from the stack. - * - * @return the new stack without the former top element. - */ - def pop: Stack[A] = error("no element on stack"); - - /** Returns the n-th element of this stack. The top element has index - * 0, elements below are indexed with increasing numbers. - * - * @param n the index number. - * @return the n-th element on the stack. - */ - def apply(n: Int): A = error("no element on stack"); - - /** Returns an iterator over all elements on the stack. The iterator - * issues elements in the reversed order they were inserted into the - * stack (LIFO order). - * - * @return an iterator over all stack elements. - */ - def elements: Iterator[A] = toList.elements; - - /** Creates a list of all stack elements in LIFO order. - * - * @return the created list. - */ - override def toList: List[A] = Nil; - - /** Compares this stack with the given object. - * - * @return true, iff the two stacks are equal; i.e. they contain the - * same elements in the same order. - */ - override def equals(obj: Any): Boolean = - if (obj.isInstanceOf[Stack[A]]) - toList.equals((obj.asInstanceOf[Stack[A]]).toList); - else - false; - - /** Returns the hash code for this stack. - * - * @return the hash code of the stack. - */ - override def hashCode(): Int = 0; - - /** - * Redefines the prefix of the string representation. - */ - override def stringPrefix: String = "Stack"; - - // Here comes true magic: covariant lists with implicit tail references - [serializable] - protected class Node[+B >: A](elem: B) extends Stack[B] { - override def isEmpty: Boolean = false; - override def length: Int = Stack.this.length + 1; - override def +[C >: B](elem: C): Stack[C] = new Node(elem); - override def +[C >: B](elems: Iterable[C]): Stack[C] = super.+(elems); - override def top: B = elem; - override def pop: Stack[B] = Stack.this; - override def apply(n: Int): B = if (n > 0) Stack.this(n - 1) else elem; - override def toList: List[B] = elem :: Stack.this.toList; - override def hashCode(): Int = elem.hashCode() + Stack.this.hashCode(); - } - -} diff --git a/sources/scala/collection/immutable/Tree.scala b/sources/scala/collection/immutable/Tree.scala deleted file mode 100644 index fdb3f8cf46..0000000000 --- a/sources/scala/collection/immutable/Tree.scala +++ /dev/null @@ -1,374 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -/* General Balanced Trees - highly efficient functional dictionaries. -** -** This is a scala version of gb_trees.erl which is -** copyrighted (C) 1999-2001 by Sven-Olof Nystrom, and Richard Carlsson -** -** An efficient implementation of Prof. Arne Andersson's General -** Balanced Trees. These have no storage overhead compared to plain -** unbalanced binary trees, and their performance is in general better -** than AVL trees. -** --------------------------------------------------------------------- -** This library is free software; you can redistribute it and/or modify -** it under the terms of the GNU Lesser General Public License as -** published by the Free Software Foundation; either version 2 of the -** License, or (at your option) any later version. -** -** This library is distributed in the hope that it will be useful, but -** WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -** Lesser General Public License for more details. -** -** You should have received a copy of the GNU Lesser General Public -** License along with this library; if not, write to the Free Software -** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -** USA -** -** Author contact: erik.stenman@epfl.ch -** --------------------------------------------------------------------- -*/ - -package scala.collection.immutable; - -/** General Balanced Trees - highly efficient functional dictionaries. - * - * An efficient implementation of Prof. Arne Andersson's General - * Balanced Trees. These have no storage overhead compared to plain - * unbalanced binary trees, and their performance is in general better - * than AVL trees. - *

- * This implementation does not balance the trees after deletions. - * Since deletions don't increase the height of a tree, this should - * be OK in most applications. A balance method is provided for those - * cases where rebalancing is needed. - *

- * The tree consists of entries conatining a key with an order. - *

- * When instanciating the tree an order for the keys has to be - * supplied. - * - * @author Erik Stenman - * @author Michel Schinz - * @version 1.1, 2005-01-20 - */ -//[serializable] -abstract class Tree[A <% Ordered[A], B]() extends AnyRef with java.io.Serializable { - /* Data structure: - ** - size:Int - the number of elements in the tree. - ** - tree:T, which is composed of nodes of the form: - ** - GBNode(key: A, entry:B, smaller:T, bigger:T), - ** - and the "empty tree" node GBLeaf. - ** - ** Original balance condition h(T) <= ceil(c * log(|T|)) has been - ** changed to the similar (but not quite equivalent) condition - ** 2 ^ h(T) <= |T| ^ c. - ** - */ - - /** The type returned when creating a new tree. - * This type should be defined by concrete implementations - * e.g.

-  *   class C[T](...) extends Tree[A,B](...) {
-  *     type This = C[T];
-  *   
- */ - protected type This <: Tree[A,B]; - protected def getThis: This; - - /** - * The type of nodes that the tree is build from. - */ - protected type aNode = GBTree[A,B]; - - private val empty: aNode = GBLeaf[A,B](); - - /** The nodes in the tree. - */ - protected def tree: aNode = empty; - - /** This abstract method should be defined by a concrete implementation - ** C[T] as something like: - **
-  **     override def New(sz:Int,t:aNode):This {
-  **       new C[T](order) {
-  **        override def size=sz;
-  **        override protected def tree:aNode=t;
-  **     }
-  **    
- ** The concrete implementation should also override the def of This - ** override type This = C[T]; - ** - */ - protected def New(sz: Int, t: aNode): This; - - /** The size of the tree, returns 0 (zero) if the tree is empty. - ** @Returns The number of nodes in the tree as an integer. - **/ - def size: Int = 0; - - /** - * A new tree with the entry added is returned, - * assuming that key is not in the tree. - */ - protected def add(key: A, entry: B): This = { - val newSize = size+1; - New(newSize, tree.insert(key, entry, newSize * newSize).node); - } - - /** - * A new tree with the entry added is returned, - * if key is not in the tree, otherwise - * the key is updated with the new entry. - */ - protected def updateOrAdd(key: A, entry: B): This = { - if (tree.isDefinedAt(key)) - New(size,tree.update(key,entry)) - else - add(key,entry); - } - - /** Removes the key from the tree. */ - protected def deleteAny(key: A): This = - if (tree.isDefinedAt(key)) - delete(key) - else - getThis; - - /** Removes the key from the tree, assumimg that key is present. */ - private def delete(key:A): This = - New(size - 1, tree.delete(key)); - - /** Check if this map maps key to a value and return the - * value if it exists. - * - * @param key the key of the mapping of interest - * @return the value of the mapping, if it exists - */ - protected def findValue(key:A): Option[B] = - tree.get(key); - - /** - * Gives you an iterator over all elements in the tree. - * The iterator structure corresponds to - * the call stack of an in-order traversal. - * - * Note: The iterator itself has a state, i.e., it is not functional. - */ - protected def entries: Iterator[B] = - new Iterator[B] { - var iter = tree.mk_iter(scala.Nil); - def hasNext = !iter.isEmpty; - def next = - iter match { - case (GBNode(_,v,_,t)::iter_tail) => { - iter= t.mk_iter(iter_tail); - v; - } - case scala.Nil => - error("next on empty iterator"); - } - } - - /** - * Create a new balanced tree from the tree. Might be useful to call - * after many deletions, since deletion does not rebalance the tree. - */ - def balance: This = - New(size, tree.balance(size)); -} - -protected abstract class InsertTree[A <% Ordered[A],B]() extends AnyRef { - def insertLeft(k: A, v: B, t: GBTree[A,B]): InsertTree[A,B]; - def insertRight(k: A, v: B, t: GBTree[A,B]): InsertTree[A,B]; - def node: GBTree[A,B]; -} - -private case class ITree[A <% Ordered[A],B](t: GBTree[A,B]) - extends InsertTree[A,B] { - def insertLeft(key: A, value: B, bigger: GBTree[A,B]) = - ITree(GBNode(key, value, t, bigger)); - def insertRight(key: A, value: B, smaller: GBTree[A,B]) = - ITree(GBNode(key, value, smaller, t)); - def node = t; -} - -private case class INode[A <% Ordered[A],B](t1: GBTree[A,B], - height: int, - size: int) - extends InsertTree[A,B] { - def insertLeft(key: A, value: B, bigger: GBTree[A,B]) = - balance_p(GBNode(key, value, t1, bigger), bigger); - def insertRight(key: A, value: B, smaller: GBTree[A,B]) = - balance_p(GBNode(key, value, smaller, t1),smaller); - protected def balance_p(t:GBTree[A,B],subtree:GBTree[A,B]):InsertTree[A,B] = { - val Pair(subHeight, subSize) = subtree.count; - val totalHeight = 2 * scala.runtime.compat.Math.max(height, subHeight); - val totalSize = size + subSize + 1; - val BalanceHeight = totalSize * totalSize; - if(totalHeight > BalanceHeight) ITree(t.balance(totalSize)); - else INode(t, totalHeight, totalSize); - } - def node = t1; -} - -/** -* GBTree is an internal class used by Tree. -*/ -//[serializable] -protected abstract class GBTree[A <% Ordered[A],B] extends AnyRef with java.io.Serializable { - type aNode = GBTree[A,B]; - type anInsertTree = InsertTree[A,B]; - - /** Calculates 2^h, and size, where h is the height of the tree - * and size is the number of nodes in the tree. - */ - def count:Pair[Int,Int]; - def isDefinedAt(Key:A):Boolean; - def get(key:A):Option[B]; - def apply(key:A):B; - def update(key:A, value:B):aNode; - def insert(key:A, value:B, size:int):anInsertTree; - def toList(acc: List[Pair[A,B]]): List[Pair[A,B]]; - def mk_iter(iter_tail:List[aNode]): List[aNode]; - def delete(key:A):aNode; - def merge(t:aNode):aNode; - def takeSmallest:Triple[A,B,aNode]; - def balance(s:int):GBTree[A,B]; -} - -private case class GBLeaf[A <% Ordered[A],B]() extends GBTree[A,B] { - def count = Pair(1, 0); - def isDefinedAt(key:A) = false; - def get(_key:A) = None; - def apply(key:A) = error("key " + key + " not found"); - def update(key:A, value:B) = error("key " + key + " not found"); - def insert(key:A, value:B, s:int):anInsertTree = { - if (s == 0) - INode(GBNode(key, value, this, this), 1, 1) - else - ITree(GBNode(key, value, this, this)) - } - def toList(acc: List[Pair[A,B]]): List[Pair[A,B]] = acc; - def mk_iter(iter_tail:List[GBTree[A,B]]) = iter_tail; - def merge(larger:GBTree[A,B]) = larger; - def takeSmallest:Triple[A,B,GBTree[A,B]] = - error("Take Smallest on empty tree"); - def delete(_key:A) = error("Delete on empty tree."); - def balance(s:int) = this; - override def hashCode() = 0; -} - -private case class GBNode[A <% Ordered[A],B](key: A, - value: B, - smaller: GBTree[A,B], - bigger: GBTree[A,B]) - extends GBTree[A,B] { - def count: Pair[Int,Int] = { - val Pair(sHeight, sSize) = smaller.count; - val Pair(bHeight, bSize) = bigger.count; - val mySize = sSize + bSize + 1; - if (mySize == 1) - Pair(1, mySize) - else - Pair(2 * scala.runtime.compat.Math.max(sHeight, bHeight), mySize); - } - - def isDefinedAt(sKey:A):Boolean = { - if (sKey < key) smaller.isDefinedAt(sKey) - else if (sKey > key) bigger.isDefinedAt(sKey) - else true; - } - - def get(sKey:A):Option[B] = - if (sKey < key) smaller.get(sKey); - else if (sKey > key) bigger.get(sKey); - else Some(value); - - def apply(sKey:A):B = - if (sKey < key) smaller.apply(sKey); - else if (sKey > key) bigger.apply(sKey); - else value; - - def update(newKey:A, newValue:B):aNode = - if (newKey < key) - GBNode(key, value, smaller.update(newKey,newValue), bigger); - else if (newKey > key) - GBNode(key, value, smaller, bigger.update(newKey,newValue)); - else - GBNode(newKey, newValue, smaller, bigger); - - def insert(newKey:A, newValue:B, s:int): anInsertTree = { - if (newKey < key) - smaller.insert(newKey, newValue, s / 2).insertLeft(key, value, bigger); - else if (newKey > key) - bigger.insert(newKey, newValue, s / 2).insertRight(key, value, smaller); - else - error("Key exists: " + newKey); - } - - def toList(acc: List[Pair[A,B]]): List[Pair[A,B]] = - smaller.toList(Pair(key, value) :: bigger.toList(acc)); - - def mk_iter(iter_tail:List[aNode]):List[aNode] = - smaller.mk_iter(this :: iter_tail); - - def delete(sKey:A):aNode = { - if (sKey < key) - GBNode(key, value, smaller.delete(sKey), bigger); - else if (sKey > key) - GBNode(key, value, smaller, bigger.delete(sKey)); - else - smaller.merge(bigger) - } - - def merge(larger: aNode): GBTree[A,B] = larger match { - case GBLeaf() => - this - case _ => - val Triple(key1, value1, larger1) = larger.takeSmallest; - GBNode(key1, value1, this, larger1) - } - - def takeSmallest: Triple[A, B, aNode] = smaller match { - case GBLeaf() => - Triple(key, value, bigger) - case _ => - val Triple(key1, value1, smaller1) = smaller.takeSmallest; - Triple(key1, value1, GBNode(key, value, smaller1, bigger)) - } - - def balance(s:int): GBTree[A,B] = - balance_list(toList(scala.Nil), s); - - protected def balance_list(list: List[Pair[A,B]], s:int): GBTree[A,B] = { - val empty = GBLeaf[A,B](); - def bal(list: List[Pair[A,B]], s:int): Pair[aNode,List[Pair[A,B]]] = { - if (s > 1) { - val sm = s - 1; - val s2 = sm / 2; - val s1 = sm - s2; - val Pair(t1, Pair(k, v) :: l1) = bal(list, s1); - val Pair(t2, l2) = bal(l1, s2); - val t = GBNode(k, v, t1, t2); - Pair(t, l2) - } else - if (s == 1) { - val Pair(k,v) :: rest = list; - Pair(GBNode(k, v, empty, empty), rest) - } else - Pair(empty, list) - } - bal(list, s)._1 - } - - override def hashCode() = - value.hashCode() + smaller.hashCode() + bigger.hashCode(); -} diff --git a/sources/scala/collection/immutable/TreeMap.scala b/sources/scala/collection/immutable/TreeMap.scala deleted file mode 100644 index 12814b7a41..0000000000 --- a/sources/scala/collection/immutable/TreeMap.scala +++ /dev/null @@ -1,107 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.immutable; - -object TreeMap { - def Empty[A <% Ordered[A], B] = new TreeMap[A, B]; -} - -/** This class implements immutable maps using a tree. - * - * @author Erik Stenman - * @author Matthias Zenger - * @version 1.1, 03/05/2004 - */ -//[serializable] -class TreeMap[A <% Ordered[A], B] extends Tree[A, Pair[A, B]] with Map[A, B] with java.io.Serializable { - - override protected type This = TreeMap[A, B]; - override protected def getThis: This = this; - - /** A factory to create empty maps of the same type of keys. - */ - def empty[C] = new TreeMap[A, C]; - - /** Creates a new TreeMap from a GBTree and its size. - */ - protected def New(sz:Int,t:aNode):This = new TreeMap[A,B] { - override def size=sz; - override protected def tree:aNode=t; - } - - /** A new TreeMap with the entry added is returned, - * if key is not in the TreeMap, otherwise - * the key is updated with the new entry. - */ - def update(key:A, value:B) = updateOrAdd(key, Pair(key, value)); - - /** A new TreeMap with the entry added is returned, - * assuming that key is not in the TreeMap. - */ - def insert(key:A,value:B) = add(key, Pair(key, value)); - - /** Removes the key from the TreeMap. - */ - def -(key:A) = deleteAny(key); - - /** Check if this map maps key to a value and return the - * value if it exists. - * - * @param key the key of the mapping of interest - * @return the value of the mapping, if it exists - */ - override def get(key: A): Option[B] = - findValue(key) match { - case Some(Pair(_, value: B)) => Some(value) - case _ => None - } - - /** Retrieve the value which is associated with the given key. This - * method throws an exception if there is no mapping from the given - * key to a value. - * - * @param key the key - * @return the value associated with the given key. - * @throws Error("key not found"). - */ - override def apply(key:A):B = tree.apply(key)._2; - - /** Creates a list of all (key, value) mappings. - * - * @return the list of all mappings - */ - override def toList: List[Pair[A,B]] = - tree.toList(scala.Nil) map (._2); - - /** Creates a new iterator over all elements contained in this - * object. - * - * @return the new iterator - */ - def elements: Iterator[Pair[A,B]] = entries; - - /** Compares two maps structurally; i.e. checks if all mappings - * contained in this map are also contained in the other map, - * and vice versa. - * - * @return true, iff both maps contain exactly the same mappings. - */ - override def equals(obj: Any): Boolean = - obj.isInstanceOf[scala.collection.Map[A, B]] && { - val that = obj.asInstanceOf[scala.collection.Map[A, B]]; - size == that.size && elements.forall { - case Pair(key, value) => that.get(key) match { - case None => false; - case Some(v) => v == value; - } - } - }; -} - diff --git a/sources/scala/collection/immutable/TreeSet.scala b/sources/scala/collection/immutable/TreeSet.scala deleted file mode 100644 index bb3099e007..0000000000 --- a/sources/scala/collection/immutable/TreeSet.scala +++ /dev/null @@ -1,69 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.collection.immutable; - - -/** This class implements immutable sets using a tree. - * - * @author Matthias Zenger - * @author Burak Emir - * @version 1.1, 03/05/2004 - */ -//[serializable] -class TreeSet[A <% Ordered[A]]() extends Tree[A, A] with Set[A] with java.io.Serializable { - - override protected type This = TreeSet[A]; - override protected def getThis: This = this; - - protected def New(sz: Int, t: aNode): This = new TreeSet[A] { - override def size = sz; - override protected def tree: aNode = t; - } - - /** Checks if this set contains element elem. - * - * @param elem the element to check for membership. - * @return true, iff elem is contained in this set. - */ - def contains(elem: A): Boolean = !findValue(elem).isEmpty; - - /** This method creates a new set with an additional element. - */ - def +(elem: A): TreeSet[A] = updateOrAdd(elem, elem); - - /** - can be used to remove a single element from - * a set. - */ - def -(elem: A): TreeSet[A] = deleteAny(elem); - - /** Creates a new iterator over all elements contained in this - * object. - * - * @return the new iterator - */ - def elements: Iterator[A] = entries; - - /** Transform this set into a list of all elements. - * - * @return a list which enumerates all elements of this set. - */ - override def toList: List[A] = - tree.toList(scala.Nil) map (._2); - - /** Compares two sets for equality. - * Two set are equal iff they contain the same elements. - */ - override def equals(obj: Any): Boolean = - obj.isInstanceOf[scala.collection.Set[A]] && { - val that = obj.asInstanceOf[scala.collection.Set[A]]; - (size == that.size) && toList.forall(that.contains); - } -} diff --git a/sources/scala/collection/mutable/ArrayBuffer.scala b/sources/scala/collection/mutable/ArrayBuffer.scala deleted file mode 100644 index e89e1a9c81..0000000000 --- a/sources/scala/collection/mutable/ArrayBuffer.scala +++ /dev/null @@ -1,148 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** An implementation of the Buffer trait using an array to - * represent the assembled sequence internally. - * - * @author Matthias Zenger - * @version 1.0, 15/03/2004 - */ -[serializable] -class ArrayBuffer[A] extends Buffer[A] with ResizableArray[A] { - - def apply(n: Int): A = { - if ((n < 0) || (n >= size)) - error("cannot access element " + n + " in ArrayBuffer"); - else - array(n); - } - - /** Append a single element to this buffer and return - * the identity of the buffer. - * - * @param elem the element to append. - */ - def +(elem: A): Buffer[A] = { - ensureSize(size+1); - array(size) = elem; - size = size + 1; - this - } - - /** Appends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - override def ++(iter: Iterable[A]): Buffer[A] = { insertAll(size, iter); this } - - /** Prepend a single element to this buffer and return - * the identity of the buffer. - * - * @param elem the element to append. - */ - def +:(elem: A): Buffer[A] = { - ensureSize(size+1); - copy(0, 1, size); - array(0) = elem; - size = size + 1; - this - } - - /** Prepends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - override def ++:(iter: Iterable[A]): Buffer[A] = { insertAll(0, iter); this } - - /** Inserts new elements at the index n. Opposed to method - * update, this method will not replace an element with a - * one. Instead, it will insert a new element at index n. - * - * @param n the index where a new element will be inserted. - * @param iter the iterable object providing all elements to insert. - */ - def insertAll(n: Int, iter: Iterable[A]): Unit = { - if ((n < 0) || (n > size)) - error("cannot insert element " + n + " in ListBuffer"); - val xs = iter.elements.toList; - val len = xs.length; - ensureSize(size+len); - copy(n, n + len, size - n); - xs.copyToArray(array, n); - size = size + len; - } - - /** Replace element at index n with the new element - * newelem. - * - * @param n the index of the element to replace. - * @param newelem the new element. - */ - def update(n: Int, newelem: A): Unit = { - if ((n < 0) || (n >= size)) - error("cannot update element " + n + " in ArrayBuffer"); - else { - val res = array(n); - array(n) = newelem; - res - } - } - - /** Removes the element on a given index position. - * - * @param n the index which refers to the element to delete. - */ - def remove(n: Int): A = { - if ((n < 0) || (n >= size)) - error("cannot remove element " + n + " in Buffer"); - val res = array(n); - copy(n + 1, n, size - n - 1); - size = size - 1; - res - } - - /** Clears the buffer contents. - */ - def clear: Unit = { - size = 0; - } - - /** Return a clone of this buffer. - * - * @return an ArrayBuffer with the same elements. - */ - override def clone(): Buffer[A] = { - val res = new ArrayBuffer[A]; - res ++= this; - res - } - - /** Checks if two buffers are structurally identical. - * - * @return true, iff both buffers contain the same sequence of elements. - */ - override def equals(obj: Any): Boolean = obj match { - case that: ArrayBuffer[A] => - elements.zip(that.elements).forall { - case Pair(thiselem, thatelem) => thiselem == thatelem; - } - case _ => false - } - - /** Defines the prefix of the string representation. - */ - override protected def stringPrefix: String = "ArrayBuffer"; -} diff --git a/sources/scala/collection/mutable/BitSet.scala b/sources/scala/collection/mutable/BitSet.scala deleted file mode 100644 index 40d0bf0529..0000000000 --- a/sources/scala/collection/mutable/BitSet.scala +++ /dev/null @@ -1,87 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable ; - -/** mutable, resizable bit sets, to represent dense sets of small integers - * Bit indices are between 0..(size-1) inclusive - * @author Burak Emir - * @param initSize: initial size in nbits - */ -[serializable] -class BitSet(initSize: Int) extends scala.collection.BitSet { - import scala.runtime.compat.Platform.arraycopy; - - /** default constructor, initial size of 512 bits */ - def this() = this( 512 ); // ResizableArray.initialSize << 5 - - [serializable] - class ByteArray extends AnyRef with ResizableArray[Int] { - - final def ensureBits(nbits: Int): Unit = { - super[ResizableArray].ensureSize(memsize( nbits )); - } - final def and(j: Int, mask:Int): Unit = { - array.update( j, array(j) & mask ); - } - final def or(j: Int, mask:Int): Unit = { - array.update( j, array(j) | mask ); - } - def get(j:Int, mask:Int):Boolean = { - (array(j) & mask) != 0; - } - def freeze: Array[Int] = { - val arr = new Array[Int]( array.length ); - arraycopy(array, 0, arr, 0, arr.length); - arr - } - } - - /** size of this bitset in nbytes */ - var size: Int = initSize; - protected val internal = new ByteArray(); - internal.ensureBits( size ); - - /** ensure that this bitset can store at least nbits bits */ - def ensureSize(n: Int): Unit = { - internal.ensureBits( n ); - if( size < n ) size = n; - } - - /** calls set or clear for i-th bit */ - final def set(i: Int, b: Boolean): Unit = if( b ) set(i) else clear(i); - - /** sets i-th bit to true. Grows to size i+1 if needed. */ - final def set(i: Int): Unit = { - ensureSize(i+1); - val j = (i >>> 5); - val mask = (1 << (i & 0x1F)); - internal.or(j, mask); - } - - /** clears i-th bit. Grows to size i+1 if needed. */ - def clear(i: Int): Unit = { - ensureSize(i+1); - val j = (i >>> 5); - val mask = (1 << (i & 0x1F)); - internal.and(j, ~mask); - } - - /** gets i-th bit. Grows to size i+1 if needed. */ - def apply(i: Int):Boolean = { - val j = (i >>> 5); - val mask = (1 << (i & 0x1F)); - internal.get(j, mask); - } - - def toArray: Array[Int] = internal.freeze; - - def makeImmutable = new scala.collection.immutable.BitSet(this); - -} diff --git a/sources/scala/collection/mutable/Buffer.scala b/sources/scala/collection/mutable/Buffer.scala deleted file mode 100644 index f1e8d0fe9b..0000000000 --- a/sources/scala/collection/mutable/Buffer.scala +++ /dev/null @@ -1,214 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - -/** Buffers are used to create sequences of elements incrementally by - * appending, prepending, or inserting new elements. It is also - * possible to access and modify elements in a random access fashion - * via the index of the element in the current sequence. - * - * @author Matthias Zenger - * @version 1.1, 02/03/2004 - */ -[cloneable] -trait Buffer[A] extends AnyRef with Seq[A] with Scriptable[Message[Pair[Location, A]]] { - - /** Append a single element to this buffer and return - * the identity of the buffer. - * - * @param elem the element to append. - */ - def +(elem: A): Buffer[A]; - - /** Append a single element to this buffer. - * - * @param elem the element to append. - */ - def +=(elem: A): Unit = this + elem; - - /** Appends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - def ++(elems: Iterable[A]): Buffer[A] = this ++ elems.elements; - - /** Appends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - def ++(iter: Iterator[A]): Buffer[A] = { - iter.foreach(e => this += e); - this - } - - /** Appends a number of elements provided by an iterable object - * via its elements method. - * - * @param iter the iterable object. - */ - def ++=(elems: Iterable[A]): Unit = this ++ elems.elements; - - /** Appends a number of elements provided by an iterable object - * via its elements method. - * - * @param iter the iterable object. - */ - def ++=(it: Iterator[A]): Unit = this ++ it; - - /** Appends a sequence of elements to this buffer. - * - * @param elems the elements to append. - */ - def append(elems: A*): Unit = this ++ elems; - - /** Appends a number of elements provided by an iterable object - * via its elements method. - * - * @param iter the iterable object. - */ - def appendAll(iter: Iterable[A]): Unit = this ++ iter; - - /** Prepend a single element to this buffer and return - * the identity of the buffer. - * - * @param elem the element to append. - */ - def +:(elem: A): Buffer[A]; - - /** Prepends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - def ++:(iter: Iterable[A]): Buffer[A] = { - iter.elements.toList.reverse.foreach(e => e +: this); - this - } - - /** Prepend an element to this list. - * - * @param elem the element to prepend. - */ - def prepend(elems: A*): Unit = elems ++: this; - - /** Prepends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - def prependAll(elems: Iterable[A]): Unit = elems ++: this; - - /** Inserts new elements at the index n. Opposed to method - * update, this method will not replace an element with a - * one. Instead, it will insert the new elements at index n. - * - * @param n the index where a new element will be inserted. - * @param elems the new elements to insert. - */ - def insert(n: Int, elems: A*): Unit = insertAll(n, elems); - - /** Inserts new elements at the index n. Opposed to method - * update, this method will not replace an element with a - * one. Instead, it will insert a new element at index n. - * - * @param n the index where a new element will be inserted. - * @param iter the iterable object providing all elements to insert. - */ - def insertAll(n: Int, iter: Iterable[A]): Unit; - - /** Replace element at index n with the new element - * newelem. - * - * @param n the index of the element to replace. - * @param newelem the new element. - */ - def update(n: Int, newelem: A): Unit; - - /** Removes the element on a given index position. - * - * @param n the index which refers to the element to delete. - */ - def remove(n: Int): A; - - /** Removes the first n elements. - * - * @param n the number of elements to remove from the beginning - * of this buffer. - */ - def trimStart(n: Int): Unit = { - var i = n; - while (i > 0) { remove(0); i = i - 1; } - } - - /** Removes the last n elements. - * - * @param n the number of elements to remove from the end - * of this buffer. - */ - def trimEnd(n: Int): Unit = { - var i = n; - while (i > 0) { remove(length - 1); i = i - 1; } - } - - /** Clears the buffer contents. - */ - def clear: Unit; - - /** Send a message to this scriptable object. - * - * @param cmd the message to send. - */ - def <<(cmd: Message[Pair[Location, A]]): Unit = cmd match { - case Include(Pair(l, elem)) => l match { - case Start => prepend(elem); - case End => append(elem); - case Index(n) => insert(n, elem); - case _ => error("message " + cmd + " not understood"); - } - case Update(Pair(l, elem)) => l match { - case Start => update(0, elem); - case End => update(length - 1, elem); - case Index(n) => update(n, elem); - case _ => error("message " + cmd + " not understood"); - } - case Remove(Pair(l, _)) => l match { - case Start => remove(0); - case End => remove(length - 1); - case Index(n) => remove(n); - case _ => error("message " + cmd + " not understood"); - } - case Reset() => clear; - case s: Script[Pair[Location, A]] => s.elements foreach <<; - case _ => error("message " + cmd + " not understood"); - } - - /** Return a clone of this buffer. - * - * @return a buffer with the same elements. - */ - override def clone(): Buffer[A] = super.clone().asInstanceOf[Buffer[A]]; - - /** The hashCode method always yields an error, since it is not - * safe to use buffers as keys in hash tables. - * - * @return never. - */ - override def hashCode(): Int = error("unsuitable as hash key"); - - /** Defines the prefix of the string representation. - */ - override protected def stringPrefix: String = "Buffer"; -} diff --git a/sources/scala/collection/mutable/BufferProxy.scala b/sources/scala/collection/mutable/BufferProxy.scala deleted file mode 100644 index c06202024a..0000000000 --- a/sources/scala/collection/mutable/BufferProxy.scala +++ /dev/null @@ -1,147 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This is a simple proxy class for scala.collection.mutable.Buffer. - * It is most useful for assembling customized set abstractions - * dynamically using object composition and forwarding. - * - * @author Matthias Zenger - * @version 1.0, 16/04/2004 - */ -trait BufferProxy[A] extends Buffer[A] with Proxy { - - def self: Buffer[A]; - - def length: Int = self.length; - - def elements: Iterator[A] = self.elements; - - def apply(n: Int): A = self.apply(n); - - /** Append a single element to this buffer and return - * the identity of the buffer. - * - * @param elem the element to append. - */ - def +(elem: A): Buffer[A] = self.+(elem); - - /** Append a single element to this buffer. - * - * @param elem the element to append. - */ - override def +=(elem: A): Unit = self.+=(elem); - - /** Appends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - override def ++(iter: Iterable[A]): Buffer[A] = self.++(iter); - - /** Appends a number of elements provided by an iterable object - * via its elements method. - * - * @param iter the iterable object. - */ - override def ++=(iter: Iterable[A]): Unit = self.++=(iter); - - /** Appends a sequence of elements to this buffer. - * - * @param elems the elements to append. - */ - override def append(elems: A*): Unit = self.++=(elems); - - /** Appends a number of elements provided by an iterable object - * via its elements method. - * - * @param iter the iterable object. - */ - override def appendAll(iter: Iterable[A]): Unit = self.appendAll(iter); - - /** Prepend a single element to this buffer and return - * the identity of the buffer. - * - * @param elem the element to append. - */ - def +:(elem: A): Buffer[A] = self.+:(elem); - - /** Prepends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - override def ++:(iter: Iterable[A]): Buffer[A] = self.++:(iter); - - /** Prepend an element to this list. - * - * @param elem the element to prepend. - */ - override def prepend(elems: A*): Unit = self.prependAll(elems); - - /** Prepends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - override def prependAll(elems: Iterable[A]): Unit = self.prependAll(elems); - - /** Inserts new elements at the index n. Opposed to method - * update, this method will not replace an element with a - * one. Instead, it will insert the new elements at index n. - * - * @param n the index where a new element will be inserted. - * @param elems the new elements to insert. - */ - override def insert(n: Int, elems: A*): Unit = self.insertAll(n, elems); - - /** Inserts new elements at the index n. Opposed to method - * update, this method will not replace an element with a - * one. Instead, it will insert a new element at index n. - * - * @param n the index where a new element will be inserted. - * @param iter the iterable object providing all elements to insert. - */ - def insertAll(n: Int, iter: Iterable[A]): Unit = self.insertAll(n, iter); - - /** Replace element at index n with the new element - * newelem. - * - * @param n the index of the element to replace. - * @param newelem the new element. - */ - def update(n: Int, newelem: A): Unit = self.update(n, newelem); - - /** Removes the element on a given index position. - * - * @param n the index which refers to the element to delete. - */ - def remove(n: Int): A = self.remove(n); - - /** Clears the buffer contents. - */ - def clear: Unit = self.clear; - - /** Send a message to this scriptable object. - * - * @param cmd the message to send. - */ - override def <<(cmd: Message[Pair[Location, A]]): Unit = self << cmd; - - /** Return a clone of this buffer. - * - * @return a Buffer with the same elements. - */ - override def clone(): Buffer[A] = new BufferProxy[A] { def self = BufferProxy.this.self.clone() } -} diff --git a/sources/scala/collection/mutable/DefaultMapModel.scala b/sources/scala/collection/mutable/DefaultMapModel.scala deleted file mode 100644 index 6ae089bc3e..0000000000 --- a/sources/scala/collection/mutable/DefaultMapModel.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This trait is used internally. It implements the mutable Map - * trait in terms of three functions: findEntry, addEntry, - * and entries. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -trait DefaultMapModel[A, B] extends AnyRef with scala.collection.mutable.Map[A, B] { - protected type Entry = DefaultEntry[A,B]; - - protected def findEntry(key: A): Option[Entry]; - - protected def addEntry(e: Entry): Unit; - - protected def entries: Iterator[Entry]; - - def get(key: A) = findEntry(key) match { - case None => None - case Some(e) => Some(e.value); - } - - def update(key: A, value: B) = findEntry(key) match { - case None => addEntry(new Entry(key, value)); - case Some(e) => e.value = value; - } - - def elements = new Iterator[Pair[A, B]] { - val iter = entries; - def hasNext = iter.hasNext; - def next = iter.next.toPair; - } -} - -[serializable] -protected class DefaultEntry[A,B](k: A, v: B) extends AnyRef { - def key = k; - var value = v; - def toPair = Pair(k, value); - override def toString() = k.toString() + " -> " + value; -} diff --git a/sources/scala/collection/mutable/DoubleLinkedList.scala b/sources/scala/collection/mutable/DoubleLinkedList.scala deleted file mode 100644 index 977f42b23a..0000000000 --- a/sources/scala/collection/mutable/DoubleLinkedList.scala +++ /dev/null @@ -1,49 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - -/** This extensible class may be used as a basis for implementing double - * linked lists. Type variable A refers to the element type - * of the list, type variable This is used to model self - * types of linked lists. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[serializable] -abstract class DoubleLinkedList[A, This <: DoubleLinkedList[A, This]]: This - extends SingleLinkedList[A, This] { - - var prev: This = _; - - override def append(that: This): Unit = - if (that == null) - () - else if (next == null) { - next = that; - that.prev = this; - } else - next.append(that); - - override def insert(that: This): Unit = if (that != null) { - that.append(next); - next = that; - that.prev = this; - } - - def remove: Unit = { - if (next != null) - next.prev = prev; - if (prev != null) - prev.next = next; - prev = null; - next = null; - } -} diff --git a/sources/scala/collection/mutable/HashMap.scala b/sources/scala/collection/mutable/HashMap.scala deleted file mode 100644 index dcdde2e40c..0000000000 --- a/sources/scala/collection/mutable/HashMap.scala +++ /dev/null @@ -1,36 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - -/** This class implements mutable maps using a hashtable. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[serializable] -class HashMap[A, B] extends scala.collection.mutable.Map[A, B] - with HashTable[A] - with DefaultMapModel[A, B] { - - def -=(key: A): Unit = removeEntry(key); - - protected def entryKey(e: Entry) = e.key; - - override def clear = { - initTable(table); - tableSize = 0; - } - - override def clone(): Map[A, B] = { - val res = new HashMap[A, B]; - res ++= this; - res - } -} diff --git a/sources/scala/collection/mutable/HashSet.scala b/sources/scala/collection/mutable/HashSet.scala deleted file mode 100644 index 7f71b037b4..0000000000 --- a/sources/scala/collection/mutable/HashSet.scala +++ /dev/null @@ -1,49 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class implements mutable sets using a hashtable. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[serializable] -class HashSet[A] extends scala.collection.mutable.Set[A] with HashTable[A] { - - def contains(elem: A): Boolean = findEntry(elem) match { - case None => false - case Some(_) => true - } - - def +=(elem: A): Unit = findEntry(elem) match { - case None => addEntry(elem); - case Some(_) => - } - - def -=(elem: A): Unit = removeEntry(elem); - - def elements = entries; - - def clear = { - initTable(table); - tableSize = 0; - } - - protected type Entry = A; - - protected def entryKey(e: Entry) = e; - - override def clone(): HashSet[A] = { - val res = new HashSet[A]; - res ++= this; - res - } -} diff --git a/sources/scala/collection/mutable/HashTable.scala b/sources/scala/collection/mutable/HashTable.scala deleted file mode 100644 index 984f33f561..0000000000 --- a/sources/scala/collection/mutable/HashTable.scala +++ /dev/null @@ -1,148 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - -import Predef._; - -/** This class can be used to construct data structures that are based - * on hashtables. Class HashTable[A] implements a hashtable - * that maps keys of type A to values of the fully abstract - * member type Entry. Classes that make use of HashTable - * have to provide an implementation for Entry and implement the - * function entryKey.

- * - * There are mainly two parameters that affect the performance of a hashtable: - * the initial size and the load factor. The size - * refers to the number of buckets in the hashtable, and the load - * factor is a measure of how full the hashtable is allowed to get before - * its size is automatically doubled. Both parameters may be changed by - * overriding the corresponding values in class HashTable. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[_trait_] abstract class HashTable[A] extends AnyRef { - - /** The load factor for the hash table. - */ - protected val loadFactor: Float = 0.75f; - - /** The initial size of the hash table. - */ - protected val initialSize: Int = 16; - - /** The initial threshold - */ - protected val initialThreshold: Int = newThreshold(initialSize); - - /** The actual hash table. - */ - protected var table: Array[List[Entry]] = new Array(initialSize); - initTable(table); - - /** The number of mappings contained in this hash table. - */ - protected var tableSize: Int = 0; - - /** The next size value at which to resize (capacity * load factor). - */ - protected var threshold: Int = initialThreshold; - - /** Returns the size of this hash map. - */ - def size = tableSize; - - protected def findEntry(key: A): Option[Entry] = - table(index(elemHashCode(key))).find(entryFor(key)); - - protected def addEntry(e: Entry): Unit = { - val h = index(elemHashCode(entryKey(e))); - table(h) = e :: table(h); - tableSize = tableSize + 1; - if (tableSize > threshold) - resize(2 * table.length); - } - - protected def removeEntry(key: A): Unit = { - val old = findEntry(key); - old match { - case None => - case Some(e) => { - val idx = index(elemHashCode(key)); - table(idx) = table(idx).filter(e => !elemEquals(entryKey(e), key)); - tableSize = tableSize - 1; - } - } - } - - protected type Entry; - - protected def entryKey(e: Entry): A; - - protected def entries: Iterator[Entry] = new Iterator[Entry] { - val iterTable = table; - var idx = table.length - 1; - var xs = iterTable(idx); - scan(); - def hasNext = !xs.isEmpty; - def next = { - val res = xs.head; - xs = xs.tail; - scan(); - res; - } - def scan(): Unit = if (xs.isEmpty && (idx > 0)) { - idx = idx - 1; - xs = iterTable(idx); - scan(); - } - } - - private def entryFor(key: A) = (e: Entry => elemEquals(entryKey(e), key)); - - protected def initTable(tb: Array[List[Entry]]): Unit = { - var i = tb.length - 1; - while (i >= 0) { - tb(i) = Nil; - i = i - 1; - } - } - - private def newThreshold(size: Int) = - (size * loadFactor).asInstanceOf[Int]; - - private def resize(newSize: Int) = { - val newTable: Array[List[Entry]] = new Array(newSize); - initTable(newTable); - var i = table.length - 1; - while (i >= 0) { - table(i).foreach { e => { - val idx = improve(elemHashCode(entryKey(e))) & (newSize - 1); - newTable(idx) = e :: newTable(idx); - }}; - i = i - 1; - } - table = newTable; - threshold = newThreshold(newSize); - } - - protected def elemEquals(key1: A, key2: A): Boolean = (key1 == key2); - - protected def elemHashCode(key: A) = key.hashCode(); - - protected final def improve(hcode: Int) = { - var h: Int = hcode + ~(hcode << 9); - h = h ^ (h >>> 14); - h = h + (h << 4); - h ^ (h >>> 10); - } - - protected final def index(hcode: Int) = improve(hcode) & (table.length - 1); -} diff --git a/sources/scala/collection/mutable/History.scala b/sources/scala/collection/mutable/History.scala deleted file mode 100644 index 43be629602..0000000000 --- a/sources/scala/collection/mutable/History.scala +++ /dev/null @@ -1,42 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** History[A, B] objects may subscribe to events of - * type A published by an object of type B. - * The history subscriber object records all published events - * up to maximum number of maxHistory events. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[serializable] -class History[A, B] extends AnyRef with Subscriber[A, B] with Iterable[Pair[B, A]] { - - protected val log: Queue[Pair[B, A]] = new Queue[Pair[B, A]]; - - val maxHistory: Int = 1000; - - def notify(pub: B, event: A): Unit = { - if (log.length >= maxHistory) { - val old = log.dequeue; - } - log.enqueue(Pair(pub, event)); - } - - def elements: Iterator[Pair[B, A]] = log.elements; - - def events: Iterator[A] = log.elements.map { case Pair(_, e) => e } - - def size: Int = log.length; - - def clear: Unit = log.clear; -} diff --git a/sources/scala/collection/mutable/ImmutableMapAdaptor.scala b/sources/scala/collection/mutable/ImmutableMapAdaptor.scala deleted file mode 100644 index 5167636b40..0000000000 --- a/sources/scala/collection/mutable/ImmutableMapAdaptor.scala +++ /dev/null @@ -1,64 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class can be used as an adaptor to create mutable maps from - * immutable map implementations. Only method empty has - * to be redefined if the immutable map on which this mutable map is - * originally based is not empty. empty is supposed to - * return the representation of an empty map. - * - * @author Matthias Zenger - * @version 1.0, 21/07/2003 - */ -[serializable] -class ImmutableMapAdaptor[A, B](m: scala.collection.immutable.Map[A, B]) extends Map[A, B] { - - protected var imap = m; - - def size: Int = imap.size; - - def get(key: A): Option[B] = imap.get(key); - - override def isEmpty: Boolean = imap.isEmpty; - - override def apply(key: A): B = imap.apply(key); - - override def contains(key: A): Boolean = imap.contains(key); - - override def isDefinedAt(key: A) = imap.isDefinedAt(key); - - override def keys: Iterator[A] = imap.keys; - - override def values: Iterator[B] = imap.values; - - def elements: Iterator[Pair[A, B]] = imap.elements; - - override def foreach(f: (A, B) => Unit) = imap.foreach(f); - - override def toList: List[Pair[A, B]] = imap.toList; - - override def toString() = imap.toString(); - - def update(key: A, value: B): Unit = { imap = imap.update(key, value); } - - def -=(key: A): Unit = { imap = imap - key; } - - override def clear: Unit = { imap = empty; } - - override def map(f: (A, B) => B): Unit = { imap = imap.map(f); } - - override def filter(p: (A, B) => Boolean): Unit = { imap = imap.filter(p); } - - override def mappingToString(p: Pair[A, B]) = imap.mappingToString(p); - - protected def empty: scala.collection.immutable.Map[A, B] = m; -} diff --git a/sources/scala/collection/mutable/ImmutableSetAdaptor.scala b/sources/scala/collection/mutable/ImmutableSetAdaptor.scala deleted file mode 100644 index 623074b3d9..0000000000 --- a/sources/scala/collection/mutable/ImmutableSetAdaptor.scala +++ /dev/null @@ -1,50 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class can be used as an adaptor to create mutable sets from - * immutable set implementations. Only method empty has - * to be redefined if the immutable set on which this mutable set is - * originally based is not empty. empty is supposed to - * return the representation of an empty set. - * - * @author Matthias Zenger - * @version 1.0, 21/07/2003 - */ -[serializable] -class ImmutableSetAdaptor[A](s: scala.collection.immutable.Set[A]) extends Set[A] { - - protected var set = s; - - def size: Int = set.size; - - override def isEmpty: Boolean = set.isEmpty; - - def contains(elem: A): Boolean = set.contains(elem); - - override def foreach(f: A => Unit): Unit = set.foreach(f); - - override def exists(p: A => Boolean): Boolean = set.exists(p); - - override def toList: List[A] = set.toList; - - override def toString() = set.toString(); - - def elements: Iterator[A] = set.elements; - - def +=(elem: A): Unit = { set = set + elem; } - - def -=(elem: A): Unit = { set = set - elem; } - - def clear: Unit = { set = empty; } - - protected def empty: scala.collection.immutable.Set[A] = s; -} diff --git a/sources/scala/collection/mutable/JavaMapAdaptor.scala b/sources/scala/collection/mutable/JavaMapAdaptor.scala deleted file mode 100644 index 3679e787e8..0000000000 --- a/sources/scala/collection/mutable/JavaMapAdaptor.scala +++ /dev/null @@ -1,66 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class can be used as an adaptor to create mutable maps from - * Java classes that implementat the java.util.Map interface. - * - * @author Matthias Zenger - * @version 1.0, 21/07/2003 - */ -class JavaMapAdaptor[A, B](jmap: java.util.Map) extends Map[A, B] { - - def size: Int = jmap.size(); - - def get(key: A): Option[B] = - if (jmap.containsKey(key)) Some(jmap.get(key).asInstanceOf[B]) else None; - - override def isEmpty: Boolean = jmap.isEmpty(); - - override def apply(key: A): B = jmap.get(key).asInstanceOf[B]; - - override def contains(key: A): Boolean = jmap.containsKey(key); - - override def isDefinedAt(key: A) = jmap.containsKey(key); - - override def keys: Iterator[A] = new Iterator[A] { - val iter = jmap.keySet().iterator(); - def hasNext = iter.hasNext(); - def next = iter.next().asInstanceOf[A]; - } - - override def values: Iterator[B] = new Iterator[B] { - val iter = jmap.values().iterator(); - def hasNext = iter.hasNext(); - def next = iter.next().asInstanceOf[B]; - } - - def elements: Iterator[Pair[A, B]] = new Iterator[Pair[A, B]] { - val iter = jmap.keySet().iterator(); - def hasNext = iter.hasNext(); - def next = { - val key = iter.next().asInstanceOf[A]; - Pair(key, apply(key)) - } - } - - def update(key: A, value: B): Unit = { val x = jmap.put(key, value); } - - def -=(key: A): Unit = { val x = jmap.remove(key); } - - override def clear: Unit = jmap.clear(); - - override def clone(): Map[A, B] = { - val res = new HashMap[A, B]; - res ++= this; - res - } -} diff --git a/sources/scala/collection/mutable/JavaSetAdaptor.scala b/sources/scala/collection/mutable/JavaSetAdaptor.scala deleted file mode 100644 index 3279e85a13..0000000000 --- a/sources/scala/collection/mutable/JavaSetAdaptor.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class can be used as an adaptor to create mutable sets from - * Java classes that implement interface java.util.Set. - * - * @author Matthias Zenger - * @version 1.0, 19/09/2003 - */ -class JavaSetAdaptor[A](jset: java.util.Set) extends Set[A] { - - def size: Int = jset.size(); - - override def isEmpty: Boolean = jset.isEmpty(); - - def contains(elem: A): Boolean = jset.contains(elem); - - def elements: Iterator[A] = new Iterator[A] { - val iter = jset.iterator(); - def hasNext = iter.hasNext(); - def next = iter.next().asInstanceOf[A]; - } - - def +=(elem: A): Unit = { val x = jset.add(elem); } - - def -=(elem: A): Unit = { val x = jset.remove(elem); } - - def clear: Unit = jset.clear(); - - override def clone(): Set[A] = { - val res = new HashSet[A]; - res ++= this; - res; - } -} diff --git a/sources/scala/collection/mutable/LinkedList.scala b/sources/scala/collection/mutable/LinkedList.scala deleted file mode 100644 index c08928a04a..0000000000 --- a/sources/scala/collection/mutable/LinkedList.scala +++ /dev/null @@ -1,34 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - -/** This class implements single linked lists where both the head (elem) - * and the tail (next) are mutable. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[serializable] -class LinkedList[A](head: A, tail: LinkedList[A]) - extends SingleLinkedList[A, LinkedList[A]] -{ - elem = head; - next = tail; - - override def equals(obj: Any): Boolean = ( - obj.isInstanceOf[LinkedList[A]] - && toList.equals((obj.asInstanceOf[LinkedList[A]]).toList) - ); - - override protected def stringPrefix: String = "LinkedList"; -} - - - diff --git a/sources/scala/collection/mutable/ListBuffer.scala b/sources/scala/collection/mutable/ListBuffer.scala deleted file mode 100644 index 527741bbc9..0000000000 --- a/sources/scala/collection/mutable/ListBuffer.scala +++ /dev/null @@ -1,143 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** A list buffer uses a list internally to assemble sequences of elements - * incrementally by appending or prepending new elements. It is also - * possible to access and modify elements in a random access fashion - * via the index of the element in the sequence. - * - * @author Matthias Zenger - * @version 1.0, 15/03/2004 - */ -class ListBuffer[A] extends Buffer[A] with MutableList[A] { - - /** Append a single element to this buffer and return - * the identity of the buffer. - * - * @param elem the element to append. - */ - def +(elem: A): Buffer[A] = { appendElem(elem); this } - - /** Prepend a single element to this buffer and return - * the identity of the buffer. - * - * @param elem the element to append. - */ - def +:(elem: A): Buffer[A] = { prependElem(elem); this } - - /** Inserts new elements at the index n. Opposed to method - * update, this method will not replace an element with a - * one. Instead, it will insert a new element at index n. - * - * @param n the index where a new element will be inserted. - * @param iter the iterable object providing all elements to insert. - */ - def insertAll(n: Int, iter: Iterable[A]): Unit = { - val it = iter.elements; - while (it.hasNext) { - val newelem = it.next; - if (n == 0) - prepend(newelem); - else if (n >= len) - append(newelem); - else { - var elem = first; - var i = n; - while (i > 1) { - elem = elem.next; - if (elem == null) - error("cannot insert element " + n + " in ListBuffer"); - i = i - 1; - } - val old = elem.next; - elem.next = new LinkedList[A](newelem, old); - } - } - } - - /** Replace element at index n with the new element - * newelem. - * - * @param n the index of the element to replace. - * @param newelem the new element. - */ - def update(n: Int, newelem: A): Unit = { - var elem = first; - var i = n; - while (i > 0) { - elem = elem.next; - if (elem == null) - error("cannot update element " + n + " in Buffer"); - i = i - 1; - } - elem.elem = newelem; - } - - /** Removes the element on a given index position. - * - * @param n the index which refers to the element to delete. - */ - def remove(n: Int): A = { - val old = apply(n); - if (n >= len) - error("cannot remove element " + n + " in Buffer"); - if ((n == 0) && (len == 1)) { - first = null; - last = null; - } else if (n == 0) { - first = first.next; - } else { - var elem = first; - var i = n; - while (i > 1) { - elem = elem.next; - i = i - 1; - } - elem.next = elem.next.next; - if (n == (len - 1)) { - last = elem.next; - } - } - len = len - 1; - old; - } - - /** Clears the buffer contents. - */ - def clear: Unit = reset; - - /** Return a clone of this buffer. - * - * @return an ArrayBuffer with the same elements. - */ - override def clone(): Buffer[A] = { - val res = new ListBuffer[A]; - res ++= this; - res - } - - /** Checks if two buffers are structurally identical. - * - * @return true, iff both buffers contain the same sequence of elements. - */ - override def equals(obj: Any): Boolean = obj match { - case that: ListBuffer[A] => - elements.zip(that.elements).forall { - case Pair(thiselem, thatelem) => thiselem == thatelem; - } - case _ => false - } - - /** Defines the prefix of the string representation. - */ - override protected def stringPrefix: String = "ListBuffer"; -} diff --git a/sources/scala/collection/mutable/Location.scala b/sources/scala/collection/mutable/Location.scala deleted file mode 100644 index 30abd06781..0000000000 --- a/sources/scala/collection/mutable/Location.scala +++ /dev/null @@ -1,27 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** Class Location describes locations in messages implemented - * by class Message. - * - * @author Matthias Zenger - * @version 1.0, 10/05/2004 - */ -trait Location; - -case object NA extends Location; - -case object Start extends Location; - -case object End extends Location; - -case class Index(n: Int) extends Location; diff --git a/sources/scala/collection/mutable/Map.scala b/sources/scala/collection/mutable/Map.scala deleted file mode 100644 index 75f544193e..0000000000 --- a/sources/scala/collection/mutable/Map.scala +++ /dev/null @@ -1,169 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - -/** This trait represents mutable maps. Concrete map implementations - * just have to provide functionality for the abstract methods in - * scala.collection.Map as well as for update, - * and remove. - * - * @author Matthias Zenger - * @version 1.1, 09/05/2004 - */ -[cloneable] -trait Map[A, B] extends AnyRef with scala.collection.Map[A, B] with Scriptable[Message[Pair[A, B]]] { - - /** This method allows one to add a new mapping from key - * to value to the map. If the map already contains a - * mapping for key, it will be overridden by this - * function. - * - * @param key - * @param value - */ - def update(key: A, value: B): Unit; - - /** This method defines syntactic sugar for adding or modifying - * mappings. It is typically used in the following way: - *

-   *  map += key -> value;
-   *  
- */ - def +=(key: A): MapTo = new MapTo(key); - - /** This method adds all the mappings provided by an iterator of - * parameter map to the map. - * - * @param map - */ - def ++=(map: Iterable[Pair[A, B]]): Unit = ++=(map.elements); - - /** This method adds all the mappings provided by an iterator of - * parameter map to the map. - * - * @param it - */ - def ++=(it: Iterator[Pair[A, B]]): Unit = it foreach { - case Pair(key, value) => update(key, value); - } - - /** incl can be used to add many mappings at the same time - * to the map. The method assumes that a mapping is represented - * by a Pair object who's first component denotes the - * key, and who's second component refers to the value. - * - * @param mappings - */ - def incl(mappings: Pair[A, B]*): Unit = ++=(mappings.elements); - - /** This method removes a mapping from the given key. - * If the map does not contain a mapping for the given key, the - * method does nothing. - */ - def -=(key: A): Unit; - - /** This method removes all the mappings for keys provided by an - * iterator over the elements of the keys object. - * - * @param keys - */ - def --=(keys: Iterable[A]): Unit = --=(keys.elements); - - /** This method removes all the mappings for keys provided by an - * iterator over the elements of the keys object. - * - * @param it - */ - def --=(it: Iterator[A]): Unit = it foreach -=; - - /** This method will remove all the mappings for the given sequence - * of keys from the map. - * - * @param keys - */ - def excl(keys: A*): Unit = --=(keys.elements); - - /** Removes all mappings from the map. After this operation is - * completed, the map is empty. - */ - def clear: Unit = keys foreach -=; - - /** This function transforms all the values of mappings contained - * in this map with function f. - * - * @param f - */ - def map(f: (A, B) => B): Unit = elements foreach { - case Pair(key, value) => update(key, f(key, value)); - } - - /** This method removes all the mappings for which the predicate - * p returns false. - * - * @param p - */ - def filter(p: (A, B) => Boolean): Unit = toList foreach { - case Pair(key, value) => if (!p(key, value)) -=(key); - } - - /** Send a message to this scriptable object. - * - * @param cmd the message to send. - */ - def <<(cmd: Message[Pair[A, B]]): Unit = cmd match { - case Include(Pair(k, v)) => update(k, v); - case Update(Pair(k, v)) => update(k, v); - case Remove(Pair(k, _)) => this -= k; - case Reset() => clear; - case s: Script[Pair[A, B]] => s.elements foreach <<; - case _ => error("message " + cmd + " not understood"); - } - - /** Return a clone of this map. - * - * @return an map with the same elements. - */ - override def clone(): Map[A, B] = super.clone().asInstanceOf[Map[A, B]]; - - /** The hashCode method always yields an error, since it is not - * safe to use mutable maps as keys in hash tables. - * - * @return never. - */ - override def hashCode(): Int = error("unsuitable as hash key"); - - /** Returns a string representation of this map which shows - * all the mappings. - */ - override def toString() = - if (size == 0) - "{}" - else - "{" + { - val iter = elements; - var res = mappingToString(iter.next); - while (iter.hasNext) { - res = res + ", " + mappingToString(iter.next); - } - res; - } + "}"; - - /** This method controls how a mapping is represented in the string - * representation provided by method toString. - * - * @param p - */ - def mappingToString(p: Pair[A, B]) = p._1.toString() + " -> " + p._2; - - class MapTo(key: A) { - def ->(value: B): Unit = update(key, value); - } - -} diff --git a/sources/scala/collection/mutable/MapProxy.scala b/sources/scala/collection/mutable/MapProxy.scala deleted file mode 100644 index 8081e3a66a..0000000000 --- a/sources/scala/collection/mutable/MapProxy.scala +++ /dev/null @@ -1,53 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This is a simple wrapper class for scala.collection.mutable.Map. - * It is most useful for assembling customized map abstractions - * dynamically using object composition and forwarding. - * - * @author Matthias Zenger - * @version 1.0, 21/07/2003 - */ -trait MapProxy[A, B] extends Map[A, B] with scala.collection.MapProxy[A, B] { - - def self: Map[A, B]; - - def update(key: A, value: B): Unit = self.update(key, value); - - override def ++=(map: Iterable[Pair[A, B]]): Unit = self ++= map; - - override def ++=(it: Iterator[Pair[A, B]]): Unit = self ++= it; - - override def incl(mappings: Pair[A, B]*): Unit = self ++= mappings; - - def -=(key: A): Unit = self -= key; - - override def --=(keys: Iterable[A]): Unit = self --= keys; - - override def --=(it: Iterator[A]): Unit = self --= it; - - override def excl(keys: A*): Unit = self --= keys; - - override def clear: Unit = self.clear; - - override def map(f: (A, B) => B): Unit = self.map(f); - - override def filter(p: (A, B) => Boolean): Unit = self.filter(p); - - override def toString() = self.toString(); - - override def mappingToString(p: Pair[A, B]) = self.mappingToString(p); - - override def <<(cmd: Message[Pair[A, B]]): Unit = self << cmd; - - override def clone(): Map[A, B] = new MapProxy[A, B] { def self = MapProxy.this.self.clone() } -} diff --git a/sources/scala/collection/mutable/Message.scala b/sources/scala/collection/mutable/Message.scala deleted file mode 100644 index bd805c5d6e..0000000000 --- a/sources/scala/collection/mutable/Message.scala +++ /dev/null @@ -1,77 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** Class Message represents messages that are issued by observable - * collection classes whenever a data structure is changed. Class Message - * has several subclasses for the various kinds of events: Update - * Remove, Include, Reset, and - * Script. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -trait Message[+A]; - -/** This observable update refers to inclusion operations that add new elements - * to collection classes. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -case class Include[+I](elem: I) extends Message[I]; - -/** This observable update refers to destructive modification operations - * of elements from collection classes. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -case class Update[+A](elem: A) extends Message[A]; - -/** This observable update refers to removal operations of elements - * from collection classes. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -case class Remove[+A](elem: A) extends Message[A]; - -/** This command refers to reset operations. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -case class Reset[+A]() extends Message[A]; - -/** Objects of this class represent compound messages consisting - * of a sequence of other messages. - * - * @author Matthias Zenger - * @version 1.0, 10/05/2004 - */ -class Script[A] extends ArrayBuffer[Message[A]] with Message[A] { - - override def toString(): String = { - var res = "Script("; - var it = elements; - var i = 1; - while (it.hasNext) { - if (i > 1) - res = res + ", "; - res = res + "[" + i + "] " + it.next; - i = i + 1; - } - res + ")"; - } - - override def hashCode(): Int = error("scripts are not suitable as hash keys"); -} diff --git a/sources/scala/collection/mutable/MultiMap.scala b/sources/scala/collection/mutable/MultiMap.scala deleted file mode 100644 index 0569d0b0c9..0000000000 --- a/sources/scala/collection/mutable/MultiMap.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - -/** This class is typically used as a mixin. It turns maps which map A - * to Set[B] objects into multi maps which map A to - * B objects. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -trait MultiMap[A, B] extends scala.collection.mutable.Map[A, scala.collection.mutable.Set[B]] { - protected def makeSet: scala.collection.mutable.Set[B] = new HashSet[B]; - - def add(key: A, value: B): Unit = get(key) match { - case None => val set = makeSet; - set += value; - this(key) = set; - case Some(set) => set += value; - } - - def remove(key: A, value: B) = get(key) match { - case None => - case Some(set) => set -= value; - } - - def entryExists(key: A, p: B => Boolean): Boolean = get(key) match { - case None => false - case Some(set) => set exists p; - } -} diff --git a/sources/scala/collection/mutable/MutableList.scala b/sources/scala/collection/mutable/MutableList.scala deleted file mode 100644 index 37bb9ada63..0000000000 --- a/sources/scala/collection/mutable/MutableList.scala +++ /dev/null @@ -1,77 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class is used internally to represent mutable lists. It is the - * basis for the implementation of the classes Buffer, - * Stack, and Queue. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[_trait_] abstract class MutableList[A] extends Seq[A] with PartialFunction[Int, A] { - - protected var first: LinkedList[A] = null; - protected var last: LinkedList[A] = null; - protected var len: Int = 0; - - /** Returns the length of this list. - */ - def length: Int = len; - - /** Returns the nth element of this list. This method - * yields an error if the element does not exist. - */ - def apply(n: Int): A = get(n) match { - case None => error("element not found") - case Some(value) => value - } - - /** Returns the nth element of this list or None - * if this element does not exist. - */ - def get(n: Int): Option[A] = first.get(n); - - protected def prependElem(elem: A): Unit = { - first = new LinkedList[A](elem, first); - if (len == 0) - last = first; - len = len + 1; - } - - protected def appendElem(elem: A): Unit = { - if (len == 0) - prependElem(elem); - else { - last.next = new LinkedList[A](elem, null); - last = last.next; - len = len + 1; - } - } - - protected def reset: Unit = { - first = null; - last = null; - len = 0; - } - - /** Returns an iterator over all elements of this list. - */ - def elements: Iterator[A] = - if (first == null) Nil.elements else first.elements; - - /** Returns an instance of scala.List containing the same - * sequence of elements. - */ - override def toList: List[A] = if (first == null) Nil else first.toList; - - override protected def stringPrefix: String = "MutableList"; -} diff --git a/sources/scala/collection/mutable/ObservableBuffer.scala b/sources/scala/collection/mutable/ObservableBuffer.scala deleted file mode 100644 index e3439b1dff..0000000000 --- a/sources/scala/collection/mutable/ObservableBuffer.scala +++ /dev/null @@ -1,74 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class is typically used as a mixin. It adds a subscription - * mechanism to the Buffer class into which this abstract - * class is mixed in. Class ObservableBuffer publishes - * events of the type Message. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[_trait_] abstract class ObservableBuffer[A, This <: ObservableBuffer[A, This]]: This - extends Buffer[A] - with Publisher[Message[Pair[Location, A]] with Undoable, This] { - - abstract override def +(element: A): Buffer[A] = { - super.+(element); - publish(new Include(Pair(End, element)) with Undoable { - def undo: Unit = trimEnd(1); - }); - this - } - - abstract override def +:(element: A): Buffer[A] = { - super.+:(element); - publish(new Include(Pair(Start, element)) with Undoable { - def undo: Unit = trimStart(1); - }); - this - } - - abstract override def insertAll(n: Int, iter: Iterable[A]): Unit = { - super.insertAll(n, iter); - var i = n; - val it = iter.elements; - while (it.hasNext) { - publish(new Include(Pair(Index(i), it.next)) with Undoable { - def undo: Unit = remove(i); - }); - i = i + 1; - } - } - - abstract override def update(n: Int, newelement: A): Unit = { - val oldelement = apply(n); - super.update(n, newelement); - publish(new Update(Pair(Index(n), newelement)) with Undoable { - def undo: Unit = update(n, oldelement); - }); - } - - abstract override def remove(n: Int): A = { - val oldelement = apply(n); - super.remove(n); - publish(new Remove(Pair(Index(n), oldelement)) with Undoable { - def undo: Unit = insert(n, oldelement); - }); - oldelement - } - - abstract override def clear: Unit = { - super.clear; - publish(new Reset with Undoable { def undo: Unit = error("cannot undo"); }); - } -} diff --git a/sources/scala/collection/mutable/ObservableMap.scala b/sources/scala/collection/mutable/ObservableMap.scala deleted file mode 100644 index 207a294753..0000000000 --- a/sources/scala/collection/mutable/ObservableMap.scala +++ /dev/null @@ -1,48 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class is typically used as a mixin. It adds a subscription - * mechanism to the Map class into which this abstract - * class is mixed in. Class ObservableMap publishes - * events of the type Message. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[_trait_] abstract class ObservableMap[A, B, This <: ObservableMap[A, B, This]]: This - extends scala.collection.mutable.Map[A, B] - with Publisher[Message[Pair[A, B]] with Undoable, This] { - - abstract override def update(key: A, value: B): Unit = get(key) match { - case None => super.update(key, value); - publish(new Include(Pair(key, value)) with Undoable { - def undo = -=(key); - }); - case Some(old) => super.update(key, value); - publish(new Update(Pair(key, value)) with Undoable { - def undo = update(key, old); - }); - } - - abstract override def -=(key: A): Unit = get(key) match { - case None => - case Some(old) => super.-=(key); - publish(new Remove(Pair(key, old)) with Undoable { - def undo = update(key, old); - }); - } - - abstract override def clear: Unit = { - super.clear; - publish(new Reset with Undoable { def undo: Unit = error("cannot undo"); }); - } -} diff --git a/sources/scala/collection/mutable/ObservableSet.scala b/sources/scala/collection/mutable/ObservableSet.scala deleted file mode 100644 index 656545d78e..0000000000 --- a/sources/scala/collection/mutable/ObservableSet.scala +++ /dev/null @@ -1,39 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class is typically used as a mixin. It adds a subscription - * mechanism to the Set class into which this abstract - * class is mixed in. Class ObservableSet publishes - * events of the type Message. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[_trait_] abstract class ObservableSet[A, This <: ObservableSet[A, This]]: This - extends scala.collection.mutable.Set[A] - with Publisher[Message[A] with Undoable, This] { - - abstract override def +=(elem: A): Unit = if (!contains(elem)) { - super.+=(elem); - publish(new Include(elem) with Undoable { def undo = -=(elem); }); - } - - abstract override def -=(elem: A): Unit = if (contains(elem)) { - super.-=(elem); - publish(new Remove(elem) with Undoable { def undo = +=(elem); }); - } - - abstract override def clear: Unit = { - super.clear; - publish(new Reset with Undoable { def undo: Unit = error("cannot undo"); }); - } -} diff --git a/sources/scala/collection/mutable/PriorityQueue.scala b/sources/scala/collection/mutable/PriorityQueue.scala deleted file mode 100644 index 83552417cc..0000000000 --- a/sources/scala/collection/mutable/PriorityQueue.scala +++ /dev/null @@ -1,180 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class implements priority queues using a heap. The - * elements of the queue have to be ordered in terms of the - * Ordered[T] trait. - * - * @author Matthias Zenger - * @version 1.0, 03/05/2004 - */ -//[serializable, cloneable] -class PriorityQueue[A <% Ordered[A]] extends ResizableArray[A] with java.io.Serializable { - size = size + 1; // we do not use array(0) - - protected def fixUp(as: Array[A], m: Int): Unit = { - var k: Int = m; - while ((k > 1) && (as(k / 2) < as(k))) { - swap(k, k / 2); - k = k / 2; - } - } - - protected def fixDown(as: Array[A], m: Int, n: Int): Unit = { - var k: Int = m; - var loop: Boolean = true; - while (loop && (n >= 2 * k)) { - var j = 2 * k; - if ((j < n) && (as(j) < as(j + 1))) - j = j + 1; - if (!(as(k) < as(j))) - loop = false; - else { - val h = as(k); - as(k) = as(j); - as(j) = h; - k = j; - } - } - } - - /** Checks if the queue is empty. - * - * @return true, iff there is no element in the queue. - */ - def isEmpty: Boolean = size < 2; - - /** Inserts a single element into the priority queue. - * - * @param elem the element to insert - */ - def +=(elem: A): Unit = { - ensureSize(size+1); - array(size) = elem; - fixUp(array, size); - size = size + 1; - } - - /** Adds all elements provided by an Iterable object - * into the priority queue. - * - * @param iter an iterable object - */ - def ++=(iter: Iterable[A]): Unit = this ++= iter.elements; - - /** Adds all elements provided by an iterator into the priority queue. - * - * @param it an iterator - */ - def ++=(it: Iterator[A]): Unit = it foreach { e => this += e }; - - /** Adds all elements to the queue. - * - * @param elems the elements to add. - */ - def enqueue(elems: A*): Unit = (this ++= elems); - - /** Returns the element with the highest priority in the queue, - * and removes this element from the queue. - * - * @return the element with the highest priority. - */ - def dequeue: A = { - if (size > 1) { - size = size - 1; - swap(1, size); - fixDown(array, 1, size - 1); - array(size) - } else - error("no element to remove from heap"); - } - - /** Returns the element with the highest priority in the queue, - * or throws an error if there is no element contained in the queue. - * - * @return the element with the highest priority. - */ - def max: A = if (size > 1) array(1) else error("queue is empty"); - - /** Removes all elements from the queue. After this operation is completed, - * the queue will be empty. - */ - def clear: Unit = { - size = 1; - } - - /** Returns an iterator which yiels all the elements of the priority - * queue in descending priority order. - * - * @return an iterator over all elements sorted in descending order. - */ - override def elements: Iterator[A] = new Iterator[A] { - val as: Array[A] = new Array[A](size); - java.lang.System.arraycopy(array, 0, as, 0, size); - var i = size - 1; - def hasNext: Boolean = i > 0; - def next: A = { - val res = as(1); - as(1) = as(i); - i = i - 1; - fixDown(as, 1, i); - res - } - } - - /** Checks if two queues are structurally identical. - * - * @return true, iff both queues contain the same sequence of elements. - */ - override def equals(that: Any): Boolean = ( - that.isInstanceOf[PriorityQueue[A]] && - { val other = that.asInstanceOf[PriorityQueue[A]]; - elements.zip(other.elements).forall { - case Pair(thiselem, thatelem) => thiselem == thatelem; - }} - ); - - /** The hashCode method always yields an error, since it is not - * safe to use mutable queues as keys in hash tables. - * - * @return never. - */ - override def hashCode(): Int = error("unsuitable as hash key"); - - /** Returns a regular queue containing the same elements. - */ - def toQueue: Queue[A] = { - val res = new Queue[A]; - res ++= this; - res - } - - /** Returns a list of all elements. - */ - def toList: List[A] = elements.toList; - - /** Returns a textual representation of a queue as a string. - * - * @return the string representation of this queue. - */ - override def toString() = toList.mkString("PriorityQueue(", ", ", ")"); - - /** This method clones the priority queue. - * - * @return a priority queue with the same elements. - */ - override def clone(): PriorityQueue[A] = { - val res = new PriorityQueue[A]; - res ++= this; - res - } -} diff --git a/sources/scala/collection/mutable/PriorityQueueProxy.scala b/sources/scala/collection/mutable/PriorityQueueProxy.scala deleted file mode 100644 index e78b98065f..0000000000 --- a/sources/scala/collection/mutable/PriorityQueueProxy.scala +++ /dev/null @@ -1,94 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class implements priority queues using a heap. The - * elements of the queue have to be ordered in terms of the - * Ordered[T] trait. - * - * @author Matthias Zenger - * @version 1.0, 03/05/2004 - */ -abstract class PriorityQueueProxy[A <% Ordered[A]] extends PriorityQueue[A] with IterableProxy[A] { - - def self: PriorityQueue[A]; - - /** Creates a new iterator over all elements contained in this - * object. - * - * @return the new iterator - */ - override def elements: Iterator[A] = self.elements; - - /** Returns the length of this priority queue. - */ - override def length: Int = self.length; - - /** Checks if the queue is empty. - * - * @return true, iff there is no element in the queue. - */ - override def isEmpty: Boolean = self.isEmpty; - - /** Inserts a single element into the priority queue. - * - * @param elem the element to insert - */ - override def +=(elem: A): Unit = self += elem; - - /** Adds all elements provided by an Iterable object - * into the priority queue. - * - * @param iter an iterable object - */ - override def ++=(iter: Iterable[A]): Unit = self ++= iter; - - /** Adds all elements provided by an iterator into the priority queue. - * - * @param it an iterator - */ - override def ++=(it: Iterator[A]): Unit = self ++= it; - - /** Adds all elements to the queue. - * - * @param elems the elements to add. - */ - override def enqueue(elems: A*): Unit = self ++= elems; - - /** Returns the element with the highest priority in the queue, - * and removes this element from the queue. - * - * @return the element with the highest priority. - */ - override def dequeue: A = self.dequeue; - - /** Returns the element with the highest priority in the queue, - * or throws an error if there is no element contained in the queue. - * - * @return the element with the highest priority. - */ - override def max: A = self.max; - - /** Removes all elements from the queue. After this operation is completed, - * the queue will be empty. - */ - override def clear: Unit = self.clear; - - /** Returns a regular queue containing the same elements. - */ - override def toQueue: Queue[A] = self.toQueue; - - /** This method clones the priority queue. - * - * @return a priority queue with the same elements. - */ - override def clone(): PriorityQueue[A] = new PriorityQueueProxy[A] { def self = PriorityQueueProxy.this.self.clone() } -} diff --git a/sources/scala/collection/mutable/Publisher.scala b/sources/scala/collection/mutable/Publisher.scala deleted file mode 100644 index ee442eccd2..0000000000 --- a/sources/scala/collection/mutable/Publisher.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** Publisher[A,This] objects publish events of type A - * to all registered subscribers. When subscribing, a subscriber may specify - * a filter which can be used to constrain the number of events sent to the - * subscriber. Subscribers may suspend their subscription, or reactivate a - * suspended subscription. Class Publisher is typically used - * as a mixin. The type variable This models self types. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[_trait_] abstract class Publisher[A, This <: Publisher[A, This]]: This { - private val filters = new HashMap[Subscriber[A, This], - scala.collection.mutable.Set[A => Boolean]] - with MultiMap[Subscriber[A, This], A => Boolean]; - private val suspended = new HashSet[Subscriber[A, This]]; - - def subscribe(sub: Subscriber[A, This]): Unit = subscribe(sub, (event => true)); - - def subscribe(sub: Subscriber[A, This], filter: A => Boolean): Unit = - filters.add(sub, filter); - - def suspendSubscription(sub: Subscriber[A, This]): Unit = suspended += sub; - - def activateSubscription(sub: Subscriber[A, This]): Unit = suspended -= sub; - - def removeSubscription(sub: Subscriber[A, This]): Unit = filters -= sub; - - def removeSubscriptions: Unit = filters.clear; - - protected def publish(event: A): Unit = - filters.keys.foreach(sub => - if (filters.entryExists(sub, (p => p(event)))) sub.notify(this, event)); -} diff --git a/sources/scala/collection/mutable/Queue.scala b/sources/scala/collection/mutable/Queue.scala deleted file mode 100644 index 0d297f5e0d..0000000000 --- a/sources/scala/collection/mutable/Queue.scala +++ /dev/null @@ -1,194 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** Queue objects implement data structures that allow to - * insert and retrieve elements in a first-in-first-out (FIFO) manner. - * - * @author Matthias Zenger - * @version 1.1, 03/05/2004 - */ -[serializable, cloneable] -class Queue[A] extends MutableList[A] { - - /** Checks if the queue is empty. - * - * @return true, iff there is no element in the queue. - */ - def isEmpty: Boolean = (first == null); - - /** Inserts a single element at the end of the queue. - * - * @param elem the element to insert - */ - def +=(elem: A): Unit = appendElem(elem); - - /** Adds all elements provided by an Iterable object - * at the end of the queue. The elements are prepended in the order they - * are given out by the iterator. - * - * @param iter an iterable object - */ - def ++=(iter: Iterable[A]): Unit = this ++= iter.elements; - - /** Adds all elements provided by an iterator - * at the end of the queue. The elements are prepended in the order they - * are given out by the iterator. - * - * @param it an iterator - */ - def ++=(it: Iterator[A]): Unit = it foreach appendElem; - - /** Adds all elements to the queue. - * - * @param elems the elements to add. - */ - def enqueue(elems: A*): Unit = (this ++= elems); - - /** Returns the first element in the queue, and removes this element - * from the queue. - * - * @return the first element of the queue. - */ - def dequeue: A = { - if (first == null) - error("queue empty"); - else { - val res = first.elem; - first = first.next; - if (first == null) - last = null; - len = len - 1; - res; - } - } - - /** Returns the first element in the queue which satisfies the - * given predicate, and removes this element from the queue. - * - * @param p the predicate used for choosing the first element - * @return the first element of the queue for which p yields true - */ - def dequeueFirst(p: A => Boolean): Option[A] = { - if (first == null) - None - else if (p(first.elem)) { - val res: Option[A] = Some(first.elem); - first = first.next; - len = len - 1; - if (first == null) { - last = null; - } else if (first.next == null) { - last = first; - } - res - } else - extractFirst(first, p) match { - case None => None - case Some(cell) => Some(cell.elem) - } - } - - /** Returns all elements in the queue which satisfy the - * given predicate, and removes those elements from the queue. - * - * @param p the predicate used for choosing elements - * @return a sequence of all elements in the queue for which - * p yields true. - */ - def dequeueAll(p: A => Boolean): Seq[A] = { - val res = new ArrayBuffer[A]; - if (first == null) - res; - else { - while (p(first.elem)) { - res += first.elem; - first = first.next; - len = len - 1; - if (first == null) { - last = null; - } else if (first.next == null) { - last = first; - } - } - var cell: Option[LinkedList[A]] = extractFirst(first, p); - while (!cell.isEmpty) { - res += cell.get.elem; - cell = extractFirst(cell.get, p); - } - res - } - } - - private def extractFirst(start: LinkedList[A], p: A => Boolean): Option[LinkedList[A]] = { - var cell = start; - while ((cell.next != null) && !p(cell.next.elem)) { - cell = cell.next; - } - if (cell.next == null) - None - else { - val res: Option[LinkedList[A]] = Some(cell.next); - cell.next = cell.next.next; - if (cell.next == null) - last = cell; - len = len - 1; - res - } - } - - /** Returns the first element in the queue, or throws an error if there - * is no element contained in the queue. - * - * @return the first element. - */ - def front: A = first.elem; - - /** Removes all elements from the queue. After this operation is completed, - * the queue will be empty. - */ - def clear: Unit = reset; - - /** Checks if two queues are structurally identical. - * - * @return true, iff both queues contain the same sequence of elements. - */ - override def equals(that: Any): Boolean = ( - that.isInstanceOf[Queue[A]] && - { val other = that.asInstanceOf[Queue[A]]; - elements.zip(other.elements).forall { - case Pair(thiselem, thatelem) => thiselem == thatelem; - }} - ); - - /** The hashCode method always yields an error, since it is not - * safe to use mutable queues as keys in hash tables. - * - * @return never. - */ - override def hashCode(): Int = error("unsuitable as hash key"); - - /** Returns a textual representation of a queue as a string. - * - * @return the string representation of this queue. - */ - override def toString() = toList.mkString("Queue(", ", ", ")"); - - /** This method clones the queue. - * - * @return a queue with the same elements. - */ - override def clone(): Queue[A] = { - val res = new Queue[A]; - res ++= this; - res - } -} diff --git a/sources/scala/collection/mutable/QueueProxy.scala b/sources/scala/collection/mutable/QueueProxy.scala deleted file mode 100644 index 65c426a9c2..0000000000 --- a/sources/scala/collection/mutable/QueueProxy.scala +++ /dev/null @@ -1,97 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** Queue objects implement data structures that allow to - * insert and retrieve elements in a first-in-first-out (FIFO) manner. - * - * @author Matthias Zenger - * @version 1.1, 03/05/2004 - */ -trait QueueProxy[A] extends Queue[A] with SeqProxy[A] { - - def self: Queue[A]; - - /** Access element number n. - * - * @return the element at index n. - */ - override def apply(n: Int): A = self.apply(n); - - /** Returns the length of this queue. - */ - override def length: Int = self.length; - - /** Checks if the queue is empty. - * - * @return true, iff there is no element in the queue. - */ - override def isEmpty: Boolean = self.isEmpty; - - /** Inserts a single element at the end of the queue. - * - * @param elem the element to insert - */ - override def +=(elem: A): Unit = self += elem; - - /** Adds all elements provided by an Iterable object - * at the end of the queue. The elements are prepended in the order they - * are given out by the iterator. - * - * @param iter an iterable object - */ - override def ++=(iter: Iterable[A]): Unit = self ++= iter; - - /** Adds all elements provided by an iterator - * at the end of the queue. The elements are prepended in the order they - * are given out by the iterator. - * - * @param iter an iterator - */ - override def ++=(it: Iterator[A]): Unit = self ++= it; - - /** Adds all elements to the queue. - * - * @param elems the elements to add. - */ - override def enqueue(elems: A*): Unit = self ++= elems; - - /** Returns the first element in the queue, and removes this element - * from the queue. - * - * @return the first element of the queue. - */ - override def dequeue: A = self.dequeue; - - /** Returns the first element in the queue, or throws an error if there - * is no element contained in the queue. - * - * @return the first element. - */ - override def front: A = self.front; - - /** Removes all elements from the queue. After this operation is completed, - * the queue will be empty. - */ - override def clear: Unit = self.clear; - - /** Returns an iterator over all elements on the queue. - * - * @return an iterator over all queue elements. - */ - override def elements: Iterator[A] = self.elements; - - /** This method clones the queue. - * - * @return a queue with the same elements. - */ - override def clone(): Queue[A] = new QueueProxy[A] { def self = QueueProxy.this.self.clone() } -} diff --git a/sources/scala/collection/mutable/ResizableArray.scala b/sources/scala/collection/mutable/ResizableArray.scala deleted file mode 100644 index 5f1c5f053c..0000000000 --- a/sources/scala/collection/mutable/ResizableArray.scala +++ /dev/null @@ -1,64 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class is used internally to implement data structures that - * are based on resizable arrays. - * - * @author Matthias Zenger, Burak Emir - * @version 1.0, 03/05/2004 - */ -[serializable] -[_trait_] abstract class ResizableArray[A] extends AnyRef with Iterable[A] { - import scala.runtime.compat.Platform.arraycopy; - - protected val initialSize: Int = 16; - protected var array: Array[A] = new Array[A](initialSize); - protected var size: Int = 0; - - /** ensure that the internal array has at n cells */ - protected def ensureSize(n: Int): Unit = { - if (n > array.length) { - var newsize = array.length * 2; - while( n > newsize ) - newsize = newsize * 2; - val newar: Array[A] = new Array(newsize); - arraycopy(array, 0, newar, 0, size); - array = newar; - } - } - - /** Swap two elements of this array. - */ - protected def swap(a: Int, b: Int): Unit = { - val h = array(a); - array(a) = array(b); - array(b) = h; - } - - /** Move parts of the array. - */ - protected def copy(m: Int, n: Int, len: Int) = { - arraycopy(array, m, array, n, len); - } - - /** Returns the length of this resizable array. - */ - def length: Int = size; - - /** Returns a new iterator over all elements of this resizable array. - */ - def elements: Iterator[A] = new Iterator[A] { - var i = 0; - def hasNext: Boolean = i < size; - def next: A = { i = i + 1; array(i - 1) } - } -} diff --git a/sources/scala/collection/mutable/RevertableHistory.scala b/sources/scala/collection/mutable/RevertableHistory.scala deleted file mode 100644 index c9bb1ef6d1..0000000000 --- a/sources/scala/collection/mutable/RevertableHistory.scala +++ /dev/null @@ -1,31 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** A revertable history is a History object which supports - * an undo operation. Type variable A refers to the type - * of the published events, B denotes the publisher type. - * Type B is typically a subtype of Publisher. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[serializable] -class RevertableHistory[A <: Undoable, B] extends History[A, B] with Undoable { - - /** Rollback the full history. - */ - def undo: Unit = { - val old = log.toList.reverse; - clear; - old.foreach { case Pair(sub, event) => event.undo; } - } -} diff --git a/sources/scala/collection/mutable/Scriptable.scala b/sources/scala/collection/mutable/Scriptable.scala deleted file mode 100644 index 448109bde3..0000000000 --- a/sources/scala/collection/mutable/Scriptable.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** Classes that implement the Scriptable trait allow - * messages to be sent to objects of that class. - * - * @author Matthias Zenger - * @version 1.0, 09/05/2004 - */ -trait Scriptable[A] { - - /** Send a message to this scriptable object. - */ - def <<(cmd: A): Unit; -} diff --git a/sources/scala/collection/mutable/Set.scala b/sources/scala/collection/mutable/Set.scala deleted file mode 100644 index d493ee1560..0000000000 --- a/sources/scala/collection/mutable/Set.scala +++ /dev/null @@ -1,111 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This trait represents mutable sets. Concrete set implementations - * just have to provide functionality for the abstract methods in - * scala.collection.Set as well as for add, - * remove, and clear. - * - * @author Matthias Zenger - * @version 1.1, 09/05/2004 - */ -[cloneable] -trait Set[A] extends AnyRef with scala.collection.Set[A] with Scriptable[Message[A]] { - - /** This method allows one to add or remove an element elem - * from this set depending on the value of parameter included. - * Typically, one would use the following syntax: - *
set(elem) = true
- */ - def update(elem: A, included: Boolean): Unit = - if (included) +=(elem) else -=(elem); - - /** This method adds a new element to the set. - */ - def +=(elem: A): Unit; - - /** This method will add all the elements provided by an iterator - * of the iterable object that to the set. - */ - def ++=(that: Iterable[A]): Unit = ++=(that.elements); - - /** This method will add all the elements provided by an iterator - * of the iterable object that to the set. - */ - def ++=(it: Iterator[A]): Unit = it foreach +=; - - /** incl can be used to add many elements to the set - * at the same time. - */ - def incl(elems: A*): Unit = ++=(elems.elements); - - /** -= can be used to remove a single element from - * a set. - */ - def -=(elem: A): Unit; - - /** This method removes all the elements provided by the - * the iterable object that from the set. - */ - def --=(that: Iterable[A]): Unit = --=(that.elements); - - /** This method removes all the elements provided by an iterator - * it from the set. - */ - def --=(it: Iterator[A]): Unit = it foreach -=; - - /** excl removes many elements from the set. - */ - def excl(elems: A*): Unit = --=(elems.elements); - - /** This method computes an intersection with set that. - * It removes all the elements that are not present in that. - */ - def intersect(that: Set[A]): Unit = filter(that.contains); - - /** Method filter removes all elements from the set for - * which the predicate p yields the value false. - */ - def filter(p: A => Boolean): Unit = toList.foreach { - elem => if (!p(elem)) -=(elem); - } - - /** Removes all elements from the set. After this operation is completed, - * the set will be empty. - */ - def clear: Unit; - - /** Send a message to this scriptable object. - * - * @param cmd the message to send. - */ - def <<(cmd: Message[A]): Unit = cmd match { - case Include(elem) => this += elem; - case Remove(elem) => this -= elem; - case Reset() => clear; - case s: Script[A] => s.elements foreach <<; - case _ => error("message " + cmd + " not understood"); - } - - /** Return a clone of this set. - * - * @return a set with the same elements. - */ - override def clone(): Set[A] = super.clone().asInstanceOf[Set[A]]; - - /** The hashCode method always yields an error, since it is not - * safe to use mutable stacks as keys in hash tables. - * - * @return never. - */ - override def hashCode(): Int = error("unsuitable as hash key"); -} diff --git a/sources/scala/collection/mutable/SetProxy.scala b/sources/scala/collection/mutable/SetProxy.scala deleted file mode 100644 index 4cd759a60d..0000000000 --- a/sources/scala/collection/mutable/SetProxy.scala +++ /dev/null @@ -1,51 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This is a simple wrapper class for scala.collection.mutable.Set. - * It is most useful for assembling customized set abstractions - * dynamically using object composition and forwarding. - * - * @author Matthias Zenger - * @version 1.1, 09/05/2004 - */ -trait SetProxy[A] extends Set[A] with scala.collection.SetProxy[A] { - - def self: Set[A]; - - override def update(elem: A, included: Boolean): Unit = self(elem) = included; - - def +=(elem: A): Unit = self += elem; - - override def ++=(that: Iterable[A]): Unit = self ++= that; - - override def ++=(it: Iterator[A]): Unit = self ++= it; - - override def incl(elems: A*): Unit = self ++= elems; - - def -=(elem: A): Unit = self -= elem; - - override def --=(that: Iterable[A]): Unit = self --= that; - - override def --=(it: Iterator[A]): Unit = self --= it; - - override def excl(elems: A*): Unit = self --= elems; - - override def intersect(that: Set[A]): Unit = self.intersect(that); - - def clear: Unit = self.clear; - - override def filter(p: A => Boolean): Unit = self.filter(p); - - override def <<(cmd: Message[A]): Unit = self << cmd; - - override def clone(): Set[A] = new SetProxy[A] { def self = SetProxy.this.self.clone() } -} diff --git a/sources/scala/collection/mutable/SingleLinkedList.scala b/sources/scala/collection/mutable/SingleLinkedList.scala deleted file mode 100644 index b60d32ba1b..0000000000 --- a/sources/scala/collection/mutable/SingleLinkedList.scala +++ /dev/null @@ -1,63 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This extensible class may be used as a basis for implementing linked - * list. Type variable A refers to the element type of the - * list, type variable This is used to model self types of - * linked lists. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -[serializable] -abstract class SingleLinkedList[A, This <: SingleLinkedList[A, This]]: This extends AnyRef with Seq[A] { - - var elem: A = _; - - var next: This = _; - - def length: Int = 1 + (if (next == null) 0 else next.length); - - def append(that: This): Unit = - if (next == null) { next = that; } else next.append(that); - - def insert(that: This): Unit = if (that != null) { - that.append(next); - next = that; - } - - def apply(n: Int): A = { - if (n == 0) elem - else if (next == null) error("unknown element") - else next.apply(n - 1); - } - - def get(n: Int): Option[A] = { - if (n == 0) Some(elem) - else if (next == null) None - else next.get(n - 1); - } - - def elements: Iterator[A] = new Iterator[A] { - var elems = SingleLinkedList.this; - def hasNext = (elems != null); - def next = { - val res = elems.elem; - elems = elems.next; - res; - } - } - - override def toList: List[A] = - if (next == null) (elem :: Nil) else (elem :: next.toList); - -} diff --git a/sources/scala/collection/mutable/Stack.scala b/sources/scala/collection/mutable/Stack.scala deleted file mode 100644 index 0cf269dba7..0000000000 --- a/sources/scala/collection/mutable/Stack.scala +++ /dev/null @@ -1,132 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** A stack implements a data structure which allows to store and retrieve - * objects in a last-in-first-out (LIFO) fashion. - * - * @author Matthias Zenger - * @version 1.1, 03/05/2004 - */ -[serializable, cloneable] -class Stack[A] extends MutableList[A] { - - /** Checks if the stack is empty. - * - * @return true, iff there is no element on the stack - */ - def isEmpty: Boolean = (first == null); - - /** Pushes a single element on top of the stack. - * - * @param elem the element to push onto the stack - */ - def +=(elem: A): Unit = prependElem(elem); - - /** Pushes all elements provided by an Iterable object - * on top of the stack. The elements are pushed in the order they - * are given out by the iterator. - * - * @param iter an iterable object - */ - def ++=(iter: Iterable[A]): Unit = this ++= iter.elements; - - /** Pushes all elements provided by an iterator - * on top of the stack. The elements are pushed in the order they - * are given out by the iterator. - * - * @param iter an iterator - */ - def ++=(it: Iterator[A]): Unit = it foreach { e => prependElem(e) }; - - /** Pushes a sequence of elements on top of the stack. The first element - * is pushed first, etc. - * - * @param elems a sequence of elements - */ - def push(elems: A*): Unit = (this ++= elems); - - /** Returns the top element of the stack. This method will not remove - * the element from the stack. An error is signaled if there is no - * element on the stack. - * - * @return the top element - */ - def top: A = if (first == null) error("stack empty"); else first.elem; - - /** Removes the top element from the stack. - */ - def pop: A = - if (first != null) { - val res = first.elem; - first = first.next; - len = len - 1; - res - } else - error("stack empty"); - - /** - * Removes all elements from the stack. After this operation completed, - * the stack will be empty. - */ - def clear: Unit = reset; - - /** Returns an iterator over all elements on the stack. This iterator - * is stable with respect to state changes in the stack object; i.e. - * such changes will not be reflected in the iterator. The iterator - * issues elements in the order they were inserted into the stack - * (FIFO order). - * - * @return an iterator over all stack elements. - */ - override def elements: Iterator[A] = toList.elements; - - /** Creates a list of all stack elements in FIFO order. - * - * @return the created list. - */ - override def toList: List[A] = super[MutableList].toList.reverse; - - /** Checks if two stacks are structurally identical. - * - * @return true, iff both stacks contain the same sequence of elements. - */ - override def equals(that: Any): Boolean = ( - that.isInstanceOf[Stack[A]] && - { val other = that.asInstanceOf[Stack[A]]; - elements.zip(other.elements).forall { - case Pair(thiselem, thatelem) => thiselem == thatelem; - }} - ); - - /** The hashCode method always yields an error, since it is not - * safe to use mutable stacks as keys in hash tables. - * - * @return never. - */ - override def hashCode(): Int = error("unsuitable as hash key"); - - /** Returns a textual representation of a stack as a string. - * - * @return the string representation of this stack. - */ - override def toString(): String = toList.mkString("Stack(", ", ", ")"); - - /** This method clones the stack. - * - * @return a stack with the same elements. - */ - override def clone(): Stack[A] = { - val res = new Stack[A]; - res ++= this; - res - } -} diff --git a/sources/scala/collection/mutable/StackProxy.scala b/sources/scala/collection/mutable/StackProxy.scala deleted file mode 100644 index cfca6ca56c..0000000000 --- a/sources/scala/collection/mutable/StackProxy.scala +++ /dev/null @@ -1,108 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** A stack implements a data structure which allows to store and retrieve - * objects in a last-in-first-out (LIFO) fashion. - * - * @author Matthias Zenger - * @version 1.0, 10/05/2004 - */ -trait StackProxy[A] extends Stack[A] with SeqProxy[A] { - - def self: Stack[A]; - - /** Access element number n. - * - * @return the element at index n. - */ - override def apply(n: Int): A = self.apply(n); - - /** Returns the length of this stack. - */ - override def length: Int = self.length; - - /** Checks if the stack is empty. - * - * @return true, iff there is no element on the stack - */ - override def isEmpty: Boolean = self.isEmpty; - - /** Pushes a single element on top of the stack. - * - * @param elem the element to push onto the stack - */ - override def +=(elem: A): Unit = self += elem; - - /** Pushes all elements provided by an Iterable object - * on top of the stack. The elements are pushed in the order they - * are given out by the iterator. - * - * @param iter an iterable object - */ - override def ++=(iter: Iterable[A]): Unit = self ++= iter; - - - /** Pushes all elements provided by an iterator - * on top of the stack. The elements are pushed in the order they - * are given out by the iterator. - * - * @param iter an iterator - */ - override def ++=(it: Iterator[A]): Unit = self ++= it; - - /** Pushes a sequence of elements on top of the stack. The first element - * is pushed first, etc. - * - * @param elems a sequence of elements - */ - override def push(elems: A*): Unit = self ++= elems; - - /** Returns the top element of the stack. This method will not remove - * the element from the stack. An error is signaled if there is no - * element on the stack. - * - * @return the top element - */ - override def top: A = self.top; - - /** Removes the top element from the stack. - */ - override def pop: A = self.pop; - - /** - * Removes all elements from the stack. After this operation completed, - * the stack will be empty. - */ - override def clear: Unit = self.clear; - - /** Returns an iterator over all elements on the stack. This iterator - * is stable with respect to state changes in the stack object; i.e. - * such changes will not be reflected in the iterator. The iterator - * issues elements in the order they were inserted into the stack - * (FIFO order). - * - * @return an iterator over all stack elements. - */ - override def elements: Iterator[A] = self.elements; - - /** Creates a list of all stack elements in FIFO order. - * - * @return the created list. - */ - override def toList: List[A] = self.toList; - - /** This method clones the stack. - * - * @return a stack with the same elements. - */ - override def clone(): Stack[A] = new StackProxy[A] { def self = StackProxy.this.self.clone() } -} diff --git a/sources/scala/collection/mutable/Subscriber.scala b/sources/scala/collection/mutable/Subscriber.scala deleted file mode 100644 index 30ca2d03e2..0000000000 --- a/sources/scala/collection/mutable/Subscriber.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** Subscriber[A, B] objects may subscribe to events of - * type A published by an object of type B. - * B is typically a subtype of Publisher. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -trait Subscriber[-A, -B] { - def notify(pub: B, event: A): Unit; -} diff --git a/sources/scala/collection/mutable/SynchronizedBuffer.scala b/sources/scala/collection/mutable/SynchronizedBuffer.scala deleted file mode 100644 index e15c59b4b4..0000000000 --- a/sources/scala/collection/mutable/SynchronizedBuffer.scala +++ /dev/null @@ -1,189 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This trait should be used as a mixin. It synchronizes the Buffer - * methods of the class into which it is mixed in. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -trait SynchronizedBuffer[A] extends Buffer[A] { - - abstract override def length: Int = synchronized { - super.length; - } - - abstract override def elements: Iterator[A] = synchronized { - super.elements; - } - - abstract override def apply(n: Int): A = synchronized { - super.apply(n); - } - - /** Append a single element to this buffer and return - * the identity of the buffer. - * - * @param elem the element to append. - */ - abstract override def +(elem: A): Buffer[A] = synchronized { - super.+(elem); - } - - /** Append a single element to this buffer. - * - * @param elem the element to append. - */ - override def +=(elem: A): Unit = synchronized { - super.+=(elem); - } - - /** Appends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - override def ++(iter: Iterable[A]): Buffer[A] = synchronized { - super.++(iter); - } - - /** Appends a number of elements provided by an iterable object - * via its elements method. - * - * @param iter the iterable object. - */ - override def ++=(iter: Iterable[A]): Unit = synchronized { - super.++=(iter); - } - - /** Appends a sequence of elements to this buffer. - * - * @param elems the elements to append. - */ - override def append(elems: A*): Unit = synchronized { - super.++=(elems); - } - - /** Appends a number of elements provided by an iterable object - * via its elements method. - * - * @param iter the iterable object. - */ - override def appendAll(iter: Iterable[A]): Unit = synchronized { - super.appendAll(iter); - } - - /** Prepend a single element to this buffer and return - * the identity of the buffer. - * - * @param elem the element to append. - */ - abstract override def +:(elem: A): Buffer[A] = synchronized { - super.+:(elem); - } - - /** Prepends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - override def ++:(iter: Iterable[A]): Buffer[A] = synchronized { - super.++:(iter); - } - - /** Prepend an element to this list. - * - * @param elem the element to prepend. - */ - override def prepend(elems: A*): Unit = synchronized { - super.prependAll(elems); - } - - /** Prepends a number of elements provided by an iterable object - * via its elements method. The identity of the - * buffer is returned. - * - * @param iter the iterable object. - */ - override def prependAll(elems: Iterable[A]): Unit = synchronized { - super.prependAll(elems); - } - - /** Inserts new elements at the index n. Opposed to method - * update, this method will not replace an element with a - * one. Instead, it will insert the new elements at index n. - * - * @param n the index where a new element will be inserted. - * @param elems the new elements to insert. - */ - override def insert(n: Int, elems: A*): Unit = synchronized { - super.insertAll(n, elems); - } - - /** Inserts new elements at the index n. Opposed to method - * update, this method will not replace an element with a - * one. Instead, it will insert a new element at index n. - * - * @param n the index where a new element will be inserted. - * @param iter the iterable object providing all elements to insert. - */ - abstract override def insertAll(n: Int, iter: Iterable[A]): Unit = synchronized { - super.insertAll(n, iter); - } - - /** Replace element at index n with the new element - * newelem. - * - * @param n the index of the element to replace. - * @param newelem the new element. - */ - abstract override def update(n: Int, newelem: A): Unit = synchronized { - super.update(n, newelem); - } - - /** Removes the element on a given index position. - * - * @param n the index which refers to the element to delete. - */ - abstract override def remove(n: Int): A = synchronized { - super.remove(n); - } - - /** Clears the buffer contents. - */ - abstract override def clear: Unit = synchronized { - super.clear; - } - - override def <<(cmd: Message[Pair[Location, A]]): Unit = synchronized { - super.<<(cmd); - } - - /** Return a clone of this buffer. - * - * @return an ArrayBuffer with the same elements. - */ - override def clone(): Buffer[A] = synchronized { - super.clone(); - } - - /** The hashCode method always yields an error, since it is not - * safe to use buffers as keys in hash tables. - * - * @return never. - */ - override def hashCode(): Int = synchronized { - super.hashCode(); - } -} diff --git a/sources/scala/collection/mutable/SynchronizedMap.scala b/sources/scala/collection/mutable/SynchronizedMap.scala deleted file mode 100644 index b0db7078de..0000000000 --- a/sources/scala/collection/mutable/SynchronizedMap.scala +++ /dev/null @@ -1,116 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This trait should be used as a mixin. It synchronizes the Map - * functions of the class into which it is mixed in. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -trait SynchronizedMap[A, B] extends scala.collection.mutable.Map[A, B] { - - abstract override def size: Int = synchronized { - super.size; - } - - abstract override def get(key: A): Option[B] = synchronized { - super.get(key); - } - - override def isEmpty: Boolean = synchronized { - super.isEmpty; - } - - override def apply(key: A): B = synchronized { - super.apply(key); - } - - override def contains(key: A): Boolean = synchronized { - super.contains(key); - } - - override def isDefinedAt(key: A) = synchronized { - super.isDefinedAt(key); - } - - override def keys: Iterator[A] = synchronized { - super.keys; - } - - override def values: Iterator[B] = synchronized { - super.values; - } - - override def foreach(f: (A, B) => Unit) = synchronized { - super.foreach(f); - } - - override def toList: List[Pair[A, B]] = synchronized { - super.toList; - } - - abstract override def update(key: A, value: B): Unit = synchronized { - super.update(key, value); - } - - override def ++=(map: Iterable[Pair[A, B]]): Unit = synchronized { - super.++=(map); - } - - override def ++=(it: Iterator[Pair[A, B]]): Unit = synchronized { - super.++=(it); - } - - override def incl(mappings: Pair[A, B]*): Unit = synchronized { - super.++=(mappings); - } - - abstract override def -=(key: A): Unit = synchronized { - super.-=(key); - } - - override def --=(keys: Iterable[A]): Unit = synchronized { - super.--=(keys); - } - - override def --=(it: Iterator[A]): Unit = synchronized { - super.--=(it); - } - - override def excl(keys: A*): Unit = synchronized { - super.--=(keys); - } - - override def clear: Unit = synchronized { - super.clear; - } - - override def map(f: (A, B) => B): Unit = synchronized { - super.map(f); - } - - override def filter(p: (A, B) => Boolean): Unit = synchronized { - super.filter(p); - } - - override def toString() = synchronized { - super.toString(); - } - - override def <<(cmd: Message[Pair[A, B]]): Unit = synchronized { - super.<<(cmd); - } - - override def clone(): Map[A, B] = synchronized { - super.clone(); - } -} diff --git a/sources/scala/collection/mutable/SynchronizedPriorityQueue.scala b/sources/scala/collection/mutable/SynchronizedPriorityQueue.scala deleted file mode 100644 index 8b3078e74b..0000000000 --- a/sources/scala/collection/mutable/SynchronizedPriorityQueue.scala +++ /dev/null @@ -1,97 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This class implements synchronized priority queues using a heap. - * The elements of the queue have to be ordered in terms of the - * Ordered[T] trait. - * - * @author Matthias Zenger - * @version 1.0, 03/05/2004 - */ -class SynchronizedPriorityQueue[A <% Ordered[A]] extends PriorityQueue[A] { - - /** Checks if the queue is empty. - * - * @return true, iff there is no element in the queue. - */ - override def isEmpty: Boolean = synchronized { super.isEmpty; } - - /** Inserts a single element into the priority queue. - * - * @param elem the element to insert - */ - override def +=(elem: A): Unit = synchronized { super.+=(elem); } - - /** Adds all elements provided by an Iterable object - * into the priority queue. - * - * @param iter an iterable object - */ - override def ++=(iter: Iterable[A]): Unit = synchronized { super.++=(iter); } - - /** Adds all elements provided by an iterator into the priority queue. - * - * @param it an iterator - */ - override def ++=(it: Iterator[A]): Unit = synchronized { super.++=(it); } - - /** Adds all elements to the queue. - * - * @param elems the elements to add. - */ - override def enqueue(elems: A*): Unit = synchronized { super.++=(elems); } - - /** Returns the element with the highest priority in the queue, - * and removes this element from the queue. - * - * @return the element with the highest priority. - */ - override def dequeue: A = synchronized { super.dequeue; } - - /** Returns the element with the highest priority in the queue, - * or throws an error if there is no element contained in the queue. - * - * @return the element with the highest priority. - */ - override def max: A = synchronized { super.max; } - - /** Removes all elements from the queue. After this operation is completed, - * the queue will be empty. - */ - override def clear: Unit = synchronized { super.clear; } - - /** Returns an iterator which yiels all the elements of the priority - * queue in descending priority order. - * - * @return an iterator over all elements sorted in descending order. - */ - override def elements: Iterator[A] = synchronized { super.elements; } - - /** Checks if two queues are structurally identical. - * - * @return true, iff both queues contain the same sequence of elements. - */ - override def equals(that: Any): Boolean = synchronized { super.equals(that); } - - /** The hashCode method always yields an error, since it is not - * safe to use mutable queues as keys in hash tables. - * - * @return never. - */ - override def hashCode(): Int = synchronized { super.hashCode(); } - - /** Returns a textual representation of a queue as a string. - * - * @return the string representation of this queue. - */ - override def toString(): String = synchronized { super.toString(); } -} diff --git a/sources/scala/collection/mutable/SynchronizedQueue.scala b/sources/scala/collection/mutable/SynchronizedQueue.scala deleted file mode 100644 index 74fb9782b5..0000000000 --- a/sources/scala/collection/mutable/SynchronizedQueue.scala +++ /dev/null @@ -1,93 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This is a synchronized version of the Queue[T] class. It - * implements a data structure that allows one to insert and retrieve - * elements in a first-in-first-out (FIFO) manner. - * - * @author Matthias Zenger - * @version 1.0, 03/05/2004 - */ -class SynchronizedQueue[A] extends Queue[A] { - - /** Checks if the queue is empty. - * - * @return true, iff there is no element in the queue. - */ - override def isEmpty: Boolean = synchronized { super.isEmpty; } - - /** Inserts a single element at the end of the queue. - * - * @param elem the element to insert - */ - override def +=(elem: A): Unit = synchronized { super.+=(elem); } - - /** Adds all elements provided by an Iterable object - * at the end of the queue. The elements are prepended in the order they - * are given out by the iterator. - * - * @param iter an iterable object - */ - override def ++=(iter: Iterable[A]): Unit = synchronized { super.++=(iter); } - - /** Adds all elements provided by an iterator - * at the end of the queue. The elements are prepended in the order they - * are given out by the iterator. - * - * @param it an iterator - */ - override def ++=(it: Iterator[A]): Unit = synchronized { super.++=(it); } - - /** Adds all elements to the queue. - * - * @param elems the elements to add. - */ - override def enqueue(elems: A*): Unit = synchronized { super.++=(elems); } - - /** Returns the first element in the queue, and removes this element - * from the queue. - * - * @return the first element of the queue. - */ - override def dequeue: A = synchronized { super.dequeue; } - - /** Returns the first element in the queue, or throws an error if there - * is no element contained in the queue. - * - * @return the first element. - */ - override def front: A = synchronized { super.front; } - - /** Removes all elements from the queue. After this operation is completed, - * the queue will be empty. - */ - override def clear: Unit = synchronized { super.clear; } - - /** Checks if two queues are structurally identical. - * - * @return true, iff both queues contain the same sequence of elements. - */ - override def equals(that: Any): Boolean = synchronized { super.equals(that); } - - /** The hashCode method always yields an error, since it is not - * safe to use mutable queues as keys in hash tables. - * - * @return never. - */ - override def hashCode(): Int = synchronized { super.hashCode(); } - - /** Returns a textual representation of a queue as a string. - * - * @return the string representation of this queue. - */ - override def toString() = synchronized { super.toString(); } -} diff --git a/sources/scala/collection/mutable/SynchronizedSet.scala b/sources/scala/collection/mutable/SynchronizedSet.scala deleted file mode 100644 index 743a5a85c4..0000000000 --- a/sources/scala/collection/mutable/SynchronizedSet.scala +++ /dev/null @@ -1,104 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This trait should be used as a mixin. It synchronizes the Set - * functions of the class into which it is mixed in. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -trait SynchronizedSet[A] extends scala.collection.mutable.Set[A] { - - abstract override def size: Int = synchronized { - super.size - } - - override def isEmpty: Boolean = synchronized { - super.isEmpty - } - - abstract override def contains(elem: A) = synchronized { - super.contains(elem); - } - - abstract override def update(elem: A, included: Boolean): Unit = synchronized { - super.update(elem, included); - } - - abstract override def +=(elem: A): Unit = synchronized { - super.+=(elem); - } - - override def ++=(that: Iterable[A]) = synchronized { - super.++=(that); - } - - override def ++=(it: Iterator[A]) = synchronized { - super.++=(it); - } - - override def incl(elems: A*): Unit = synchronized { - super.++=(elems); - } - - abstract override def -=(elem: A): Unit = synchronized { - super.-=(elem); - } - - override def --=(that: Iterable[A]) = synchronized { - super.--=(that); - } - - override def --=(it: Iterator[A]) = synchronized { - super.--=(it); - } - - override def excl(elems: A*): Unit = synchronized { - super.--=(elems); - } - - override def intersect(that: Set[A]) = synchronized { - super.intersect(that); - } - - abstract override def clear: Unit = synchronized { - super.clear; - } - - override def subsetOf(that: scala.collection.Set[A]) = synchronized { - super.subsetOf(that); - } - - override def foreach(f: A => Unit) = synchronized { - super.foreach(f); - } - - override def filter(p: A => Boolean) = synchronized { - super.filter(p); - } - - override def toList: List[A] = synchronized { - super.toList; - } - - override def toString() = synchronized { - super.toString(); - } - - override def <<(cmd: Message[A]): Unit = synchronized { - super.<<(cmd); - } - - override def clone(): Set[A] = synchronized { - super.clone(); - } -} diff --git a/sources/scala/collection/mutable/SynchronizedStack.scala b/sources/scala/collection/mutable/SynchronizedStack.scala deleted file mode 100644 index c21a17b22d..0000000000 --- a/sources/scala/collection/mutable/SynchronizedStack.scala +++ /dev/null @@ -1,109 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** This is a synchronized version of the Stack[T] class. It - * implements a data structure which allows to store and retrieve - * objects in a last-in-first-out (LIFO) fashion. - * - * @author Matthias Zenger - * @version 1.0, 03/05/2004 - */ -class SynchronizedStack[A] extends Stack[A] { - - /** Checks if the stack is empty. - * - * @return true, iff there is no element on the stack - */ - override def isEmpty: Boolean = synchronized { super.isEmpty } - - /** Pushes a single element on top of the stack. - * - * @param elem the element to push onto the stack - */ - override def +=(elem: A): Unit = synchronized { super.+=(elem); } - - /** Pushes all elements provided by an Iterable object - * on top of the stack. The elements are pushed in the order they - * are given out by the iterator. - * - * @param iter an iterable object - */ - override def ++=(iter: Iterable[A]): Unit = synchronized { super.++=(iter); } - - /** Pushes all elements provided by an iterator - * on top of the stack. The elements are pushed in the order they - * are given out by the iterator. - * - * @param iter an iterator - */ - override def ++=(it: Iterator[A]): Unit = synchronized { super.++=(it); } - - /** Pushes a sequence of elements on top of the stack. The first element - * is pushed first, etc. - * - * @param elems a sequence of elements - */ - override def push(elems: A*): Unit = synchronized { super.++=(elems); } - - /** Returns the top element of the stack. This method will not remove - * the element from the stack. An error is signaled if there is no - * element on the stack. - * - * @return the top element - */ - override def top: A = synchronized { super.top; } - - /** Removes the top element from the stack. - */ - override def pop: A = synchronized { super.pop; } - - /** - * Removes all elements from the stack. After this operation completed, - * the stack will be empty. - */ - override def clear: Unit = synchronized { super.clear; } - - /** Returns an iterator over all elements on the stack. This iterator - * is stable with respect to state changes in the stack object; i.e. - * such changes will not be reflected in the iterator. The iterator - * issues elements in the order they were inserted into the stack - * (FIFO order). - * - * @return an iterator over all stack elements. - */ - override def elements: Iterator[A] = synchronized { super.elements; } - - /** Creates a list of all stack elements in FIFO order. - * - * @return the created list. - */ - override def toList: List[A] = synchronized { super.toList; } - - /** Checks if two stacks are structurally identical. - * - * @return true, iff both stacks contain the same sequence of elements. - */ - override def equals(that: Any): Boolean = synchronized { super.equals(that); } - - /** The hashCode method always yields an error, since it is not - * safe to use mutable stacks as keys in hash tables. - * - * @return never. - */ - override def hashCode(): Int = synchronized { super.hashCode(); } - - /** Returns a textual representation of a stack as a string. - * - * @return the string representation of this stack. - */ - override def toString() = synchronized { super.toString(); } -} diff --git a/sources/scala/collection/mutable/Undoable.scala b/sources/scala/collection/mutable/Undoable.scala deleted file mode 100644 index 62e7335411..0000000000 --- a/sources/scala/collection/mutable/Undoable.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.collection.mutable; - - -/** Classes that implement the Undoable trait provide an operation - * undo which can be used to undo the last operation. - * - * @author Matthias Zenger - * @version 1.0, 08/07/2003 - */ -trait Undoable { - - /** Undo the last operation. - */ - def undo: Unit; -} diff --git a/sources/scala/concurrent/Actor.scala b/sources/scala/concurrent/Actor.scala deleted file mode 100644 index 4ba4ab3078..0000000000 --- a/sources/scala/concurrent/Actor.scala +++ /dev/null @@ -1,29 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.concurrent; - -abstract class Actor extends Thread { - private val in = new MailBox; - - def send(msg: in.Message) = - in.send(msg); - - def receive[a](f: PartialFunction[in.Message, a]): a = - if (Thread.currentThread() == this) in.receive(f); - else error("receive called not on own process"); - - def receiveWithin[a](msec: long)(f: PartialFunction[in.Message, a]): a = - if (Thread.currentThread() == this) in.receiveWithin(msec)(f); - else error("receiveWithin called not on own process"); -} - - - diff --git a/sources/scala/concurrent/Channel.scala b/sources/scala/concurrent/Channel.scala deleted file mode 100644 index a57fd7f530..0000000000 --- a/sources/scala/concurrent/Channel.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.concurrent; - -class Channel[a] { - class LinkedList[a] { - var elem: a = _; - var next: LinkedList[a] = null; - } - private var written = new LinkedList[a]; // FIFO buffer, realized through - private var lastWritten = written; // aliasing of a linked list - private var nreaders = 0; - - def write(x: a) = synchronized { - lastWritten.elem = x; - lastWritten.next = new LinkedList[a]; - lastWritten = lastWritten.next; - if (nreaders > 0) notify(); - } - - def read: a = synchronized { - if (written.next == null) { - nreaders = nreaders + 1; wait(); nreaders = nreaders - 1; - } - val x = written.elem; - written = written.next; - x - } -} diff --git a/sources/scala/concurrent/Lock.scala b/sources/scala/concurrent/Lock.scala deleted file mode 100644 index a473c358c8..0000000000 --- a/sources/scala/concurrent/Lock.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.concurrent; - -class Lock { - var available = true; - def acquire = synchronized { - if (!available) wait(); - available = false - } - def release = synchronized { - available = true; - notify() - } -} diff --git a/sources/scala/concurrent/MailBox.scala b/sources/scala/concurrent/MailBox.scala deleted file mode 100644 index 427d424b28..0000000000 --- a/sources/scala/concurrent/MailBox.scala +++ /dev/null @@ -1,170 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.concurrent; - - -//class MailBox with Monitor with LinkedListQueueCreator { -class MailBox extends AnyRef with ListQueueCreator { - - type Message = AnyRef; - - private abstract class PreReceiver { - var msg: Message = null; - def isDefinedAt(msg: Message): boolean; - } - - private class Receiver[a](receiver: PartialFunction[Message, a]) extends PreReceiver { - - def isDefinedAt(msg: Message) = receiver.isDefinedAt(msg); - - def receive(): a = synchronized { - if (msg == null) wait(); - receiver(msg) - } - - def receiveWithin(msec: long): a = synchronized { - if (msg == null) wait(msec); - receiver(if (msg != null) msg else TIMEOUT()) - } - } - - private val messageQueue = queueCreate[Message]; - private val receiverQueue = queueCreate[PreReceiver]; - - /** Unconsumed messages. */ - private var sent = messageQueue.make; - - /** Pending receivers. */ - private var receivers = receiverQueue.make; - - /** - * Check whether the receiver can be applied to an unconsumed message. - * If yes, the message is extracted and associated with the receiver. - * Otherwise the receiver is appended to the list of pending receivers. - */ - private def scanSentMsgs[a](receiver: Receiver[a]): unit = synchronized { - messageQueue.extractFirst(sent, msg => receiver.isDefinedAt(msg)) match { - case None => receivers = receiverQueue.append(receivers, receiver) - case Some(Pair(msg, withoutMsg)) => { - sent = withoutMsg; - receiver.msg = msg - } - } - } - - /** - * First check whether a pending receiver is applicable to the sent - * message. If yes, the receiver is notified. Otherwise the message - * is appended to the linked list of sent messages. - */ - def send(msg: Message): unit = synchronized { - receiverQueue.extractFirst(receivers, r => r.isDefinedAt(msg)) match { - case None => sent = messageQueue.append(sent, msg) - case Some(Pair(receiver, withoutReceiver)) => { - receivers = withoutReceiver; - receiver.msg = msg; - receiver synchronized { receiver.notify() }; - } - } - } - - /** - * Block until there is a message in the mailbox for which the processor - * f is defined. - */ - def receive[a](f: PartialFunction[Message, a]): a = { - val r = new Receiver(f); - scanSentMsgs(r); - r.receive() - } - - /** - * Block until there is a message in the mailbox for which the processor - * f is defined or the timeout is over. - */ - def receiveWithin[a](msec: long)(f: PartialFunction[Message, a]): a = { - val r = new Receiver(f); - scanSentMsgs(r); - r.receiveWithin(msec) - } - -} - -///////////////////////////////////////////////////////////////// - -/** -* Module for dealing with queues. -*/ -trait QueueModule[a] { - /** Type of queues. */ - type t; - /** Create an empty queue. */ - def make: t; - /** Append an element to a queue. */ - def append(l: t, x: a): t; - /** Extract an element satisfying a predicate from a queue. */ - def extractFirst(l: t, p: a => boolean): Option[Pair[a, t]]; -} - -/** Inefficient but simple queue module creator. */ -trait ListQueueCreator { - def queueCreate[a]: QueueModule[a] = new QueueModule[a] { - type t = List[a]; - def make: t = Nil; - def append(l: t, x: a): t = l ::: x :: Nil; - def extractFirst(l: t, p: a => boolean): Option[Pair[a, t]] = - l match { - case Nil => None - case head :: tail => - if (p(head)) - Some(Pair(head, tail)) - else - extractFirst(tail, p) match { - case None => None - case Some(Pair(x, without_x)) => Some(Pair(x, head :: without_x)) - } - } - } -} - -/** Efficient queue module creator based on linked lists. */ -trait LinkedListQueueCreator { - import scala.collection.mutable.LinkedList; - def queueCreate[a <: AnyRef]: QueueModule[a] = new QueueModule[a] { - type t = Pair[LinkedList[a], LinkedList[a]]; // fst = the list, snd = last elem - def make: t = { - val l = new LinkedList[a](null, null); - Pair(l, l) - } - def append(l: t, x: a): t = { - val atTail = new LinkedList(x, null); - l._2 append atTail; - Pair(l._1, atTail) - } - def extractFirst(l: t, p: a => boolean): Option[Pair[a, t]] = { - var xs = l._1; - var xs1 = xs.next; - while (xs1 != null && !p(xs1.elem)) { - xs = xs1; - xs1 = xs1.next; - } - if (xs1 != null) { - xs.next = xs1.next; - if (xs.next == null) - Some(Pair(xs1.elem, Pair(l._1, xs))) - else - Some(Pair(xs1.elem, l)) - } - else - None - } - } -} - diff --git a/sources/scala/concurrent/NameServer.scala b/sources/scala/concurrent/NameServer.scala deleted file mode 100644 index b7646e6deb..0000000000 --- a/sources/scala/concurrent/NameServer.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.concurrent; - - -object NameServer { - - val names = new scala.collection.mutable.HashMap[Symbol, Process]; - - def register(name: Symbol, proc: Process) = { - if (names.contains(name)) error("Name:" + name + " already registred"); - names += name -> proc; - } - - def unregister(name: Symbol) = { - if (names.contains(name)) - names -= name; - else - error("Name:" + name + " not registred"); - } - - def whereis(name: Symbol): Option[Process] = - names.get(name); - - def send(name: Symbol, msg: MailBox#Message) = - names(name).send(msg); - -} diff --git a/sources/scala/concurrent/Process.scala b/sources/scala/concurrent/Process.scala deleted file mode 100644 index 950220da35..0000000000 --- a/sources/scala/concurrent/Process.scala +++ /dev/null @@ -1,78 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.concurrent; - - -object Process { - def spawn(body: => Unit): Process = { - val p = new Process(body); - p.start(); - p; - } - def spawn_link(body: => Unit): Process = { - self.spawn_link(body); - } - - def send(p: Process,msg: MailBox#Message) = - p.send(msg); - def receive[a](f: PartialFunction[MailBox#Message, a]): a = - self.receive(f); - - def receiveWithin[a](msec: long)(f: PartialFunction[MailBox#Message, a]): a = - self.receiveWithin(msec)(f); - - def self: Process = { - if (Thread.currentThread().isInstanceOf[Process]) - Thread.currentThread().asInstanceOf[Process] - else error("Self called outside a process"); - } - - def exit(p: Process, reason: AnyRef) = - p.exit(reason); -} - -class Process(body: => Unit) extends Actor() { - private var exitReason: AnyRef = null; - private var links: List[Process] = Nil; - override def run() = { - try {body} - catch { - case _: java.lang.InterruptedException => - signal(exitReason); - case (exitSignal) => - signal(exitSignal); - } - } - - private def signal(s: MailBox#Message) = { - links.foreach((p:Process) => p.send(Tuple3('EXIT,this,s))); - } - - def !(msg: MailBox#Message) = - send(msg); - - def link(p: Process) = { - links = p::links; - } - - def spawn_link(body: => Unit) = { - val p = new Process(body); - p.link(this); - p.start(); - p - } - - def self = this; - - def exit(reason: AnyRef): Unit = { - exitReason = reason; - interrupt(); - } -} diff --git a/sources/scala/concurrent/SyncChannel.scala b/sources/scala/concurrent/SyncChannel.scala deleted file mode 100644 index 6cab7b2ad6..0000000000 --- a/sources/scala/concurrent/SyncChannel.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.concurrent; - - -class SyncChannel[a] { - private var data: a = _; - private var reading = false; - private var writing = false; - - def await(cond: => Boolean) = while (!cond) { wait() } - - def write(x: a) = synchronized { - await(!writing); - data = x; - writing = true; - if (reading) notifyAll(); - else await(reading) - } - - def read: a = synchronized { - await(!reading); - reading = true; - await(writing); - val x = data; - writing = false; - reading = false; - notifyAll(); - x - } -} diff --git a/sources/scala/concurrent/SyncVar.scala b/sources/scala/concurrent/SyncVar.scala deleted file mode 100644 index 0e1b9fd38c..0000000000 --- a/sources/scala/concurrent/SyncVar.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.concurrent; - - -class SyncVar[a] { - - private var isDefined: Boolean = false; - private var value: a = _; - - def get = synchronized { - if (!isDefined) wait(); - value - } - - def set(x: a) = synchronized { - value = x; - isDefined = true; - notifyAll() - } - - def isSet: Boolean = synchronized { - isDefined; - } - - def unset = synchronized { - isDefined = false - } - -} diff --git a/sources/scala/concurrent/TIMEOUT.scala b/sources/scala/concurrent/TIMEOUT.scala deleted file mode 100644 index d665fdf649..0000000000 --- a/sources/scala/concurrent/TIMEOUT.scala +++ /dev/null @@ -1,12 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.concurrent; - -case class TIMEOUT(); diff --git a/sources/scala/concurrent/jolib.scala b/sources/scala/concurrent/jolib.scala deleted file mode 100644 index 08611be513..0000000000 --- a/sources/scala/concurrent/jolib.scala +++ /dev/null @@ -1,75 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.concurrent; - - -/** -* Library for using join-calculus concurrent primitives in Scala. -*/ -object jolib { - - type Pattern = List[Signal]; - - type Rule = PartialFunction[List[Any], unit]; - - /////////////////// JOIN DEFINITION ///////////////////////// - - class Join { - - private var ruls: List[Pair[Pattern, Rule]] = null; - - def canMatch(p: Pattern) = - p forall { s => !s.queue.isEmpty }; - - def values(p: Pattern): List[Any] = - p map { s => s.queue.dequeue: Any }; - - def rules(rs: Pair[Pattern, Rule]*) = - ruls = rs.asInstanceOf[List[Pair[Pattern, Rule]]]; - - def tryMatch = - (ruls find { case Pair(p, _) => canMatch(p) }) match { - case None => () => (); - case Some(Pair(p, r)) => { - val args = values(p); - () => concurrent.ops.spawn(r(args)) - } - } - - } - - /////////////////// SIGNALS ///////////////////////// - - abstract class Signal(join: Join) { - type C; - val queue = new collection.mutable.Queue[C]; - def tryReduction(x: C): unit = { - val continuation = join synchronized { - queue.enqueue(x); - join.tryMatch - }; - continuation() - } - } - - abstract class Asynchr(join: Join) extends Signal(join) { - def apply(x: C): unit = tryReduction(x); - } - - abstract class Synchr[a](join: Join) extends Signal(join) { - type C <: SyncVar[a]; - def apply(x: C): a = { - tryReduction(x); - x.get - } - } - -} - diff --git a/sources/scala/concurrent/ops.scala b/sources/scala/concurrent/ops.scala deleted file mode 100644 index 04bee676ec..0000000000 --- a/sources/scala/concurrent/ops.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-04, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.concurrent; - - -object ops { - - def spawn(p: => Unit) = { - val t = new Thread() { override def run() = p; } - t.start() - } - - def future[a](p: => a): () => a = { - val result = new SyncVar[a]; - spawn { result set p } - () => result.get - } - - def par[a, b](xp: => a, yp: => b): Pair[a, b] = { - val y = new SyncVar[b]; - spawn { y set yp } - Pair(xp, y.get) - } - - def replicate(start: Int, end: Int)(p: Int => Unit): Unit = { - if (start == end) - () - else if (start + 1 == end) - p(start) - else { - val mid = (start + end) / 2; - spawn { replicate(start, mid)(p) } - replicate(mid, end)(p) - } - } - -/* - def parMap[a,b](f: a => b, xs: Array[a]): Array[b] = { - val results = new Array[b](xs.length); - replicate(0, xs.length) { i => results(i) = f(xs(i)) } - results - } -*/ - -} diff --git a/sources/scala/concurrent/pilib.scala b/sources/scala/concurrent/pilib.scala deleted file mode 100644 index 6ce7a560af..0000000000 --- a/sources/scala/concurrent/pilib.scala +++ /dev/null @@ -1,189 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.concurrent; - -/** -* Library for using Pi-calculus concurrent primitives in Scala. As an example, -the definition of a two-place buffer using the pilib library looks like: -*
-*def Buffer[a](put: Chan[a], get: Chan[a]): unit = {
-*  def B0: unit = choice ( put * { x => B1(x) } );
-*  def B1(x: a): unit = choice ( get(x) * B0, put * { y => B2(x, y) } );
-*  def B2(x: a, y: a): unit = choice ( get(x) * B1(y) );
-*  B0
-*}
-*
-* -* @see PiLib: A Hosted Language for Pi-Calculus Style Concurrency -* @author Vincent Cremet, Martin Odersky -*/ -object pilib { - - /////////////////////////// SPAWN ////////////////////////////// - - /** - * Run several processes in parallel using the following syntax: - * spawn < p_1 | ... | p_n > - */ - trait Spawn { - def <(p: => unit): Spawn; - def |(p: => unit): Spawn; - def > : unit; - } - val spawn = new Spawn { - //object spawn extends Spawn { // BUG ! - def <(p: => unit): Spawn = { scala.concurrent.ops.spawn(p); this } - def |(p: => unit): Spawn = { scala.concurrent.ops.spawn(p); this } - def > : unit = () - } - - //////////////////////// GUARDED PROCESSES ///////////////////////// - - /** Untyped channel. */ - class UChan { - /** Default log function. */ - var log = (x: Any) => (); - } - - /** An untyped guarded process. - * @param n channel name - * @param polarity input (true) or output (false) - * @param v transmitted value - * @param c continuation - */ - case class UGP(n: UChan, polarity: boolean, v: Any, c: Any => Any); - - /** Typed guarded process. */ - class GP[a](n: UChan, polarity: boolean, v: Any, c: Any => a) { - val untyped = UGP(n, polarity, v, c); - } - - ////////////////////////// CHANNELS ////////////////////////////// - - /** - * Name on which one can emit, receive or that can be emitted or received - * during a communication. - */ - class Chan[a] extends UChan with Function1[a, Product[a]] { - - var defaultValue: a = _; - - /** Creates an input guarded process. */ - def input[b](c: a => b) = - new GP(this, true, (), x => c(x.asInstanceOf[a])); - - /** Creates an input guarded process. */ - def output[b](v: a, c: () => b) = - new GP(this, false, v, x => c()); - - /** Blocking read. */ - def read = { - var res: a = defaultValue; - choice ( input(x => res = x) ); - res - } - - /** Blocking write. */ - def write(x: a) = - choice ( output(x, () => ()) ); - - /** Syntactic sugar for input. */ - def *[b](f: a => b) = - input(f); - - /** Syntactic sugar for output. */ - def apply(v: a) = - new Product(this, v); - - /** Attach a function to be evaluated at each communication event - * on this channel. Replace previous attached function. - */ - def attach(f: a => unit) = - log = x => f(x.asInstanceOf[a]); - } - - class Product[a](c: Chan[a], v: a) { - def *[b](f: => b) = c.output(v, () => f); - } - - //////////////////// SUM OF GUARDED PROCESSES ////////////////////// - - case class Sum(gs: List[UGP]) { - - /** Continuation of the sum. */ - var cont: () => Any = _; - - var initialized = false; - - /** - * Block if not initialized otherwise continue with the - * continuation. - */ - def continue = synchronized { - if (!initialized) wait(); - cont() - } - - /** Set the values of parameters and awake the sleeping sum. */ - def set(f: () => Any) = synchronized { - cont = f; - initialized = true; - notify() - } - } - - /////////////////////////// COMMUNICATION ////////////////////////// - - private var sums: List[Sum] = Nil; - - /** Test if two lists of guarded processes can communicate. */ - private def matches(gs1: List[UGP], gs2: List[UGP]): Option[Triple[() => unit, () => Any, () => Any]] = - Pair(gs1, gs2) match { - case Pair(Nil, _) => None - case Pair(_, Nil) => None - case Pair(UGP(a1, d1, v1, c1) :: rest1, UGP(a2, d2, v2, c2) :: rest2) => - if (a1 == a2 && d1 == !d2) - Some(Triple(() => if (d1) a1.log(v2) else a1.log(v1), () => c1(v2), () => c2(v1))) - else matches(gs1, rest2) match { - case None => matches(rest1, gs2) - case Some(t) => Some(t) - } - } - - /** - * Test if the given sum can react with one of the pending sums. - * If yes then do the reaction otherwise append the sum at the end - * of the pending sums. - */ - private def compare(s1: Sum, ss: List[Sum]): List[Sum] = - ss match { - case Nil => ss ::: List(s1) - case s2 :: rest => matches(s1.gs, s2.gs) match { - case None => s2 :: compare(s1, rest) - case Some(Triple(log, c1, c2)) => { - log(); - s1.set(c1); - s2.set(c2); - rest - } - } - } - - /** Pi-calculus non-deterministic choice. */ - def choice[a](s: GP[a]*): a = { - val sum = Sum(s.asInstanceOf[List[GP[a]]] map { x => x.untyped }); - synchronized { sums = compare(sum, sums) }; - (sum.continue).asInstanceOf[a] - } - - -} - diff --git a/sources/scala/dbc/DataType.scala b/sources/scala/dbc/DataType.scala deleted file mode 100644 index b984169350..0000000000 --- a/sources/scala/dbc/DataType.scala +++ /dev/null @@ -1,66 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc; - -/** An ISO-9075:2003 (SQL) data type. Mappings between SQL types and - * database specific types should be provided by the database driver. - */ -abstract class DataType { - - /** Tests whether this datatype is equivalent to another. Usually, two - * types are defined as equivalent if they are equal. Two types can be - * equivalent without being equal if values of those types will be - * encoded in the same native Scala type. - */ - def isEquivalent(datatype: DataType): Boolean; - - /** Tests whether this datatype is equivalent or a subtype of another - * datatype. Type A is said to be subtype of type - * B if any value of type A can be - * represented as a value of type B. - */ - def isSubtypeOf(datatype: DataType): Boolean; - - /** The native Scala type in which values of this SQL type will be - * encoded. - */ - type NativeType <: Any; - - /** The native Scala type in which values of this SQL type will be - * encoded. This must point to the same type as NativeType. - */ - def nativeTypeId: DataType.Id; - - /** Whether the value can take the null value, None when this property is - * unknown. - */ - def nullable: Option[Boolean] = None; - - /** The SQL name of the type */ - def sqlString: String = "UNDEFINED DATA TYPE" - -} - -object DataType { - - type Id = Int; - - val OBJECT : Id = 10; - val BOOLEAN : Id = 20; - val BYTE : Id = 30; - val SHORT : Id = 31; - val INT : Id = 32; - val LONG : Id = 33; - val BIG_INTEGER: Id = 34; - val BIG_DECIMAL: Id = 35; - val FLOAT : Id = 40; - val DOUBLE : Id = 41; - val STRING : Id = 50; - -} diff --git a/sources/scala/dbc/Database.scala b/sources/scala/dbc/Database.scala deleted file mode 100644 index 28270184b5..0000000000 --- a/sources/scala/dbc/Database.scala +++ /dev/null @@ -1,186 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc; - -import java.sql._; - -/** A link to a database. The Database abstract class must - * be specialised for every different DBMS. - * - * @author Gilles Dubochet - */ -case class Database(dbms: Vendor) { - - class Closed extends Exception; - - /** A lock used for operations that need to be atomic for this database - * instance. */ - private val lock: scala.concurrent.Lock = new scala.concurrent.Lock(); - - /** The vendor of the DBMS that contains this database. */ - private val vendor: Vendor = dbms; - - /** The Database connections available to use. */ - private var availableConnections: List[Connection] = Nil; - - /** The connections that are currently in use. */ - private var usedConnections: List[Connection] = Nil; - - /** Whether the database no longer accepts new connections. */ - private var closing: Boolean = false; - - /** Retrieves a connection from the available connection pool or creates - * a new one. - * - * @returns A connection that can be used to access the database. - */ - private def getConnection: Connection = { - if (closing) { - throw new Closed; - } else { - availableConnections match { - case Nil => { - lock.acquire; - val connection = vendor.getConnection; - usedConnections = connection :: usedConnections; - lock.release; - connection - } - case connection :: cs => { - lock.acquire; - availableConnections = cs; - usedConnections = connection :: usedConnections; - lock.release; - connection; - } - } - } - } - - /** Closes a connection to this database. A closed connection might - * also return to the available connection pool if the latter is depleted. - * - * @param connection The connection that should be closed. - */ - private def closeConnection(connection: Connection): Unit = { - if (closing) { - connection.close(); - } else { - lock.acquire; - usedConnections = usedConnections.remove(e => (e.equals(connection))); - if (availableConnections.length < vendor.retainedConnections) - availableConnections = connection :: availableConnections - else - connection.close(); - lock.release; - } - } - - /** .. - */ - def close: Unit = { - closing = true; - for (val conn <- availableConnections) conn.close(); - } - - /** Executes a statement that returns a relation on this database. - * - * @param relationStatement The statement to execute. - * @return The relation returned by the database for this statement. - */ - def executeStatement(relationStatement: statement.Relation): result.Relation = - executeStatement(relationStatement, false); - - /** Executes a statement that returns a relation on this database. - * - * @param relationStatement The statement to execute. - * @param debug Whether debugging information should be printed on the console. - * @return The relation returned by the database for this statement. - */ - def executeStatement(relationStatement: statement.Relation, - debug: Boolean): result.Relation = - new scala.dbc.result.Relation { - val statement = relationStatement; - if (debug) Console.println("## " + statement.sqlString); - private val connection = getConnection; - val sqlResult = connection.createStatement().executeQuery(statement.sqlString); - closeConnection(connection); - statement.typeCheck(this); - } - - /** Executes a statement that updates the state of the database. - * - * @param statusStatement The statement to execute. - * @return The status of the database after the statement has been executed. - */ - def executeStatement(statusStatement: statement.Status): result.Status[Unit] = - executeStatement(statusStatement, false); - - /** Executes a statement that updates the state of the database. - * - * @param statusStatement The statement to execute. - * @param debug Whether debugging information should be printed on the console. - * @return The status of the database after the statement has been executed. - */ - def executeStatement(statusStatement: statement.Status, - debug: Boolean): result.Status[Unit] = - new scala.dbc.result.Status[Unit] { - val statement = statusStatement; - if (debug) Console.println("## " + statement.sqlString); - def result = (); - private val connection = getConnection; - val jdbcStatement: java.sql.Statement = connection.createStatement(); - jdbcStatement.execute(statement.sqlString); - val touchedCount = Some(jdbcStatement.getUpdateCount()); - closeConnection(connection); - } - - /** Executes a list of statements or other operations inside a transaction. - * Only statements are protected in a transaction, other Scala code is not. - * - * @param transactionStatement The transaction to execute as a closure. - * @return The status of the database after the transaction has been executed. - */ - def executeStatement[ResultType](transactionStatement: statement.Transaction[ResultType]): result.Status[ResultType] = - executeStatement(transactionStatement, false); - - /** Executes a list of statements or other operations inside a transaction. - * Only statements are protected in a transaction, other Scala code is not. - * - * @param transactionStatement The transaction to execute as a closure. - * @param debug Whether debugging information should be printed on the console. - * @return The status of the database after the transaction has been executed. - */ - def executeStatement[ResultType](transactionStatement: statement.Transaction[ResultType], debug: Boolean): result.Status[ResultType] = { - new scala.dbc.result.Status[ResultType] { - val touchedCount = None; - val statement = transactionStatement; - private val connection = getConnection; - connection.setAutoCommit(false); - val jdbcStatement: java.sql.Statement = connection.createStatement(); - if (debug) Console.println("## " + transactionStatement.sqlStartString); - jdbcStatement.execute(transactionStatement.sqlStartString); - val result: ResultType = try { - val buffer = transactionStatement.transactionBody(Database.this); - if (debug) Console.println("## " + transactionStatement.sqlCommitString); - jdbcStatement.execute(transactionStatement.sqlCommitString); - buffer - } catch { - case e: Throwable => { - if (debug) Console.println("## " + transactionStatement.sqlAbortString); - jdbcStatement.execute(transactionStatement.sqlAbortString); - throw e; - } - } - connection.setAutoCommit(true); - closeConnection(connection); - } - } - -} diff --git a/sources/scala/dbc/Syntax.scala b/sources/scala/dbc/Syntax.scala deleted file mode 100644 index cde8112979..0000000000 --- a/sources/scala/dbc/Syntax.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API tests ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc; - -import java.math.{BigDecimal, BigInteger}; - - -/** This class .. - * - */ -object Syntax { - - import syntax.DataTypeUtil; - - /* Data types */ - def boolean = DataTypeUtil.boolean; - def tinyint = DataTypeUtil.tinyint; - def smallint = DataTypeUtil.smallint; - def integer = DataTypeUtil.integer; - def bigint = DataTypeUtil.bigint; - def real = DataTypeUtil.real; - - def numeric(precision: Int) = DataTypeUtil.numeric(precision); - def numeric(precision: Int, scale: Int) = DataTypeUtil.numeric(precision, scale); - - def doublePrecision = DataTypeUtil.doublePrecision; - def character(length: Int) = DataTypeUtil.character(length); - def characterVarying(length: Int) = DataTypeUtil.characterVarying(length); - def characterLargeObject = DataTypeUtil.characterLargeObject; - - /* Statements */ - //def select - - /* Other stuff */ - def database (server: String, username: String, password: String): dbc.Database = - syntax.Database.database(server, username, password); - -} diff --git a/sources/scala/dbc/Utilities.scala b/sources/scala/dbc/Utilities.scala deleted file mode 100644 index 46ca27a019..0000000000 --- a/sources/scala/dbc/Utilities.scala +++ /dev/null @@ -1,25 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc; - -/** An object offering transformation methods (views) on various values. - * This object's members must be visible in an expression to use value - * auto-conversion. - */ -object Utilities { - - def view (obj: statement.expression.Constant): Value = - obj.constantValue; - - def view (obj: Value): statement.expression.Constant = - new statement.expression.Constant { - val constantValue = obj; - } - -} diff --git a/sources/scala/dbc/Value.scala b/sources/scala/dbc/Value.scala deleted file mode 100644 index 3ab2d0cbe5..0000000000 --- a/sources/scala/dbc/Value.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc; - -/** A SQL-99 value of any type. */ -abstract class Value { - - /** The SQL-99 type of the value. */ - val dataType: DataType; - - type NativeType = dataType.type#NativeType; - - val nativeValue: NativeType; - - /** A SQL-99 compliant string representation of the value. */ - def sqlString: String; - -} \ No newline at end of file diff --git a/sources/scala/dbc/Vendor.scala b/sources/scala/dbc/Vendor.scala deleted file mode 100644 index db44ddec42..0000000000 --- a/sources/scala/dbc/Vendor.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc; - -import java.sql.{Connection, Driver}; - - -/** This class .. - */ -abstract class Vendor { - - def nativeDriverClass: Class; - def uri: java.net.URI; - def user: String; - def pass: String; - def nativeProperties: java.util.Properties = { - val properties = new java.util.Properties(); - properties.setProperty("user", user); - properties.setProperty("password", pass); - properties - } - - def retainedConnections: Int; - - def getConnection: Connection = { - val driver = nativeDriverClass.newInstance().asInstanceOf[Driver]; - driver.connect(uri.toString(),nativeProperties) - } - - def urlProtocolString: String; - -} diff --git a/sources/scala/dbc/datatype/ApproximateNumeric.scala b/sources/scala/dbc/datatype/ApproximateNumeric.scala deleted file mode 100644 index d75da1eb50..0000000000 --- a/sources/scala/dbc/datatype/ApproximateNumeric.scala +++ /dev/null @@ -1,53 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -/** A type category for all SQL types that store varying-precision - * numbers. - */ -abstract class ApproximateNumeric[Type] ( - override val nativeTypeId: DataType.Id -) extends datatype.Numeric[Type](nativeTypeId) { - - def isEquivalent(datatype: DataType) = datatype match { - case dt: ApproximateNumeric[Type] => - (nativeTypeId == dt.nativeTypeId && - precisionRadix == dt.precisionRadix && - precision == dt.precision && - signed == dt.signed) - case _ => - false - } - - def isSubtypeOf (datatype:DataType) = datatype match { - case dt:ApproximateNumeric[Type] => - (nativeTypeId == dt.nativeTypeId && - precisionRadix == dt.precisionRadix && - precision <= dt.precision && - signed == dt.signed) - case _ => - false - } - - /** A SQL-99 compliant string representation of the type. - *

Compatibility notice

This method assumes that a real - * uses 32 bits and a double 64. This is not defined in the - * standard but is usually the case. - */ - override def sqlString: java.lang.String = Tuple2(precisionRadix,precision) match { - case Tuple2(2,64) => "REAL" - case Tuple2(2,128) => "DOUBLE PRECISION" - case Tuple2(2,p) => - throw exception.UnsupportedFeature("SQL-99 does not support an approximate numeric type with a binary defined precision other than 16, 32 and 64 bits"); - case Tuple2(10,p) => "FLOAT (" + p.toString() + ")" - case Tuple2(pr,_) => - throw exception.UnsupportedFeature("SQL-99 does not support the precision of an approximate numeric type to be defined in a radix other than 2 or 10"); - } - -} diff --git a/sources/scala/dbc/datatype/Boolean.scala b/sources/scala/dbc/datatype/Boolean.scala deleted file mode 100644 index 7c68ab9c7d..0000000000 --- a/sources/scala/dbc/datatype/Boolean.scala +++ /dev/null @@ -1,27 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -/** The SQL type for a truth value. */ -class Boolean extends DataType { - - def isEquivalent (datatype:DataType) = datatype match { - case dt:Boolean => true - case _ => false - } - - def isSubtypeOf (datatype:DataType) = isEquivalent(datatype); - - type NativeType = scala.Boolean; - val nativeTypeId = DataType.BOOLEAN; - - /** A SQL-99 compliant string representation of the type. */ - override def sqlString: java.lang.String = "BOOLEAN"; - -} \ No newline at end of file diff --git a/sources/scala/dbc/datatype/Character.scala b/sources/scala/dbc/datatype/Character.scala deleted file mode 100644 index ded08c5602..0000000000 --- a/sources/scala/dbc/datatype/Character.scala +++ /dev/null @@ -1,36 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API tests ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -/** A SQL type for a string of characters of arbitrary length with - * arbitrary character set. - */ -abstract class Character extends CharacterString { - - def isEquivalent(datatype: DataType) = datatype match { - case dt: Character => - length == dt.length && encoding == dt.encoding - case _ => - false - } - - def isSubtypeOf(datatype: DataType) = datatype match { - case dt: Character => - length >= dt.length && encoding == dt.encoding - case _ => - false - } - - /** The length of the string defined in characters. */ - def length: Int; - - /** A SQL-99 compliant string representation of the type. */ - override def sqlString: java.lang.String = "CHARACTER (" + length.toString() + ")"; - -} diff --git a/sources/scala/dbc/datatype/CharacterLargeObject.scala b/sources/scala/dbc/datatype/CharacterLargeObject.scala deleted file mode 100644 index adbd979f6e..0000000000 --- a/sources/scala/dbc/datatype/CharacterLargeObject.scala +++ /dev/null @@ -1,27 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -/** A SQL type for an unbounded length string of characters with arbitrary - * character set. */ -class CharacterLargeObject extends CharacterString { - - def isEquivalent (datatype:DataType) = datatype match { - case dt:CharacterLargeObject => { - encoding == dt.encoding - } - case _ => false - } - - def isSubtypeOf (datatype:DataType) = isEquivalent(datatype); - - /** A SQL-99 compliant string representation of the type. */ - override def sqlString: java.lang.String = "CHARACTER LARGE OBJECT"; - -} \ No newline at end of file diff --git a/sources/scala/dbc/datatype/CharacterString.scala b/sources/scala/dbc/datatype/CharacterString.scala deleted file mode 100644 index e937d10b9e..0000000000 --- a/sources/scala/dbc/datatype/CharacterString.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -/** A type category for all SQL types that store strings of characters. */ -abstract class CharacterString extends String { - - type NativeType = java.lang.String; - val nativeTypeId = DataType.STRING; - - /** The name of the character set in which the string is encoded. */ - def encoding: Option[java.lang.String] = None; - -} \ No newline at end of file diff --git a/sources/scala/dbc/datatype/CharacterVarying.scala b/sources/scala/dbc/datatype/CharacterVarying.scala deleted file mode 100644 index b7f743ce0b..0000000000 --- a/sources/scala/dbc/datatype/CharacterVarying.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -/** A SQL type for a varying length string of characters with arbitrary - * maximal length and arbitrary character set. - */ -abstract class CharacterVarying extends CharacterString { - - def isEquivalent(datatype: DataType) = datatype match { - case dt: CharacterVarying => - length == dt.length && encoding == dt.encoding - case _ => - false - } - - def isSubtypeOf(datatype: DataType) = datatype match { - case dt: CharacterVarying => - length >= dt.length && encoding == dt.encoding - case _ => - false - } - - /** The maximal length of the string defined in characters. */ - def length: Int; - - /** A SQL-99 compliant string representation of the type. */ - override def sqlString: java.lang.String = - "CHARACTER VARYING (" + length.toString() + ")"; - -} diff --git a/sources/scala/dbc/datatype/ExactNumeric.scala b/sources/scala/dbc/datatype/ExactNumeric.scala deleted file mode 100644 index 9152a7e928..0000000000 --- a/sources/scala/dbc/datatype/ExactNumeric.scala +++ /dev/null @@ -1,61 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -/** A type category for all SQL types that store constant-precision - * numbers. - */ -abstract class ExactNumeric[Type]( - override val nativeTypeId: DataType.Id -) extends datatype.Numeric[Type](nativeTypeId) { - - def isEquivalent(datatype: DataType) = datatype match { - case dt: ExactNumeric[Type] => - (nativeTypeId == dt.nativeTypeId && - precisionRadix == dt.precisionRadix && - precision == dt.precision && - scale == dt.scale && - signed == dt.signed) - case _ => - false - } - - def isSubtypeOf(datatype: DataType) = datatype match { - case dt: ExactNumeric[Type] => - (nativeTypeId == dt.nativeTypeId && - precisionRadix == dt.precisionRadix && - precision <= dt.precision && - scale <= dt.scale && - signed == dt.signed) - case _ => - false - } - - /** The number of digits used after the decimal point. */ - def scale: Int; - - /** A SQL-99 compliant string representation of the type. - *

Compatibility notice

This method assumes that an integer - * uses 32 bits, a small 16 and a big 64. This is not defined in the - * standard but is usually the case. - */ - override def sqlString: java.lang.String = Tuple3(precisionRadix,precision,scale) match { - case Tuple3(2,16,0) => "SMALLINT" - case Tuple3(2,32,0) => "INTEGER" - case Tuple3(2,64,0) => "BIGINT" - case Tuple3(2,java.lang.Integer.MAX_VALUE,0) => "BIGINT" - case Tuple3(2,p,s) => - throw exception.UnsupportedFeature("SQL-99 does not support an exact numeric type with a binary defined precision other than 16, 32 and 64 bits"); - case Tuple3(10,p,0) => "NUMERIC (" + p.toString() + ")" - case Tuple3(10,p,s) => "NUMERIC (" + p.toString() + ", " + s.toString() + ")" - case Tuple3(pr,_,_) => - throw exception.UnsupportedFeature("SQL-99 does not support the precision of an exact numeric type to be defined in a radix other than 2 or 10"); - } - -} diff --git a/sources/scala/dbc/datatype/Factory.scala b/sources/scala/dbc/datatype/Factory.scala deleted file mode 100644 index 13d9cd35e2..0000000000 --- a/sources/scala/dbc/datatype/Factory.scala +++ /dev/null @@ -1,246 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -import java.sql.Types._; -import java.math.BigInteger; -import java.math.BigDecimal; - -object Factory { - - final val java_lang_Integer_SIZE = 32; - final val java_lang_Long_SIZE = 64; - - /** Returns a mullable property formated as a boolean option */ - def isNullable (metadata:java.sql.ResultSetMetaData, index:Int): Option[scala.Boolean] = - metadata.isNullable(index) match { - case java.sql.ResultSetMetaData.columnNoNulls => Some(false); - case java.sql.ResultSetMetaData.columnNullable => Some(true); - case java.sql.ResultSetMetaData.columnNoNulls => None; - } - - /** Returns the binary precision for an integer field. This should only be - * used to find precision for integer numbers. It assumes that - * bytes cannot be used partially (result % 8 = 0). */ - def bytePrecision (precision:Int, signed:scala.Boolean, safe:scala.Boolean): Int = { - val decimalPrecision = precision + (if (safe) 1 else 0); - Pair(signed,decimalPrecision) match { - case Pair(_,0) => java.lang.Integer.MAX_VALUE // That's a bit of a hack. - case Pair(_,dp) if (dp <= 3) => 8 - case Pair(_,dp) if (dp <= 5) => 16 - case Pair(true,dp) if (dp <= 7) => 24 - case Pair(false,dp) if (dp <= 8) => 24 - case Pair(_,dp) if (dp <= 10) => 32 - case Pair(true,dp) if (dp <= 12) => 40 - case Pair(false,dp) if (dp <= 13) => 40 - case Pair(_,dp) if (dp <= 15) => 48 - case Pair(_,dp) if (dp <= 17) => 56 - case Pair(true,dp) if (dp <= 19) => 64 - case Pair(false,dp) if (dp <= 20) => 64 - case Pair(_,dp) if (dp <= 22) => 72 - case Pair(true,dp) if (dp <= 24) => 80 - case Pair(false,dp) if (dp <= 25) => 80 - case Pair(_,dp) if (dp <= 27) => 88 - case Pair(_,dp) if (dp <= 29) => 96 - case Pair(_,dp) if (dp <= 32) => 104 - case Pair(_,dp) if (dp <= 34) => 112 - case Pair(true,dp) if (dp <= 36) => 120 - case Pair(false,dp) if (dp <= 37) => 120 - case Pair(_,dp) if (dp <= 39) => 128 - case _ => java.lang.Integer.MAX_VALUE - } - } - - def create (metadata:java.sql.ResultSetMetaData, index:Int): DataType = { - metadata.getColumnType(index) match { - /* Boolean data types. */ - case BOOLEAN => new datatype.Boolean { - override val nullable = isNullable(metadata,index); - } - case BIT => new datatype.Boolean { - override val nullable = isNullable(metadata,index); - } - /* Fixed precision numeric data types. */ - case DECIMAL => { - Pair(bytePrecision(metadata.getPrecision(index),metadata.isSigned(index),true),metadata.getScale(index) == 0) match { - case Pair(bp,true) if (bp <= java_lang_Integer_SIZE) => - new datatype.ExactNumeric[Int](DataType.INT) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 10; - val precision = metadata.getPrecision(index); - val signed = metadata.isSigned(index); - val scale = metadata.getScale(index); - } - case Pair(bp,true) if (bp <= java_lang_Long_SIZE) => - new datatype.ExactNumeric[Long](DataType.LONG) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 10; - val precision = metadata.getPrecision(index); - val signed = metadata.isSigned(index); - val scale = metadata.getScale(index); - } - case Pair(_,true) => - new datatype.ExactNumeric[BigInteger](DataType.BIG_INTEGER) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 10; - val precision = metadata.getPrecision(index); - val signed = metadata.isSigned(index); - val scale = metadata.getScale(index); - } - case Pair(_,false) => - new datatype.ExactNumeric[BigDecimal](DataType.BIG_DECIMAL) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 10; - val precision = metadata.getPrecision(index); - val signed = metadata.isSigned(index); - val scale = metadata.getScale(index); - } - } - } - case NUMERIC => { - Pair(bytePrecision(metadata.getPrecision(index),metadata.isSigned(index),true),metadata.getScale(index) == 0) match { - case Pair(bp,true) if (bp <= java_lang_Integer_SIZE) => - new datatype.ExactNumeric[Int](DataType.INT) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 10; - val precision = metadata.getPrecision(index); - val signed = metadata.isSigned(index); - val scale = metadata.getScale(index); - } - case Pair(bp,true) if (bp <= java_lang_Long_SIZE) => - new datatype.ExactNumeric[Long](DataType.LONG) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 10; - val precision = metadata.getPrecision(index); - val signed = metadata.isSigned(index); - val scale = metadata.getScale(index); - } - case Pair(_,true) => - new datatype.ExactNumeric[BigInteger](DataType.BIG_INTEGER) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 10; - val precision = metadata.getPrecision(index); - val signed = metadata.isSigned(index); - val scale = metadata.getScale(index); - } - case Pair(_,false) => - new datatype.ExactNumeric[BigDecimal](DataType.BIG_DECIMAL) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 10; - val precision = metadata.getPrecision(index); - val signed = metadata.isSigned(index); - val scale = metadata.getScale(index); - } - } - } - /* Fixed precision integer data types. */ - case BIGINT => - new datatype.ExactNumeric[Long](DataType.LONG) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 2; - val precision = 64; - val signed = metadata.isSigned(index); - val scale = 0; - } - case INTEGER => - new datatype.ExactNumeric[Int](DataType.INT) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 2; - val precision = 32; - val signed = metadata.isSigned(index); - val scale = 0; - } - case SMALLINT => - new datatype.ExactNumeric[Short](DataType.SHORT) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 2; - val precision = 16; - val signed = metadata.isSigned(index); - val scale = 0; - } - case TINYINT => - new datatype.ExactNumeric[Byte](DataType.BYTE) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 2; - val precision = 8; - val signed = metadata.isSigned(index); - val scale = 0; - } - /* Floating point numeric data types. */ - case REAL => - new datatype.ApproximateNumeric[Float](DataType.FLOAT) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 2; - val precision = 64; - val signed = metadata.isSigned(index); - } - case DOUBLE => - new datatype.ApproximateNumeric[Double](DataType.DOUBLE) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 2; - val precision = 128; - val signed = metadata.isSigned(index); - } - case FLOAT => - new datatype.ApproximateNumeric[Double](DataType.DOUBLE) { - override val nullable = isNullable(metadata,index); - val precisionRadix = 2; - val precision = 128; - val signed = metadata.isSigned(index); - } - /* Character string data types. */ - case CHAR => new datatype.Character { - override val nullable = isNullable(metadata,index); - val length = metadata.getColumnDisplaySize(index); - } - case CLOB => new datatype.CharacterLargeObject { - override val nullable = isNullable(metadata,index); - } - case LONGVARCHAR => { - if (metadata.getColumnDisplaySize(index) >= 0) - new datatype.CharacterVarying { - override val nullable = isNullable(metadata,index); - def length = metadata.getColumnDisplaySize(index); - } - else // A PostgreSQL Hack - new datatype.CharacterLargeObject { - override val nullable = isNullable(metadata,index); - } - } - case VARCHAR => { - if (metadata.getColumnDisplaySize(index) >= 0) - new datatype.CharacterVarying { - override val nullable = isNullable(metadata,index); - def length = metadata.getColumnDisplaySize(index); - } - else // A PostgreSQL Hack - new datatype.CharacterLargeObject { - override val nullable = isNullable(metadata,index); - } - } - /* Undefined cases. */ - case OTHER => new datatype.Unknown { - override val nullable = isNullable(metadata, index); - } - /* Unsupported data types. */ - case REF | ARRAY | STRUCT => - error ("I don't support composite data types yet."); - case DATALINK | DISTINCT | JAVA_OBJECT | NULL => - error ("I won't support strange data types."); - /* Unsupported binary string data types. */ - case BINARY | BLOB | LONGVARBINARY | VARBINARY => - error ("I don't support binary string data types yet."); - /* Unsupported date and time data types. */ - case DATE | TIME | TIMESTAMP => - error ("I don't support date and time data types yet."); - /* Default case */ - case x => error ("I don't know about this ("+metadata.getColumnTypeName(index)+") JDBC type.") - } - } -} diff --git a/sources/scala/dbc/datatype/Numeric.scala b/sources/scala/dbc/datatype/Numeric.scala deleted file mode 100644 index ef3eee1f32..0000000000 --- a/sources/scala/dbc/datatype/Numeric.scala +++ /dev/null @@ -1,28 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -/** A type category for all SQL types that store numbers. */ -abstract class Numeric[Type](_nativeTypeId: DataType.Id) extends DataType { - - type NativeType = Type; - val nativeTypeId = _nativeTypeId; - - /** The radix in which the precision (and scale when appliable) is defined. - * ISO-9075 only allows 2 and 10 for this value. - */ - def precisionRadix: Int; - - /** The number of significant digits for that number. */ - def precision: Int; - - /** Whether the number is signed or not. */ - def signed: scala.Boolean; - -} diff --git a/sources/scala/dbc/datatype/String.scala b/sources/scala/dbc/datatype/String.scala deleted file mode 100644 index 7d409e6c2d..0000000000 --- a/sources/scala/dbc/datatype/String.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -/** A type category for all SQL types that store strings of elements. - */ -abstract class String extends DataType { - - /** The maximal possible length of the string defined in characters. - * This is an implementation-specific value. - */ - def maxLength: Option[Int] = None; - -} diff --git a/sources/scala/dbc/datatype/Unknown.scala b/sources/scala/dbc/datatype/Unknown.scala deleted file mode 100644 index 1e7895eb46..0000000000 --- a/sources/scala/dbc/datatype/Unknown.scala +++ /dev/null @@ -1,30 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.datatype; - -/** The SQL type for a truth value. */ -class Unknown extends DataType { - - def isEquivalent(datatype: DataType) = datatype match { - case dt: Unknown => - nativeTypeId == dt.nativeTypeId - case _ => - false - } - - def isSubtypeOf(datatype: DataType) = true; - - type NativeType = Object; - val nativeTypeId = DataType.OBJECT; - - /** A SQL-99 compliant string representation of the type. */ - override def sqlString: java.lang.String = - error("The 'UNKNOWN' data type cannot be represented."); - -} diff --git a/sources/scala/dbc/exception/IncompatibleSchema.scala b/sources/scala/dbc/exception/IncompatibleSchema.scala deleted file mode 100644 index 6095fbec82..0000000000 --- a/sources/scala/dbc/exception/IncompatibleSchema.scala +++ /dev/null @@ -1,15 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.exception; - -/** A type category for all SQL types that store constant-precision numbers. */ -case class IncompatibleSchema ( - expectedSchema: List[DataType], - foundSchema: List[DataType] -) extends Exception; \ No newline at end of file diff --git a/sources/scala/dbc/exception/UnsupportedFeature.scala b/sources/scala/dbc/exception/UnsupportedFeature.scala deleted file mode 100644 index 9fbaed81d7..0000000000 --- a/sources/scala/dbc/exception/UnsupportedFeature.scala +++ /dev/null @@ -1,12 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.exception; - -/** A type category for all SQL types that store constant-precision numbers. */ -case class UnsupportedFeature (msg: String) extends Exception; \ No newline at end of file diff --git a/sources/scala/dbc/result/Field.scala b/sources/scala/dbc/result/Field.scala deleted file mode 100644 index af129d18b7..0000000000 --- a/sources/scala/dbc/result/Field.scala +++ /dev/null @@ -1,60 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.result; - -import scala.dbc.datatype._; -import scala.dbc.value._; - -/** An ISO-9075:2003 (SQL) table field. */ -abstract class Field { - - /** The content (value) of the field. The type of this value is undefined, - * transformation into a useful type will be done by an automatic view - * function defined in the field object. */ - def content: Value; - - final def value[Type <: Value]: Type = - content.asInstanceOf[Type]; - - final def exactNumericValue[NativeType] = - content.asInstanceOf[dbc.value.ExactNumeric[NativeType]]; - - final def approximateNumericValue[NativeType] = - content.asInstanceOf[dbc.value.ApproximateNumeric[NativeType]]; - - final def booleanValue = - content.asInstanceOf[dbc.value.Boolean]; - - final def characterValue = - content.asInstanceOf[dbc.value.Character]; - - final def characterLargeObjectValue = - content.asInstanceOf[dbc.value.CharacterLargeObject]; - - final def characterVaryingValue = - content.asInstanceOf[dbc.value.CharacterVarying]; - - final def unknownValue = - content.asInstanceOf[dbc.value.Unknown]; - - /** The tuple that contains this field. */ - def originatingTuple: Tuple; - - /** The field metadata attached to this field. */ - def metadata: FieldMetadata; - -} - -object Field { - - implicit def view (field:Field): Value = field.content; - - - -} diff --git a/sources/scala/dbc/result/FieldMetadata.scala b/sources/scala/dbc/result/FieldMetadata.scala deleted file mode 100644 index 97c5bdb3a3..0000000000 --- a/sources/scala/dbc/result/FieldMetadata.scala +++ /dev/null @@ -1,32 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.result; - -/** Informations attached to a field about its content and its relationship to the originating database. */ -abstract class FieldMetadata { - - /** The name of the field. */ - def name: String; - - /** The index of the field in the tuple. */ - def index: Int; - - /** The expected type of the field. This information is used for automatic transformation of the field value into a usable type. */ - def datatype: DataType; - - /** The name of the catalog in the database from which the field originates */ - def catalog: String; - - /** The name of the schema in the database from which the field originates */ - def schema: String; - - /** The name of the table in the database from which the field originates */ - def table: String; - -} \ No newline at end of file diff --git a/sources/scala/dbc/result/Relation.scala b/sources/scala/dbc/result/Relation.scala deleted file mode 100644 index 006b6dbf07..0000000000 --- a/sources/scala/dbc/result/Relation.scala +++ /dev/null @@ -1,68 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.result; - -/** An ISO-9075:2003 (SQL) table. This is equivalent to a relation in the - * relational model. */ -abstract class Relation extends Object with Iterable[Tuple] { - - /** The statement that generated this relation. */ - def statement: scala.dbc.statement.Relation; - - /** A JDBC result containing this relation. */ - protected def sqlResult: java.sql.ResultSet; - - /** A JDBC metadata object attached to the relation. */ - protected def sqlMetadata: java.sql.ResultSetMetaData = sqlResult.getMetaData(); - - /** Metadata about all fields in a tuple of the relation. */ - def metadata: List[FieldMetadata] = - for (val count <- List.range(1, sqlMetadata.getColumnCount()+1)) yield - new FieldMetadata { - val name: String = sqlMetadata.getColumnName(count); - val index: Int = count; - val datatype: DataType = dbc.datatype.Factory.create(sqlMetadata,count); - val catalog: String = sqlMetadata.getCatalogName(count); - val schema: String = sqlMetadata.getSchemaName(count); - val table: String = sqlMetadata.getTableName(count); - } - - /** Metadata about the field at the given index. If there is no such - * field None is returned instead. */ - def metadataFor (index:Int): Option[FieldMetadata] = - try {Some(metadata(index))} catch {case e => None} - - /** Metadata about the field with the given column name. If there is no - * such field, None is returned instead. */ - def metadataFor (name:String): Option[FieldMetadata] = - metadata.find(f=>(f.name==name)); - - /** An iterator on the tuples of the relation. - *

Caution

A Relation only has one single iterator, due to limitations - * in DBMS. This means that if this method is called multiple times, all returned - * iterators will share the same state. */ - def elements: Iterator[Tuple] = new Iterator[Tuple] { - protected val result: java.sql.ResultSet = Relation.this.sqlResult; - def hasNext: Boolean = !(result.isLast()); - def next: Tuple = { - if (result.next()) { - new Tuple { - val me = this; - val originatingRelation = Relation.this; - val fields: List[Field] = for (val fieldMetadata <- metadata) yield - new Field { - val metadata = fieldMetadata; - val content = dbc.value.Factory.create(result,metadata.index,metadata.datatype); - val originatingTuple = me; - } - } - } else error("next on empty iterator") - } - } -} diff --git a/sources/scala/dbc/result/Status.scala b/sources/scala/dbc/result/Status.scala deleted file mode 100644 index 56d83d4ae6..0000000000 --- a/sources/scala/dbc/result/Status.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.result; - -import scala.dbc.datatype._; - -/** An object containing the status of a query */ -abstract class Status[ResultType] { - - /** The statement that generated this status result. */ - def statement: scala.dbc.statement.Statement; - - /** The number of elements modified or added by this statement. */ - def touchedCount: Option[Int]; - - def result: ResultType; - -} \ No newline at end of file diff --git a/sources/scala/dbc/result/Tuple.scala b/sources/scala/dbc/result/Tuple.scala deleted file mode 100644 index 41c2f1f6d1..0000000000 --- a/sources/scala/dbc/result/Tuple.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.result; - -/** An ISO-9075:2003 (SQL) table row. This is equivalent to a tuple in the relational model. */ -abstract class Tuple { - - /** All the fields contained in the tuple. */ - def fields: List[Field]; - - /** The relation that contains the tuple. */ - def originatingRelation: Relation; - - /** The field at the given index. If there is no such field (that is the index is out of bounds), None is returned instead. */ - def apply (index:Int): Field = - try { - fields(index) - } catch { - case e => - throw new java.lang.IndexOutOfBoundsException("Field at index "+index+" does not exist in relation"); - } - - /** The field with the given column name. If there is no such field, None is returned instead. */ - def apply (name:String): Field = { - def findField (fields: List[Field], name:String): Field = fields match { - case Nil => throw new java.lang.IndexOutOfBoundsException("Field '"+name+"' does not exist in relation") - case field :: _ if (field.metadata.name == name) => field - case field :: fields => findField (fields, name) - } - findField (fields, name); - } -} diff --git a/sources/scala/dbc/statement/AccessMode.scala b/sources/scala/dbc/statement/AccessMode.scala deleted file mode 100644 index 815f8b3c37..0000000000 --- a/sources/scala/dbc/statement/AccessMode.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -abstract class AccessMode { - def sqlString: String; -} - -object AccessMode { - case object ReadOnly extends AccessMode { - def sqlString = "READ ONLY"; - } - case object ReadWrite extends AccessMode { - def sqlString = "READ WRITE" - } -} \ No newline at end of file diff --git a/sources/scala/dbc/statement/DerivedColumn.scala b/sources/scala/dbc/statement/DerivedColumn.scala deleted file mode 100644 index 020304f979..0000000000 --- a/sources/scala/dbc/statement/DerivedColumn.scala +++ /dev/null @@ -1,32 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -abstract class DerivedColumn { - - /** The value for the column. This value can be of any type but must be - * calculated from fields that appear in a relation that takes part - * in the query. */ - def valueExpression: Expression; - - /** A new name for this field. This name must be unique for the query in - * which the column takes part. */ - def asClause: Option[String]; - - /** A SQL-99 compliant string representation of the derived column - * sub-statement. This only has a meaning inside a select statement. */ - def sqlString: String = ( - valueExpression.sqlInnerString + - (asClause match { - case None => "" - case Some(ac) => " AS " + ac - }) - ); - -} diff --git a/sources/scala/dbc/statement/Expression.scala b/sources/scala/dbc/statement/Expression.scala deleted file mode 100644 index 51cada90bb..0000000000 --- a/sources/scala/dbc/statement/Expression.scala +++ /dev/null @@ -1,25 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -/** An expression that calculates some value from fields. */ -abstract class Expression extends Relation { - - def fieldTypes: List[DataType] = Nil; - - /** A SQL-99 compliant string representation of the expression. */ - def sqlString: String = { - "SELECT " + sqlInnerString - } - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String; - -} diff --git a/sources/scala/dbc/statement/Insert.scala b/sources/scala/dbc/statement/Insert.scala deleted file mode 100644 index 23f93ec4a0..0000000000 --- a/sources/scala/dbc/statement/Insert.scala +++ /dev/null @@ -1,32 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -import scala.dbc.statement.expression._; - -/** An insertion of values into a table. */ -case class Insert ( - insertionTarget: String, - insertionData: InsertionData -) extends Status { - - /** A SQL-99 compliant string representation of the select statement. */ - def sqlString: String = ( - "INSERT INTO " + - insertionTarget + - " " + insertionData.sqlString - ); - - /** The name of the table where the data should be added. */ - //def insertionTarget: String; - - /** The data that will be added tot he table. */ - //def insertionData: InsertionData; - -} diff --git a/sources/scala/dbc/statement/InsertionData.scala b/sources/scala/dbc/statement/InsertionData.scala deleted file mode 100644 index 2d6f370319..0000000000 --- a/sources/scala/dbc/statement/InsertionData.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -import scala.dbc.statement.expression._; - -/** Data to be inserted into a table in an Insert. */ -abstract class InsertionData { - def sqlString: String; -} - -object InsertionData { - /** Insertion of data resulting from a query on the database. */ - case class Subquery (query:Relation) extends InsertionData { - def sqlString = query.sqlString; - } - /** Insertion of data as explicitly defined values. */ - case class Constructor ( - columnNames:Option[List[String]], - columnValues:List[Expression] - ) extends InsertionData { - def sqlString = ( - (columnNames match { - case None => "" - case Some(cn) => cn.mkString(" (",", ",")") - }) + - " VALUES" + - columnValues.map(e=>e.sqlInnerString).mkString(" (",", ",")") - ) - } -} diff --git a/sources/scala/dbc/statement/IsolationLevel.scala b/sources/scala/dbc/statement/IsolationLevel.scala deleted file mode 100644 index f63ebe39e8..0000000000 --- a/sources/scala/dbc/statement/IsolationLevel.scala +++ /dev/null @@ -1,28 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -abstract class IsolationLevel { - def sqlString: String; -} - -object IsolationLevel { - case object ReadUncommitted extends IsolationLevel { - def sqlString = "ISOLATION LEVEL READ UNCOMMITTED" - } - case object ReadCommitted extends IsolationLevel { - def sqlString = "ISOLATION LEVEL READ COMMITTED" - } - case object RepeatableRead extends IsolationLevel { - def sqlString = "ISOLATION LEVEL REPEATABLE READ" - } - case object Serializable extends IsolationLevel { - def sqlString = "ISOLATION LEVEL SERIALIZABLE" - } -} \ No newline at end of file diff --git a/sources/scala/dbc/statement/JoinType.scala b/sources/scala/dbc/statement/JoinType.scala deleted file mode 100644 index 60d14cf968..0000000000 --- a/sources/scala/dbc/statement/JoinType.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -/** A join behaviour in a Jointure. */ -abstract class JoinType { - /** A SQL-99 string representation of the join behaviour. */ - def sqlString: String; -} - -object JoinType { - /** A join behaviour where a joined tuple is created only when a - * corresponding tuple exists in both original relations. */ - case object Inner extends JoinType { - val sqlString = "INNER JOIN" - } - /** A join behaviour family where a joined tuple is created even when a - * tuple has no corresponding tuple in the other relation. The fields - * populated by values of the other tuple will receive the NULL value. - */ - abstract class Outer extends JoinType; - object Outer { - /** An outer join behaviour where there will be at least on tuple for - * every tuple in the left relation. */ - case object Left extends Outer { - val sqlString = "LEFT OUTER JOIN" - } - /** An outer join behaviour where there will be at least on tuple for - * every tuple in the right relation. */ - case object Right extends Outer { - val sqlString = "RIGHT OUTER JOIN" - } - /** An outer join behaviour where there will be at least on tuple for - * every tuple in both right and left relations. */ - case object Full extends Outer { - val sqlString = "FULL OUTER JOIN" - } - } -} diff --git a/sources/scala/dbc/statement/Jointure.scala b/sources/scala/dbc/statement/Jointure.scala deleted file mode 100644 index b2ea55d5c9..0000000000 --- a/sources/scala/dbc/statement/Jointure.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -/** A jointure between two relations. */ -abstract class Jointure extends Relation { - - /** The relation on the left part of the join. */ - def leftRelation: Relation; - - /** The relation on the right part of the join. */ - def rightRelation: Relation; - - /** The type of the jointure. */ - def joinType: JoinType; - - /** The condition on which the jointure needs be done. */ - def joinCondition: Option[Expression]; - - /** A SQL-99 compliant string representation of the relation statement. */ - def sqlString: String = { - "SELECT * FROM " + sqlInnerString - } - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside a query. */ - def sqlInnerString: String = ( - leftRelation.sqlInnerString + " " + - joinType.sqlString + " " + - rightRelation.sqlInnerString + - (joinCondition match { - case Some(jc) => jc.sqlString - case None => "" - }) - ) - -} diff --git a/sources/scala/dbc/statement/Relation.scala b/sources/scala/dbc/statement/Relation.scala deleted file mode 100644 index 5e9c24025f..0000000000 --- a/sources/scala/dbc/statement/Relation.scala +++ /dev/null @@ -1,53 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -/** A statement that returns a relation. */ -abstract class Relation extends Statement { - - def isCompatibleType: (DataType,DataType)=>Boolean = - ((dt,wdt)=>dt.isSubtypeOf(wdt)); - - def typeCheck (relation: result.Relation): Unit = { - if (typeCheck != Nil) { - val sameType: Boolean = ( - relation.metadata.length == fieldTypes.length && - (relation.metadata.zip(fieldTypes).forall({case Pair(field,expectedType) => - isCompatibleType(field.datatype, expectedType)})) - ); - if (!sameType) - throw new exception.IncompatibleSchema(fieldTypes,relation.metadata.map(field=>field.datatype)); - } - } - - def fieldTypes: List[DataType]; - - def sqlTypeString: String = - if (fieldTypes.isEmpty) - "UNTYPED" - else - fieldTypes.map(dt=>dt.sqlString).mkString("RELATION (",", ",")"); - - /** A SQL-99 compliant string representation of the statement. */ - def sqlString: String; - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String; - - /** Executes the statement on the given database. */ - def execute (database: scala.dbc.Database): scala.dbc.result.Relation = { - database.executeStatement(this); - } - - def execute (database:scala.dbc.Database, debug:Boolean): scala.dbc.result.Relation = { - database.executeStatement(this,debug); - } - -} diff --git a/sources/scala/dbc/statement/Select.scala b/sources/scala/dbc/statement/Select.scala deleted file mode 100644 index 47c449d0e1..0000000000 --- a/sources/scala/dbc/statement/Select.scala +++ /dev/null @@ -1,91 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -/** A statement that when executed on a database will return a relation. - * The returned relation will be a subset of a table in the database or - * a jointure between such subsets. */ -abstract class Select extends Relation { - - /** Defines if duplicated tuples should be removed from the returned - * relation.

Compatibility notice

Some DBMS (PostgreSQL) allow - * uniqueness constrains on an arbitrary field instead of the entire - * tuple. */ - def setQuantifier: Option[SetQuantifier]; - - /** Defines the output fields that a tuple in the returned relation will - * contain, and their content with respect to the tables in the - * database. If the fields are not specified (that is the list is - * empty), all possible input fields will be returned.

Compatibility - * notice

SQL's qualified asterisk select sublist is not - * available. */ - def selectList: List[DerivedColumn]; - - /** Defines the relations from which the query will obtain its data.*/ - def fromClause: List[Relation]; - - /** Defines condition that must be true in the returned relation's tuples. - * This value expression must return a boolean or boolean-compatible - * value. This condition is applied before any GROUP BY clause. */ - def whereClause: Option[Expression]; - - /** Defines the grouping of the returned relation's tuples. One tuple is - * returned for every group. The value of selectList must - * use aggregate functions for calculation. */ - def groupByClause: Option[List[Expression]]; - - /** Defines conditions that must be true in the returned relation's tuples. - * The value expression must return a boolean can only refer to fields - * that are grouped or to any field from inside an aggregate function. */ - def havingClause: Option[Expression]; - - /* def windowClause: Option[_]; */ - - /** A SQL-99 compliant string representation of the select statement. */ - def sqlString: String = ( - "SELECT" + - (setQuantifier match { - case None => "" - case Some(sq) => " " + sq.sqlString - }) + - (selectList match { - case Nil => " *" - case _ => (" " + selectList.tail.foldLeft(selectList.head.sqlString) - ((name:String, dc:DerivedColumn) => name + ", " + dc.sqlString)) - }) + - (fromClause match { - case Nil => error("Empty from clause is not allowed") - case _ => (" FROM " + fromClause.tail.foldLeft(fromClause.head.sqlInnerString) - ((name:String, rel:Relation) => name + ", " + rel.sqlInnerString)) - }) + - (whereClause match { - case None => "" - case Some(expr) => " WHERE " + expr.sqlInnerString - }) + - (groupByClause match { - case None => "" - case Some(gbl) => gbl match { - case Nil => error("Empty group by clause is not allowed") - case _ => - (" GROUP BY " + - gbl.tail.foldLeft(gbl.head.sqlInnerString) - ((name:String, gb) => name + ", " + gb.sqlInnerString)) - } - }) + - (havingClause match { - case None => "" - case Some(expr) => " HAVING " + expr.sqlString - }) - ); - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside a query. */ - def sqlInnerString: String = "("+sqlString+")"; - -} diff --git a/sources/scala/dbc/statement/SetClause.scala b/sources/scala/dbc/statement/SetClause.scala deleted file mode 100644 index 292879d3d0..0000000000 --- a/sources/scala/dbc/statement/SetClause.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -import scala.dbc.statement.expression._; - -/** Data to be inserted into a table in an Insert. */ -case class SetClause (name:String, expr:Expression) { - val value: Pair[String,Expression] = Pair(name,expr); - def sqlString: String = - value._1 + " = " + value._2.sqlInnerString; -} \ No newline at end of file diff --git a/sources/scala/dbc/statement/SetQuantifier.scala b/sources/scala/dbc/statement/SetQuantifier.scala deleted file mode 100644 index a2fbbb854a..0000000000 --- a/sources/scala/dbc/statement/SetQuantifier.scala +++ /dev/null @@ -1,30 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -/** A set quantifier that defines the collection type of a relation. */ -abstract class SetQuantifier { - /** A SQL-99 compliant string representation of the set quantifier. */ - def sqlString: String; -} - -object SetQuantifier { - /** A set quantifier that defines a relation as being a bag. That means - * that duplicates are allowed. */ - case object AllTuples extends SetQuantifier { - /** A SQL-99 compliant string representation of the set quantifier. */ - def sqlString: String = "ALL"; - } - /** A set quantifier that defines a relation as being a set. That means - * that duplicates are not allowed and will be pruned. */ - case object DistinctTuples extends SetQuantifier { - /** A SQL-99 compliant string representation of the set quantifier. */ - def sqlString: String = "DISTINCT"; - } -} \ No newline at end of file diff --git a/sources/scala/dbc/statement/Statement.scala b/sources/scala/dbc/statement/Statement.scala deleted file mode 100644 index 64f0967483..0000000000 --- a/sources/scala/dbc/statement/Statement.scala +++ /dev/null @@ -1,14 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -/** An ISO-9075:2003 (SQL) statement. */ -abstract class Statement { - -} diff --git a/sources/scala/dbc/statement/Status.scala b/sources/scala/dbc/statement/Status.scala deleted file mode 100644 index 61ab479199..0000000000 --- a/sources/scala/dbc/statement/Status.scala +++ /dev/null @@ -1,26 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -/** A statement that changes the status of the database. */ -abstract class Status extends Statement { - - /** A SQL-99 compliant string representation of the statement. */ - def sqlString: String; - - /** Executes the statement on the given database. */ - def execute (database: scala.dbc.Database): scala.dbc.result.Status[Unit] = { - database.executeStatement(this); - } - - def execute (database: scala.dbc.Database, debug: Boolean): scala.dbc.result.Status[Unit] = { - database.executeStatement(this,debug); - } - -} \ No newline at end of file diff --git a/sources/scala/dbc/statement/Table.scala b/sources/scala/dbc/statement/Table.scala deleted file mode 100644 index 18a065e221..0000000000 --- a/sources/scala/dbc/statement/Table.scala +++ /dev/null @@ -1,36 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -/** A reference to a table in the database. - * @author Gilles Dubochet - * @version 1.0 */ -abstract class Table extends Relation { - - /** The name of the table in the database. */ - def tableName: String; - - /** The name that the table will be called in the enclosing statement. */ - def tableRename: Option[String]; - - /** A SQL-99 compliant string representation of the relation statement. */ - def sqlString: String = { - "SELECT * FROM " + tableName - } - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside a query. */ - def sqlInnerString: String = ( - tableName + - (tableRename match { - case None => "" - case Some(rename) => " AS " + rename - }) - ) -} diff --git a/sources/scala/dbc/statement/Transaction.scala b/sources/scala/dbc/statement/Transaction.scala deleted file mode 100644 index b87c0ccc35..0000000000 --- a/sources/scala/dbc/statement/Transaction.scala +++ /dev/null @@ -1,51 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -/** A statement that changes the status of the database. */ -case class Transaction [ResultType] ( - transactionBody: (scala.dbc.Database=>ResultType), - accessMode: Option[AccessMode], - isolationLevel: Option[IsolationLevel] -) extends Statement { - - /** A SQL-99 compliant string representation of the statement. */ - def sqlStartString: String = ( - "START TRANSACTION" + - (Pair(accessMode,isolationLevel) match { - case Pair(None,None) => "" - case Pair(Some(am),None) => " " + am.sqlString - case Pair(None,Some(il)) => " " + il.sqlString - case Pair(Some(am),Some(il)) => " " + am.sqlString + ", " + il.sqlString - }) - ); - - def sqlCommitString: String = { - "COMMIT" - } - - def sqlAbortString: String = { - "ROLLBACK" - } - - //def transactionBody: (()=>Unit); - - //def accessMode: Option[AccessMode]; - - //def isolationLevel: Option[IsolationLevel]; - - def execute (database: scala.dbc.Database): scala.dbc.result.Status[ResultType] = { - database.executeStatement(this); - } - - def execute (database: scala.dbc.Database, debug: Boolean): scala.dbc.result.Status[ResultType] = { - database.executeStatement(this,debug); - } - -} diff --git a/sources/scala/dbc/statement/Update.scala b/sources/scala/dbc/statement/Update.scala deleted file mode 100644 index bc541200c4..0000000000 --- a/sources/scala/dbc/statement/Update.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement; - -import scala.dbc.statement.expression._; - -/** An update of the state of a table. */ -case class Update ( - updateTarget: String, - setClauses: List[SetClause], - whereClause: Option[Expression] -) extends Status { - - - /** A SQL-99 compliant string representation of the select statement. */ - def sqlString: String = ( - "UPDATE " + - updateTarget + - " SET " + setClauses.map(sc=>sc.sqlString).mkString("",", ","") + - (whereClause match { - case None => "" - case Some(expr) => " WHERE " + expr.sqlString - }) - ); - - /** The name of the table that should be updated. */ - //def updateTarget: String; - - /** The data that will be added tot he table. */ - //def setClauses: List[SetClause]; - - /** Defines condition that must be true in the tuples that will be updated. - * This value expression must return a boolean or boolean-compatible - * value. */ - //def whereClause: Option[scala.dbc.statement.expression.Expression]; - -} diff --git a/sources/scala/dbc/statement/expression/Aggregate.scala b/sources/scala/dbc/statement/expression/Aggregate.scala deleted file mode 100644 index d0dfd6a133..0000000000 --- a/sources/scala/dbc/statement/expression/Aggregate.scala +++ /dev/null @@ -1,30 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement.expression; - -abstract class Aggregate extends Expression { - - def aggregateName: String; - - def setFunction: SetFunction; - - def filterClause: Option[Expression]; - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String = ( - aggregateName + - "(" + setFunction.sqlString + ")" + - (filterClause match { - case None => "" - case Some(fc) => " FILTER (WHERE " + fc.sqlString + ")" - }) - ) - -} diff --git a/sources/scala/dbc/statement/expression/BinaryOperator.scala b/sources/scala/dbc/statement/expression/BinaryOperator.scala deleted file mode 100644 index a0d964a798..0000000000 --- a/sources/scala/dbc/statement/expression/BinaryOperator.scala +++ /dev/null @@ -1,28 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement.expression; - -abstract class BinaryOperator extends Expression { - - /** The name of the operator. */ - def operator: String; - - /** The expression applied on the left of the operator. */ - def leftOperand: Expression; - - /** The expression applied on the right of the operator. */ - def rightOperand: Expression; - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String = { - leftOperand.sqlInnerString + " " + operator + " " + rightOperand.sqlInnerString - } - -} diff --git a/sources/scala/dbc/statement/expression/Constant.scala b/sources/scala/dbc/statement/expression/Constant.scala deleted file mode 100644 index 12a089ea48..0000000000 --- a/sources/scala/dbc/statement/expression/Constant.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement.expression; - -abstract class Constant extends Expression { - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String = constantValue.sqlString; - - /** The value of the constant. */ - def constantValue: Value; -} \ No newline at end of file diff --git a/sources/scala/dbc/statement/expression/Default.scala b/sources/scala/dbc/statement/expression/Default.scala deleted file mode 100644 index 2b84a6ce4f..0000000000 --- a/sources/scala/dbc/statement/expression/Default.scala +++ /dev/null @@ -1,17 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement.expression; - -case object Default extends Expression { - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String = "DEFAULT"; - -} \ No newline at end of file diff --git a/sources/scala/dbc/statement/expression/Field.scala b/sources/scala/dbc/statement/expression/Field.scala deleted file mode 100644 index 55b7c96053..0000000000 --- a/sources/scala/dbc/statement/expression/Field.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement.expression; - -abstract class Field extends Expression { - - /** The name of the schema in the database where the field is located. */ - def schemaName: Option[String] = None; - - /** The name of the table in the database where the field is located. */ - def tableName: Option[String]; - - /** The name of the field in the database. */ - def fieldName: String; - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String = ( - (schemaName match { - case None => "" - case Some(sn) => sn + "." - }) + - (tableName match { - case None => "" - case Some(tn) => tn + "." - }) + fieldName - ) - -} diff --git a/sources/scala/dbc/statement/expression/FunctionCall.scala b/sources/scala/dbc/statement/expression/FunctionCall.scala deleted file mode 100644 index 030b05812b..0000000000 --- a/sources/scala/dbc/statement/expression/FunctionCall.scala +++ /dev/null @@ -1,28 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement.expression; - -case class FunctionCall ( - functionName: String, - arguments: List[Expression] -) extends Expression { - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String = { - functionName + "(" + arguments.mkString("",", ","") + ")" - } - - /** The name of the function to call. */ - //def functionName: String; - - /** A list of all argument expressions to pass to the function, in order. */ - //def arguments: List[Expression]; - -} \ No newline at end of file diff --git a/sources/scala/dbc/statement/expression/Select.scala b/sources/scala/dbc/statement/expression/Select.scala deleted file mode 100644 index bce9a5d002..0000000000 --- a/sources/scala/dbc/statement/expression/Select.scala +++ /dev/null @@ -1,23 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement.expression; - -abstract class Select extends Expression { - - /** The actual select statement */ - def selectStatement: statement.Select; - - /** A SQL-99 compliant string representation of the expression. */ - override def sqlString: String = selectStatement.sqlString; - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String = "("+selectStatement.sqlString+")"; - -} diff --git a/sources/scala/dbc/statement/expression/SetFunction.scala b/sources/scala/dbc/statement/expression/SetFunction.scala deleted file mode 100644 index 6a3ba37d2d..0000000000 --- a/sources/scala/dbc/statement/expression/SetFunction.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement.expression; - -abstract class SetFunction { - /** A SQL-99 compliant string representation of the set quantifier. */ - def sqlString: String; -} - -object SetFunction { - abstract class Asterisk extends SetFunction { - def sqlString = "(*)"; - } - abstract class General extends SetFunction { - def setQuantifier: Option[SetQuantifier]; - def valueExpression: Expression; - def sqlString = ( - "(" + - (setQuantifier match { - case None => "" - case Some(sq) => sq.sqlString + " " - }) + - valueExpression.sqlString + ")" - ); - } - abstract class Binary extends SetFunction { - def sqlString = error("Binary set function is not supported yet."); - } -} diff --git a/sources/scala/dbc/statement/expression/TypeCast.scala b/sources/scala/dbc/statement/expression/TypeCast.scala deleted file mode 100644 index 25d1874381..0000000000 --- a/sources/scala/dbc/statement/expression/TypeCast.scala +++ /dev/null @@ -1,27 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement.expression; - -case class TypeCast ( - expression: Expression, - castType: DataType -) extends Expression { - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String = { - "CAST (" + expression.sqlInnerString + " AS " + castType.sqlString + ")"; - } - - /** The expression that will be casted. */ - //def expression: Expression; - - /** The type to which to cast. */ - //def castType: scala.dbc.datatype.DataType; -} \ No newline at end of file diff --git a/sources/scala/dbc/statement/expression/UnaryOperator.scala b/sources/scala/dbc/statement/expression/UnaryOperator.scala deleted file mode 100644 index 1e7ab028f7..0000000000 --- a/sources/scala/dbc/statement/expression/UnaryOperator.scala +++ /dev/null @@ -1,28 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.statement.expression; - -abstract class UnaryOperator extends Expression { - - /** The name of the operator */ - def operator: String; - - /** Whether the operator comes before the operand or not. */ - def operatorIsLeft: Boolean; - - /** The operand applied to the operator. */ - def operand: Expression; - - /** A SQL-99 compliant string representation of the relation sub- - * statement. This only has a meaning inside another statement. */ - def sqlInnerString: String = operatorIsLeft match { - case true => operator + " " + operand.sqlInnerString; - case false => operand.sqlInnerString + " " + operator; - } -} diff --git a/sources/scala/dbc/syntax/DataTypeUtil.scala b/sources/scala/dbc/syntax/DataTypeUtil.scala deleted file mode 100644 index 1df3d20317..0000000000 --- a/sources/scala/dbc/syntax/DataTypeUtil.scala +++ /dev/null @@ -1,94 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API tests ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.syntax; - -import java.math.BigDecimal; -import java.math.BigInteger; - -object DataTypeUtil { - - final val java_lang_Integer_SIZE = 32; - final val java_lang_Long_SIZE = 64; - - def boolean = new datatype.Boolean; - def tinyint = new datatype.ExactNumeric[Byte](dbc.DataType.BYTE) { - val precisionRadix = 2; - val precision = 8; - val signed = true; - val scale = 0; - } - def smallint = new datatype.ExactNumeric[Short](dbc.DataType.SHORT) { - val precisionRadix = 2; - val precision = 16; - val signed = true; - val scale = 0; - } - def integer = new datatype.ExactNumeric[Int](dbc.DataType.INT) { - val precisionRadix = 2; - val precision = 32; - val signed = true; - val scale = 0; - } - def bigint = new datatype.ExactNumeric[Long](dbc.DataType.LONG) { - val precisionRadix = 2; - val precision = 64; - val signed = true; - val scale = 0; - } - def numeric (_precision:Int): DataType = numeric(_precision,0); - def numeric (_precision:Int, _scale:Int): DataType = - Pair(datatype.Factory.bytePrecision(_precision,true,true),_scale == 0) match { - case Pair(bp,true) if (bp <= java_lang_Integer_SIZE) => - new datatype.ExactNumeric[Int](DataType.INT) { - val precisionRadix = 10; - val precision = _precision; - val signed = true; - val scale = 0; - } - case Pair(bp,true) if (bp <= java_lang_Long_SIZE) => - new datatype.ExactNumeric[Long](DataType.LONG) { - val precisionRadix = 10; - val precision = _precision; - val signed = true; - val scale = 0; - } - case Pair(_,true) => - new datatype.ExactNumeric[BigInteger](DataType.BIG_INTEGER) { - val precisionRadix = 10; - val precision = _precision; - val signed = true; - val scale = 0; - } - case Pair(_,false) => - new datatype.ExactNumeric[BigDecimal](DataType.BIG_DECIMAL) { - val precisionRadix = 10; - val precision = _precision; - val signed = true; - val scale = _scale; - } - } - def real = new datatype.ApproximateNumeric[Float](DataType.FLOAT) { - val precisionRadix = 2; - val precision = 64; - val signed = true; - } - def doublePrecision = new datatype.ApproximateNumeric[Double](DataType.DOUBLE) { - val precisionRadix = 2; - val precision = 128; - val signed = true; - } - def character (_length: Int) = new datatype.Character { - val length = _length; - } - def characterVarying (_length: Int) = new datatype.CharacterVarying { - def length = _length; - } - def characterLargeObject = new datatype.CharacterLargeObject; - -} diff --git a/sources/scala/dbc/syntax/Database.scala b/sources/scala/dbc/syntax/Database.scala deleted file mode 100644 index d819931e95..0000000000 --- a/sources/scala/dbc/syntax/Database.scala +++ /dev/null @@ -1,29 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API tests ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.syntax; - -import java.net.URI; - -object Database { - - def database (server:String, username:String, password:String): dbc.Database = { - val uri = new URI(server); - // Java 1.5 if (uri.toString().contains("postgres")) { - if (uri.toString().indexOf("postgres") != -1) { - new dbc.Database(new vendor.PostgreSQL { - val uri = new URI(server); - val user = username; - val pass = password; - }) - } else { - throw new Exception("No DBMS vendor support could be found for the given URI"); - } - } - -} diff --git a/sources/scala/dbc/syntax/Statement.scala b/sources/scala/dbc/syntax/Statement.scala deleted file mode 100644 index c4dd2e7434..0000000000 --- a/sources/scala/dbc/syntax/Statement.scala +++ /dev/null @@ -1,270 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.syntax; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import StatementExpression._; - -/* - -ASSUMPTIONS: - -IMPROVABLE: -For type safety, all types must be defined. If one is missing, none is taken into account. -It is possible to redefine many types or renamings for a field, in that case, - only the last one is taken into account ("a" as "b" as "c" of boolean as "e" of integer - is equivalent to "a" as "e" of integer). - -FIXED: - -*/ - -object Statement { - - // SELECT ZYGOTE ... - - def select: SelectZygote = new SelectZygote { - val setQuantifier = None; - } - def selectBag: SelectZygote = new SelectZygote { - val setQuantifier = Some(statement.SetQuantifier.AllTuples); - } - def selectSet: SelectZygote = new SelectZygote { - val setQuantifier = Some(statement.SetQuantifier.DistinctTuples); - } - - abstract class SelectZygote { - def setQuantifier: Option[statement.SetQuantifier]; - def fields (sdc:SelectDerivedColumns): SelectOf = new SelectOf { - val setQuantifier = SelectZygote.this.setQuantifier; - val selectList = sdc.selectList; - val selectTypes = sdc.selectTypes; - } - } - - abstract class SelectDerivedField { - def fieldValue: StatementField; - def fieldRename: Option[String] = {val x = None; x} - def fieldType: Option[dbc.DataType] = {val x = None; x} - def as (rename:String): SelectDerivedField = new SelectDerivedField { - val fieldValue = SelectDerivedField.this.fieldValue; - override val fieldRename = Some(rename); - override val fieldType = SelectDerivedField.this.fieldType; - } - def of (datatype:dbc.DataType): SelectDerivedField = new SelectDerivedField { - val fieldValue = SelectDerivedField.this.fieldValue; - override val fieldRename = SelectDerivedField.this.fieldRename; - override val fieldType = Some(datatype); - } - } - - implicit def view (fv:StatementField): SelectDerivedField = new SelectDerivedField { - val fieldValue = fv; - } - - implicit def view (fv:String): SelectDerivedField = new SelectDerivedField { - val fieldValue: StatementField = StatementExpression.view(fv); - } - - abstract class SelectDerivedColumns { - def selectList: List[statement.DerivedColumn]; - def selectTypes: List[DataType]; - def and (sdc:SelectDerivedColumns): SelectDerivedColumns = new SelectDerivedColumns { - val selectList = SelectDerivedColumns.this.selectList ::: sdc.selectList; - val selectTypes = - if (SelectDerivedColumns.this.selectTypes.isEmpty | sdc.selectTypes.isEmpty) - Nil - else - SelectDerivedColumns.this.selectTypes ::: sdc.selectTypes; - } - } - - implicit def view (sdf:SelectDerivedField): SelectDerivedColumns = new SelectDerivedColumns { - val selectList = List(new statement.DerivedColumn { - val valueExpression = sdf.fieldValue.toStatement; - val asClause = sdf.fieldRename; - }); - val selectTypes = if (sdf.fieldType.isEmpty) Nil else List(sdf.fieldType.get); - } - - implicit def view (sdfs:String): SelectDerivedColumns = { - val sdf: SelectDerivedField = sdfs; - view(sdf); - } - - // SELECT OF ... - - abstract class SelectOf { - def setQuantifier: Option[statement.SetQuantifier]; - def selectList: List[statement.DerivedColumn]; - def selectTypes: List[DataType]; - def from (sst:SelectSourceTables): SelectBeyond = new SelectBeyond { - val setQuantifier = SelectOf.this.setQuantifier; - val selectList = SelectOf.this.selectList; - val selectTypes = SelectOf.this.selectTypes; - val fromClause = sst.fromClause; - val whereClause = None; - val groupByClause = None; - val havingClause = None; - } - } - - abstract class SelectSourceTable { - def fromRelation: statement.Relation; - def innerJoin (sst: SelectSourceTable): SelectSourceTable = new SelectSourceTable { - val fromRelation = new statement.Jointure { - val leftRelation = SelectSourceTable.this.fromRelation; - val rightRelation = sst.fromRelation; - val joinType = statement.JoinType.Inner; - val joinCondition = None; - val fieldTypes = leftRelation.fieldTypes ::: rightRelation.fieldTypes; - } - } - def leftOuterJoin (sst: SelectSourceTable): SelectSourceTable = new SelectSourceTable { - val fromRelation = new statement.Jointure { - val leftRelation = SelectSourceTable.this.fromRelation; - val rightRelation = sst.fromRelation; - val joinType = statement.JoinType.Outer.Left; - val joinCondition = None; - val fieldTypes = leftRelation.fieldTypes ::: rightRelation.fieldTypes; - } - } - def rightOuterJoin (sst: SelectSourceTable): SelectSourceTable = new SelectSourceTable { - val fromRelation = new statement.Jointure { - val leftRelation = SelectSourceTable.this.fromRelation; - val rightRelation = sst.fromRelation; - val joinType = statement.JoinType.Outer.Right; - val joinCondition = None; - val fieldTypes = leftRelation.fieldTypes ::: rightRelation.fieldTypes; - } - } - def fullOuterJoin (sst: SelectSourceTable): SelectSourceTable = new SelectSourceTable { - val fromRelation = new statement.Jointure { - val leftRelation = SelectSourceTable.this.fromRelation; - val rightRelation = sst.fromRelation; - val joinType = statement.JoinType.Outer.Full; - val joinCondition = None; - val fieldTypes = leftRelation.fieldTypes ::: rightRelation.fieldTypes; - } - } - } - - implicit def view (sct:String): SelectSourceTable = new SelectSourceTable { - val fromRelation = new statement.Table { - val tableName = sct; - val tableRename = None; - val fieldTypes = Nil; - } - } - - implicit def view (sct:statement.Select): SelectSourceTable = new SelectSourceTable { - val fromRelation = sct; - } - - abstract class SelectSourceTables { - def fromClause: List[statement.Relation]; - def join (sct:SelectSourceTable): SelectSourceTables = new SelectSourceTables { - val fromClause = SelectSourceTables.this.fromClause ::: List(sct.fromRelation); - } - } - - implicit def view (sct:String): SelectSourceTables = new SelectSourceTables { - val fromClause = List(new statement.Table { - val tableName = sct; - val tableRename = None; - val fieldTypes = Nil; - }); - } - - implicit def view (sct:statement.Select): SelectSourceTables = new SelectSourceTables { - val fromClause = List(sct); - } - - implicit def view (sct:SelectSourceTable): SelectSourceTables = new SelectSourceTables { - val fromClause = List(sct.fromRelation); - } - - // SELECT BEYOND ... - - abstract class SelectBeyond { - def setQuantifier: Option[statement.SetQuantifier]; - def selectList: List[statement.DerivedColumn]; - def selectTypes: List[DataType]; - def fromClause: List[statement.Relation]; - def whereClause: Option[statement.Expression]; - def groupByClause: Option[List[statement.Expression]]; - def havingClause: Option[statement.Expression]; - def where (se:StatementExpression): SelectBeyond = new SelectBeyond { - val setQuantifier = SelectBeyond.this.setQuantifier; - val selectList = SelectBeyond.this.selectList; - val selectTypes = SelectBeyond.this.selectTypes; - val fromClause = SelectBeyond.this.fromClause; - val whereClause = Some(se.toStatement); - val groupByClause = SelectBeyond.this.groupByClause; - val havingClause = SelectBeyond.this.havingClause; - } - def groupBy (sgb:SelectGroupBy): SelectBeyond = new SelectBeyond { - val setQuantifier = SelectBeyond.this.setQuantifier; - val selectList = SelectBeyond.this.selectList; - val selectTypes = SelectBeyond.this.selectTypes; - val fromClause = SelectBeyond.this.fromClause; - val whereClause = SelectBeyond.this.whereClause; - val groupByClause = Some(sgb.groupByClause); - val havingClause = SelectBeyond.this.havingClause; - } - def having (se:StatementExpression): SelectBeyond = new SelectBeyond { - val setQuantifier = SelectBeyond.this.setQuantifier; - val selectList = SelectBeyond.this.selectList; - val selectTypes = SelectBeyond.this.selectTypes; - val fromClause = SelectBeyond.this.fromClause; - val whereClause = SelectBeyond.this.whereClause; - val groupByClause = SelectBeyond.this.groupByClause; - val havingClause = Some(se.toStatement); - } - } - - implicit def view (sb:SelectBeyond): statement.Select = new statement.Select { - val setQuantifier = sb.setQuantifier; - val selectList = sb.selectList; - val fromClause = sb.fromClause; - val whereClause = sb.whereClause; - val groupByClause = sb.groupByClause; - val havingClause = sb.havingClause; - val fieldTypes = sb.selectTypes; - } - - abstract class SelectGroupBy { - def groupByClause: List[statement.Expression]; - def then (se:StatementExpression): SelectGroupBy = new SelectGroupBy { - val groupByClause = - SelectGroupBy.this.groupByClause ::: List(se.toStatement); - } - def then (se:String): SelectGroupBy = new SelectGroupBy { - val groupByClause = - SelectGroupBy.this.groupByClause ::: List(new statement.expression.Field { - val tableName = None; - val fieldName = se; - }); - } - } - - implicit def view (se:StatementExpression): SelectGroupBy = new SelectGroupBy { - val groupByClause = List(se.toStatement); - } - - implicit def view (se:String): SelectGroupBy = new SelectGroupBy { - val groupByClause = List(new statement.expression.Field { - val tableName = None; - val fieldName = se; - }); - } - -} diff --git a/sources/scala/dbc/syntax/StatementExpression.scala b/sources/scala/dbc/syntax/StatementExpression.scala deleted file mode 100644 index e03be2a476..0000000000 --- a/sources/scala/dbc/syntax/StatementExpression.scala +++ /dev/null @@ -1,217 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.syntax; - -import java.math.BigDecimal; -import java.math.BigInteger; - -abstract class StatementExpression { - - def toStatement: statement.Expression; - - def and (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "AND"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def or (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "OR"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def == (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "="; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def < (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "<"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def > (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = ">"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def <= (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "<="; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def >= (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = ">="; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def <> (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "<>"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def isNull: StatementExpression = new StatementExpression { - val toStatement = new statement.expression.UnaryOperator { - val operator = "IS NULL"; - val operatorIsLeft = false; - val operand = StatementExpression.this.toStatement; - } - } - def isNotNull: StatementExpression = new StatementExpression { - val toStatement = new statement.expression.UnaryOperator { - val operator = "IS NOT NULL"; - val operatorIsLeft = false; - val operand = StatementExpression.this.toStatement; - } - } - def + (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "+"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def - (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "-"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def * (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "*"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def / (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "/"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def % (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "%"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def ^ (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "^"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def not : StatementExpression = new StatementExpression { - val toStatement = new statement.expression.UnaryOperator { - val operator = "!"; - val operatorIsLeft = false; - val operand = StatementExpression.this.toStatement; - } - } - def || (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "||"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def like (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "LIKE"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def similar (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "SIMILAR"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = se.toStatement; - } - } - def in (se:statement.Select): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.BinaryOperator { - val operator = "IN"; - val leftOperand = StatementExpression.this.toStatement; - val rightOperand = new statement.expression.Select { - val selectStatement = se; - }; - } - } - -} - -object StatementExpression { - - def not (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.UnaryOperator { - val operator = "NOT"; - val operatorIsLeft = true; - val operand = se.toStatement; - } - } - def abs (se:StatementExpression): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.UnaryOperator { - val operator = "@"; - val operatorIsLeft = true; - val operand = se.toStatement; - } - } - def exists (se:statement.Select): StatementExpression = new StatementExpression { - val toStatement = new statement.expression.UnaryOperator { - val operator = "EXISTS"; - val operatorIsLeft = true; - val operand = new statement.expression.Select { - val selectStatement = se; - }; - } - } - - abstract class StatementField extends StatementExpression { - def fieldName: String; - def tableName: Option[String] = None; - def in (tn:String): StatementField = new StatementField { - val fieldName = StatementField.this.fieldName; - override val tableName = Some(tn); - } - def toStatement: statement.expression.Field = new statement.expression.Field { - override val schemaName = None; - val tableName = StatementField.this.tableName; - val fieldName = StatementField.this.fieldName; - } - } - - implicit def view (ef:String): StatementField = new StatementField { - val fieldName = ef; - } - - - - -} diff --git a/sources/scala/dbc/value/ApproximateNumeric.scala b/sources/scala/dbc/value/ApproximateNumeric.scala deleted file mode 100644 index 4b0c495f54..0000000000 --- a/sources/scala/dbc/value/ApproximateNumeric.scala +++ /dev/null @@ -1,24 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.value; - -abstract class ApproximateNumeric [Type] extends Value { - - val dataType: datatype.ApproximateNumeric[Type]; - - def sqlString = nativeValue.toString(); - - } - -object ApproximateNumeric { - - def view (obj:value.ApproximateNumeric[Float]): Float = obj.nativeValue; - def view (obj:value.ApproximateNumeric[Double]): Double = obj.nativeValue; - -} diff --git a/sources/scala/dbc/value/Boolean.scala b/sources/scala/dbc/value/Boolean.scala deleted file mode 100644 index fa20a066af..0000000000 --- a/sources/scala/dbc/value/Boolean.scala +++ /dev/null @@ -1,23 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.value; - -abstract class Boolean extends Value { - - val dataType: datatype.Boolean; - - def sqlString = if (nativeValue) "TRUE" else "FALSE"; - -} - -object Boolean { - - def view (obj:value.Boolean): scala.Boolean = obj.nativeValue; - -} \ No newline at end of file diff --git a/sources/scala/dbc/value/Character.scala b/sources/scala/dbc/value/Character.scala deleted file mode 100644 index 1d5433b991..0000000000 --- a/sources/scala/dbc/value/Character.scala +++ /dev/null @@ -1,31 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.value; - -/** A SQL-99 value of type character string. */ -abstract class Character extends Value { - - override val dataType: datatype.Character; - - /** An SQL-99 compliant string representation of the value. */ - def sqlString: String = { - "'" + nativeValue + "'" - } - -} - -/** An object offering transformation methods (views) on the value. - * This object must be visible in an expression to use value auto- - * conversion. */ -object Character { - - /** A character string value as a native string. */ - def view (obj:value.Character): String = obj.nativeValue; - -} \ No newline at end of file diff --git a/sources/scala/dbc/value/CharacterLargeObject.scala b/sources/scala/dbc/value/CharacterLargeObject.scala deleted file mode 100644 index c4fb7097e0..0000000000 --- a/sources/scala/dbc/value/CharacterLargeObject.scala +++ /dev/null @@ -1,31 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.value; - -/** A SQL-99 value of type character large object. */ -abstract class CharacterLargeObject extends Value { - - override val dataType: datatype.CharacterLargeObject; - - /** An SQL-99 compliant string representation of the value. */ - def sqlString: String = { - "'" + nativeValue + "'" - } - -} - -/** An object offering transformation methods (views) on the value. - * This object must be visible in an expression to use value auto- - * conversion. */ -object CharacterLargeObject { - - /** A character large object value as a native string. */ - def view (obj:value.CharacterLargeObject): String = obj.nativeValue; - -} \ No newline at end of file diff --git a/sources/scala/dbc/value/CharacterVarying.scala b/sources/scala/dbc/value/CharacterVarying.scala deleted file mode 100644 index 61142e536c..0000000000 --- a/sources/scala/dbc/value/CharacterVarying.scala +++ /dev/null @@ -1,31 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.value; - -/** A SQL-99 value of type character varying string. */ -abstract class CharacterVarying extends Value { - - override val dataType: datatype.CharacterVarying; - - /** An SQL-99 compliant string representation of the value. */ - def sqlString: String = { - "'" + nativeValue + "'" - } - -} - -/** An object offering transformation methods (views) on the value. - * This object must be visible in an expression to use value auto- - * conversion. */ -object CharacterVarying { - - /** A character varying string value as a native string. */ - def view (obj:value.CharacterVarying): String = obj.nativeValue; - -} \ No newline at end of file diff --git a/sources/scala/dbc/value/Conversion.scala b/sources/scala/dbc/value/Conversion.scala deleted file mode 100644 index 5c5dda4220..0000000000 --- a/sources/scala/dbc/value/Conversion.scala +++ /dev/null @@ -1,153 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.value; - -import java.math._; - -object Conversion { - - class Illegal (msg:String) extends Exception(msg); - - implicit def view (value:Value): Byte = { - if (value.dataType.nativeTypeId == DataType.BYTE) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Byte]]; - v.nativeValue - } else { - throw new Illegal("Cannot convert value to byte: "+value) - } - } - - implicit def view (value:Value): Short = { - if (value.dataType.nativeTypeId == DataType.BYTE) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Byte]]; - v.nativeValue.coerce - } else if (value.dataType.nativeTypeId == DataType.SHORT) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Short]]; - v.nativeValue - } else { - throw new Illegal("Cannot convert value to short: "+value) - } - } - - implicit def view (value:Value): Int = { - if (value.dataType.nativeTypeId == DataType.BYTE) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Byte]]; - v.nativeValue.coerce - } else if (value.dataType.nativeTypeId == DataType.SHORT) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Short]]; - v.nativeValue.coerce - } else if (value.dataType.nativeTypeId == DataType.INT) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Int]]; - v.nativeValue - } else { - throw new Illegal("Cannot convert value to int: "+value) - } - } - - implicit def view (value:Value): Long = { - if (value.dataType.nativeTypeId == DataType.BYTE) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Byte]]; - v.nativeValue.coerce - } else if (value.dataType.nativeTypeId == DataType.SHORT) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Short]]; - v.nativeValue.coerce - } else if (value.dataType.nativeTypeId == DataType.INT) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Int]]; - v.nativeValue.coerce - } else if (value.dataType.nativeTypeId == DataType.LONG) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Long]]; - v.nativeValue - } else { - throw new Illegal("Cannot convert value to long: "+value) - } - } - - implicit def view (value:Value): BigInteger = { - if (value.dataType.nativeTypeId == DataType.BYTE) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Byte]]; - new BigInteger(v.nativeValue.toString(),10) - } else if (value.dataType.nativeTypeId == DataType.SHORT) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Short]]; - new BigInteger(v.nativeValue.toString(),10) - } else if (value.dataType.nativeTypeId == DataType.INT) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Int]]; - new BigInteger(v.nativeValue.toString(),10) - } else if (value.dataType.nativeTypeId == DataType.LONG) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Long]]; - new BigInteger(v.nativeValue.toString(),10) - } else if (value.dataType.nativeTypeId == DataType.BIG_INTEGER) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[BigInteger]]; - v.nativeValue - } else { - throw new Illegal("Cannot convert value to big integer: "+value) - } - } - - implicit def view (value:Value): BigDecimal = { - if (value.dataType.nativeTypeId == DataType.BYTE) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Byte]]; - new BigDecimal(v.nativeValue.toString()) - } else if (value.dataType.nativeTypeId == DataType.SHORT) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Short]]; - new BigDecimal(v.nativeValue.toString()) - } else if (value.dataType.nativeTypeId == DataType.INT) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Int]]; - new BigDecimal(v.nativeValue.toString()) - } else if (value.dataType.nativeTypeId == DataType.LONG) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[Long]]; - new BigDecimal(v.nativeValue.toString()) - } else if (value.dataType.nativeTypeId == DataType.BIG_INTEGER) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[BigInteger]]; - new BigDecimal(v.nativeValue) - } else if (value.dataType.nativeTypeId == DataType.BIG_DECIMAL) { - val v = value.asInstanceOf[dbc.value.ExactNumeric[BigDecimal]]; - v.nativeValue - } else { - throw new Illegal("Cannot convert value to big decimal: "+value) - } - } - - implicit def view (value:Value): Float = { - if (value.dataType.nativeTypeId == DataType.FLOAT) { - val v = value.asInstanceOf[dbc.value.ApproximateNumeric[Float]]; - v.nativeValue - } else { - throw new Illegal("Cannot convert value to float: "+value) - } - } - - implicit def view (value:Value): Double = { - if (value.dataType.nativeTypeId == DataType.FLOAT) { - val v = value.asInstanceOf[dbc.value.ApproximateNumeric[Float]]; - v.nativeValue.coerce - } else if (value.dataType.nativeTypeId == DataType.DOUBLE) { - val v = value.asInstanceOf[dbc.value.ApproximateNumeric[Double]]; - v.nativeValue - } else { - throw new Illegal("Cannot convert value to double: "+value) - } - } - - implicit def view (value:Value): scala.Boolean = { - if (value.dataType.nativeTypeId == DataType.BOOLEAN) { - val v = value.asInstanceOf[dbc.value.Boolean]; - v.nativeValue - } else { - throw new Illegal("Cannot convert value to boolean: "+value) - } - } - - implicit def view (value:Value): String = value match { - case v:dbc.value.Character => v.nativeValue; - case v:dbc.value.CharacterLargeObject => v.nativeValue; - case v:dbc.value.CharacterVarying => v.nativeValue; - case _ => throw new Illegal("Cannot convert value to string") - } - -} \ No newline at end of file diff --git a/sources/scala/dbc/value/ExactNumeric.scala b/sources/scala/dbc/value/ExactNumeric.scala deleted file mode 100644 index f3e1a54aac..0000000000 --- a/sources/scala/dbc/value/ExactNumeric.scala +++ /dev/null @@ -1,31 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.value; - -import java.math.BigInteger; -import java.math.BigDecimal; - -abstract class ExactNumeric [Type] extends Value { - - val dataType: datatype.ExactNumeric[Type]; - - def sqlString = nativeValue.toString(); - -} - -object ExactNumeric { - - def view (obj:value.ExactNumeric[Byte]): Byte = obj.nativeValue; - def view (obj:value.ExactNumeric[Short]): Short = obj.nativeValue; - def view (obj:value.ExactNumeric[Int]): Int = obj.nativeValue; - def view (obj:value.ExactNumeric[Long]): Long = obj.nativeValue; - def view (obj:value.ExactNumeric[BigInteger]): BigInteger = obj.nativeValue; - def view (obj:value.ExactNumeric[BigDecimal]): BigDecimal = obj.nativeValue; - -} \ No newline at end of file diff --git a/sources/scala/dbc/value/Factory.scala b/sources/scala/dbc/value/Factory.scala deleted file mode 100644 index b24f985354..0000000000 --- a/sources/scala/dbc/value/Factory.scala +++ /dev/null @@ -1,91 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.value; - -import java.math.BigInteger; -import java.math.BigDecimal; - -object Factory { - - def create (result: java.sql.ResultSet, index: Int, expectedDataType: DataType): Value = { - expectedDataType.nativeTypeId match { - case DataType.OBJECT => - new value.Unknown { - val dataType = expectedDataType.asInstanceOf[datatype.Unknown]; - val nativeValue: Object = result.getObject(index); - } - case DataType.STRING => { - expectedDataType match { - case t:datatype.Character => - new value.Character { - val dataType = t; - val nativeValue: String = result.getString(index); - } - case t:datatype.CharacterVarying => - new value.CharacterVarying { - val dataType = t; - val nativeValue: String = result.getString(index); - } - case t:datatype.CharacterLargeObject => - new value.CharacterLargeObject { - val dataType = t; - val nativeValue: String = result.getString(index); - } - } - } - case DataType.BOOLEAN => - new value.Boolean { - val dataType = expectedDataType.asInstanceOf[datatype.Boolean]; - val nativeValue: scala.Boolean = result.getBoolean(index); - } - case DataType.FLOAT => - new value.ApproximateNumeric[Float] { - val dataType = expectedDataType.asInstanceOf[datatype.ApproximateNumeric[Float]]; - val nativeValue: Float = result.getFloat(index); - } - case DataType.DOUBLE => - new value.ApproximateNumeric[Double] { - val dataType = expectedDataType.asInstanceOf[datatype.ApproximateNumeric[Double]]; - val nativeValue: Double = result.getDouble(index); - } - case DataType.BYTE => - new value.ExactNumeric[Byte] { - val dataType = expectedDataType.asInstanceOf[datatype.ExactNumeric[Byte]]; - val nativeValue: Byte = result.getByte(index); - } - case DataType.SHORT => - new value.ExactNumeric[Short] { - val dataType = expectedDataType.asInstanceOf[datatype.ExactNumeric[Short]]; - val nativeValue: Short = result.getShort(index); - } - case DataType.INT => - new value.ExactNumeric[Int] { - val dataType = expectedDataType.asInstanceOf[datatype.ExactNumeric[Int]]; - val nativeValue: Int = result.getInt(index); - } - case DataType.LONG => - new value.ExactNumeric[Long] { - val dataType = expectedDataType.asInstanceOf[datatype.ExactNumeric[Long]]; - val nativeValue:Long = result.getLong(index); - } - case DataType.BIG_INTEGER => - new value.ExactNumeric[BigInteger] { - val dataType = expectedDataType.asInstanceOf[datatype.ExactNumeric[BigInteger]]; - val nativeValue: BigInteger = result.getBigDecimal(index).unscaledValue(); - } - case DataType.BIG_DECIMAL => - new value.ExactNumeric[BigDecimal] { - val dataType = expectedDataType.asInstanceOf[datatype.ExactNumeric[BigDecimal]]; - val nativeValue: BigDecimal = result.getBigDecimal(index); - } - - } - } - -} diff --git a/sources/scala/dbc/value/Unknown.scala b/sources/scala/dbc/value/Unknown.scala deleted file mode 100644 index b40df69011..0000000000 --- a/sources/scala/dbc/value/Unknown.scala +++ /dev/null @@ -1,23 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.value; - -abstract class Unknown extends Value { - - val dataType: datatype.Unknown; - - def sqlString = error ("An 'ANY' value cannot be represented."); - -} - -object UnknownType { - - def view (obj:value.Unknown): Object = obj.nativeValue; - -} \ No newline at end of file diff --git a/sources/scala/dbc/vendor/PostgreSQL.scala b/sources/scala/dbc/vendor/PostgreSQL.scala deleted file mode 100644 index 2653ed714a..0000000000 --- a/sources/scala/dbc/vendor/PostgreSQL.scala +++ /dev/null @@ -1,23 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.dbc.vendor; - -abstract class PostgreSQL extends Vendor { - - def uri:java.net.URI; - def user:String; - def pass:String; - - val retainedConnections = 5; - - val nativeDriverClass = Class.forName("org.postgresql.Driver"); - - val urlProtocolString = "jdbc:postgresql:" - -} \ No newline at end of file diff --git a/sources/scala/io/Position.scala b/sources/scala/io/Position.scala deleted file mode 100644 index ef61e01317..0000000000 --- a/sources/scala/io/Position.scala +++ /dev/null @@ -1,92 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.io; - -/** convenience methods to encode line and column number in one - * single integer. The encode line (column) - * numbers range from 0 to LINE_MASK (COLUMN_MASK), where 0 indicates - * that the line (column) is the undefined and 1 represents the first - * line (column). Line (Column) numbers greater than LINE_MASK - * (COLUMN_MASK) are replaced by LINE_MASK (COLUMN_MASK). Furthermore, - * if the encoded line number is LINE_MASK, the column number is - * always set to 0. - - * The following properties hold: - * - the undefined position is 0: encode(0,0) == 0 - * - encodings are non-negative : encode(line,column) >= 0 - * - position order is preserved: - * (line1 < line2) || (line1 == line2 && column1 < column2) - * implies - * encode(line1,column1) <= encode(line2,column2) - * @author Burak Emir (translated from work by Matthias Zengers and others) - */ -object Position { - - /** Number of bits used to encode the line number */ - final val LINE_BITS = 20; - /** Number of bits used to encode the column number */ - final val COLUMN_BITS = 31 - LINE_BITS; // no negatives => 31 - - /** Mask to decode the line number */ - final val LINE_MASK = (1 << LINE_BITS) - 1; - /** Mask to decode the column number */ - final val COLUMN_MASK = (1 << COLUMN_BITS) - 1; - - /** The undefined position */ - final val NOPOS = 0; - - /** The first position in a source file */ - final val FIRSTPOS = encode(1, 1); - - //######################################################################## - // Public Functions - - /** Encodes a position into a single integer. */ - final def encode(line: Int, column: Int): Int = { - var line1, column1 = 0; - if( line < 0 ) - error(line+" < 0"); - if(( line == 0 )&&(column != 0)) - error(line+","+column+" not allowed"); - if( column < 0 ) - error(line+","+column+" not allowed"); - - {if (line >= LINE_MASK) { - line1 = LINE_MASK; - column1 = 0; - } else { - line1 = line; - if (column > COLUMN_MASK) - column1 = COLUMN_MASK; - else - column1 = column - }} - {(line1 << COLUMN_BITS) | column1;} - } - - /** Returns the line number of the encoded position. */ - final def line(pos: Int): Int = { - (pos >> COLUMN_BITS) & LINE_MASK; - } - - /** Returns the column number of the encoded position. */ - final def column(pos: Int): Int = { - pos & COLUMN_MASK; - } - - /** Returns a string representation of the encoded position. */ - def toString(pos: Int): String = { - val sb = new StringBuffer(); - sb.append(line(pos)); - sb.append(':'); - sb.append(column(pos)); - sb.toString(); - } -} diff --git a/sources/scala/io/Source.scala b/sources/scala/io/Source.scala deleted file mode 100644 index a22657e4be..0000000000 --- a/sources/scala/io/Source.scala +++ /dev/null @@ -1,252 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.io; - -import java.io.{ File, FileInputStream, PrintStream }; - -/** convenience methods to create an iterable representation of a source - * file - * @author buraq - */ -object Source { - - /** creates Source from array of bytes, with empty description - */ - def fromBytes(bytes: Array[Byte]): Source = - fromString(new String(bytes)); - - /** creates Source from array of bytes with given encoding, with empty description - */ - def fromBytes(bytes: Array[Byte], enc: String): Source = - fromString(new String(bytes, enc)); - - /** creates Source from a single char */ - def fromChar(c: Char): Source = { - val it = Iterator.single(c); - new Source { - def reset = fromChar(c); - val iter = it; - } - } - /** creates Source from array of characters, with empty description - */ - def fromChars(chars: Array[Char]): Source = { - val it = Iterator.fromArray(chars); - new Source { - def reset = fromChars(chars); - val iter = it; - } - } - /** creates Source from string, with empty description - */ - def fromString(s: String): Source = { - val it = Iterator.fromString(s); - new Source { - def reset = fromString(s); - val iter = it; - } - } - - /** creates Source from file with given name, setting its description to - * filename. - */ - def fromFile(name: String): Source = - fromFile( new File( name )); - - /** creates Source from file with given name, using given encoding, setting - * its description to filename. - */ - def fromFile(name: String, enc: String): Source = - fromFile( new File( name ), enc); - - /** creates Source from file with given file: URI - */ - def fromFile(uri: java.net.URI): Source = - fromFile(new File(uri)); - - /** creates Source from file, using default character encoding, setting its - * description to filename. - */ - def fromFile(file: java.io.File): Source = { - val arr: Array[Byte] = new Array[Byte]( file.length().asInstanceOf[Int] ); - val is = new FileInputStream( file ); - is.read( arr ); - val s = fromBytes(arr); - return setFileDescriptor(file,s); - } - - /** creates Source from file, using given character encoding, setting its - * description to filename. - */ - def fromFile(file: java.io.File, enc: String): Source = { - val arr: Array[Byte] = new Array[Byte]( file.length().asInstanceOf[Int] ); - val is = new FileInputStream( file ); - is.read( arr ); - val s = fromBytes(arr, enc); - s.descr = file.getName(); - return setFileDescriptor(file,s); - } - - def setFileDescriptor(file: File, s: Source): Source = { - s.descr = new StringBuffer() - .append( "file:" ) - .append( file.getAbsolutePath() ) - .toString(); - s - } - - def fromURL(s:String): Source = - fromURL(new java.net.URL(s)); - - def fromURL(url: java.net.URL): Source = { - val it = new Iterator[Char] { - var data: Int = _; - def hasNext = {data != -1}; - def next = {val x = data.asInstanceOf[char]; data = bufIn.read(); x} - val in = url.openStream(); - val bufIn = new java.io.BufferedInputStream(in); - data = bufIn.read() - } - val s = new Source { - def reset = fromURL(url); - val iter = it; - }; - s.descr = url.toString(); - s - } - -} - -/** an iterable representation of source files. - * calling method reset returns an identical, resetted source - * - * @author buraq - */ -abstract class Source extends Iterator[Char] { - - - // ------ protected values - - /** the actual iterator */ - protected val iter: Iterator[Char]; - - protected var cline = 1; - protected var ccol = 1; - - // ------ public values - - /** position of last character returned by next*/ - var pos = 0; - - /** the last character returned by next. - * the value before the first call to next is undefined. - */ - var ch: Char = _; - - /** description of this source, default empty */ - var descr: String = ""; - - var nerrors = 0; - var nwarnings = 0; - - /** default col increment for tabs '\t', set to 4 initially - */ - var tabinc = 4; - - // - // -- methods - // - - /** convenience method, returns given line (not including newline) - * from Source - */ - def getLine(line: Int): String = { - val buf = new StringBuffer(); - val it = reset; - var i = 0; - - while( it.hasNext && i < (line-1)) - if('\n' == it.next) - i = i + 1; - - if(!it.hasNext) { // this should not happen - throw new java.lang.IllegalArgumentException( - "line "+line+" does not exist?!" - ); - } - var ch = it.next; - while(it.hasNext && '\n' != ch) { - buf.append( ch ); - ch = it.next; - } - val res = buf.toString(); - buf.setLength( 0 ); - res - } - - /** returns true if this source has more characters - */ - def hasNext = iter.hasNext; - - /** returns next character and has the following side-effects: updates - * position (ccol and cline) and assigns the character to ch - */ - def next = { - ch = iter.next; - pos = Position.encode(cline,ccol); - ch match { - case '\n' => - ccol = 1; - cline = cline + 1; - case '\t' => - ccol = ccol + tabinc; - case _ => - ccol = ccol + 1; - } - ch - }; - - - /** reports an error message to console */ - def reportError(pos: Int, msg: String): Unit = { - report(pos, msg, java.lang.System.out); - } - - def reportError(pos: Int, msg: String, out: PrintStream): Unit = { - nerrors = nerrors + 1; - report(pos, msg, java.lang.System.out); - } - - def report(pos: Int, msg: String, out: PrintStream): Unit = { - val line = Position.line(pos); - val col = Position.column(pos); - Console.println(descr+":"+line+":"+col+": "+msg); - Console.println(getLine(line)); - var i = 1; - while( i < col ) { - Console.print(' '); - i = i + 1; - } - Console.println('^'); - } - - /** reports a warning message to java.lang.System.out */ - def reportWarning(pos: Int, msg: String): Unit = - reportWarning(pos, msg, java.lang.System.out); - - def reportWarning(pos: Int, msg: String, out: PrintStream): Unit = { - nwarnings = nwarnings + 1; - report(pos, "warning! "+msg, out); - } - - /** the actual reset method */ - def reset: Source; - -} diff --git a/sources/scala/mobile/Code.scala b/sources/scala/mobile/Code.scala deleted file mode 100644 index 1ce9997a3d..0000000000 --- a/sources/scala/mobile/Code.scala +++ /dev/null @@ -1,234 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.mobile; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - - -/** The class Code provides apply methods - * with different arities (actually up to 9 parameters) to invoke - * a function simply by specifying its name and argument types.

- * - * Example:

- *    val url = new URL("http://scala.epfl.ch/classes/examples.jar");
- *    val obj = new Location(url) create "examples.sort";
- *    val ar = Array(6, 2, 8, 5, 1);
- *    obj[Array[Int], Unit]("println")(ar);
- *    obj[Array[Int], Unit]("sort")(ar);
- *    obj[Array[Int], Unit]("println")(ar);
- * - * @see Location - * - * @author Stephane Micheloud - * @version 1.0, 04/05/2004 - */ -class Code(clazz: java.lang.Class) { - - private type JObject = java.lang.Object; - - private var instance: JObject = _; - - ///////////////////////////// apply methods /////////////////////////////// - - def apply[R](funName: String) = - () => { - val args = Predef.Array[JObject](); - val types = Predef.Array[Class](); - applyFun(funName, args, types).asInstanceOf[R]; - }; - - def apply[A0, R](funName: String) = - (_0: A0) => { - val p = boxValue(_0); - val args = Predef.Array(p._1); - val types = Predef.Array(p._2); - applyFun(funName, args, types).asInstanceOf[R]; - }; - - def apply[A0, A1, R](funName: String) = - (_0: A0, _1: A1) => { - val p0 = boxValue(_0); - val p1 = boxValue(_1); - val args = Predef.Array(p0._1, p1._1); - val types = Predef.Array(p0._2, p1._2); - applyFun(funName, args, types).asInstanceOf[R]; - }; - - def apply[A0, A1, A2, R](funName: String) = - (_0: A0, _1: A1, _2: A2) => { - val p0 = boxValue(_0); - val p1 = boxValue(_1); - val p2 = boxValue(_2); - val args = Predef.Array(p0._1, p1._1, p2._1); - val types = Predef.Array(p0._2, p1._2, p2._2); - applyFun(funName, args, types).asInstanceOf[R]; - }; - - def apply[A0, A1, A2, A3, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3) => { - val p0 = boxValue(_0); - val p1 = boxValue(_1); - val p2 = boxValue(_2); - val p3 = boxValue(_3); - val args = Predef.Array(p0._1, p1._1, p2._1, p3._1); - val types = Predef.Array(p0._2, p1._2, p2._2, p3._2); - applyFun(funName, args, types).asInstanceOf[R]; - }; - - def apply[A0, A1, A2, A3, A4, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4) => { - val p0 = boxValue(_0); - val p1 = boxValue(_1); - val p2 = boxValue(_2); - val p3 = boxValue(_3); - val p4 = boxValue(_4); - val args = Predef.Array(p0._1, p1._1, p2._1, p3._1, p4._1); - val types = Predef.Array(p0._2, p1._2, p2._2, p3._2, p4._2); - applyFun(funName, args, types).asInstanceOf[R]; - }; - - def apply[A0, A1, A2, A3, A4, A5, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5) => { - val p0 = boxValue(_0); - val p1 = boxValue(_1); - val p2 = boxValue(_2); - val p3 = boxValue(_3); - val p4 = boxValue(_4); - val p5 = boxValue(_5); - val args = Predef.Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1); - val types = Predef.Array(p0._2, p1._2, p2._2, p3._2, p4._2, p5._2); - applyFun(funName, args, types).asInstanceOf[R]; - }; - - def apply[A0, A1, A2, A3, A4, A5, A6, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6) => { - val p0 = boxValue(_0); - val p1 = boxValue(_1); - val p2 = boxValue(_2); - val p3 = boxValue(_3); - val p4 = boxValue(_4); - val p5 = boxValue(_5); - val p6 = boxValue(_6); - val args = Predef.Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1); - val types = Predef.Array(p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2); - applyFun(funName, args, types).asInstanceOf[R]; - }; - - def apply[A0, A1, A2, A3, A4, A5, A6, A7, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6, _7: A7) => { - val p0 = boxValue(_0); - val p1 = boxValue(_1); - val p2 = boxValue(_2); - val p3 = boxValue(_3); - val p4 = boxValue(_4); - val p5 = boxValue(_5); - val p6 = boxValue(_6); - val p7 = boxValue(_7); - val args = Predef.Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1, p7._1); - val types = Predef.Array(p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2, p7._2); - applyFun(funName, args, types).asInstanceOf[R]; - }; - - def apply[A0, A1, A2, A3, A4, A5, A6, A7, A8, R](funName: String) = - (_0: A0, _1: A1, _2: A2, _3: A3, _4: A4, _5: A5, _6: A6, _7: A7, _8: A8) => { - val p0 = boxValue(_0); - val p1 = boxValue(_1); - val p2 = boxValue(_2); - val p3 = boxValue(_3); - val p4 = boxValue(_4); - val p5 = boxValue(_5); - val p6 = boxValue(_6); - val p7 = boxValue(_7); - val p8 = boxValue(_8); - val args = Predef.Array(p0._1, p1._1, p2._1, p3._1, p4._1, p5._1, p6._1, p7._1, p8._1); - val types = Predef.Array(p0._2, p1._2, p2._2, p3._2, p4._2, p5._2, p6._2, p7._2, p8._2); - applyFun(funName, args, types).asInstanceOf[R]; - }; - - ////////////////////// private functions /////////////////////// - - private def boxValue(value: Any) = value match { - case x: Byte => Pair(new java.lang.Byte(x), java.lang.Byte.TYPE) - case x: Boolean => Pair(new java.lang.Boolean(x), java.lang.Boolean.TYPE) - case x: Char => Pair(new java.lang.Character(x), java.lang.Character.TYPE) - case x: Short => Pair(new java.lang.Short(x), java.lang.Short.TYPE) - case x: Int => Pair(new java.lang.Integer(x), java.lang.Integer.TYPE) - case x: Long => Pair(new java.lang.Long(x), java.lang.Long.TYPE) - case x: Float => Pair(new java.lang.Float(x), java.lang.Float.TYPE) - case x: Double => Pair(new java.lang.Double(x), java.lang.Double.TYPE) - case _ => - val x = value.asInstanceOf[JObject]; - Pair(x, x.getClass()) - } - - private def isConstructorName(methName: String) = { - var className = clazz.getName(); - val classInx = className.lastIndexOf("."); - val methInx = methName.lastIndexOf("."); - if (classInx > 0 && methInx < 0) - className = className.substring(classInx + 1, className.length()); - methName.equals(className) - } - - private def applyFun(methName: String, args: Array[JObject], argTypes: Array[Class]): JObject = { - try { - val method = clazz.getMethod(methName, argTypes); - var obj: JObject = null; - if (! Modifier.isStatic(method.getModifiers())) { - if (instance == null) { - instance = try { - clazz.newInstance(); - } catch { case _ => - val cs = clazz.getConstructors(); -//Console.println("cs.length=" + cs.length); - if (cs.length > 0) { - cs(0).newInstance(Predef.Array("")) - } else { - error("class " + clazz.getName() + " has no public constructor"); - null - } - } - } - obj = instance; - } - val result = method.invoke(obj, args); - if (result == null) ().asInstanceOf[JObject] else result - } - catch { - case me: NoSuchMethodException => - if (isConstructorName(methName)) { - try { - val cstr = clazz.getConstructor(argTypes); - instance = cstr.newInstance(args); - instance - } - catch { - case e: Exception => - Console.println(e.getMessage()); - e.printStackTrace(); - } - } - else { - Console.println(me.getMessage()); - me.printStackTrace(); - } - null - case e: Exception => - Console.println(e.getMessage()); - e.printStackTrace(); - null - } - } - -} - diff --git a/sources/scala/mobile/Location.scala b/sources/scala/mobile/Location.scala deleted file mode 100644 index c6f7d57648..0000000000 --- a/sources/scala/mobile/Location.scala +++ /dev/null @@ -1,96 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.mobile; - -import java.net._; - -import scala.collection.mutable._; - - -/** The class Location provides a create - * method to instantiate objects from a network location by - * specifying the URL address of the jar/class file.

- * - * An update of the jar/class file should not break your code as far - * as the used class names and method signatures are the same.

- * - * Example:

- *    val url = new URL("http://scala.epfl.ch/classes/examples.jar");
- *    val obj = new Location(url) create "examples.sort";
- * - * @see Code - * - * @author Stephane Micheloud - * @version 1.0, 04/05/2004 - */ -class Location(url: URL) { - - /** A cache containing all class loaders of this location. - */ - private var lcache: Map[URL, ClassLoader] = new HashMap; - - /** The class loader associated with this location. - */ - private val loader = if (url == null) - ClassLoader.getSystemClassLoader() - else - lcache.get(url) match { - case Some(cl) => - cl - case _ => - val cl = new URLClassLoader(Predef.Array(url)); - lcache(url) = cl; - cl - }; - - /** A cache containing all classes of this location. - */ - private var ccache: Map[String, java.lang.Class] = new HashMap; - - /** Return the code description for the string className - * at this location. - * - * @param the name of the class - * @return the code description corresponding to className - */ - def create(className: String) = new Code( - ccache.get(className) match { - case Some(clazz) => - clazz - case _ => - val clazz = if (loader.loadClass(className).isInterface()) { - // Scala source: class A { ... }; - // Java bytecode: interface A.class + class A$class.class - loader.loadClass(className + "$class"); - } - else { - // Scala source: object A { ... }; - // Java bytecode: interface A.class + class A$.class - loader.loadClass(className + "$"); - } - ccache(className) = clazz; - clazz - } - ); - -} - -/** The object Location can be used to instantiate - * objects on the same Java VM. It is just provided to illustrate - * the special case where resources are available locally.

- * - * Example:

- *    val obj = Location.create("xcode.Math");
- *    val x = obj[Int, Int]("square")(5);
- * - * @author Stephane Micheloud - * @version 1.0, 04/05/2004 - */ -object Location extends Location(null); diff --git a/sources/scala/reflect/Code.scala b/sources/scala/reflect/Code.scala deleted file mode 100644 index b354bd753f..0000000000 --- a/sources/scala/reflect/Code.scala +++ /dev/null @@ -1,21 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.reflect; - -abstract class Code; - -case class Ident(sym: Symbol) extends Code; -case class Select(qual: Code, sym: Symbol) extends Code; -case class Literal(value: Any) extends Code; -case class Apply(fun: Code, args: List[Code]) extends Code; -case class TypeApply(fun: Code, args: List[Type]) extends Code; -case class Function(params: List[Symbol], body: Code) extends Code; -case class This(sym: Symbol) extends Code; diff --git a/sources/scala/reflect/Print.scala b/sources/scala/reflect/Print.scala deleted file mode 100644 index decfe933cc..0000000000 --- a/sources/scala/reflect/Print.scala +++ /dev/null @@ -1,113 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.reflect; - -object Print extends Function1[Any, String] { - - def apply (any: Any): String = { - if (any.isInstanceOf[TypedCode[Any]]) - apply(any.asInstanceOf[TypedCode[Any]]) - else if (any.isInstanceOf[Code]) - apply(any.asInstanceOf[Code]) - else if (any.isInstanceOf[Symbol]) - apply(any.asInstanceOf[Symbol]) - else if (any.isInstanceOf[Type]) - apply(any.asInstanceOf[Type]) - else "UnknownAny" - } - - def apply (typedCode: TypedCode[Any]): String = - Print(typedCode.code); - - def apply (code: Code): String = code match { - case reflect.Ident(sym) => - "Ident (" + Print(sym) + ")" - case reflect.Select(qual, sym) => - "Select (" + Print(qual) + " from " + Print(sym) + ")" - case reflect.Literal(value) => - "Literal (" + value + ")" - case reflect.Apply(fun, args) => - ("Apply (" + Print(fun) + " on " + - ((args match { - case Nil => "nothing " - case _ :: _ => args.map(Print).mkString("", ", ", "") - }):String) + ")") - case reflect.TypeApply(fun, args) => - ("TypeApply (" + Print(fun) + " on " + - ((args match { - case Nil => "nothing" - case _ :: _ => args.map(Print).mkString("", ", ", "") - }):String) + ")") - case reflect.Function(params, body) => - ("Function (" + - ((params match { - case Nil => "nothing" - case _ :: _ => params.map(Print).mkString("", ", ", "") - }):String) + " is " + Print(body) + ")") - case reflect.This(sym) => - "This (" + Print(sym) + ")" - case _ => "UnknownCode" - } - - def apply (symbol: Symbol): String = symbol match { - case reflect.Class(name) => - "Class (" + name + ")" - case reflect.Method(name, datatype) => - "Method (" + name + " of " + Print(datatype) + ")" - case reflect.Field(name, datatype) => - "Field (" + name + " of " + Print(datatype) + ")" - case reflect.TypeField(name, datatype) => - "TypeField (" + name + " of " + Print(datatype) + ")" - case reflect.LocalValue(owner, name, datatype) => - ("LocalValue (" + name + " owned by " + Print(owner) + - " of " + Print(datatype) + ")") - case reflect.LocalMethod(owner, name, datatype) => - ("LocalMethod (" + name + " owned by " + Print(owner) + - " of " + Print(datatype) + ")") - case reflect.NoSymbol => "NoSymbol" - case reflect.RootSymbol => "RootSymbol" - case _ => "UnknownSymbol" - } - - def apply (datatype: Type): String = datatype match { - case reflect.NoPrefix => "NoPrefix" - case reflect.NoType => "NoType" - case reflect.NamedType(name) => - "NamedType (" + name + ")" - case reflect.PrefixedType(prefix, symbol) => - "PrefixedType (" + Print(symbol) + " in " + Print(prefix) + ")" - case reflect.SingleType(prefix, symbol) => - "SingleType (" + Print(symbol) + " in " + Print(prefix) + ")" - case reflect.ThisType(clazz) => - "ThisType (" + Print(clazz) + ")" - case reflect.AppliedType(datatype, args) => - ("AppliedType (" + Print(datatype) + " on " + - ((args match { - case Nil => "nothing" - case _ :: _ => args.map(Print).mkString("", ", ", "") - }):String) + ")") - case reflect.TypeBounds(lo, hi) => - "TypeBounds (" + Print(lo) + " to " + Print(hi) + ")" - case reflect.MethodType(formals, resultType) => - ("MethodType (" + - ((formals match { - case Nil => "nothing" - case _ :: _ => formals.map(Print).mkString("", ", ", "") - }):String) + " is " + Print(resultType) + ")") - case reflect.PolyType(typeParams, typeBounds, resultType) => - ("PolyType (" + (typeParams zip typeBounds).map{ - case Pair(typeParam, Pair(lo, hi)) => - Print(lo) + " < " + Print(typeParam) + " < " + Print(hi) - }.mkString("", ", ", "") + " to " + Print(resultType) + ")") - case _ => "UnknownType" - } - -} diff --git a/sources/scala/reflect/Symbol.scala b/sources/scala/reflect/Symbol.scala deleted file mode 100644 index 14be8e9317..0000000000 --- a/sources/scala/reflect/Symbol.scala +++ /dev/null @@ -1,51 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ -package scala.reflect; - -abstract class Symbol { - val owner: Symbol; - val name: String; - val tpe: Type; -} - -abstract class GlobalSymbol(val fullname: String) extends Symbol { - private val pointIndex = fullname.lastIndexOf('.'); - val owner: Symbol = - if (pointIndex < 0) RootSymbol else Class(fullname.substring(0, pointIndex)); - val name: String = - if (pointIndex < 0) fullname else fullname.substring(pointIndex, fullname.length()); -} - -abstract class LocalSymbol extends Symbol {} - -case class Class(override val fullname: String) extends GlobalSymbol(fullname) { - val tpe = NamedType(fullname); -} - -case class Method(override val fullname: String, tpe: Type) extends GlobalSymbol(fullname); - -case class Field(override val fullname: String, tpe: Type) extends GlobalSymbol(fullname); - -case class TypeField(override val fullname: String, tpe: Type) extends GlobalSymbol(fullname); - -case class LocalValue(owner: Symbol, name: String, tpe: Type) extends LocalSymbol; - -case class LocalMethod(owner: Symbol, name: String, tpe: Type) extends LocalSymbol; - -case object NoSymbol extends Symbol { - val owner = null; - val name = null; - val tpe = NoType -} - -case object RootSymbol extends Symbol { - val owner = NoSymbol; - val name = ""; - val tpe = NoPrefix -} diff --git a/sources/scala/reflect/Type.scala b/sources/scala/reflect/Type.scala deleted file mode 100644 index c0b86162f6..0000000000 --- a/sources/scala/reflect/Type.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.reflect; - -abstract class Type; - -case object NoPrefix extends Type; -case object NoType extends Type; - -/** fullname */ -case class NamedType(fullname: String) extends Type; - -/** pre # sym */ -case class PrefixedType(pre: Type, sym: Symbol) extends Type; - -/** pre.type # sym == pre.sym */ -case class SingleType(pre: Type, sym: Symbol) extends Type; - -/** clazz.this */ -case class ThisType(clazz: Symbol) extends Type; - -/** clazz.super[superClazz] */ -/** tpe[args1, ..., argsn] */ -case class AppliedType(tpe: Type, args: List[Type]) extends Type; - -/** [a <: lo >: hi] */ -case class TypeBounds(lo: Type, hi: Type) extends Type; - -/** (formals1 ... formalsn) restpe */ -case class MethodType(formals: List[Type], restpe: Type) extends Type; - -/** */ -case class PolyType(typeParams: List[Symbol], typeBounds: List[Pair[Type, Type]], resultType: Type) extends Type; - -/** */ -class ImplicitMethodType(formals: List[Type], restpe: Type) extends MethodType(formals, restpe); diff --git a/sources/scala/reflect/TypedCode.scala b/sources/scala/reflect/TypedCode.scala deleted file mode 100644 index 38ce0512c7..0000000000 --- a/sources/scala/reflect/TypedCode.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ -package scala.reflect; - -class TypedCode[T](val code: Code) { -} - diff --git a/sources/scala/remote.scala b/sources/scala/remote.scala deleted file mode 100644 index 825cfbdc44..0000000000 --- a/sources/scala/remote.scala +++ /dev/null @@ -1,12 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id:$ -*/ - -package scala; - -class remote extends Attribute {} diff --git a/sources/scala/runtime/AtomicReference.java b/sources/scala/runtime/AtomicReference.java deleted file mode 100644 index 7eb4abdb0e..0000000000 --- a/sources/scala/runtime/AtomicReference.java +++ /dev/null @@ -1,54 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -/** - * Blocking (i.e. non-atomic) placeholder for Java 1.5's - * java.util.concurrent.atomic.AtomicReference class. - */ - -public class AtomicReference implements java.io.Serializable { - private Object value; - - public AtomicReference(Object value) { - this.value = value; - } - - public Object get() { - return value; - } - - public Object getAndSet(Object update) { - Object previousValue = value; - value = update; - return previousValue; - } - - public void set(Object update) { - value = update; - } - - public synchronized boolean compareAndSet(Object expected, Object update) { - if (value == expected) { - value = update; - return true; - } else - return false; - } - - public boolean weakCompareAndSet(Object expected, Object update) { - return compareAndSet(expected, update); - } - - public String toString() { - return value.toString(); - } -} diff --git a/sources/scala/runtime/BooleanRef.java b/sources/scala/runtime/BooleanRef.java deleted file mode 100644 index f0ebcabe97..0000000000 --- a/sources/scala/runtime/BooleanRef.java +++ /dev/null @@ -1,16 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -public class BooleanRef implements java.io.Serializable { - public boolean elem; - public BooleanRef(boolean elem) { this.elem = elem; } -} diff --git a/sources/scala/runtime/BoxedAnyArray.scala b/sources/scala/runtime/BoxedAnyArray.scala deleted file mode 100644 index ac37a62427..0000000000 --- a/sources/scala/runtime/BoxedAnyArray.scala +++ /dev/null @@ -1,154 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -/** Arrays created by new Array[T](length) where T is a type variable - */ -[serializable] -final class BoxedAnyArray(val length: Int) extends BoxedArray { - - private var boxed = new Array[Object](length); - private val hash = boxed.hashCode(); - private var unboxed: Object = null; - private var elemTag: String = null; - - def apply(index: Int): Object = synchronized { - if (unboxed == null) - boxed(index); - else if (elemTag == ScalaRunTime.IntTag) - BoxedInt.box(unboxed.asInstanceOf[Array[Int]](index)) - else if (elemTag == ScalaRunTime.DoubleTag) - BoxedDouble.box(unboxed.asInstanceOf[Array[Double]](index)) - else if (elemTag == ScalaRunTime.FloatTag) - BoxedFloat.box(unboxed.asInstanceOf[Array[Float]](index)) - else if (elemTag == ScalaRunTime.LongTag) - BoxedLong.box(unboxed.asInstanceOf[Array[Long]](index)) - else if (elemTag == ScalaRunTime.CharTag) - BoxedChar.box(unboxed.asInstanceOf[Array[Char]](index)) - else if (elemTag == ScalaRunTime.ByteTag) - BoxedByte.box(unboxed.asInstanceOf[Array[Byte]](index)) - else if (elemTag == ScalaRunTime.ShortTag) - BoxedShort.box(unboxed.asInstanceOf[Array[Short]](index)) - else if (elemTag == ScalaRunTime.BooleanTag) - BoxedBoolean.box(unboxed.asInstanceOf[Array[Boolean]](index)) - else - unboxed.asInstanceOf[Array[Object]](index) - } - - def update(index: Int, elem: Object): Unit = synchronized { - if (unboxed == null) - boxed(index) = elem; - else if (elemTag == ScalaRunTime.IntTag) - unboxed.asInstanceOf[Array[Int]](index) = elem.asInstanceOf[BoxedNumber].intValue() - else if (elemTag == ScalaRunTime.DoubleTag) - unboxed.asInstanceOf[Array[Double]](index) = elem.asInstanceOf[BoxedNumber].doubleValue() - else if (elemTag == ScalaRunTime.FloatTag) - unboxed.asInstanceOf[Array[Float]](index) = elem.asInstanceOf[BoxedNumber].floatValue() - else if (elemTag == ScalaRunTime.LongTag) - unboxed.asInstanceOf[Array[Long]](index) = elem.asInstanceOf[BoxedNumber].longValue() - else if (elemTag == ScalaRunTime.CharTag) - unboxed.asInstanceOf[Array[Char]](index) = elem.asInstanceOf[BoxedNumber].charValue() - else if (elemTag == ScalaRunTime.ByteTag) - unboxed.asInstanceOf[Array[Byte]](index) = elem.asInstanceOf[BoxedNumber].byteValue() - else if (elemTag == ScalaRunTime.ShortTag) - unboxed.asInstanceOf[Array[Short]](index) = elem.asInstanceOf[BoxedNumber].shortValue() - else if (elemTag == ScalaRunTime.BooleanTag) - unboxed.asInstanceOf[Array[Boolean]](index) = elem.asInstanceOf[BoxedBoolean].value - else - unboxed.asInstanceOf[Array[Object]](index) = elem - } - - def unbox(elemTag: String): Object = synchronized { - if (unboxed == null) { - this.elemTag = elemTag; - if (elemTag == ScalaRunTime.IntTag) { - val newvalue = new Array[Int](length); - var i = 0; - while (i < length) { - newvalue(i) = boxed(i).asInstanceOf[BoxedNumber].intValue(); - i = i + 1 - } - unboxed = newvalue; - } else if (elemTag == ScalaRunTime.DoubleTag) { - val newvalue = new Array[Double](length); - var i = 0; - while (i < length) { - newvalue(i) = boxed(i).asInstanceOf[BoxedNumber].doubleValue(); - i = i + 1 - } - unboxed = newvalue; - } else if (elemTag == ScalaRunTime.FloatTag) { - val newvalue = new Array[Float](length); - var i = 0; - while (i < length) { - newvalue(i) = boxed(i).asInstanceOf[BoxedNumber].floatValue(); - i = i + 1 - } - unboxed = newvalue; - } else if (elemTag == ScalaRunTime.LongTag) { - val newvalue = new Array[Long](length); - var i = 0; - while (i < length) { - newvalue(i) = boxed(i).asInstanceOf[BoxedNumber].longValue(); - i = i + 1 - } - unboxed = newvalue; - } else if (elemTag == ScalaRunTime.CharTag) { - val newvalue = new Array[Char](length); - var i = 0; - while (i < length) { - newvalue(i) = boxed(i).asInstanceOf[BoxedNumber].charValue(); - i = i + 1 - } - unboxed = newvalue; - } else if (elemTag == ScalaRunTime.ByteTag) { - val newvalue = new Array[Byte](length); - var i = 0; - while (i < length) { - newvalue(i) = boxed(i).asInstanceOf[BoxedNumber].byteValue(); - i = i + 1 - } - unboxed = newvalue; - } else if (elemTag == ScalaRunTime.ShortTag) { - val newvalue = new Array[Short](length); - var i = 0; - while (i < length) { - newvalue(i) = boxed(i).asInstanceOf[BoxedNumber].shortValue(); - i = i + 1 - } - unboxed = newvalue; - } else if (elemTag == ScalaRunTime.BooleanTag) { - val newvalue = new Array[Boolean](length); - var i = 0; - while (i < length) { - newvalue(i) = boxed(i).asInstanceOf[BoxedBoolean].value; - i = i + 1 - } - unboxed = newvalue; - } else if (elemTag == boxed.getClass().getComponentType()) { - unboxed = boxed; - } else { - unboxed = java.lang.reflect.Array.newInstance(Class.forName(elemTag), length); - System.arraycopy(boxed, 0, unboxed, 0, length); - } - boxed = null - } - unboxed - } - - override def equals(other: Any): Boolean = ( - other.isInstanceOf[BoxedAnyArray] && (this eq (other.asInstanceOf[BoxedAnyArray])) || - (if (unboxed == null) boxed == other else unboxed == other) - ); - - override def hashCode(): Int = hash; -} - diff --git a/sources/scala/runtime/BoxedArray.scala b/sources/scala/runtime/BoxedArray.scala deleted file mode 100644 index 29b4ccf0e2..0000000000 --- a/sources/scala/runtime/BoxedArray.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ -package scala.runtime; - -/** A class representing Array[T] - */ -abstract class BoxedArray extends PartialFunction[Int, Object] with Seq[Object] { - /** The length of the array */ - def length: Int; - - /** The element at given index */ - def apply(index: Int): Object; - - /** Update element at given index */ - def update(index: Int, elem: Object): Unit; - - /** Convert to Java array. - * @param elemTag Either one of the tags ".N" where N is the name of a primitive type - * (@see ScalaRunTime), or a full class name. - */ - def unbox(elemTag: String): Object; - - override def isDefinedAt(x: Int): Boolean = 0 <= x && x < length; - - override def toString(): String = { - val buf = new StringBuffer(); - buf.append("Array("); - val len = length; - var i = 0; - while (i < len) { buf.append(apply(i)); i = i + 1 } - buf.append(")"); - buf.toString() - } - - def elements = new Iterator[Object] { - var index = 0; - def hasNext: Boolean = index < length; - def next: Object = { val i = index; index = i + 1; apply(i) } - } -} diff --git a/sources/scala/runtime/BoxedBoolean.java b/sources/scala/runtime/BoxedBoolean.java deleted file mode 100644 index ad7ec887e4..0000000000 --- a/sources/scala/runtime/BoxedBoolean.java +++ /dev/null @@ -1,49 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -public final class BoxedBoolean - implements java.io.Serializable -{ - - private final static BoxedBoolean TRUE = new BoxedBoolean(true); - private final static BoxedBoolean FALSE = new BoxedBoolean(false); - - public static BoxedBoolean box(boolean value) { - return (value ? TRUE : FALSE); - } - - public final boolean value; - - private BoxedBoolean(boolean value) { this.value = value; } - - public final boolean booleanValue() { return value; } - - public final boolean $eq$eq(java.lang.Object other) { - return equals(other); - } - - public final boolean $bang$eq(java.lang.Object other) { - return !equals(other); - } - - public boolean equals(java.lang.Object other) { - return other instanceof BoxedBoolean && value == ((BoxedBoolean) other).value; - } - - public int hashCode() { - return value ? 1 : 0; - } - - public String toString() { - return String.valueOf(value); - } -} diff --git a/sources/scala/runtime/BoxedBooleanArray.scala b/sources/scala/runtime/BoxedBooleanArray.scala deleted file mode 100644 index 27b4af2643..0000000000 --- a/sources/scala/runtime/BoxedBooleanArray.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -[serializable] -final class BoxedBooleanArray(val value: Array[Boolean]) extends BoxedArray { - - def length: Int = value.length; - - def apply(index: Int): Object = BoxedBoolean.box(value(index)); - - def update(index: Int, elem: Object): Unit = { - value(index) = elem.asInstanceOf[BoxedBoolean].value - } - - def unbox(elemTag: String): Object = value; - - override def equals(other: Any) = ( - value == other || - other.isInstanceOf[BoxedBooleanArray] && value == other.asInstanceOf[BoxedBooleanArray].value - ); - - override def hashCode(): Int = value.hashCode(); -} - diff --git a/sources/scala/runtime/BoxedByte.java b/sources/scala/runtime/BoxedByte.java deleted file mode 100644 index b29570081e..0000000000 --- a/sources/scala/runtime/BoxedByte.java +++ /dev/null @@ -1,58 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ -package scala.runtime; - -public final class BoxedByte extends BoxedNumber - implements java.io.Serializable -{ - - private static final int MinHashed = -128; - private static final int MaxHashed = 127; - private static BoxedByte[] canonical = new BoxedByte[MaxHashed - MinHashed + 1]; - - static { - for (int i = MinHashed; i <= MaxHashed; i++) - canonical[i - MinHashed] = new BoxedByte((byte)i); - } - - public static BoxedByte box(byte value) { - return canonical[value - MinHashed]; - } - - public final byte value; - - private BoxedByte(byte value) { this.value = value; } - - public byte byteValue() { return (byte)value; } - public short shortValue() { return (short)value; } - public char charValue() { return (char)value; } - public int intValue() { return (int)value; } - public long longValue() { return (long)value; } - public float floatValue() { return (float)value; } - public double doubleValue() { return (double)value; } - - public final boolean $eq$eq(java.lang.Object other) { - return equals(other); - } - - public final boolean $bang$eq(java.lang.Object other) { - return !equals(other); - } - - public boolean equals(java.lang.Object other) { - return other instanceof BoxedNumber && value == ((BoxedNumber) other).byteValue(); - } - - public int hashCode() { - return value; - } - - public String toString() { - return String.valueOf(value); - } -} diff --git a/sources/scala/runtime/BoxedByteArray.scala b/sources/scala/runtime/BoxedByteArray.scala deleted file mode 100644 index e011b8e805..0000000000 --- a/sources/scala/runtime/BoxedByteArray.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -[serializable] -final class BoxedByteArray(val value: Array[Byte]) extends BoxedArray { - - def length: Int = value.length; - - def apply(index: Int): Object = BoxedByte.box(value(index)); - - def update(index: Int, elem: Object): Unit = { - value(index) = elem.asInstanceOf[BoxedNumber].byteValue() - } - - def unbox(elemTag: String): Object = value; - - override def equals(other: Any) = ( - value == other || - other.isInstanceOf[BoxedByteArray] && value == other.asInstanceOf[BoxedByteArray].value - ); - - override def hashCode(): Int = value.hashCode(); -} - diff --git a/sources/scala/runtime/BoxedChar.java b/sources/scala/runtime/BoxedChar.java deleted file mode 100644 index 02b81e111d..0000000000 --- a/sources/scala/runtime/BoxedChar.java +++ /dev/null @@ -1,59 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ -package scala.runtime; - -public class BoxedChar extends BoxedNumber - implements java.io.Serializable -{ - - private static final int MinHashed = 0; - private static final int MaxHashed = 255; - private static BoxedChar[] canonical = new BoxedChar[MaxHashed - MinHashed + 1]; - - static { - for (int i = MinHashed; i <= MaxHashed; i++) - canonical[i - MinHashed] = new BoxedChar((char)i); - } - - public static BoxedChar box(char value) { - if (MinHashed <= value && value <= MaxHashed) return canonical[value - MinHashed]; - else return new BoxedChar(value); - } - - public final char value; - - private BoxedChar(char value) { this.value = value; } - - public byte byteValue() { return (byte)value; } - public short shortValue() { return (short)value; } - public char charValue() { return (char)value; } - public int intValue() { return (int)value; } - public long longValue() { return (long)value; } - public float floatValue() { return (float)value; } - public double doubleValue() { return (double)value; } - - public final boolean $eq$eq(java.lang.Object other) { - return equals(other); - } - - public final boolean $bang$eq(java.lang.Object other) { - return !equals(other); - } - - public boolean equals(java.lang.Object other) { - return other instanceof BoxedNumber && value == ((BoxedNumber) other).charValue(); - } - - public int hashCode() { - return value; - } - - public String toString() { - return String.valueOf(value); - } -} diff --git a/sources/scala/runtime/BoxedCharArray.scala b/sources/scala/runtime/BoxedCharArray.scala deleted file mode 100644 index 49e3cba25c..0000000000 --- a/sources/scala/runtime/BoxedCharArray.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -[serializable] -final class BoxedCharArray(val value: Array[Char]) extends BoxedArray { - - def length: Int = value.length; - - def apply(index: Int): Object = BoxedChar.box(value(index)); - - def update(index: Int, elem: Object): Unit = { - value(index) = elem.asInstanceOf[BoxedNumber].charValue() - } - - def unbox(elemTag: String): Object = value; - - override def equals(other: Any) = ( - value == other || - other.isInstanceOf[BoxedCharArray] && value == other.asInstanceOf[BoxedCharArray].value - ); - - override def hashCode(): Int = value.hashCode(); -} - diff --git a/sources/scala/runtime/BoxedDouble.java b/sources/scala/runtime/BoxedDouble.java deleted file mode 100644 index 98736f03a4..0000000000 --- a/sources/scala/runtime/BoxedDouble.java +++ /dev/null @@ -1,50 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ -package scala.runtime; - -public class BoxedDouble extends BoxedNumber - implements java.io.Serializable -{ - - public static BoxedDouble box(double value) { - return new BoxedDouble(value); - } - - public final double value; - - private BoxedDouble(double value) { this.value = value; } - - public final byte byteValue() { return (byte)value; } - public final short shortValue() { return (short)value; } - public final char charValue() { return (char)value; } - public final int intValue() { return (int)value; } - public final long longValue() { return (long)value; } - public final float floatValue() { return (float)value; } - public final double doubleValue() { return (double)value; } - - public final boolean $eq$eq(java.lang.Object other) { - return equals(other); - } - - public final boolean $bang$eq(java.lang.Object other) { - return !equals(other); - } - - public boolean equals(java.lang.Object other) { - return other instanceof BoxedNumber && value == ((BoxedNumber) other).doubleValue(); - } - - public int hashCode() { - long bits = java.lang.Double.doubleToLongBits(value); - return (int)(bits ^ (bits >>> 32)); - } - - public String toString() { - return String.valueOf(value); - } -} diff --git a/sources/scala/runtime/BoxedDoubleArray.scala b/sources/scala/runtime/BoxedDoubleArray.scala deleted file mode 100644 index 752ab99950..0000000000 --- a/sources/scala/runtime/BoxedDoubleArray.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -[serializable] -final class BoxedDoubleArray(val value: Array[Double]) extends BoxedArray { - - def length: Int = value.length; - - def apply(index: Int): Object = BoxedDouble.box(value(index)); - - def update(index: Int, elem: Object): Unit = { - value(index) = elem.asInstanceOf[BoxedNumber].doubleValue() - } - - def unbox(elemTag: String): Object = value; - - override def equals(other: Any) = ( - value == other || - other.isInstanceOf[BoxedDoubleArray] && value == other.asInstanceOf[BoxedDoubleArray].value - ); - - override def hashCode(): Int = value.hashCode(); -} - diff --git a/sources/scala/runtime/BoxedFloat.java b/sources/scala/runtime/BoxedFloat.java deleted file mode 100644 index 630ee6bece..0000000000 --- a/sources/scala/runtime/BoxedFloat.java +++ /dev/null @@ -1,49 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ -package scala.runtime; - -public class BoxedFloat extends BoxedNumber - implements java.io.Serializable -{ - - public static BoxedFloat box(float value) { - return new BoxedFloat(value); - } - - public final float value; - - private BoxedFloat(float value) { this.value = value; } - - public final byte byteValue() { return (byte)value; } - public final short shortValue() { return (short)value; } - public final char charValue() { return (char)value; } - public final int intValue() { return (int)value; } - public final long longValue() { return (long)value; } - public final float floatValue() { return (float)value; } - public final double doubleValue() { return (double)value; } - - public final boolean $eq$eq(java.lang.Object other) { - return equals(other); - } - - public final boolean $bang$eq(java.lang.Object other) { - return !equals(other); - } - - public boolean equals(java.lang.Object other) { - return other instanceof BoxedNumber && value == ((BoxedNumber) other).floatValue(); - } - - public int hashCode() { - return java.lang.Float.floatToIntBits(value); - } - - public String toString() { - return String.valueOf(value); - } -} diff --git a/sources/scala/runtime/BoxedFloatArray.scala b/sources/scala/runtime/BoxedFloatArray.scala deleted file mode 100644 index bdf25b8f6b..0000000000 --- a/sources/scala/runtime/BoxedFloatArray.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -[serializable] -final class BoxedFloatArray(val value: Array[Float]) extends BoxedArray { - - def length: Int = value.length; - - def apply(index: Int): Object = BoxedFloat.box(value(index)); - - def update(index: Int, elem: Object): Unit = { - value(index) = elem.asInstanceOf[BoxedNumber].floatValue() - } - - def unbox(elemTag: String): Object = value; - - override def equals(other: Any) = ( - value == other || - other.isInstanceOf[BoxedFloatArray] && value == other.asInstanceOf[BoxedFloatArray].value - ); - - override def hashCode(): Int = value.hashCode(); -} - diff --git a/sources/scala/runtime/BoxedInt.java b/sources/scala/runtime/BoxedInt.java deleted file mode 100644 index 9842fde1ad..0000000000 --- a/sources/scala/runtime/BoxedInt.java +++ /dev/null @@ -1,59 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ -package scala.runtime; - -public final class BoxedInt extends BoxedNumber - implements java.io.Serializable -{ - - private static final int MinHashed = -128; - private static final int MaxHashed = 1024; - private static BoxedInt[] canonical = new BoxedInt[MaxHashed - MinHashed + 1]; - - static { - for (int i = MinHashed; i <= MaxHashed; i++) - canonical[i - MinHashed] = new BoxedInt(i); - } - - public static BoxedInt box(int value) { - if (MinHashed <= value && value <= MaxHashed) return canonical[value - MinHashed]; - else return new BoxedInt(value); - } - - public final int value; - - private BoxedInt(int value) { this.value = value; } - - public final byte byteValue() { return (byte)value; } - public final short shortValue() { return (short)value; } - public final char charValue() { return (char)value; } - public final int intValue() { return (int)value; } - public final long longValue() { return (long)value; } - public final float floatValue() { return (float)value; } - public final double doubleValue() { return (double)value; } - - public final boolean $eq$eq(java.lang.Object other) { - return equals(other); - } - - public final boolean $bang$eq(java.lang.Object other) { - return !equals(other); - } - - public final boolean equals(java.lang.Object other) { - return other instanceof BoxedNumber && value == ((BoxedNumber) other).intValue(); - } - - public final int hashCode() { - return value; - } - - public final String toString() { - return String.valueOf(value); - } -} diff --git a/sources/scala/runtime/BoxedIntArray.scala b/sources/scala/runtime/BoxedIntArray.scala deleted file mode 100644 index 9d0db5b233..0000000000 --- a/sources/scala/runtime/BoxedIntArray.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -[serializable] -final class BoxedIntArray(val value: Array[Int]) extends BoxedArray { - - def length: Int = value.length; - - def apply(index: Int): Object = BoxedInt.box(value(index)); - - def update(index: Int, elem: Object): Unit = { - value(index) = elem.asInstanceOf[BoxedNumber].intValue() - } - - def unbox(elemTag: String): Object = value; - - override def equals(other: Any) = ( - value == other || - other.isInstanceOf[BoxedIntArray] && value == other.asInstanceOf[BoxedIntArray].value - ); - - override def hashCode(): Int = value.hashCode(); -} - diff --git a/sources/scala/runtime/BoxedLong.java b/sources/scala/runtime/BoxedLong.java deleted file mode 100644 index ebc86e4c92..0000000000 --- a/sources/scala/runtime/BoxedLong.java +++ /dev/null @@ -1,50 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ -package scala.runtime; - -public class BoxedLong extends BoxedNumber - implements java.io.Serializable -{ - - public static BoxedLong box(long value) { - return new BoxedLong(value); - } - - public final long value; - - private BoxedLong(long value) { this.value = value; } - - public final byte byteValue() { return (byte)value; } - public final short shortValue() { return (short)value; } - public final char charValue() { return (char)value; } - public final int intValue() { return (int)value; } - public final long longValue() { return (long)value; } - public final float floatValue() { return (float)value; } - public final double doubleValue() { return (double)value; } - - public final boolean $eq$eq(java.lang.Object other) { - return equals(other); - } - - public final boolean $bang$eq(java.lang.Object other) { - return !equals(other); - } - - public boolean equals(java.lang.Object other) { - return other instanceof BoxedNumber && value == ((BoxedNumber) other).longValue(); - } - - public int hashCode() { - long bits = value; - return (int)(bits ^ (bits >>> 32)); - } - - public String toString() { - return String.valueOf(value); - } -} diff --git a/sources/scala/runtime/BoxedLongArray.scala b/sources/scala/runtime/BoxedLongArray.scala deleted file mode 100644 index 624e992e01..0000000000 --- a/sources/scala/runtime/BoxedLongArray.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -[serializable] -final class BoxedLongArray(val value: Array[Long]) extends BoxedArray { - - def length: Int = value.length; - - def apply(index: Int): Object = BoxedLong.box(value(index)); - - def update(index: Int, elem: Object): Unit = { - value(index) = elem.asInstanceOf[BoxedNumber].longValue() - } - - def unbox(elemTag: String): Object = value; - - override def equals(other: Any) = ( - value == other || - other.isInstanceOf[BoxedLongArray] && value == other.asInstanceOf[BoxedLongArray].value - ); - - override def hashCode(): Int = value.hashCode(); -} - diff --git a/sources/scala/runtime/BoxedNumber.java b/sources/scala/runtime/BoxedNumber.java deleted file mode 100644 index a21abab2db..0000000000 --- a/sources/scala/runtime/BoxedNumber.java +++ /dev/null @@ -1,21 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $OldId: RunTime.java,v 1.13 2002/11/19 12:01:40 paltherr Exp $ -// $Id$ -package scala.runtime; - -public abstract class BoxedNumber { - public abstract byte byteValue(); - public abstract short shortValue(); - public abstract char charValue(); - public abstract int intValue(); - public abstract long longValue(); - public abstract float floatValue(); - public abstract double doubleValue(); -} diff --git a/sources/scala/runtime/BoxedObjectArray.scala b/sources/scala/runtime/BoxedObjectArray.scala deleted file mode 100644 index 12ff59da8c..0000000000 --- a/sources/scala/runtime/BoxedObjectArray.scala +++ /dev/null @@ -1,29 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -final class BoxedObjectArray(val value: Array[Object]) extends BoxedArray { - - def length: Int = value.length; - - def apply(index: Int): Object = value(index); - - def update(index: Int, elem: Object): Unit = { value(index) = elem } - - def unbox(elemTag: String): Object = value; - - override def equals(other: Any): Boolean = ( - value == other || - other.isInstanceOf[BoxedObjectArray] && value == other.asInstanceOf[BoxedObjectArray].value - ); - - override def hashCode(): Int = value.hashCode(); -} diff --git a/sources/scala/runtime/BoxedShort.java b/sources/scala/runtime/BoxedShort.java deleted file mode 100644 index f1074c7b7f..0000000000 --- a/sources/scala/runtime/BoxedShort.java +++ /dev/null @@ -1,59 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ -package scala.runtime; - -public final class BoxedShort extends BoxedNumber - implements java.io.Serializable -{ - - private static final int MinHashed = -128; - private static final int MaxHashed = 127; - private static BoxedShort[] canonical = new BoxedShort[MaxHashed - MinHashed + 1]; - - static { - for (int i = MinHashed; i <= MaxHashed; i++) - canonical[i - MinHashed] = new BoxedShort((short)i); - } - - public static BoxedShort box(short value) { - if (MinHashed <= value && value <= MaxHashed) return canonical[value - MinHashed]; - else return new BoxedShort(value); - } - - public final short value; - - private BoxedShort(short value) { this.value = value; } - - public byte byteValue() { return (byte)value; } - public short shortValue() { return (short)value; } - public char charValue() { return (char)value; } - public int intValue() { return (int)value; } - public long longValue() { return (long)value; } - public float floatValue() { return (float)value; } - public double doubleValue() { return (double)value; } - - public final boolean $eq$eq(java.lang.Object other) { - return equals(other); - } - - public final boolean $bang$eq(java.lang.Object other) { - return !equals(other); - } - - public boolean equals(java.lang.Object other) { - return other instanceof BoxedNumber && value == ((BoxedNumber) other).shortValue(); - } - - public int hashCode() { - return value; - } - - public String toString() { - return String.valueOf(value); - } -} diff --git a/sources/scala/runtime/BoxedShortArray.scala b/sources/scala/runtime/BoxedShortArray.scala deleted file mode 100644 index 01e00c5a21..0000000000 --- a/sources/scala/runtime/BoxedShortArray.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -[serializable] -final class BoxedShortArray(val value: Array[Short]) extends BoxedArray { - - def length: Int = value.length; - - def apply(index: Int): Object = BoxedShort.box(value(index)); - - def update(index: Int, elem: Object): Unit = { - value(index) = elem.asInstanceOf[BoxedNumber].shortValue() - } - - def unbox(elemTag: String): Object = value; - - override def equals(other: Any) = ( - value == other || - other.isInstanceOf[BoxedShortArray] && value == other.asInstanceOf[BoxedShortArray].value - ); - - override def hashCode(): Int = value.hashCode(); -} - diff --git a/sources/scala/runtime/BoxedUnit.java b/sources/scala/runtime/BoxedUnit.java deleted file mode 100644 index 91e5f5d03a..0000000000 --- a/sources/scala/runtime/BoxedUnit.java +++ /dev/null @@ -1,37 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ -package scala.runtime; - -public final class BoxedUnit - implements java.io.Serializable -{ - - public final static BoxedUnit UNIT = new BoxedUnit(); - - private BoxedUnit() { } - - public final boolean $eq$eq(java.lang.Object other) { - return equals(other); - } - - public final boolean $bang$eq(java.lang.Object other) { - return !equals(other); - } - - public boolean equals(java.lang.Object other) { - return this == other; - } - - public int hashCode() { - return 0; - } - - public String toString() { - return "()"; - } -} diff --git a/sources/scala/runtime/ByteRef.java b/sources/scala/runtime/ByteRef.java deleted file mode 100644 index f4a98b8ff6..0000000000 --- a/sources/scala/runtime/ByteRef.java +++ /dev/null @@ -1,16 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -public class ByteRef implements java.io.Serializable { - public byte elem; - public ByteRef(byte elem) { this.elem = elem; } -} diff --git a/sources/scala/runtime/CharRef.java b/sources/scala/runtime/CharRef.java deleted file mode 100644 index 71d3666b4e..0000000000 --- a/sources/scala/runtime/CharRef.java +++ /dev/null @@ -1,16 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -public class CharRef implements java.io.Serializable { - public char elem; - public CharRef(char elem) { this.elem = elem; } -} diff --git a/sources/scala/runtime/DoubleRef.java b/sources/scala/runtime/DoubleRef.java deleted file mode 100644 index a0fd0ff68b..0000000000 --- a/sources/scala/runtime/DoubleRef.java +++ /dev/null @@ -1,16 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -public class DoubleRef implements java.io.Serializable { - public double elem; - public DoubleRef(double elem) { this.elem = elem; } -} diff --git a/sources/scala/runtime/FNV_Hash.java b/sources/scala/runtime/FNV_Hash.java deleted file mode 100644 index 6259c33efb..0000000000 --- a/sources/scala/runtime/FNV_Hash.java +++ /dev/null @@ -1,51 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -/** - * Provide methods to compute the various kinds of Fowler / Noll / Vo - * (FNV) hash. - * - * @author Michel Schinz - */ - -public class FNV_Hash { - public static final int INIT = -2128831035; - - public static int hashStep8(int current, int newInt8) { - return (current * 16777619) ^ newInt8; - } - - public static int hashStep32(int current, int newInt32) { - final int v1 = hashStep8(current, newInt32 >> 24); - final int v2 = hashStep8(v1, (newInt32 >> 16) & 0xFF); - final int v3 = hashStep8(v2, (newInt32 >> 8) & 0xFF); - return hashStep8(v3, newInt32 & 0xFF); - } - - public static int hash32(byte[] bytes) { - final int len = bytes.length; - - int h = INIT; - for (int i = 0; i < len; ++i) - h = hashStep8(h, bytes[i]); - - return h; - } - - public static int hash32(String str) { - try { - return hash32(str.getBytes("UTF-8")); - } catch (java.io.UnsupportedEncodingException e) { - throw new Error(e); - } - } -} diff --git a/sources/scala/runtime/FloatRef.java b/sources/scala/runtime/FloatRef.java deleted file mode 100644 index dc8c332b66..0000000000 --- a/sources/scala/runtime/FloatRef.java +++ /dev/null @@ -1,16 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -public class FloatRef implements java.io.Serializable { - public float elem; - public FloatRef(float elem) { this.elem = elem; } -} diff --git a/sources/scala/runtime/IOMap.java b/sources/scala/runtime/IOMap.java deleted file mode 100644 index e93b3c4a9d..0000000000 --- a/sources/scala/runtime/IOMap.java +++ /dev/null @@ -1,171 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -/** - * Purely functional maps from integers to objects. Implemented as - * red-black trees. - * - * @author Michel Schinz - * @version 1.0 - */ - -public class IOMap implements java.io.Serializable { - - /** The map class itself */ - public static class T implements java.io.Serializable { - public case N(int c, T l, T r, int k, Object v); - public case E; - } - - public static final T EMPTY = T.E; - - // Node colors (Black and Red) - private static final int B = 0; - private static final int R = 1; - - public static class ConflictException extends Exception { - public final int key; - public final Object oldValue, newValue; - - public ConflictException(int key, Object oldValue, Object newValue) { - this.key = key; - this.oldValue = oldValue; - this.newValue = newValue; - } - public Throwable fillInStackTrace() { - // do nothing, to speed up things - return this; - } - } - - public Object resolveConflict(int k, Object oldV, Object newV) - throws ConflictException { - throw new ConflictException(k, oldV, newV); - } - - public T put(T map, int key, Object value) throws ConflictException { - switch (putAux(map, key, value)) { - case N(_, T l, T r, int k, Object v): - return T.N(B, l, r, k, v); - default: - throw new Error(); - } - } - - private T putAux(T map, int key, Object value) throws ConflictException { - switch (map) { - case N(int c, T l, T r, int k, Object v): - if (key < k) - return balance(T.N(c, putAux(l, key, value), r, k, v)); - else if (key > k) - return balance(T.N(c, l, putAux(r, key, value), k, v)); - else - return T.N(c, l, r, k, resolveConflict(k, v, value)); - case E: - return T.N(R, T.E, T.E, key, value); - default: - throw new Error(); - } - } - - private T balance(T t) { - switch (t) { - case N(B, - N(R, N(R, T a, T b, int xK, Object xV), T c, int yK, Object yV), - T d, - int zK, Object zV): - return T.N(R, T.N(B, a, b, xK, xV), T.N(B, c, d, zK, zV), yK, yV); - case N(B, - N(R, T a, N(R, T b, T c, int yK, Object yV), int xK, Object xV), - T d, - int zK, Object zV): - return T.N(R, T.N(B, a, b, xK, xV), T.N(B, c, d, zK, zV), yK, yV); - case N(B, - T a, - N(R, N(R, T b, T c, int yK, Object yV), T d, int zK, Object zV), - int xK, Object xV): - return T.N(R, T.N(B, a, b, xK, xV), T.N(B, c, d, zK, zV), yK, yV); - case N(B, - T a, - N(R, T b, N(R, T c, T d, int zK, Object zV), int yK, Object yV), - int xK, Object xV): - return T.N(R, T.N(B, a, b, xK, xV), T.N(B, c, d, zK, zV), yK, yV); - default: - return t; - } - } - - public Object get(T map, int key) { - switch (map) { - case N(_, T l, T r, int k, Object v): - if (key < k) - return get(l, key); - else if (key > k) - return get(r, key); - else - return v; - case E: - return null; - default: - throw new Error("unexpected node " + this); - } - } - - public int size(T map) { - switch (map) { - case N(_, T l, T r, _, _): - return size(l) + size(r) + 1; - case E: - return 0; - default: - throw new Error("unexpected node " + this); - } - } - - public int depth(T map) { - switch (map) { - case N(_, T l, T r, _, _): - return Math.max(depth(l), depth(r)) + 1; - case E: - return 0; - default: - throw new Error("unexpected node " + this); - } - } -} - -// class RBTest { -// static class MyIOMap extends IOMap { -// public Object resolveConflict(int k, Object oldV, Object newV) { -// throw new Error("conflict!!!"); -// } -// } - -// public static void main(String[] args) { -// MyIOMap map = new MyIOMap(); -// MyIOMap.T t = map.EMPTY; - -// long start = System.currentTimeMillis(); -// for (int i = 0; i < args.length; ++i) { -// t = map.put(t, FNV_Hash.hash32(args[i]), new Integer(i)); -// } - -// for (int i = 0; i < args.length; ++i) { -// map.get(t, FNV_Hash.hash32(args[i])); -// } -// long end = System.currentTimeMillis(); -// System.out.println("time: " + (end - start) + "ms"); - -// System.out.println("size = " + map.size(t)); -// System.out.println("depth = " + map.depth(t)); -// } -// } diff --git a/sources/scala/runtime/IntRef.java b/sources/scala/runtime/IntRef.java deleted file mode 100644 index 1f5feacec7..0000000000 --- a/sources/scala/runtime/IntRef.java +++ /dev/null @@ -1,16 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -public class IntRef implements java.io.Serializable { - public int elem; - public IntRef(int elem) { this.elem = elem; } -} diff --git a/sources/scala/runtime/InterpreterSupport.java b/sources/scala/runtime/InterpreterSupport.java deleted file mode 100644 index 9272583ca1..0000000000 --- a/sources/scala/runtime/InterpreterSupport.java +++ /dev/null @@ -1,108 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -/** This class provides support methods for the interpreter. */ -public class InterpreterSupport { - - //######################################################################## - // Public classes - - /** This interface provides method to show definitions. */ - public static interface DefinitionPrinter { - - /** This method is invoked for each non-value definition. */ - public void showDefinition(String signature); - - /** This method is invoked for each value definition. */ - public void showValueDefinition(String signature, Object value); - - } - - /** This class describes an evaluation result. */ - public static class EvaluationResult { - - /** The value of the result */ - public final Object value; - - /** The type of the result */ - public final String type; - - /** Creates a new instance */ - public EvaluationResult(Object value, String type) { - this.value = value; - this.type = type; - } - } - - //######################################################################## - // Private Variables - - private static final ThreadLocal printer = new ThreadLocal(); - private static final ThreadLocal result = new ThreadLocal(); - - //######################################################################## - // Public Functions - - /** Sets the definition printer of the current thread. */ - public static void setDefinitionPrinter(DefinitionPrinter object) { - printer.set(object); - } - - /** Returns the definition printer of the current thread. */ - public static DefinitionPrinter getDefinitionPrinter() { - return (DefinitionPrinter)printer.get(); - } - - /** - * This function is invoked for each non-value definition. It - * forwards the call to the current thread's definition printer. - * - * @meta method (java.lang.String, scala.Any) scala.Unit; - */ - public static void showDefinition(String signature) { - DefinitionPrinter printer = getDefinitionPrinter(); - if (printer != null) printer.showDefinition(signature); - } - - /** - * This method is invoked for each value definition. It forwards - * the call to the current thread's definition printer. - * - * @meta method (java.lang.String, scala.Any) scala.Unit; - */ - public static void showValueDefinition(String signature, Object value) { - DefinitionPrinter printer = getDefinitionPrinter(); - if (printer != null) printer.showValueDefinition(signature, value); - } - - /** - * Sets the evaluation result of the current thread. - * - * @meta method (scala.Any, java.lang.String) scala.Unit; - */ - public static void setEvaluationResult(Object value, String type) { - result.set(new EvaluationResult(value, type)); - } - - /** - * Returns and resets the evaluation result of the current - * thread. A null value indicates that the last evaluation had no - * result (only definitions). - */ - public static EvaluationResult getAndResetEvaluationResult() { - Object object = result.get(); - result.set(null); - return (EvaluationResult)object; - } - - //######################################################################## -} diff --git a/sources/scala/runtime/LongRef.java b/sources/scala/runtime/LongRef.java deleted file mode 100644 index 863472c666..0000000000 --- a/sources/scala/runtime/LongRef.java +++ /dev/null @@ -1,16 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -public class LongRef implements java.io.Serializable { - public long elem; - public LongRef(long elem) { this.elem = elem; } -} diff --git a/sources/scala/runtime/MetaAttribute.cs b/sources/scala/runtime/MetaAttribute.cs deleted file mode 100644 index 28ab499bdd..0000000000 --- a/sources/scala/runtime/MetaAttribute.cs +++ /dev/null @@ -1,34 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; - -namespace scala.runtime -{ - /// - /// Stores additional meta-information about classes and members. - /// Used to augment type information in classes from the scala - /// library written in Java. - /// - - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Field - | AttributeTargets.Constructor | AttributeTargets.Method, - AllowMultiple = false, Inherited = false)] - public class MetaAttribute : Attribute - { - // keeps a textual representation of the pico-style attributes - // used in some classes of the runtime library - public readonly string meta; - public MetaAttribute(string meta) - { - this.meta = meta; - } - } -} diff --git a/sources/scala/runtime/ObjectRef.java b/sources/scala/runtime/ObjectRef.java deleted file mode 100644 index c5ba9fb640..0000000000 --- a/sources/scala/runtime/ObjectRef.java +++ /dev/null @@ -1,16 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -public class ObjectRef implements java.io.Serializable { - public Object elem; - public ObjectRef(Object elem) { this.elem = elem; } -} diff --git a/sources/scala/runtime/RunTime.cs b/sources/scala/runtime/RunTime.cs deleted file mode 100644 index eadb95bacf..0000000000 --- a/sources/scala/runtime/RunTime.cs +++ /dev/null @@ -1,513 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $OldId: RunTime.java,v 1.13 2002/11/19 12:01:40 paltherr Exp $ -// $Id$ - -using System; -using scala; - -namespace scala.runtime -{ - - public abstract class RunTime - { - - //######################################################################## - // Private Constants - - private static readonly int BITS = 8; - private static readonly int ARRAY_SIZE = 2 << BITS; - private static readonly int INDEX_MASK = ARRAY_SIZE - 1; - private static readonly int CHECK_MASK = ~(ARRAY_SIZE / 2 - 1); - - private static readonly UValue uvalue = new UValue(); - private static readonly ZValue zvalue_f = new ZValue(false); - private static readonly ZValue zvalue_t = new ZValue(true); - private static readonly BValue[] bvalue = new BValue[256]; - private static readonly SValue[] svalue = new SValue[ARRAY_SIZE]; - private static readonly CValue[] cvalue = new CValue[ARRAY_SIZE / 2]; - private static readonly IValue[] ivalue = new IValue[ARRAY_SIZE]; - private static readonly LValue[] lvalue = new LValue[ARRAY_SIZE]; - - static RunTime() - { - for (int i = 0; i < bvalue.Length; i++) - bvalue[i] = new BValue((sbyte)i); - for (int i = 0; i < ARRAY_SIZE / 2; i++) - { - svalue[i] = new SValue((short)i); - cvalue[i] = new CValue((char )i); - ivalue[i] = new IValue((int )i); - lvalue[i] = new LValue((long )i); - svalue[i + ARRAY_SIZE / 2] = new SValue((short)(CHECK_MASK | i)); - ivalue[i + ARRAY_SIZE / 2] = new IValue((int )(CHECK_MASK | i)); - lvalue[i + ARRAY_SIZE / 2] = new LValue((long )(CHECK_MASK | i)); - } - } - - //######################################################################## - // Private Variables - - //private static ClassLoader loader = ClassLoader.getSystemClassLoader(); - - //######################################################################## - // Public Functions - Getting & setting class loader - -// public static ClassLoader getClassLoader() -// { -// return loader; -// } -// -// public static void setClassLoader(ClassLoader loader) -// { -// RunTime.loader = loader; -// } - - //######################################################################## - // Public Functions - Catching exceptions - public interface Runnable { - void run(); - } - - public static Exception tryCatch(Runnable runnable) - { - try - { - runnable.run(); - return null; - } - catch (Exception exception) - { - return exception; - } - } - - //######################################################################## - // Public Functions - Boxing primitives - - public static Unit box_uvalue( ) - { - return uvalue; - } - - public static Boolean box_zvalue(bool x) - { - return x ? zvalue_t : zvalue_f; - } - - public static Byte box_bvalue(sbyte x) - { - return bvalue[x & 0x000000FF]; - } - - public static Short box_svalue(short x) - { - int c = x & CHECK_MASK; - if (c == 0 || c == CHECK_MASK) return svalue[x & INDEX_MASK]; - return new SValue(x); - } - - public static Char box_cvalue(char x) - { - int c = (int)x & CHECK_MASK; - if (c == 0) return cvalue[(int)x & INDEX_MASK]; - return new CValue(x); - } - - public static Int box_ivalue(int x) - { - int c = x & CHECK_MASK; - if (c == 0 || c == CHECK_MASK) return ivalue[x & INDEX_MASK]; - return new IValue(x); - } - - public static Long box_lvalue(long x) - { - long c = x & CHECK_MASK; - if (c == 0 || c == CHECK_MASK) return lvalue[(int)x & INDEX_MASK]; - return new LValue(x); - } - - public static Float box_fvalue(float x) - { - return new FValue(x); - } - - public static Double box_dvalue(double x) - { - return new DValue(x); - } - - /** @meta method (scala.Array[scala.Boolean]) scala.Array[scala.Boolean];*/ - public static Array box_zarray(bool[] xs) - { - return new ZArray(xs); - } - - /** @meta method (scala.Array[scala.Byte]) scala.Array[scala.Byte]; */ - public static Array box_barray(sbyte [] xs) - { - return new BArray(xs); - } - - /** @meta method (scala.Array[scala.Short]) scala.Array[scala.Short]; */ - public static Array box_sarray(short [] xs) - { - return new SArray(xs); - } - - /** @meta method (scala.Array[scala.Char]) scala.Array[scala.Char]; */ - public static Array box_carray(char [] xs) - { - return new CArray(xs); - } - - /** @meta method (scala.Array[scala.Int]) scala.Array[scala.Int]; */ - public static Array box_iarray(int [] xs) - { - return new IArray(xs); - } - - /** @meta method (scala.Array[scala.Long]) scala.Array[scala.Long]; */ - public static Array box_larray(long [] xs) - { - return new LArray(xs); - } - - /** @meta method (scala.Array[scala.Float]) scala.Array[scala.Float]; */ - public static Array box_farray(float [] xs) - { - return new FArray(xs); - } - - /** @meta method (scala.Array[scala.Double]) scala.Array[scala.Double]; */ - public static Array box_darray(double [] xs) - { - return new DArray(xs); - } - - /** @meta method [?T < scala.AnyRef](scala.Array[?T]) scala.Array[?T]; */ - public static Array box_oarray(object [] xs) - { - return new OArray(xs); - } - - /** @meta method [?T](scala.Array[?T]) scala.Array[?T]; */ - public static Array box__array(object xs) - { - if (xs == null ) return box_oarray((object [])xs); - if (xs is bool[]) return box_zarray((bool[])xs); - if (xs is sbyte []) return box_barray((sbyte [])xs); - if (xs is short []) return box_sarray((short [])xs); - if (xs is char []) return box_carray((char [])xs); - if (xs is int []) return box_iarray((int [])xs); - if (xs is long []) return box_larray((long [])xs); - if (xs is float []) return box_farray((float [])xs); - if (xs is double []) return box_darray((double [])xs); - if (xs is object []) return box_oarray((object [])xs); - throw new InvalidCastException(xs.GetType() + " is not an array class"); - } - - //######################################################################## - // Public Functions - Unboxing primitives - - public static void unbox_uvalue(Unit x) { x.value(); } - public static bool unbox_zvalue(Boolean x) { return x.value ; } - public static sbyte unbox_bvalue(Byte x) { return x.value ; } - public static short unbox_svalue(Short x) { return x.value ; } - public static char unbox_cvalue(Char x) { return x.value ; } - public static int unbox_ivalue(Int x) { return x.value ; } - public static long unbox_lvalue(Long x) { return x.value ; } - public static float unbox_fvalue(Float x) { return x.value ; } - public static double unbox_dvalue(Double x) { return x.value ; } - - /** @meta method (scala.Array[scala.Boolean]) scala.Array[scala.Boolean];*/ - public static bool[] unbox_zarray(Array xs) - { - return xs == null ? null : ((ZArray)xs)._value; - } - /** @meta method (scala.Array[scala.Byte]) scala.Array[scala.Byte]; */ - public static sbyte [] unbox_barray(Array xs) - { - return xs == null ? null : ((BArray)xs)._value; - } - /** @meta method (scala.Array[scala.Short]) scala.Array[scala.Short]; */ - public static short [] unbox_sarray(Array xs) - { - return xs == null ? null : ((SArray)xs)._value; - } - /** @meta method (scala.Array[scala.Char]) scala.Array[scala.Char]; */ - public static char [] unbox_carray(Array xs) - { - return xs == null ? null : ((CArray)xs)._value; - } - /** @meta method (scala.Array[scala.Int]) scala.Array[scala.Int]; */ - public static int [] unbox_iarray(Array xs) - { - return xs == null ? null : ((IArray)xs)._value; - } - /** @meta method (scala.Array[scala.Long]) scala.Array[scala.Long]; */ - public static long [] unbox_larray(Array xs) - { - return xs == null ? null : ((LArray)xs)._value; - } - /** @meta method (scala.Array[scala.Float]) scala.Array[scala.Float]; */ - public static float [] unbox_farray(Array xs) - { - return xs == null ? null : ((FArray)xs)._value; - } - /** @meta method (scala.Array[scala.Double]) scala.Array[scala.Double]; */ - public static double [] unbox_darray(Array xs) - { - return xs == null ? null : ((DArray)xs)._value; - } - /** @meta method [?T < scala.AnyRef](scala.Array[?T]) scala.Array[scala.AnyRef]; */ - public static object [] unbox_oarray(Array xs) - { - return xs == null ? null : ((OArray)xs)._value; - } - /** @meta method [?T](scala.Array[?T]) scala.AnyRef; */ - public static object unbox__array(Array xs) - { - return xs == null ? null : xs.value(); - } - - //######################################################################## - // Public Functions - Conversion primitives - - public static sbyte b2b(sbyte x) { return (sbyte )x; } - public static short b2s(sbyte x) { return (short )x; } - public static char b2c(sbyte x) { return (char )x; } - public static int b2i(sbyte x) { return (int )x; } - public static long b2l(sbyte x) { return (long )x; } - public static float b2f(sbyte x) { return (float )x; } - public static double b2d(sbyte x) { return (double)x; } - public static sbyte s2b(short x) { return (sbyte )x; } - public static short s2s(short x) { return (short )x; } - public static char s2c(short x) { return (char )x; } - public static int s2i(short x) { return (int )x; } - public static long s2l(short x) { return (long )x; } - public static float s2f(short x) { return (float )x; } - public static double s2d(short x) { return (double)x; } - public static sbyte c2b(char x) { return (sbyte )x; } - public static short c2s(char x) { return (short )x; } - public static char c2c(char x) { return (char )x; } - public static int c2i(char x) { return (int )x; } - public static long c2l(char x) { return (long )x; } - public static float c2f(char x) { return (float )x; } - public static double c2d(char x) { return (double)x; } - public static sbyte i2b(int x) { return (sbyte )x; } - public static short i2s(int x) { return (short )x; } - public static char i2c(int x) { return (char )x; } - public static int i2i(int x) { return (int )x; } - public static long i2l(int x) { return (long )x; } - public static float i2f(int x) { return (float )x; } - public static double i2d(int x) { return (double)x; } - public static sbyte l2b(long x) { return (sbyte )x; } - public static short l2s(long x) { return (short )x; } - public static char l2c(long x) { return (char )x; } - public static int l2i(long x) { return (int )x; } - public static long l2l(long x) { return (long )x; } - public static float l2f(long x) { return (float )x; } - public static double l2d(long x) { return (double)x; } - public static sbyte f2b(float x) { return (sbyte )x; } - public static short f2s(float x) { return (short )x; } - public static char f2c(float x) { return (char )x; } - public static int f2i(float x) { return (int )x; } - public static long f2l(float x) { return (long )x; } - public static float f2f(float x) { return (float )x; } - public static double f2d(float x) { return (double)x; } - public static sbyte d2b(double x) { return (sbyte )x; } - public static short d2s(double x) { return (short )x; } - public static char d2c(double x) { return (char )x; } - public static int d2i(double x) { return (int )x; } - public static long d2l(double x) { return (long )x; } - public static float d2f(double x) { return (float )x; } - public static double d2d(double x) { return (double)x; } - - //######################################################################## - // Public Functions - Array primitives - - public static bool[] zarray(int length) { return new bool[length]; } - public static sbyte [] barray(int length) { return new sbyte [length]; } - public static short [] sarray(int length) { return new short [length]; } - public static char [] carray(int length) { return new char [length]; } - public static int [] iarray(int length) { return new int [length]; } - public static long [] larray(int length) { return new long [length]; } - public static float [] farray(int length) { return new float [length]; } - public static double [] darray(int length) { return new double [length]; } - public static object oarray(int length, string classname) - { - try - { - Type clasz = Type.GetType(classname); - return System.Array.CreateInstance(clasz, length); - } - catch (Exception exception) - { - //throw new Error(exception.ToString()); - throw new ApplicationException(exception.ToString()); - } - } - - public static int zarray_length(bool[] xs) { return xs.Length; } - public static int barray_length(sbyte [] xs) { return xs.Length; } - public static int sarray_length(short [] xs) { return xs.Length; } - public static int carray_length(char [] xs) { return xs.Length; } - public static int iarray_length(int [] xs) { return xs.Length; } - public static int larray_length(long [] xs) { return xs.Length; } - public static int farray_length(float [] xs) { return xs.Length; } - public static int darray_length(double [] xs) { return xs.Length; } - public static int oarray_length(object [] xs) { return xs.Length; } - - public static bool zarray_get(bool[] xs, int i) { return xs[i]; } - public static sbyte barray_get(sbyte [] xs, int i) { return xs[i]; } - public static short sarray_get(short [] xs, int i) { return xs[i]; } - public static char carray_get(char [] xs, int i) { return xs[i]; } - public static int iarray_get(int [] xs, int i) { return xs[i]; } - public static long larray_get(long [] xs, int i) { return xs[i]; } - public static float farray_get(float [] xs, int i) { return xs[i]; } - public static double darray_get(double [] xs, int i) { return xs[i]; } - public static object oarray_get(object [] xs, int i) { return xs[i]; } - - public static void zarray_set(bool[] xs, int i, bool x) { xs[i] = x;} - public static void barray_set(sbyte [] xs, int i, sbyte x) { xs[i] = x;} - public static void sarray_set(short [] xs, int i, short x) { xs[i] = x;} - public static void carray_set(char [] xs, int i, char x) { xs[i] = x;} - public static void iarray_set(int [] xs, int i, int x) { xs[i] = x;} - public static void larray_set(long [] xs, int i, long x) { xs[i] = x;} - public static void farray_set(float [] xs, int i, float x) { xs[i] = x;} - public static void darray_set(double [] xs, int i, double x) { xs[i] = x;} - public static void oarray_set(object [] xs, int i, object x) { xs[i] = x;} - - //######################################################################## - } - - // These classes may not be defined in class RunTime because inner - // classes confuse pico which then attributes the metadata to the - // wrong members. - - sealed class UValue : Unit { public UValue( ) : base( ) { } } - sealed class ZValue : Boolean { public ZValue(bool x ) : base(x) { } } - sealed class BValue : Byte { public BValue(sbyte x) : base(x) { } } - sealed class SValue : Short { public SValue(short x) : base(x) { } } - sealed class CValue : Char { public CValue(char x) : base(x) { } } - sealed class IValue : Int { public IValue(int x) : base(x) { } } - sealed class LValue : Long { public LValue(long x) : base(x) { } } - sealed class FValue : Float { public FValue(float x) : base(x) { } } - sealed class DValue : Double { public DValue(double x) : base(x) { } } - - /** @meta class extends scala.Array[scala.Boolean]; */ - sealed class ZArray : Array - { - internal readonly bool[] _value; - public ZArray(bool[] _value) { this._value = _value; } - public override object value() { return _value; } - public override object apply(int i) { return RunTime.box_zvalue(_value[i]); } - public override void update(int i, object x) { _value[i] = ((Boolean)x).value; } - public override int length() { return _value.Length; } - public override string ToString() { return _value.ToString(); } - } - - [Meta("class extends scala.Array[scala.Byte];")] - sealed class BArray : Array - { - internal readonly sbyte[] _value; - public BArray(sbyte[] _value) { this._value = _value; } - public override object value() { return _value; } - public override object apply(int i) { return RunTime.box_bvalue(_value[i]); } - public override void update(int i, object x) { _value[i] = ((Byte)x).value; } - public override int length() { return _value.Length; } - public override string ToString() { return _value.ToString(); } - } - - [Meta("class extends scala.Array[scala.Short];")] - sealed class SArray : Array - { - internal readonly short[] _value; - public SArray(short[] _value) { this._value = _value; } - public override object value() { return _value; } - public override object apply(int i) { return RunTime.box_svalue(_value[i]); } - public override void update(int i, object x) { _value[i] = ((Short)x).value; } - public override int length() { return _value.Length; } - public override string ToString() { return _value.ToString(); } - } - - [Meta("class extends scala.Array[scala.Char];")] - sealed class CArray : Array - { - internal readonly char[] _value; - public CArray(char[] _value) { this._value = _value; } - public override object value() { return _value; } - public override object apply(int i) { return RunTime.box_cvalue(_value[i]); } - public override void update(int i, object x) { _value[i] = ((Char)x).value; } - public override int length() { return _value.Length; } - public override string ToString() { return ((object)_value).ToString(); } - } - - [Meta("class extends scala.Array[scala.Int];")] - sealed class IArray : Array - { - internal readonly int[] _value; - public IArray(int[] _value) { this._value = _value; } - public override object value() { return _value; } - public override object apply(int i) { return RunTime.box_ivalue(_value[i]); } - public override void update(int i, object x) { _value[i] = ((Int)x).value; } - public override int length() { return _value.Length; } - public override string ToString() { return _value.ToString(); } - } - - [Meta("class extends scala.Array[scala.Long];")] - sealed class LArray : Array - { - internal readonly long[] _value; - public LArray(long[] _value) { this._value = _value; } - public override object value() { return _value; } - public override object apply(int i) { return RunTime.box_lvalue(_value[i]); } - public override void update(int i, object x) { _value[i] = ((Long)x).value; } - public override int length() { return _value.Length; } - public override string ToString() { return _value.ToString(); } - } - - [Meta("class extends scala.Array[scala.Float];")] - sealed class FArray : Array - { - internal readonly float[] _value; - public FArray(float[] _value) { this._value = _value; } - public override object value() { return _value; } - public override object apply(int i) { return RunTime.box_fvalue(_value[i]); } - public override void update(int i, object x) { _value[i] = ((Float)x).value; } - public override int length() { return _value.Length; } - public override string ToString() { return _value.ToString(); } - } - - [Meta("class extends scala.Array[scala.Double];")] - sealed class DArray : Array - { - internal readonly double[] _value; - public DArray(double[] _value) { this._value = _value; } - public override object value() { return _value; } - public override object apply(int i) { return RunTime.box_dvalue(_value[i]); } - public override void update(int i, object x) { _value[i] = ((Double)x).value; } - public override int length() { return _value.Length; } - public override string ToString() { return _value.ToString(); } - } - - [Meta("class [?T < scala.AnyRef] extends scala.Array[?T];")] - sealed class OArray : Array - { - internal readonly object[] _value; - public OArray(object[] _value) { this._value = _value; } - public override object value() { return _value; } - public override object apply(int i) { return _value[i]; } - public override void update(int i, object x) { _value[i] = x; } - public override int length() { return _value.Length; } - public override string ToString() { return _value.ToString(); } - } -} \ No newline at end of file diff --git a/sources/scala/runtime/RunTime.java b/sources/scala/runtime/RunTime.java deleted file mode 100644 index 452ca595f2..0000000000 --- a/sources/scala/runtime/RunTime.java +++ /dev/null @@ -1,473 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $OldId: RunTime.java,v 1.13 2002/11/19 12:01:40 paltherr Exp $ -// $Id$ - -package scala.runtime; - -import scala.Unit; -import scala.Boolean; -import scala.Byte; -import scala.Short; -import scala.Char; -import scala.Int; -import scala.Long; -import scala.Float; -import scala.Double; -import scala.Array; - -public abstract class RunTime { - - //######################################################################## - // Private Constants - - private static final int BITS = 8; - private static final int ARRAY_SIZE = 2 << BITS; - private static final int INDEX_MASK = ARRAY_SIZE - 1; - private static final int CHECK_MASK = ~(ARRAY_SIZE / 2 - 1); - - private static final UValue uvalue = new UValue(); - private static final ZValue zvalue_f = new ZValue(false); - private static final ZValue zvalue_t = new ZValue(true); - private static final BValue bvalue[] = new BValue[256]; - private static final SValue svalue[] = new SValue[ARRAY_SIZE]; - private static final CValue cvalue[] = new CValue[ARRAY_SIZE / 2]; - private static final IValue ivalue[] = new IValue[ARRAY_SIZE]; - private static final LValue lvalue[] = new LValue[ARRAY_SIZE]; - - static { - for (int i = 0; i < bvalue.length; i++) - bvalue[i] = new BValue((byte)i); - for (int i = 0; i < ARRAY_SIZE / 2; i++) { - svalue[i] = new SValue((short)i); - cvalue[i] = new CValue((char )i); - ivalue[i] = new IValue((int )i); - lvalue[i] = new LValue((long )i); - svalue[i + ARRAY_SIZE / 2] = new SValue((short)(CHECK_MASK | i)); - ivalue[i + ARRAY_SIZE / 2] = new IValue((int )(CHECK_MASK | i)); - lvalue[i + ARRAY_SIZE / 2] = new LValue((long )(CHECK_MASK | i)); - } - } - - //######################################################################## - // Private Variables - - private static ClassLoader loader = ClassLoader.getSystemClassLoader(); - - //######################################################################## - // Public Functions - Getting & setting class loader - - public static ClassLoader getClassLoader() { - return loader; - } - - public static void setClassLoader(ClassLoader loader) { - RunTime.loader = loader; - } - - //######################################################################## - // Public Functions - Catching exceptions - - public static Throwable tryCatch(Runnable runnable) { - try { - runnable.run(); - return null; - } catch (Throwable exception) { - return exception; - } - } - - //######################################################################## - // Public Functions - Boxing primitives - - public static Unit box_uvalue( ) { - return uvalue; - } - - public static Boolean box_zvalue(boolean x) { - return x ? zvalue_t : zvalue_f; - } - - public static Byte box_bvalue(byte x) { - return bvalue[x & 0x000000FF]; - } - - public static Short box_svalue(short x) { - int c = x & CHECK_MASK; - if (c == 0 || c == CHECK_MASK) return svalue[x & INDEX_MASK]; - return new SValue(x); - } - - public static Char box_cvalue(char x) { - int c = (int)x & CHECK_MASK; - if (c == 0) return cvalue[(int)x & INDEX_MASK]; - return new CValue(x); - } - - public static Int box_ivalue(int x) { - int c = x & CHECK_MASK; - if (c == 0 || c == CHECK_MASK) return ivalue[x & INDEX_MASK]; - return new IValue(x); - } - - public static Long box_lvalue(long x) { - long c = x & CHECK_MASK; - if (c == 0 || c == CHECK_MASK) return lvalue[(int)x & INDEX_MASK]; - return new LValue(x); - } - - public static Float box_fvalue(float x) { - return new FValue(x); - } - - public static Double box_dvalue(double x) { - return new DValue(x); - } - - /** @meta method (scala.Array[scala.Boolean]) scala.Array[scala.Boolean];*/ - public static Array box_zarray(boolean[] xs) { - return new ZArray(xs); - } - - /** @meta method (scala.Array[scala.Byte]) scala.Array[scala.Byte]; */ - public static Array box_barray(byte [] xs) { - return new BArray(xs); - } - - /** @meta method (scala.Array[scala.Short]) scala.Array[scala.Short]; */ - public static Array box_sarray(short [] xs) { - return new SArray(xs); - } - - /** @meta method (scala.Array[scala.Char]) scala.Array[scala.Char]; */ - public static Array box_carray(char [] xs) { - return new CArray(xs); - } - - /** @meta method (scala.Array[scala.Int]) scala.Array[scala.Int]; */ - public static Array box_iarray(int [] xs) { - return new IArray(xs); - } - - /** @meta method (scala.Array[scala.Long]) scala.Array[scala.Long]; */ - public static Array box_larray(long [] xs) { - return new LArray(xs); - } - - /** @meta method (scala.Array[scala.Float]) scala.Array[scala.Float]; */ - public static Array box_farray(float [] xs) { - return new FArray(xs); - } - - /** @meta method (scala.Array[scala.Double]) scala.Array[scala.Double]; */ - public static Array box_darray(double [] xs) { - return new DArray(xs); - } - - /** @meta method [?T < scala.AnyRef](scala.Array[?T]) scala.Array[?T]; */ - public static Array box_oarray(Object [] xs) { - return new OArray(xs); - } - - /** @meta method [?T](scala.Array[?T]) scala.Array[?T]; */ - public static Array box__array(Object xs) { - if (xs == null ) return box_oarray((Object [])xs); - if (xs instanceof boolean[]) return box_zarray((boolean[])xs); - if (xs instanceof byte []) return box_barray((byte [])xs); - if (xs instanceof short []) return box_sarray((short [])xs); - if (xs instanceof char []) return box_carray((char [])xs); - if (xs instanceof int []) return box_iarray((int [])xs); - if (xs instanceof long []) return box_larray((long [])xs); - if (xs instanceof float []) return box_farray((float [])xs); - if (xs instanceof double []) return box_darray((double [])xs); - if (xs instanceof Object []) return box_oarray((Object [])xs); - throw new ClassCastException(xs.getClass() + " is not an array class"); - } - - //######################################################################## - // Public Functions - Unboxing primitives - - public static void unbox_uvalue(Unit x) { x.value(); } - public static boolean unbox_zvalue(Boolean x) { return x.value ; } - public static byte unbox_bvalue(Byte x) { return x.value ; } - public static short unbox_svalue(Short x) { return x.value ; } - public static char unbox_cvalue(Char x) { return x.value ; } - public static int unbox_ivalue(Int x) { return x.value ; } - public static long unbox_lvalue(Long x) { return x.value ; } - public static float unbox_fvalue(Float x) { return x.value ; } - public static double unbox_dvalue(Double x) { return x.value ; } - - /** @meta method (scala.Array[scala.Boolean]) scala.Array[scala.Boolean];*/ - public static boolean[] unbox_zarray(Array xs) { - return xs == null ? null : ((ZArray)xs).value; - } - /** @meta method (scala.Array[scala.Byte]) scala.Array[scala.Byte]; */ - public static byte [] unbox_barray(Array xs) { - return xs == null ? null : ((BArray)xs).value; - } - /** @meta method (scala.Array[scala.Short]) scala.Array[scala.Short]; */ - public static short [] unbox_sarray(Array xs) { - return xs == null ? null : ((SArray)xs).value; - } - /** @meta method (scala.Array[scala.Char]) scala.Array[scala.Char]; */ - public static char [] unbox_carray(Array xs) { - return xs == null ? null : ((CArray)xs).value; - } - /** @meta method (scala.Array[scala.Int]) scala.Array[scala.Int]; */ - public static int [] unbox_iarray(Array xs) { - return xs == null ? null : ((IArray)xs).value; - } - /** @meta method (scala.Array[scala.Long]) scala.Array[scala.Long]; */ - public static long [] unbox_larray(Array xs) { - return xs == null ? null : ((LArray)xs).value; - } - /** @meta method (scala.Array[scala.Float]) scala.Array[scala.Float]; */ - public static float [] unbox_farray(Array xs) { - return xs == null ? null : ((FArray)xs).value; - } - /** @meta method (scala.Array[scala.Double]) scala.Array[scala.Double]; */ - public static double [] unbox_darray(Array xs) { - return xs == null ? null : ((DArray)xs).value; - } - /** @meta method [?T < scala.AnyRef](scala.Array[?T]) scala.Array[scala.AnyRef]; */ - public static Object [] unbox_oarray(Array xs) { - return xs == null ? null : ((OArray)xs).value; - } - /** @meta method [?T](scala.Array[?T]) scala.AnyRef; */ - public static Object unbox__array(Array xs) { - return xs == null ? null : xs.value(); - } - - //######################################################################## - // Public Functions - Conversion primitives - - public static byte b2b(byte x) { return (byte )x; } - public static short b2s(byte x) { return (short )x; } - public static char b2c(byte x) { return (char )x; } - public static int b2i(byte x) { return (int )x; } - public static long b2l(byte x) { return (long )x; } - public static float b2f(byte x) { return (float )x; } - public static double b2d(byte x) { return (double)x; } - public static byte s2b(short x) { return (byte )x; } - public static short s2s(short x) { return (short )x; } - public static char s2c(short x) { return (char )x; } - public static int s2i(short x) { return (int )x; } - public static long s2l(short x) { return (long )x; } - public static float s2f(short x) { return (float )x; } - public static double s2d(short x) { return (double)x; } - public static byte c2b(char x) { return (byte )x; } - public static short c2s(char x) { return (short )x; } - public static char c2c(char x) { return (char )x; } - public static int c2i(char x) { return (int )x; } - public static long c2l(char x) { return (long )x; } - public static float c2f(char x) { return (float )x; } - public static double c2d(char x) { return (double)x; } - public static byte i2b(int x) { return (byte )x; } - public static short i2s(int x) { return (short )x; } - public static char i2c(int x) { return (char )x; } - public static int i2i(int x) { return (int )x; } - public static long i2l(int x) { return (long )x; } - public static float i2f(int x) { return (float )x; } - public static double i2d(int x) { return (double)x; } - public static byte l2b(long x) { return (byte )x; } - public static short l2s(long x) { return (short )x; } - public static char l2c(long x) { return (char )x; } - public static int l2i(long x) { return (int )x; } - public static long l2l(long x) { return (long )x; } - public static float l2f(long x) { return (float )x; } - public static double l2d(long x) { return (double)x; } - public static byte f2b(float x) { return (byte )x; } - public static short f2s(float x) { return (short )x; } - public static char f2c(float x) { return (char )x; } - public static int f2i(float x) { return (int )x; } - public static long f2l(float x) { return (long )x; } - public static float f2f(float x) { return (float )x; } - public static double f2d(float x) { return (double)x; } - public static byte d2b(double x) { return (byte )x; } - public static short d2s(double x) { return (short )x; } - public static char d2c(double x) { return (char )x; } - public static int d2i(double x) { return (int )x; } - public static long d2l(double x) { return (long )x; } - public static float d2f(double x) { return (float )x; } - public static double d2d(double x) { return (double)x; } - - //######################################################################## - // Public Functions - Array primitives - - public static boolean[] zarray(int length) { return new boolean[length]; } - public static byte [] barray(int length) { return new byte [length]; } - public static short [] sarray(int length) { return new short [length]; } - public static char [] carray(int length) { return new char [length]; } - public static int [] iarray(int length) { return new int [length]; } - public static long [] larray(int length) { return new long [length]; } - public static float [] farray(int length) { return new float [length]; } - public static double [] darray(int length) { return new double [length]; } - public static Object oarray(int length, String classname) { - try { - Class clasz = Class.forName(classname, false, loader); - return java.lang.reflect.Array.newInstance(clasz, length); - } catch (ClassNotFoundException exception) { - throw new Error(exception.toString()); - } - } - - public static int zarray_length(boolean[] xs) { return xs.length; } - public static int barray_length(byte [] xs) { return xs.length; } - public static int sarray_length(short [] xs) { return xs.length; } - public static int carray_length(char [] xs) { return xs.length; } - public static int iarray_length(int [] xs) { return xs.length; } - public static int larray_length(long [] xs) { return xs.length; } - public static int farray_length(float [] xs) { return xs.length; } - public static int darray_length(double [] xs) { return xs.length; } - public static int oarray_length(Object [] xs) { return xs.length; } - - public static boolean zarray_get(boolean[] xs, int i) { return xs[i]; } - public static byte barray_get(byte [] xs, int i) { return xs[i]; } - public static short sarray_get(short [] xs, int i) { return xs[i]; } - public static char carray_get(char [] xs, int i) { return xs[i]; } - public static int iarray_get(int [] xs, int i) { return xs[i]; } - public static long larray_get(long [] xs, int i) { return xs[i]; } - public static float farray_get(float [] xs, int i) { return xs[i]; } - public static double darray_get(double [] xs, int i) { return xs[i]; } - public static Object oarray_get(Object [] xs, int i) { return xs[i]; } - - public static void zarray_set(boolean[] xs, int i, boolean x) { xs[i] = x;} - public static void barray_set(byte [] xs, int i, byte x) { xs[i] = x;} - public static void sarray_set(short [] xs, int i, short x) { xs[i] = x;} - public static void carray_set(char [] xs, int i, char x) { xs[i] = x;} - public static void iarray_set(int [] xs, int i, int x) { xs[i] = x;} - public static void larray_set(long [] xs, int i, long x) { xs[i] = x;} - public static void farray_set(float [] xs, int i, float x) { xs[i] = x;} - public static void darray_set(double [] xs, int i, double x) { xs[i] = x;} - public static void oarray_set(Object [] xs, int i, Object x) { xs[i] = x;} - - //######################################################################## -} - -// These classes may not be defined in class RunTime because inner -// classes confuse pico which then attributes the metadata to the -// wrong members. - -final class UValue extends Unit implements java.io.Serializable - { public UValue( ) { super( ); } } -final class ZValue extends Boolean implements java.io.Serializable - { public ZValue(boolean x) { super(x); } } -final class BValue extends Byte implements java.io.Serializable - { public BValue(byte x) { super(x); } } -final class SValue extends Short implements java.io.Serializable - { public SValue(short x) { super(x); } } -final class CValue extends Char implements java.io.Serializable - { public CValue(char x) { super(x); } } -final class IValue extends Int implements java.io.Serializable - { public IValue(int x) { super(x); } } -final class LValue extends Long implements java.io.Serializable - { public LValue(long x) { super(x); } } -final class FValue extends Float implements java.io.Serializable - { public FValue(float x) { super(x); } } -final class DValue extends Double implements java.io.Serializable - { public DValue(double x) { super(x); } } - -/** @meta class extends scala.Array[scala.Boolean]; */ -final class ZArray extends Array implements java.io.Serializable { - public final boolean[] value; - public ZArray(boolean[] value) { this.value = value; } - public Object value() { return value; } - public Object apply(int i) { return RunTime.box_zvalue(value[i]); } - public void update(int i, Object x) { value[i] = ((Boolean)x).value; } - public int length() { return value.length; } - public String toString() { return String.valueOf(value); } -} - -/** @meta class extends scala.Array[scala.Byte]; */ -final class BArray extends Array implements java.io.Serializable { - public final byte[] value; - public BArray(byte[] value) { this.value = value; } - public Object value() { return value; } - public Object apply(int i) { return RunTime.box_bvalue(value[i]); } - public void update(int i, Object x) { value[i] = ((Byte)x).value; } - public int length() { return value.length; } - public String toString() { return String.valueOf(value); } -} - -/** @meta class extends scala.Array[scala.Short]; */ -final class SArray extends Array implements java.io.Serializable { - public final short[] value; - public SArray(short[] value) { this.value = value; } - public Object value() { return value; } - public Object apply(int i) { return RunTime.box_svalue(value[i]); } - public void update(int i, Object x) { value[i] = ((Short)x).value; } - public int length() { return value.length; } - public String toString() { return String.valueOf(value); } -} - -/** @meta class extends scala.Array[scala.Char]; */ -final class CArray extends Array implements java.io.Serializable { - public final char[] value; - public CArray(char[] value) { this.value = value; } - public Object value() { return value; } - public Object apply(int i) { return RunTime.box_cvalue(value[i]); } - public void update(int i, Object x) { value[i] = ((Char)x).value; } - public int length() { return value.length; } - public String toString() { return String.valueOf((Object)value); } -} - -/** @meta class extends scala.Array[scala.Int]; */ -final class IArray extends Array implements java.io.Serializable { - public final int[] value; - public IArray(int[] value) { this.value = value; } - public Object value() { return value; } - public Object apply(int i) { return RunTime.box_ivalue(value[i]); } - public void update(int i, Object x) { value[i] = ((Int)x).value; } - public int length() { return value.length; } - public String toString() { return String.valueOf(value); } -} - -/** @meta class extends scala.Array[scala.Long]; */ -final class LArray extends Array implements java.io.Serializable { - public final long[] value; - public LArray(long[] value) { this.value = value; } - public Object value() { return value; } - public Object apply(int i) { return RunTime.box_lvalue(value[i]); } - public void update(int i, Object x) { value[i] = ((Long)x).value; } - public int length() { return value.length; } - public String toString() { return String.valueOf(value); } -} - -/** @meta class extends scala.Array[scala.Float]; */ -final class FArray extends Array implements java.io.Serializable { - public final float[] value; - public FArray(float[] value) { this.value = value; } - public Object value() { return value; } - public Object apply(int i) { return RunTime.box_fvalue(value[i]); } - public void update(int i, Object x) { value[i] = ((Float)x).value; } - public int length() { return value.length; } - public String toString() { return String.valueOf(value); } -} - -/** @meta class extends scala.Array[scala.Double]; */ -final class DArray extends Array implements java.io.Serializable { - public final double[] value; - public DArray(double[] value) { this.value = value; } - public Object value() { return value; } - public Object apply(int i) { return RunTime.box_dvalue(value[i]); } - public void update(int i, Object x) { value[i] = ((Double)x).value; } - public int length() { return value.length; } - public String toString() { return String.valueOf(value); } -} - -/** @meta class [?T < scala.AnyRef] extends scala.Array[?T]; */ -final class OArray extends Array implements java.io.Serializable { - public final Object[] value; - public OArray(Object[] value) { this.value = value; } - public Object value() { return value; } - public Object apply(int i) { return value[i]; } - public void update(int i, Object x) { value[i] = x; } - public int length() { return value.length; } - public String toString() { return String.valueOf(value); } -} diff --git a/sources/scala/runtime/ScalaRunTime.scala b/sources/scala/runtime/ScalaRunTime.scala deleted file mode 100644 index 8fe69a2f31..0000000000 --- a/sources/scala/runtime/ScalaRunTime.scala +++ /dev/null @@ -1,90 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -object ScalaRunTime { - - /** Names for primitive types, used by array unboxing */ - val ByteTag = ".Byte"; - val ShortTag = ".Short"; - val CharTag = ".Char"; - val IntTag = ".Int"; - val LongTag = ".Long"; - val FloatTag = ".Float"; - val DoubleTag = ".Double"; - val BooleanTag = ".Boolean"; - - trait Try[a] { - def Catch[b >: a](handler: PartialFunction[Throwable, b]): b; - def Finally(handler: Unit): a; - } - - def Try[a](block: => a): Try[a] = new Try[a] with Runnable { - var result: a = _; - var exception: Throwable = RunTime.tryCatch(this); - - def run(): Unit = result = block; - - def Catch[b >: a](handler: PartialFunction[Throwable, b]): b = - if (exception == null) - result.asInstanceOf$erased[b] - // !!! else if (exception is LocalReturn) - // !!! // ... - else if (handler isDefinedAt exception) - handler(exception) - else - throw exception; - - def Finally(handler: Unit): a = - if (exception == null) - result.asInstanceOf$erased[a] - else - throw exception; - } - - def caseFields(x: CaseClass): List[Any] = { - val arity = x.caseArity; - def fields(from: Int): List[Any] = - if (from >= arity) List() - else x.caseElement(from) :: fields(from + 1); - fields(0) - } - - def _toString(x: CaseClass): String = { - caseFields(x).mkString(x.caseName + "(", ",", ")") - } - - def _hashCode(x: CaseClass): Int = { - var code = x.getClass().hashCode(); - val arity = x.caseArity; - var i = 0; - while (i < arity) { - code = code * 41 + x.caseElement(i).hashCode(); - i = i + 1 - } - code - } - - def _equals(x: CaseClass, y: Any): Boolean = y match { - case y1: CaseClass => - (x.getClass() eq y1.getClass()) && { - val arity = x.caseArity; - var i = 0; - while (i < arity && x.caseElement(i) == y1.caseElement(i)) - i = i + 1; - i == arity - } - case _ => - false - } - - def Seq[a](xs: a*): Seq[a] = null; // interpreted specially by new backend. -} diff --git a/sources/scala/runtime/ShortRef.java b/sources/scala/runtime/ShortRef.java deleted file mode 100644 index 3cada1fab8..0000000000 --- a/sources/scala/runtime/ShortRef.java +++ /dev/null @@ -1,16 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime; - -public class ShortRef implements java.io.Serializable { - public short elem; - public ShortRef(short elem) { this.elem = elem; } -} diff --git a/sources/scala/runtime/SymtabAttribute.cs b/sources/scala/runtime/SymtabAttribute.cs deleted file mode 100644 index fcb273a857..0000000000 --- a/sources/scala/runtime/SymtabAttribute.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -using System; - -namespace scala.runtime -{ - /// - /// Stores the symbol table for every top-level Scala class. - /// - - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] - public class SymtabAttribute : Attribute - { - // stores scalac symbol table - public readonly byte[] symtab; - - // indicates if the type should be considered by the compiler; - // used for synthetic classes introduced by the Scala compiler - public readonly bool shouldLoadClass; - - public SymtabAttribute(byte[] symtab) - { - this.symtab = symtab; - this.shouldLoadClass = true; - } - - public SymtabAttribute() { - this.symtab = new byte[0]; - this.shouldLoadClass = false; - } - } -} diff --git a/sources/scala/runtime/compat/Math.scala b/sources/scala/runtime/compat/Math.scala deleted file mode 100644 index 147ffeb0f9..0000000000 --- a/sources/scala/runtime/compat/Math.scala +++ /dev/null @@ -1,36 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime.compat; - -object Math { - val MIN_BYTE = java.lang.Byte.MIN_VALUE; - val MAX_BYTE = java.lang.Byte.MAX_VALUE; - val MIN_SHORT = java.lang.Short.MIN_VALUE; - val MAX_SHORT = java.lang.Short.MAX_VALUE; - val MIN_CHAR = java.lang.Character.MIN_VALUE; - val MAX_CHAR = java.lang.Character.MAX_VALUE; - val MIN_INT = java.lang.Integer.MIN_VALUE; - val MAX_INT = java.lang.Integer.MAX_VALUE; - val MIN_LONG = java.lang.Long.MIN_VALUE; - val MAX_LONG = java.lang.Long.MAX_VALUE; - val MIN_FLOAT = java.lang.Float.MIN_VALUE; - val MAX_FLOAT = java.lang.Float.MIN_VALUE; - val MIN_DOUBLE = java.lang.Double.MIN_VALUE; - val MAX_DOUBLE = java.lang.Double.MAX_VALUE; - - def max(x: Int, y: Int): Int = java.lang.Math.max(x, y); - - def ceil (x: Double): Double = java.lang.Math.ceil(x); - def floor(x: Double): Double = java.lang.Math.floor(x); - def log (x: Double): Double = java.lang.Math.log(x); - def sqrt (x: Double): Double = java.lang.Math.sqrt(x); -} diff --git a/sources/scala/runtime/compat/Platform.scala b/sources/scala/runtime/compat/Platform.scala deleted file mode 100644 index 282421a981..0000000000 --- a/sources/scala/runtime/compat/Platform.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime.compat; - -object Platform { - def arraycopy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: int): Unit = - System.arraycopy(src, srcPos, dest, destPos, length); - def getClass(obj: AnyRef) = obj.getClass(); - def getClassName(obj: AnyRef) = obj.getClass().getName(); - def printStackTrace(exc: java.lang.Throwable) = exc.printStackTrace(); - def getMessage(exc: java.lang.Throwable) = exc.getMessage(); - def split(str: String, separator: Char): Array[String] = { - str.split(separator.toString()); - } - - def currentThread = java.lang.Thread.currentThread(); - - def parseByte(s: String): Byte = java.lang.Byte.parseByte(s); - def parseShort(s: String): Short = java.lang.Short.parseShort(s); - def parseInt(s: String): Int = java.lang.Integer.parseInt(s); - def parseLong(s: String): Long = java.lang.Long.parseLong(s); - def parseFloat(s: String): Float = java.lang.Float.parseFloat(s); - def parseDouble(s: String): Double = java.lang.Double.parseDouble(s); - - def isDigit(c: Char): Boolean = java.lang.Character.isDigit(c); -} diff --git a/sources/scala/runtime/compat/StringBuilder.scala b/sources/scala/runtime/compat/StringBuilder.scala deleted file mode 100644 index bfb790723e..0000000000 --- a/sources/scala/runtime/compat/StringBuilder.scala +++ /dev/null @@ -1,26 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - - -package scala.runtime.compat; - -class StringBuilder { - val str = new StringBuffer(); - def append(x: Any): StringBuilder = { - str.append(x); - this - } - def append(x: String): StringBuilder = { - str.append(x); - this - } - def length(): Int = str.length(); - override def toString() = str.toString(); -} diff --git a/sources/scala/runtime/matching/Address.scala b/sources/scala/runtime/matching/Address.scala deleted file mode 100644 index 3f548e402f..0000000000 --- a/sources/scala/runtime/matching/Address.scala +++ /dev/null @@ -1,30 +0,0 @@ -package scala.runtime.matching ; - -object Address { - def empty = new Address(); -} - -//import List.list2ordered; - -/** Address holds the path in reverse Dewey notation -*/ -class Address( l:Int* ) extends Ordered[Address] { - - private val list:List[Int] = l.toList; - - def compareTo [b >: Address <% Ordered[b]](y: b): int = y match { - case o:Address => list.reverse.compareTo(o.list.reverse) - //(xs => List.view(xs)(Predef.int2ordered)); - case _ => -(y compareTo this) - } - - def down: Address = new Address( ( 1 :: list ):_* ); - - /** precond: p is nonempty */ - def right: Address = list match { - case i :: rest => new Address( ((i+1) :: rest ):_* ) - } - - override def toString() = list.mkString("Address(",".",")"); - -} diff --git a/sources/scala/runtime/matching/NonTerm.scala b/sources/scala/runtime/matching/NonTerm.scala deleted file mode 100644 index 35bc0f60ce..0000000000 --- a/sources/scala/runtime/matching/NonTerm.scala +++ /dev/null @@ -1,52 +0,0 @@ -package scala.runtime.matching ; - -import scala.collection.immutable ; - -abstract class NonTerm { - - override def toString() = this match { - case TreeNT( i ) => "t"+i; - case h @ HedgeNT( i ) => "h"+i+{ if( h.nullable )"~" else "" }; - } - -} - -/** tree nonterminal. holds set of binding variable indices. - */ -case class TreeNT(i:int) extends NonTerm with Ordered[TreeNT] { - - var vset:immutable.Set[Int] = new immutable.TreeSet[Int]() ; - - /** vset should be sorted to allow fast lookup */ - def this( i:int, vset:immutable.Set[Int] ) = { - this( i ); - this.vset = new immutable.TreeSet[Int]() incl vset ; - } - - def compareTo [b >: TreeNT <% Ordered[b]](y: b): int = y match { - case TreeNT( y1 ) => i compareTo y1; - case _ => -(y compareTo this) - } -}; - -/** hedge nonterminals. holds nullable property. - */ -case class HedgeNT(i:int) extends NonTerm with Ordered[HedgeNT] { - - var nullable:boolean = false; - - def this( i:int, nullable:boolean ) = { - this( i ); - this.nullable = nullable; - } - - def compareTo [b >: HedgeNT <% Ordered[b]](y: b): int = y match { - case HedgeNT( y1 ) => i compareTo y1; - case _ => -(y compareTo this) - } -}; - -//case object EMPTYHEDGE extends HedgeNT( 0, true ) ; -//case object ANYHEDGE extends HedgeNT( 1, true ) ; -object ANYTREE extends TreeNT( 1 ); - diff --git a/sources/scala/runtime/matching/PatternTests.scala b/sources/scala/runtime/matching/PatternTests.scala deleted file mode 100644 index ea04481d58..0000000000 --- a/sources/scala/runtime/matching/PatternTests.scala +++ /dev/null @@ -1,5 +0,0 @@ -package scala.runtime.matching ; - -abstract class PatternTests extends Function2[Int,Any,Boolean]{ - def apply(i:Int, inp:Any): Boolean; -} diff --git a/sources/scala/runtime/matching/Rule.scala b/sources/scala/runtime/matching/Rule.scala deleted file mode 100644 index 7bd6d40fd1..0000000000 --- a/sources/scala/runtime/matching/Rule.scala +++ /dev/null @@ -1,102 +0,0 @@ -package scala.runtime.matching ; - -/* hedge grammar rules */ -abstract class Rule extends Ordered[Rule] { - - def compareTo [b >: Rule <% Ordered[b]](that: b): int = that match { - case r:Rule => - if( rule_smaller( this, r ) ) - -1 - else if( rule_eq( this, r ) ) - 0 - else - 1 - case _ => -(that compareTo this) - } - - final def rule_smaller( r1:Rule, r2:Rule ):boolean = r1 match { - case HedgeRule( h1, _, hh1 ) => r2 match { - case HedgeRule( h2, _, hh2 ) => - ((h1 == h2)&&( hh1.i < hh2.i )) || h1.i < h2.i; - case HedgeChainRule( h2, hh2 ) => - ((h1 == h2)&&( hh1.i < hh2.i )) || h1.i < h2.i; - case _ => false; - } - case HedgeChainRule( h1, hh1 ) => r2 match { - case HedgeRule( h2, _, hh2 ) => - ((h1 == h2)&&( hh1.i < hh2.i )) || h1.i < h2.i; - case HedgeChainRule( h2, hh2 ) => - ((h1 == h2)&&( hh1.i < hh2.i )) || h1.i < h2.i; - case _ => false; - } - case TreeRule( t1, _, hh1 ) => r2 match { - case TreeRule( t2, _, hh2 ) => - ((t1 == t2 )&&(hh1.i < hh2.i )) || t1.i < t2.i; - case AnyTreeRule( t2 ) => false; - case AnyNodeRule( t2, hh2 ) => - ((t1 == t2 )&&(hh1.i < hh2.i )) || t1.i < t2.i; - case _ => true; - } - case AnyTreeRule( t1 ) => r2 match { - case TreeRule( _, _ , _ ) => true; - case AnyTreeRule( t2 ) => t1.i < t2.i; - case AnyNodeRule( t2, _ ) => true - case _ => true; - } - case AnyNodeRule( t1, hh1 ) => r2 match { - case TreeRule( t2, _, hh2 ) => - ((t1 == t2 )&&(hh1.i < hh2.i )) || t1.i < t2.i; - case AnyTreeRule( t2 ) => false; - case AnyNodeRule( t2, hh2 ) => - ((t1 == t2 )&&(hh1.i < hh2.i )) || t1.i < t2.i; - case _ => true; - } - }; - final def rule_eq( r1:Rule, r2:Rule ):boolean = r1 == r2; - - - override def toString() = this match { - case HedgeChainRule( n, m ) => - n.toString()+" ::= "+m.toString(); - - case TreeRule( n, label, n2 ) => - (n.toString()+{ if( !n.vset.isEmpty ) n.vset.toString() else "" }+ - " ::= "+label+"( "+n2.toString()+{if( n2.nullable ) "~" else ""}+" )") - - case AnyTreeRule( n ) => - n.toString()+{ if( !n.vset.isEmpty ) n.vset.toString() else "" }+" ::= _ "; - - case AnyNodeRule( n, h ) => - n.toString()+{ if( !n.vset.isEmpty ) n.vset.toString() else "" }+" ::= _ ( "+h.toString()+" )"; - - case HedgeRule( n, t, h ) => - n.toString()+( - if( n.nullable ) "~" else " " - )+" ::= "+( - if( t == ANYTREE ) "_" else t.toString() - )+" "+h.toString(); - - } -} - -abstract class TRule extends Rule; -abstract class HRule extends Rule; -/* -a tree rule is of the from A -> s(B) -where A,B are TreeNTs and s is an identifier (string). - -If s is the empty string, then the node label is arbitrary -If HedgeNT is AnyHedgeNT, then the tree is arbitrary -*/ -case class HedgeChainRule( n: HedgeNT, rhs: HedgeNT ) extends HRule; -case class TreeRule( n:TreeNT, test:Int, h:HedgeNT ) extends TRule { - def this(i:Int, s:Int, n:Int ) = { - this( new TreeNT(i), s, new HedgeNT(n)); - } -}; -case class AnyTreeRule( n:TreeNT ) extends TRule { -} -case class AnyNodeRule( n:TreeNT, h:HedgeNT ) extends TRule { -} -case class HedgeRule( n:HedgeNT, t:TreeNT, h:HedgeNT ) extends HRule; - diff --git a/sources/scala/runtime/matching/TestAlphabet.scala b/sources/scala/runtime/matching/TestAlphabet.scala deleted file mode 100644 index 9ef4698ebc..0000000000 --- a/sources/scala/runtime/matching/TestAlphabet.scala +++ /dev/null @@ -1,9 +0,0 @@ -package scala.runtime.matching ; - -trait TestAlphabet; - -case class TestLabel(i: Int) extends TestAlphabet ; - -case object AnyNode extends TestAlphabet { - def view(x: Int): TestLabel = TestLabel(x); -} diff --git a/sources/scala/runtime/types/ClassType.java b/sources/scala/runtime/types/ClassType.java deleted file mode 100644 index b0fb83b79e..0000000000 --- a/sources/scala/runtime/types/ClassType.java +++ /dev/null @@ -1,94 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.Type; -import scala.Array; -import scala.runtime.RunTime; - -public abstract class ClassType extends Type { - public final Class clazz; - public final boolean isTrivial; - - public ClassType(Class clazz, boolean isTrivial) { - this.clazz = clazz; - this.isTrivial = isTrivial; - } - - public Array newArray(int size) { - Object[] array = - (Object[])java.lang.reflect.Array.newInstance(clazz, size); - return RunTime.box_oarray(array); - } - - public Object defaultValue() { - return null; - } - - public boolean isInstance(Object o) { - assert Statistics.incInstanceOf(); - return clazz.isInstance(o); - } - - public boolean isNonTrivialInstance(Object o) { - assert isTrivial; // must be overridden for non-trivial types - return true; - } - - public boolean isSubType(Type that) { - return (that == Type.Any) - || (that instanceof ClassType - && isSubClassType((ClassType)that)) - || (that instanceof CompoundType - && isSubCompoundType((CompoundType)that)); - } - - protected boolean isSubClassType(ClassType that) { - return that.clazz.isAssignableFrom(this.clazz); - } - - public boolean isNonTrivialSubClassType(ClassType that) { - assert isTrivial; // must be overridden for non-trivial types - return true; - } - - protected final boolean isSubCompoundType(CompoundType that) { - // TODO? check refinement - for (int i = 0; i < that.components.length; ++i) { - if (!isSubType(that.components[i])) - return false; - } - - return true; - } - - public boolean isSameType(Type that) { - return (that instanceof ClassType) - && (((ClassType)that).clazz == this.clazz); - } - - public boolean isSameAsJavaType(Class that) { - if (this.isTrivial) - return clazz == that; - else if (clazz != that) - return false; - else - throw new Error("uncomparable types"); - } - - public int hashCode() { - return clazz.hashCode(); - } - - public String toString() { - return clazz.getName(); - } -} diff --git a/sources/scala/runtime/types/CompoundType.java b/sources/scala/runtime/types/CompoundType.java deleted file mode 100644 index 4dcb830b0d..0000000000 --- a/sources/scala/runtime/types/CompoundType.java +++ /dev/null @@ -1,109 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.Type; -import scala.Array; -import scala.ScalaObject; -import scala.runtime.RunTime; - -/** - * Run-time representation for compound types. - * - * @author Michel Schinz - * @version 1.0 - */ - -public class CompoundType extends Type { - public final ClassType[] components; - public final boolean emptyRefinement; - - public CompoundType(ClassType[] components, boolean emptyRefinement) { - this.components = components; - this.emptyRefinement = emptyRefinement; - } - - public Array newArray(int size) { - if (Type.unsafeArraysAllowed.get() == java.lang.Boolean.TRUE) - return (Array) - java.lang.reflect.Array.newInstance(components[0].clazz, size); - else - throw new Error("cannot create arrays of compound types"); - } - - public Object defaultValue() { - return null; - } - - public boolean isInstance(Object o) { - assert Statistics.incInstanceOf(); - for (int i = 0; i < components.length; ++i) { - if (!components[i].isInstance(o)) - return false; - } - - return true; - } - - public boolean isSubType(Type that) { - if (!emptyRefinement) - throw new Error("cannot compute isSubType (non-empty refinement)"); - - if (that instanceof CompoundType) { - CompoundType thatCT = (CompoundType)that; - ClassType[] thatComponents = thatCT.components; - for (int i = 0; i < thatComponents.length; ++i) { - if (!this.isSubType(thatComponents[i])) - return false; - } - return true; - } else { - for (int i = 0; i < components.length; ++i) { - if (components[i].isSubType(that)) - return true; - } - return false; - } - } - - public boolean isSameType(Type that) { - if (!emptyRefinement) - throw new Error("cannot compute isSameType (non-empty refinement)"); - - if (that instanceof CompoundType) { - CompoundType thatCT = (CompoundType)that; - - if (components.length != thatCT.components.length) - return false; - - for (int i = 0; i < components.length; ++i) { - if (!components[i].isSameType(thatCT.components[i])) - return false; - } - - return true; - } else - return false; - } - - public int hashCode() { - return Type.hashCode(components); - } - - public String toString() { - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < components.length; ++i) { - if (i > 0) buf.append(" with "); - buf.append(components[i]); - } - return buf.toString(); - } -} diff --git a/sources/scala/runtime/types/JavaClassType.java b/sources/scala/runtime/types/JavaClassType.java deleted file mode 100644 index 5a73641e51..0000000000 --- a/sources/scala/runtime/types/JavaClassType.java +++ /dev/null @@ -1,53 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import java.util.HashMap; - -public class JavaClassType extends ClassType { - private static final ClassLoader loader = - ClassLoader.getSystemClassLoader(); - - private static ThreadLocal cacheLocal = new ThreadLocal() { - protected Object initialValue() { - return new HashMap(); - } - }; - - public static JavaClassType javaClassType(String fullName) { - HashMap/**/ cache = (HashMap)cacheLocal.get(); - JavaClassType jct = (JavaClassType)cache.get(fullName); - if (jct == null) { - try { - jct = new JavaClassType(fullName); - cache.put(fullName, jct); - } catch (ClassNotFoundException e) { - throw new Error(e); - } - } - return jct; - } - - public static JavaClassType javaArrayType(String elemFullName, int dimen) { - StringBuffer fullName = new StringBuffer(); - for (int i = 0; i < dimen; ++i) - fullName.append('['); - if (elemFullName.length() == 1 && "ZBCDFIJS".indexOf(elemFullName) >= 0) - fullName.append(elemFullName); - else - fullName.append('L').append(elemFullName).append(';'); - return javaClassType(fullName.toString()); - } - - public JavaClassType(String fullName) throws ClassNotFoundException { - super(Class.forName(fullName, false, loader), true); - } -} diff --git a/sources/scala/runtime/types/JavaRefArrayType.java b/sources/scala/runtime/types/JavaRefArrayType.java deleted file mode 100644 index 2b25592f7a..0000000000 --- a/sources/scala/runtime/types/JavaRefArrayType.java +++ /dev/null @@ -1,80 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.Type; -import scala.Array; - -/** - * Type for Java arrays of references. - * - * @author Michel Schinz - * @version 1.0 - */ - -public class JavaRefArrayType extends Type { - public final int dimensions; - public final Type elemType; - - public static JavaRefArrayType javaRefArrayType(Type elemType, - int dimensions) { - if (elemType instanceof JavaRefArrayType) { - JavaRefArrayType other = (JavaRefArrayType)elemType; - return new JavaRefArrayType(other.elemType, - dimensions + other.dimensions); - } else - return new JavaRefArrayType(elemType, dimensions); - } - - private JavaRefArrayType(Type elemType, int dimensions) { - this.elemType = elemType; - this.dimensions = dimensions; - } - - public Array newArray(int size) { - throw new Error(); // TODO - } - - public Object defaultValue() { - return null; - } - - public boolean isInstance(Object o) { - assert Statistics.incInstanceOf(); - return this.isSameAsJavaType(o.getClass()); - } - - public boolean isSameType(Type that) { - return (that instanceof JavaRefArrayType) - && (elemType.isSameType(((JavaRefArrayType)that).elemType)); - } - - public boolean isSameAsJavaType(Class that) { - Class thatElemType = that; - for (int i = 0; i < dimensions && thatElemType != null; ++i) - thatElemType = thatElemType.getComponentType(); - - return (thatElemType != null) - && (elemType.isSameAsJavaType(thatElemType)); - } - - public boolean isSubType(Type that) { - return isSameType(that); - } - - public String toString() { - return elemType.toString() + "[]"; - } - - public int hashCode() { - return elemType.hashCode() * 11; - } -} diff --git a/sources/scala/runtime/types/LazyParents.java b/sources/scala/runtime/types/LazyParents.java deleted file mode 100644 index 7f3e64575c..0000000000 --- a/sources/scala/runtime/types/LazyParents.java +++ /dev/null @@ -1,22 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -/** - * Abstract superclass for suspended computations of parent classes. - * - * @author Michel Schinz - * @version 1.0 - */ - -public abstract class LazyParents { - abstract public ScalaClassType[] force(); -} diff --git a/sources/scala/runtime/types/ScalaClassType.java b/sources/scala/runtime/types/ScalaClassType.java deleted file mode 100644 index 47b7b7f4d9..0000000000 --- a/sources/scala/runtime/types/ScalaClassType.java +++ /dev/null @@ -1,271 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.Type; -import scala.Array; -import scala.ScalaObject; -import scala.runtime.RunTime; -import scala.runtime.FNV_Hash; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * Provides a run-time representation of the Scala types. - * - * @author Michel Schinz - * @version 1.0 - */ - -public class ScalaClassType extends ClassType { - public static final ScalaClassType[] EMPTY_ARRAY = - new ScalaClassType[0]; - - private static final ScalaClassType[][] EMPTY_ANCESTORS = - new ScalaClassType[0][]; - - private final TypeConstructor constr; - private final Type[] inst; - - private final Object parents; - private ScalaClassType[][] ancestors = null; - - private final int hashCode; - - public ScalaClassType(TypeConstructor constr, Type[] inst, Object parents) { - super(constr.clazz, constr.isTrivial); - - this.constr = constr; - this.inst = inst; - - int hash = FNV_Hash.hashStep32(FNV_Hash.INIT, constr.hashCode()); - for (int i = 0; i < inst.length; ++i) { - hash = FNV_Hash.hashStep32(hash, inst[i].hashCode()); - } - this.hashCode = hash; - this.parents = parents; - } - - public boolean isInstance(Object o) { - return super.isInstance(o) - && (isTrivial - || ((ScalaObject)o).getScalaType().isNonTrivialSubClassType(this)); - } - - public boolean isNonTrivialInstance(Object o) { - assert Statistics.incWeakInstanceOf(); - return ((ScalaObject)o).getScalaType().isNonTrivialSubClassType(this); - } - - protected boolean isSubClassType(ClassType that) { - return (this == that) - || (super.isSubClassType(that) - && (that.isTrivial - || isNonTrivialSubClassType((ScalaClassType)that))); - } - - public boolean isNonTrivialSubClassType(ClassType that) { - ScalaClassType thatCT = (ScalaClassType)that; - ScalaClassType parentCT = myInstantiationFor(thatCT); - - // At this stage, if parentCT is null, it means that the - // constructors had different prefixes, hence we return false. - return (parentCT != null) - && (parentCT == thatCT || parentCT.hasSubInstantiation(thatCT)); - } - - // Return true iff the instantiation of THIS is "smaller" than the - // one of THAT. - private boolean hasSubInstantiation(ScalaClassType that) { - assert this.constr == that.constr; - - final Type[] thisInst = this.inst; - final Type[] thatInst = that.inst; - - int i = 0; - - // invariant parameters - final int firstM = this.constr.zCount; - while (i < firstM) { - Type thisTp = thisInst[i], thatTp = thatInst[i]; - if (!(thisTp == thatTp || thisTp.isSameType(thatTp))) - return false; - ++i; - } - // contravariant parameters - final int firstP = firstM + this.constr.mCount; - while (i < firstP) { - Type thisTp = thisInst[i], thatTp = thatInst[i]; - if (!(thisTp == thatTp || thatTp.isSubType(thisTp))) - return false; - ++i; - } - // covariant parameters - final int firstOutside = firstP + this.constr.pCount; - while (i < firstOutside) { - Type thisTp = thisInst[i], thatTp = thatInst[i]; - if (!(thisTp == thatTp || thisTp.isSubType(thatTp))) - return false; - ++i; - } - return true; - } - - public boolean isSameType(Type that) { - return this == that; - } - - private ScalaClassType myInstantiationFor(ScalaClassType that) { - // Find our instantiation for the other type, if any. - ScalaClassType[] thisSlice = getAncestors()[that.constr.level]; - - for (int i = 0; i < thisSlice.length; ++i) { - if (thisSlice[i].constr == that.constr) { - assert Statistics.addAncestorSearchIterations(i + 1); - return thisSlice[i]; - } - } - assert Statistics.addAncestorSearchIterations(thisSlice.length); - - return null; - } - - public String toString() { - StringBuffer buf = new StringBuffer(); - - int firstM = constr.zCount; - int firstP = firstM + constr.mCount; - buf.append(constr); - if (inst.length > 0) { - buf.append("["); - for (int i = 0; i < inst.length; ++i) { - if (i > 0) buf.append(", "); - if (i >= firstP) - buf.append('+'); - else if (i >= firstM) - buf.append('-'); - buf.append(inst[i]); - } - buf.append("]"); - } - return buf.toString(); - } - - public int hashCode() { - return hashCode; - } - - public ScalaClassType[] getParents() { - if (parents instanceof LazyParents) - return ((LazyParents)parents).force(); - else - return (ScalaClassType[])parents; - } - - private ScalaClassType[][] getAncestors() { - if (ancestors == null) - computeAncestors(); - return ancestors; - } - - private void computeAncestors() { - final int level = constr.level; - final int ancestorDepth = constr.ancestorCacheDepth; - final int[] ancestorCode = constr.ancestorCode; - ScalaClassType[] parents = getParents(); - - ScalaClassType[][] ancestors = new ScalaClassType[ancestorDepth][]; - ScalaClassType[][] initialAncestors = parents.length > 0 - ? parents[0].getAncestors() - : EMPTY_ANCESTORS; - - for (int l = 0, dci = 0; l < ancestorDepth; ++l) { - int toAddParents = 0; - if (dci < ancestorCode.length && ancestorCode[dci] == l) { - dci++; - toAddParents = ancestorCode[dci++]; - } - int toAddSelf = (l == level) && (!constr.isTrivial) ? 1 : 0; - int toAdd = toAddParents + toAddSelf; - ScalaClassType[] initialRow; - - if (l < initialAncestors.length) - initialRow = initialAncestors[l]; - else - initialRow = ScalaClassType.EMPTY_ARRAY; - - if (toAdd == 0) { - ancestors[l] = initialRow; - } else { - int initialLen = initialRow.length; - ScalaClassType[] newRow = - new ScalaClassType[initialLen + toAdd]; - - if (toAddSelf == 1) - newRow[0] = this; - - System.arraycopy(initialRow, 0, newRow, toAddSelf, initialLen); - for (int i = 0; i < toAddParents; ++i) { - int p = ancestorCode[dci++]; - int o = ancestorCode[dci++]; - newRow[toAddSelf + initialLen + i] = - parents[p].getAncestors()[l][o]; - } - ancestors[l] = newRow; - } - } - this.ancestors = ancestors; - } - - private static final ClassLoader loader = - ClassLoader.getSystemClassLoader(); - - // Must match value defined in class scalac.util.Names ! - private static final String INSTANTIATE_PREFIX = "instantiate$"; - - // Enforces uniqueness of the instance when serializing and - // deserializing the same Scala type object many times. - private Object readResolve() { - if (constr.clazz == null) - return this; // TODO: check why clazz may be null - String fullName = constr.clazz.getName(); - Class instClazz = constr.clazz; - if (constr.clazz.isInterface()) { - try { - instClazz = Class.forName(fullName + "$class", false, loader); - } - catch (ClassNotFoundException e) { - throw new Error(e); - } - } - try { - int inx = fullName.lastIndexOf('.'); - String className = (inx < 0) ? fullName : fullName.substring(inx + 1); - String name = INSTANTIATE_PREFIX + className + "$"; - Class[] paramTypes = new Class[]{ Type[].class }; - Method instMeth = instClazz.getDeclaredMethod(name, paramTypes); - assert Modifier.isStatic(instMeth.getModifiers()); - return instMeth.invoke(null, new Object[]{ inst }); - } - catch (NoSuchMethodException e) { - throw new Error(e); - } - catch (IllegalAccessException e) { - throw new Error(e); - } - catch (InvocationTargetException e) { - throw new Error(e); - } - } - -} diff --git a/sources/scala/runtime/types/SingleType.java b/sources/scala/runtime/types/SingleType.java deleted file mode 100644 index 44093475d2..0000000000 --- a/sources/scala/runtime/types/SingleType.java +++ /dev/null @@ -1,52 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.Type; -import scala.Array; - -public class SingleType extends Type { - private final Object instance; - - public SingleType(Object instance) { - this.instance = instance; - } - - public Array newArray(int size) { - if (Type.unsafeArraysAllowed.get() == java.lang.Boolean.TRUE) - return (Array) - java.lang.reflect.Array.newInstance(instance.getClass(), size); - else - throw new Error("cannot create array of single types"); - } - - public Object defaultValue() { - return null; - } - - public boolean isInstance(Object o) { - assert Statistics.incInstanceOf(); - return o == instance; - } - - public boolean isSubType(Type that) { - return that.isInstance(instance); - } - - public boolean isSameType(Type that) { - return (that instanceof SingleType) - && (this.instance == ((SingleType)that).instance); - } - - public int hashCode() { - return System.identityHashCode(instance); - } -} diff --git a/sources/scala/runtime/types/SpecialType.java b/sources/scala/runtime/types/SpecialType.java deleted file mode 100644 index 6c2527570b..0000000000 --- a/sources/scala/runtime/types/SpecialType.java +++ /dev/null @@ -1,42 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.Type; -import scala.Array; -import scala.runtime.RunTime; - -/** - * Abstract superclass for all "special" types, which are types - * existing in Scala but not in Java: Any, AnyVal, All and AllRef. - * - * @author Michel Schinz - * @version 1.0 - */ - -abstract public class SpecialType extends Type { - public Array newArray(int size) { - if (Type.unsafeArraysAllowed.get() == java.lang.Boolean.TRUE) - return (Array) - java.lang.reflect.Array.newInstance(Object.class, size); - else - throw new Error("cannot create arrays of special type " - + "(" + getClass().getName() + ")"); - } - - public Object defaultValue() { - return null; - } - - public boolean isSameType(Type that) { - return this == that; - } -} diff --git a/sources/scala/runtime/types/Statistics.java b/sources/scala/runtime/types/Statistics.java deleted file mode 100644 index db3317370b..0000000000 --- a/sources/scala/runtime/types/Statistics.java +++ /dev/null @@ -1,155 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import java.io.PrintStream; -import java.io.FileOutputStream; -import java.util.Map; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.ArrayList; - -import scala.Type; - -/** - * Collect various statistics about run time types, and output them to - * a file as s-expressions. - * - * Notice that all methods return true, in order to be usable as - * assertions and disabled easily. - * - * @author Michel Schinz - * @version 1.0 - */ - -public class Statistics { - private static long instantiationsCount = 0; - private static long uniqueInstantiationsCount = 0; - - private static long instanceOfCount = 0; - private static long weakInstanceOfCount = 0; - private static long typeCastCount = 0; - - private static long ancestorSearchIterations = 0; - private static long ancestorSearches = 0; - - private static HashMap instances = new HashMap(); - - static { - assert addWriteFileHook(); - } - - public static boolean addWriteFileHook() { - Thread writeFileHook = new Thread() { - public void run() { - try { - writeToFile(); - } catch (Throwable t) { - throw new Error(t); - } - } - }; - - Runtime.getRuntime().addShutdownHook(writeFileHook); - return true; - } - - public static synchronized boolean incInstantiations(boolean unique) { - ++instantiationsCount; - if (unique) ++uniqueInstantiationsCount; - return true; - } - - public static synchronized boolean incInstanceOf() { - ++instanceOfCount; - return true; - } - - public static synchronized boolean incWeakInstanceOf() { - ++weakInstanceOfCount; - return true; - } - - public static synchronized boolean decInstanceOf() { - --instanceOfCount; - return true; - } - - public static synchronized boolean incTypeCast() { - ++typeCastCount; - return true; - } - - public static synchronized boolean incInstances(String className, - Type tp) { - ArrayList currInst = (ArrayList)instances.get(className); - if (currInst == null) { - currInst = new ArrayList(); - instances.put(className, currInst); - } - currInst.add(tp); - return true; - } - - public static synchronized boolean addAncestorSearchIterations(int n) { - ancestorSearchIterations += n; - ancestorSearches++; - return true; - } - - /** - * Output statistics to a file, as an a-list associating numbers - * to tags. - */ - public static boolean writeToFile() throws java.io.FileNotFoundException { - String fileName = System.getProperty("scala.runtime.types.statfile"); - assert fileName != null - : "property scala.runtime.types.statfile not set"; - - System.out.println("Writing RTT statistics to file " + fileName); - - PrintStream stream = new PrintStream(new FileOutputStream(fileName)); - stream.println("("); - stream.println("(instantiations . " - + instantiationsCount + ")"); - stream.println("(unique-instantiations . " - + uniqueInstantiationsCount + ")"); - stream.println("(instance-of . " - + instanceOfCount + ")"); - stream.println("(weak-instance-of . " - + weakInstanceOfCount + ")"); - stream.println("(type-cast . " - + typeCastCount + ")"); - if (ancestorSearches > 0) { - stream.println("(ancestor-searches . " - + ancestorSearches + ")"); - stream.println("(ancestor-search-iterations . " - + ancestorSearchIterations + ")"); - } - stream.println("(instances . ("); - Iterator instIt = instances.entrySet().iterator(); - while (instIt.hasNext()) { - Map.Entry entry = (Map.Entry)instIt.next(); - String name = (String)entry.getKey(); - ArrayList instances = (ArrayList)entry.getValue(); - HashSet uniqueInstances = new HashSet(instances); - stream.println("(\"" + name + "\" . " - + instances.size() + ")"); - stream.println("(\"Unique" + name + "\" . " - + uniqueInstances.size() + ")"); - } - stream.print("))"); - stream.println(")"); - stream.close(); - return true; - } -} diff --git a/sources/scala/runtime/types/TypeAll.java b/sources/scala/runtime/types/TypeAll.java deleted file mode 100644 index 9c79646c69..0000000000 --- a/sources/scala/runtime/types/TypeAll.java +++ /dev/null @@ -1,34 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; - -public class TypeAll extends SpecialType { - public boolean isInstance(Object o) { - assert Statistics.incInstanceOf(); - return false; - } - - public boolean isSubType(Type that) { - return true; - } - - public String toString() { return "scala.All"; } - public int hashCode() { return 0xAAAAAAAA; } - - // Make TypeAll a serializable singleton - public static TypeAll INSTANCE = new TypeAll(); - protected TypeAll() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeAllRef.java b/sources/scala/runtime/types/TypeAllRef.java deleted file mode 100644 index e037a340f0..0000000000 --- a/sources/scala/runtime/types/TypeAllRef.java +++ /dev/null @@ -1,35 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; - -public class TypeAllRef extends SpecialType { - public boolean isInstance(Object o) { - assert Statistics.incInstanceOf(); - return false; - } - - public boolean isSubType(Type that) { - return !that.isSubType(Type.AnyVal); - } - - public String toString() { return "scala.AllRef"; } - - public int hashCode() { return 0xDDDDDDDD; } - - // Make TypeAllRef a serializable singleton - public static TypeAllRef INSTANCE = new TypeAllRef(); - protected TypeAllRef() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeAny.java b/sources/scala/runtime/types/TypeAny.java deleted file mode 100644 index 6a2a5483a4..0000000000 --- a/sources/scala/runtime/types/TypeAny.java +++ /dev/null @@ -1,35 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; - -public class TypeAny extends SpecialType { - public boolean isInstance(Object o) { - assert Statistics.incInstanceOf(); - return true; - } - - public boolean isSubType(Type that) { - return that == this; - } - - public String toString() { return "scala.Any"; } - - public int hashCode() { return 0xBBBBBBBB; } - - // Make TypeAny a serializable singleton - public static TypeAny INSTANCE = new TypeAny(); - protected TypeAny() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeAnyVal.java b/sources/scala/runtime/types/TypeAnyVal.java deleted file mode 100644 index 9fe397b576..0000000000 --- a/sources/scala/runtime/types/TypeAnyVal.java +++ /dev/null @@ -1,34 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; - -public class TypeAnyVal extends SpecialType { - public boolean isInstance(Object o) { - throw new UnsupportedOperationException(); - } - - public boolean isSubType(Type that) { - return that == Type.Any || that == this; - } - - public String toString() { return "scala.AnyVal"; } - - public int hashCode() { return 0xCCCCCCCC; } - - // Make TypeAnyVal a serializable singleton - public static TypeAnyVal INSTANCE = new TypeAnyVal(); - protected TypeAnyVal() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeBoolean.java b/sources/scala/runtime/types/TypeBoolean.java deleted file mode 100644 index 69788a9752..0000000000 --- a/sources/scala/runtime/types/TypeBoolean.java +++ /dev/null @@ -1,37 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; -import scala.Boolean; - -public class TypeBoolean extends ValueType { - private final Boolean ZERO = RunTime.box_zvalue(false); - public Object cast(Object o) { - assert scala.runtime.types.Statistics.incTypeCast(); - if (! (o == null || o instanceof scala.Boolean)) - throw new ClassCastException(); // TODO error message - return o; - } - public Object defaultValue() { return ZERO; } - public boolean isSameAsJavaType(Class that) { - return that == java.lang.Boolean.TYPE; - } - public String toString() { return "scala.Boolean"; } - public int hashCode() { return 0x88888888; } - - // Make TypeBoolean a serializable singleton - public static TypeBoolean INSTANCE = new TypeBoolean(); - protected TypeBoolean() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeByte.java b/sources/scala/runtime/types/TypeByte.java deleted file mode 100644 index cafab096f3..0000000000 --- a/sources/scala/runtime/types/TypeByte.java +++ /dev/null @@ -1,50 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; -import scala.Byte; - -public class TypeByte extends ValueType { - private final Byte ZERO = RunTime.box_bvalue((byte)0); - public Object cast(Object o) { - assert scala.runtime.types.Statistics.incTypeCast(); - if (o == null || o instanceof scala.Byte) - return o; - else if (o instanceof scala.Double) - return RunTime.box_bvalue((byte)((scala.Double)o).value); - else if (o instanceof scala.Float) - return RunTime.box_bvalue((byte)((scala.Float)o).value); - else if (o instanceof scala.Long) - return RunTime.box_bvalue((byte)((scala.Long)o).value); - else if (o instanceof scala.Int) - return RunTime.box_bvalue((byte)((scala.Int)o).value); - else if (o instanceof scala.Short) - return RunTime.box_bvalue((byte)((scala.Short)o).value); - else if (o instanceof scala.Char) - return RunTime.box_bvalue((byte)((scala.Char)o).value); - else - throw new ClassCastException(); - } - public Object defaultValue() { return ZERO; } - public boolean isSameAsJavaType(Class that) { - return that == java.lang.Byte.TYPE; - } - public String toString() { return "scala.Byte"; } - public int hashCode() { return 0x77777777; } - - // Make TypeByte a serializable singleton - public static TypeByte INSTANCE = new TypeByte(); - protected TypeByte() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeChar.java b/sources/scala/runtime/types/TypeChar.java deleted file mode 100644 index 19d42a2887..0000000000 --- a/sources/scala/runtime/types/TypeChar.java +++ /dev/null @@ -1,50 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; -import scala.Char; - -public class TypeChar extends ValueType { - private final Char ZERO = RunTime.box_cvalue((char)0); - public Object cast(Object o) { - assert scala.runtime.types.Statistics.incTypeCast(); - if (o == null || o instanceof scala.Char) - return o; - else if (o instanceof scala.Double) - return RunTime.box_cvalue((char)((scala.Double)o).value); - else if (o instanceof scala.Float) - return RunTime.box_cvalue((char)((scala.Float)o).value); - else if (o instanceof scala.Long) - return RunTime.box_cvalue((char)((scala.Long)o).value); - else if (o instanceof scala.Int) - return RunTime.box_cvalue((char)((scala.Int)o).value); - else if (o instanceof scala.Short) - return RunTime.box_cvalue((char)((scala.Short)o).value); - else if (o instanceof scala.Byte) - return RunTime.box_cvalue((char)((scala.Byte)o).value); - else - throw new ClassCastException(); - } - public Object defaultValue() { return ZERO; } - public boolean isSameAsJavaType(Class that) { - return that == char.class; - } - public String toString() { return "scala.Char"; } - public int hashCode() { return 0x66666666; } - - // Make TypeChar a serializable singleton - public static TypeChar INSTANCE = new TypeChar(); - protected TypeChar() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeConstructor.java b/sources/scala/runtime/types/TypeConstructor.java deleted file mode 100644 index b1a71916c3..0000000000 --- a/sources/scala/runtime/types/TypeConstructor.java +++ /dev/null @@ -1,157 +0,0 @@ -/* __ * \ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.Type; -import scala.Array; -import scala.runtime.AtomicReference; -import scala.runtime.IOMap; - -/** - * Class modelling a type constructor (this includes non-polymorphic - * types, which are handled as polymorphic types with zero arguments). - * - * @author Michel Schinz - * @version 1.0 - */ - -public final class TypeConstructor implements java.io.Serializable { - public final static TypeConstructor[] EMPTY_ARRAY = - new TypeConstructor[0]; - - private static class Outer implements java.io.Serializable {} - - public final static Object FUNCTION_OUTER = new Outer(); - - /** Java class corresponding to this constructor. */ - public Class clazz; - - /** - * Number of invariant (z), contravariant (m) and covariant (p) - * type arguments. - */ - public final int zCount, mCount, pCount; - - /** - * Level of this type in the hierarchy (scala.AnyRef is at 0, its - * direct children at 1, and so on). - */ - public final int level; - - /** - * Indication of triviality: a constructor is trivial iff it has - * no enclosing class, and no type arguments. - */ - public final boolean isTrivial; - - public final int ancestorCacheDepth; - /** - * "Code" to compute the ancestors for an instance of this - * constructor, based on the ancestors of its not-strongly-trivial - * parents. This code is structured as follows: - * - * l1 n1 p1,0 o1,0 p1,1 o1,1 ... l2 n2 p2,0 o2,0 ... - * - * where all l, n, p and o are integers. ni gives the number of - * additional entries to add to the ancestors of the first parent - * at level li. pi gives the index of the parent in which to pick - * this additional entry, and oi gives the offset of this entry in - * the parent's ancestors. - */ - public final int[] ancestorCode; - - /** Enclosing class for this type constructor */ - private final Object outer; - - private final InstantiationMap instMapModule = new InstantiationMap(); - private final AtomicReference/**/ instances = - new AtomicReference(IOMap.EMPTY); - - private static final ClassLoader loader = - ClassLoader.getSystemClassLoader(); - - private static final int[] EMPTY_ANCESTOR_CODE = new int[0]; - - public TypeConstructor(int level, - String fullName, - Object outer, - int zCount, - int mCount, - int pCount, - int ancestorCacheDepth, - int[] ancestorCode) { - this.level = level; - this.outer = outer; - this.zCount = zCount; - this.mCount = mCount; - this.pCount = pCount; - - this.ancestorCacheDepth = ancestorCacheDepth; - this.ancestorCode = - (ancestorCode == null ? EMPTY_ANCESTOR_CODE : ancestorCode); - - this.isTrivial = (outer == null) && (zCount + pCount + mCount == 0); - - try { - this.clazz = Class.forName(fullName, false, loader); - } catch (ClassNotFoundException e) { - throw new Error(e); - } - - assert (zCount >= 0) && (mCount >= 0) && (pCount >= 0); - } - - public String toString() { - if (outer == null) - return clazz.getName(); - else if (outer == FUNCTION_OUTER) - return "." + clazz.getName(); - else - return outer.toString() + "." + clazz.getName(); - } - - public ScalaClassType getInstantiation(Type[] args) { - ScalaClassType inst = - instMapModule.get((InstantiationMap.T)instances.get(), args); - assert Statistics.incInstantiations(inst == null); - return inst; - } - - public ScalaClassType instantiate(Type[] args, Object parents) { - ScalaClassType tp = new ScalaClassType(this, args, parents); - - try { - InstantiationMap.T oldMap, newMap; - do { - oldMap = (InstantiationMap.T)instances.get(); - newMap = instMapModule.put(oldMap, args, tp); - } while (!instances.compareAndSet(oldMap, newMap)); - } catch (IOMap.ConflictException e) { - return (ScalaClassType)e.oldValue; - } - return tp; - } - - ////////////////////////////////////////////////////////////////////// - - private static class InstantiationMap - extends IOMap - implements java.io.Serializable { - public T put(T map, Type[] inst, ScalaClassType value) - throws ConflictException { - return super.put(map, Type.hashCode(inst), value); - } - - public ScalaClassType get(T map, Type[] inst) { - return (ScalaClassType)super.get(map, Type.hashCode(inst)); - } - } -} diff --git a/sources/scala/runtime/types/TypeDouble.java b/sources/scala/runtime/types/TypeDouble.java deleted file mode 100644 index 0bc22709ee..0000000000 --- a/sources/scala/runtime/types/TypeDouble.java +++ /dev/null @@ -1,49 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; - -public public class TypeDouble extends ValueType { - private final scala.Double ZERO = RunTime.box_dvalue(0.0); - public Object cast(Object o) { - assert scala.runtime.types.Statistics.incTypeCast(); - if (o == null || o instanceof scala.Double) - return o; - else if (o instanceof scala.Float) - return RunTime.box_dvalue(((scala.Float)o).value); - else if (o instanceof scala.Long) - return RunTime.box_dvalue(((scala.Long)o).value); - else if (o instanceof scala.Int) - return RunTime.box_dvalue(((scala.Int)o).value); - else if (o instanceof scala.Short) - return RunTime.box_dvalue(((scala.Short)o).value); - else if (o instanceof scala.Char) - return RunTime.box_dvalue(((scala.Char)o).value); - else if (o instanceof scala.Byte) - return RunTime.box_dvalue(((scala.Byte)o).value); - else - throw new ClassCastException(); - } - public Object defaultValue() { return ZERO; } - public boolean isSameAsJavaType(Class that) { - return that == java.lang.Double.TYPE; - } - public String toString() { return "scala.Double"; } - public int hashCode() { return 0x11111111; } - - // Make TypeDouble a serializable singleton - public static TypeDouble INSTANCE = new TypeDouble(); - protected TypeDouble() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeFloat.java b/sources/scala/runtime/types/TypeFloat.java deleted file mode 100644 index 5f0e18898c..0000000000 --- a/sources/scala/runtime/types/TypeFloat.java +++ /dev/null @@ -1,49 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; - -public class TypeFloat extends ValueType { - private final scala.Float ZERO = RunTime.box_fvalue(0.0f); - public Object cast(Object o) { - assert scala.runtime.types.Statistics.incTypeCast(); - if (o == null || o instanceof scala.Float) - return o; - else if (o instanceof scala.Double) - return RunTime.box_fvalue((float)((scala.Double)o).value); - else if (o instanceof scala.Long) - return RunTime.box_fvalue(((scala.Long)o).value); - else if (o instanceof scala.Int) - return RunTime.box_fvalue(((scala.Int)o).value); - else if (o instanceof scala.Short) - return RunTime.box_fvalue(((scala.Short)o).value); - else if (o instanceof scala.Char) - return RunTime.box_fvalue(((scala.Char)o).value); - else if (o instanceof scala.Byte) - return RunTime.box_fvalue(((scala.Byte)o).value); - else - throw new ClassCastException(); - } - public Object defaultValue() { return ZERO; } - public boolean isSameAsJavaType(Class that) { - return that == java.lang.Float.TYPE; - } - public String toString() { return "scala.Float"; } - public int hashCode() { return 0x22222222; } - - // Make TypeFloat a serializable singleton - public static TypeFloat INSTANCE = new TypeFloat(); - protected TypeFloat() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeInt.java b/sources/scala/runtime/types/TypeInt.java deleted file mode 100644 index 3c29b70c0a..0000000000 --- a/sources/scala/runtime/types/TypeInt.java +++ /dev/null @@ -1,50 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; -import scala.Int; - -public class TypeInt extends ValueType { - private final Int ZERO = RunTime.box_ivalue(0); - public Object cast(Object o) { - assert scala.runtime.types.Statistics.incTypeCast(); - if (o == null || o instanceof scala.Int) - return o; - else if (o instanceof scala.Double) - return RunTime.box_ivalue((int)((scala.Double)o).value); - else if (o instanceof scala.Float) - return RunTime.box_ivalue((int)((scala.Float)o).value); - else if (o instanceof scala.Long) - return RunTime.box_ivalue((int)((scala.Long)o).value); - else if (o instanceof scala.Short) - return RunTime.box_ivalue(((scala.Short)o).value); - else if (o instanceof scala.Char) - return RunTime.box_ivalue(((scala.Char)o).value); - else if (o instanceof scala.Byte) - return RunTime.box_ivalue(((scala.Byte)o).value); - else - throw new ClassCastException(); - } - public Object defaultValue() { return ZERO; } - public boolean isSameAsJavaType(Class that) { - return that == java.lang.Integer.TYPE; - } - public String toString() { return "scala.Int"; } - public int hashCode() { return 0x44444444; } - - // Make TypeInt a serializable singleton - public static TypeInt INSTANCE = new TypeInt(); - protected TypeInt() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeLong.java b/sources/scala/runtime/types/TypeLong.java deleted file mode 100644 index cc03d72e8f..0000000000 --- a/sources/scala/runtime/types/TypeLong.java +++ /dev/null @@ -1,49 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; - -public class TypeLong extends ValueType { - private final scala.Long ZERO = RunTime.box_lvalue(0l); - public Object cast(Object o) { - assert scala.runtime.types.Statistics.incTypeCast(); - if (o == null || o instanceof scala.Long) - return o; - else if (o instanceof scala.Double) - return RunTime.box_lvalue((long)((scala.Double)o).value); - else if (o instanceof scala.Float) - return RunTime.box_lvalue((long)((scala.Float)o).value); - else if (o instanceof scala.Int) - return RunTime.box_lvalue(((scala.Int)o).value); - else if (o instanceof scala.Short) - return RunTime.box_lvalue(((scala.Short)o).value); - else if (o instanceof scala.Char) - return RunTime.box_lvalue(((scala.Char)o).value); - else if (o instanceof scala.Byte) - return RunTime.box_lvalue(((scala.Byte)o).value); - else - throw new ClassCastException(); - } - public Object defaultValue() { return ZERO; } - public boolean isSameAsJavaType(Class that) { - return that == java.lang.Long.TYPE; - } - public String toString() { return "scala.Long"; } - public int hashCode() { return 0x33333333; } - - // Make TypeLong a serializable singleton - public static TypeLong INSTANCE = new TypeLong(); - protected TypeLong() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeShort.java b/sources/scala/runtime/types/TypeShort.java deleted file mode 100644 index 286a518596..0000000000 --- a/sources/scala/runtime/types/TypeShort.java +++ /dev/null @@ -1,49 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; - -public class TypeShort extends ValueType { - private final scala.Short ZERO = RunTime.box_svalue((short)0); - public Object cast(Object o) { - assert scala.runtime.types.Statistics.incTypeCast(); - if (o == null || o instanceof scala.Short) - return o; - else if (o instanceof scala.Double) - return RunTime.box_svalue((short)((scala.Double)o).value); - else if (o instanceof scala.Float) - return RunTime.box_svalue((short)((scala.Float)o).value); - else if (o instanceof scala.Long) - return RunTime.box_svalue((short)((scala.Long)o).value); - else if (o instanceof scala.Int) - return RunTime.box_svalue((short)((scala.Int)o).value); - else if (o instanceof scala.Char) - return RunTime.box_svalue((short)((scala.Char)o).value); - else if (o instanceof scala.Byte) - return RunTime.box_svalue(((scala.Byte)o).value); - else - throw new ClassCastException(); - } - public Object defaultValue() { return ZERO; } - public boolean isSameAsJavaType(Class that) { - return that == java.lang.Short.TYPE; - } - public String toString() { return "scala.Short"; } - public int hashCode() { return 0x55555555; } - - // Make TypeShort a serializable singleton - public static TypeShort INSTANCE = new TypeShort(); - protected TypeShort() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/TypeUnit.java b/sources/scala/runtime/types/TypeUnit.java deleted file mode 100644 index 29edaa325f..0000000000 --- a/sources/scala/runtime/types/TypeUnit.java +++ /dev/null @@ -1,37 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.runtime.RunTime; -import scala.Type; -import scala.Array; -import scala.Unit; - -public class TypeUnit extends ValueType { - private final Unit ZERO = RunTime.box_uvalue(); - public Object cast(Object o) { - assert scala.runtime.types.Statistics.incTypeCast(); - if (! (o == null || o instanceof scala.Unit)) - throw new ClassCastException(); // TODO error message - return o; - } - public Object defaultValue() { return ZERO; } - public boolean isSameAsJavaType(Class that) { - return that == java.lang.Void.TYPE; - } - public String toString() { return "scala.Unit"; } - public int hashCode() { return 0x99999999; } - - // Make TypeUnit a serializable singleton - public static TypeUnit INSTANCE = new TypeUnit(); - protected TypeUnit() { /* exists only to that instantiation */ } - private Object readResolve() { return INSTANCE; } -} diff --git a/sources/scala/runtime/types/ValueType.java b/sources/scala/runtime/types/ValueType.java deleted file mode 100644 index 0cffb9c854..0000000000 --- a/sources/scala/runtime/types/ValueType.java +++ /dev/null @@ -1,38 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.runtime.types; - -import scala.Type; -import scala.Array; - -/** - * Abstract superclass for all value types. - * - * @author Michel Schinz - * @version 1.0 - */ - -abstract public class ValueType extends Type { - public boolean isInstance(Object o) { - throw new UnsupportedOperationException(); - } - public boolean isSubType(Type that) { - return that == Type.Any - || that == Type.AnyVal - || that == this; - } - public boolean isSameType(Type that) { - return this == that; - } - public Array newArray(int size) { - throw new Error("internal error (Scala runtime)"); - } -} diff --git a/sources/scala/serializable.scala b/sources/scala/serializable.scala deleted file mode 100644 index 2b9ad9f177..0000000000 --- a/sources/scala/serializable.scala +++ /dev/null @@ -1,12 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2005, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -*/ - -package scala; - -class serializable extends Attribute {} diff --git a/sources/scala/testing/Benchmark.scala b/sources/scala/testing/Benchmark.scala deleted file mode 100644 index f6523a7271..0000000000 --- a/sources/scala/testing/Benchmark.scala +++ /dev/null @@ -1,74 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - - -/** - * Scala benchmarking mini framework. - */ - -package scala.testing; - -/** Benchmark can be used to quickly turn an existing - * class into a benchmark. Here is a short example: - * - *
- *  object sort1 extends Sorter with Benchmark {
- *     def run = sort(List.range(1, 1000));
- *  }
- *  
- * - * The run method has to be defined by the user, who will perform - * the timed operation there. - * Run the benchmark as follows: - *
- *   scala sort1 5 times.log
- * 
- * This will run the benchmark 5 times and log the execution times in - * a file called times.log - */ -trait Benchmark { - - /** this method should be implemented by the concrete benchmark */ - def run: Unit; - - /** Run the benchmark the specified number of times - * and return a list with the execution times in milliseconds - * in reverse order of the execution */ - def runBenchmark(noTimes: Int): List[Long] = - - for (val i <- List.range(1, noTimes + 1)) yield { - val startTime = System.currentTimeMillis(); - run; - val stopTime = System.currentTimeMillis(); - System.gc(); - - stopTime - startTime - } - - /** - * The entry point. It takes two arguments: the number of - * consecutive runs, and the name of a log file where to - * append the times. - * - */ - def main(args: Array[String]): Unit = { - if (args.length > 1) { - val logFile = new java.io.FileWriter(args(1), true); // append, not overwrite - - logFile.write(getClass().getName()); - for (val t <- runBenchmark(Integer.parseInt(args(0)))) - logFile.write("\t\t" + t); - - logFile.write("\n"); - logFile.flush(); - } else - Console.println("Usage: scala benchmarks.program "); - } -} - diff --git a/sources/scala/testing/SUnit.scala b/sources/scala/testing/SUnit.scala deleted file mode 100644 index 4faa0c9cd0..0000000000 --- a/sources/scala/testing/SUnit.scala +++ /dev/null @@ -1,188 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.testing; - -/** unit testing methods in the spirit of JUnit framework. - * use these classes like this: - - import scala.testing.SUnit; - import SUnit._; - - - class MyTest(n:String) extends TestCase(n) { - - override def runTest() = n match { - case "myTest1" => assertTrue( true ); - case "myTest2" => assertTrue( "hello", false ); - } - } - - val r = new TestResult(); - suite.run(r); - for(val tf <- r.failures()) { - Console.println(tf.toString()) - } -} - - */ -object SUnit { - - /** a Test can be run with its result being collected */ - trait Test { - def run(r: TestResult):Unit; - } - - /** a TestCase defines the fixture to run multiple tests */ - class TestCase(val name: String) extends Test with Assert { - protected def createResult() = - new TestResult(); - - protected def runTest(): Unit = - {} - - def run(r: TestResult): Unit = - try { - runTest(); - } catch { - case t:Throwable => r.addFailure(this, t); - } - - def run(): Unit = - run(createResult()); - - def setUp() = - {} - - def tearDown() = - {} - - override def toString() = - name; - } - - /** a TestFailure collects a failed test together with the thrown exception */ - class TestFailure(val failedTest:Test, val thrownException:Throwable) { - - def this(p:Pair[Test,Throwable]) = this(p._1, p._2); - - override def toString() = - failedTest.toString()+" failed due to "+thrownException.toString(); - - def trace(): String = { - val s = new StringBuffer(); - for(val trElem <- thrownException.getStackTrace()) { - s.append(trElem.toString()); - s.append('\n'); - } - s.toString() - } - } - - /** a TestResult collects the result of executing a test case */ - class TestResult { - val buf = - new scala.collection.mutable.ArrayBuffer[Pair[Test,Throwable]](); - - def addFailure(test:Test, t:Throwable) = - buf += Pair(test,t); - - def failureCount() = - buf.length; - - def failures() = - buf.elements map { x => new TestFailure(x) }; - } - - /** a TestSuite runs a composite of test cases */ - class TestSuite(tests:Test*) extends Test { - - def this(names:Seq[String], constr:String=>Test) = - this((names.toList map constr):_*); - - val buf = - new scala.collection.mutable.ArrayBuffer[Test](); - - buf ++= tests; - - def addTest(t: Test) = - buf += t; - - def run(r: TestResult):Unit = { - for(val t <- buf) { - t.run(r); - } - } - } - - /** an AssertFailed is thrown for a failed assertion */ - case class AssertFailed(msg:String) extends java.lang.RuntimeException { - override def toString() = - "failed assertion:"+msg; - } - - /** this trait defined useful assert methods */ - trait Assert { - /** equality */ - def assertEquals[A](msg:String, expected:A, actual: => A): Unit = - if( expected != actual ) fail(msg); - - /** equality */ - def assertEquals[A](expected:A, actual: => A): Unit = - assertEquals("(no message)", expected, actual); - - /** falseness */ - def assertFalse(msg:String, actual: => Boolean): Unit = - assertEquals(msg, false, actual); - /** falseness */ - def assertFalse(actual: => Boolean): Unit = - assertFalse("(no message)", actual); - - /** not null */ - def assertNotNull(msg:String, actual: => AnyRef): Unit = - if( null == actual ) fail(msg); - - /** not null */ - def assertNotNull(actual: => AnyRef): Unit = - assertNotNull("(no message)", actual); - - /** reference inequality */ - def assertNotSame(msg:String, expected: => AnyRef, actual: => AnyRef): Unit = - if(expected.eq(actual)) fail(msg); - /** reference inequality */ - def assertNotSame(expected: => AnyRef, actual: => AnyRef): Unit = - assertNotSame("(no message)", expected, actual); - - /** null */ - def assertNull(msg:String, actual: => AnyRef): Unit = - if( null != actual ) fail(msg); - /** null */ - def assertNull(actual: => AnyRef): Unit = - assertNull("(no message)", actual); - - - /** reference equality */ - def assertSame(msg:String, expected: => AnyRef, actual: => AnyRef): Unit = - if(!expected.eq(actual)) fail(msg); - /** reference equality */ - def assertSame(expected: => AnyRef, actual: => AnyRef): Unit = - assertSame("(no message)", expected, actual); - - /** trueness */ - def assertTrue(msg:String, actual: => Boolean): Unit = - assertEquals(msg, true, actual); - /** trueness */ - def assertTrue(actual: => Boolean): Unit = - assertTrue("(no message)", actual); - - /** throws AssertFailed with given message */ - def fail(msg:String): Unit = - throw new AssertFailed(msg); - } -} diff --git a/sources/scala/testing/UnitTest.scala b/sources/scala/testing/UnitTest.scala deleted file mode 100644 index 2f8878b2eb..0000000000 --- a/sources/scala/testing/UnitTest.scala +++ /dev/null @@ -1,58 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2004, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -** $Id$ -\* */ - -package scala.testing; - -/** some simple methods to support unit testing with assertions -** to contain more JUnit style assertions which use Scala's features. -*/ -object UnitTest { - - class Report( report_ok:()=>Unit, report_fail:(String,String)=>Unit ) { - def ok:Unit = report_ok(); - def fail( actual:String, expected:String ):Unit = - report_fail( actual, expected ); - } - - var report = new Report( - { () => Console.println("passed ok") }, - { (actual:String, expected:String) => - Console.print("failed! we got"); - Console.print( "\""+ actual +"\"" ); - Console.println(" but expected \"" + expected + "\"") }); - - def setReporter( r:Report ) = { - this.report = r; - } - - def assertSameElements[a]( actual:Seq[a] , expected: Seq[a] ):Unit = - if( actual.sameElements( expected ) ) - report.ok - else - report.fail( actual.toString(), expected.toString() ); - - def assertEquals[a]( actual: a, expected: a ):Unit = - if( actual == expected ) - report.ok - else - report.fail( actual.toString(), expected.toString() ); - - def assertTrue( actual: Boolean ):Unit = assertEquals(actual, true); - def assertFalse( actual: Boolean ):Unit = assertEquals(actual, false); - - - def assertNotEquals[a]( actual: a, expected: a ):Unit = - if( actual != expected ) - report.ok - else - report.fail( actual.toString(), "x != "+expected.toString() ); - - //def test[a]( def doit: a, expected: a ):Unit = assertEquals( doit, expected ); - -} // unitTest diff --git a/sources/scala/text/Document.scala b/sources/scala/text/Document.scala deleted file mode 100644 index 40d5a3a7c4..0000000000 --- a/sources/scala/text/Document.scala +++ /dev/null @@ -1,119 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -// $Id$ - -package scala.text; - -import java.io.PrintWriter; -import java.io.Writer; - -case object DocNil extends Document; -case object DocBreak extends Document; -case class DocText(txt: String) extends Document; -case class DocGroup(doc: Document) extends Document; -case class DocNest(indent: Int, doc: Document) extends Document; -case class DocCons(hd: Document, tl: Document) extends Document; - -/** - * A basic pretty-printing library, based on Lindig's strict version - * of Wadler's adaptation of Hughes' pretty-printer. - * - * @version 1.0 - * @author Michel Schinz - */ - -abstract class Document { - def ::(hd: Document): Document = DocCons(hd, this); - def ::(hd: String): Document = DocCons(DocText(hd), this); - def :/:(hd: Document): Document = hd :: DocBreak :: this; - def :/:(hd: String): Document = hd :: DocBreak :: this; - - /** - * Format this document on WRITER and try to set line breaks so that - * the result fits in WIDTH columns. - */ - def format(width: Int, writer: Writer): Unit = { - type FmtState = Triple[Int,Boolean,Document]; - - def fits(w: Int, state: List[FmtState]): boolean = state match { - case _ if w < 0 => - false - case List() => - true - case Triple(_, _, DocNil) :: z => - fits(w, z) - case Triple(i, b, DocCons(h, t)) :: z => - fits(w, Triple(i,b,h) :: Triple(i,b,t) :: z) - case Triple(_, _, DocText(t)) :: z => - fits(w - t.length(), z) - case Triple(i, b, DocNest(ii, d)) :: z => - fits(w, Triple(i + ii, b, d) :: z) - case Triple(_, false, DocBreak) :: z => - fits(w - 1, z) - case Triple(_, true, DocBreak) :: z => - true - case Triple(i, _, DocGroup(d)) :: z => - fits(w, Triple(i, false, d) :: z) - } - - def spaces(n: Int): Unit = { - var rem = n; - while (rem >= 16) { writer write " "; rem = rem - 16 }; - if (rem >= 8) { writer write " "; rem = rem - 8 }; - if (rem >= 4) { writer write " "; rem = rem - 4 }; - if (rem >= 2) { writer write " "; rem = rem - 2}; - if (rem == 1) { writer write " " }; - } - - def fmt(k: Int, state: List[FmtState]): Unit = state match { - case List() => () - case Triple(_, _, DocNil) :: z => - fmt(k, z) - case Triple(i, b, DocCons(h, t)) :: z => - fmt(k, Triple(i, b, h) :: Triple(i, b, t) :: z) - case Triple(i, _, DocText(t)) :: z => - writer write t; - fmt(k + t.length(), z) - case Triple(i, b, DocNest(ii, d)) :: z => - fmt(k, Triple(i + ii, b, d) :: z) - case Triple(i, true, DocBreak) :: z => - writer write "\n"; - spaces(i); - fmt(i, z) - case Triple(i, false, DocBreak) :: z => - writer write " "; - fmt(k + 1, z) - case Triple(i, b, DocGroup(d)) :: z => - val fitsFlat = fits(width - k, Triple(i, false, d) :: z); - fmt(k, Triple(i, !fitsFlat, d) :: z) - } - - fmt(0, Triple(0, false, DocGroup(this)) :: Nil); - } -} - -object Document { - /** The empty document */ - def empty = DocNil; - - /** A break, which will either be turned into a space or a line break */ - def break = DocBreak; - - /** A document consisting of some text literal */ - def text(s: String): Document = DocText(s); - - /** - * A group, whose components will either be printed with all breaks - * rendered as spaces, or with all breaks rendered as line breaks. - */ - def group(d: Document): Document = DocGroup(d); - - /** A nested document, which will be indented as specified. */ - def nest(i: Int, d: Document): Document = DocNest(i, d); -} diff --git a/sources/scala/tools/nsc/CompilationUnits.scala b/sources/scala/tools/nsc/CompilationUnits.scala deleted file mode 100644 index 0c39d99c16..0000000000 --- a/sources/scala/tools/nsc/CompilationUnits.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -import scala.tools.nsc.util.{SourceFile, Position}; -import scala.tools.nsc.util.FreshNameCreator; -import scala.tools.util.AbstractFile; -import scala.collection.mutable.HashSet; - -[_trait_] abstract class CompilationUnits: Global { - - class CompilationUnit(val source: SourceFile, val mixinOnly: boolean) { - - /** short constructor */ - def this(source: SourceFile) = this(source, false); - - /** the fresh name creator */ - val fresh = new FreshNameCreator; - - /** the content of the compilation unit in tree form */ - var body: Tree = EmptyTree; - - val depends = new HashSet[AbstractFile]; - - def position(pos: int) = new Position(source, pos); - - def error(pos: int, msg: String) = reporter.error(position(pos), msg); - def warning(pos: int, msg: String) = reporter.warning(position(pos), msg); - override def toString() = source.toString(); - - } -} - - diff --git a/sources/scala/tools/nsc/CompilerCommand.scala b/sources/scala/tools/nsc/CompilerCommand.scala deleted file mode 100644 index 9768eaa621..0000000000 --- a/sources/scala/tools/nsc/CompilerCommand.scala +++ /dev/null @@ -1,66 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -import scala.tools.util.Reporter; - -/** A class representing command line info for scalac */ -class CompilerCommand(arguments: List[String], error: String => unit, interactive: boolean) { - private var fs: List[String] = List(); - - /** All files to compile */ - def files: List[String] = fs.reverse; - - /** The applicable settings */ - val settings: Settings = new Settings(error); - - /** A message explaining usage and options */ - def usageMsg: String = { - val helpSyntaxColumnWidth: int = - Iterable.max(settings.allSettings map (. helpSyntax.length())); - def format(s: String): String = { - val buf = new StringBuffer(); - buf.append(s); - var i = s.length(); - while (i < helpSyntaxColumnWidth) { buf.append(' '); i = i + 1 } - buf.toString() - } - settings.allSettings - .map(setting => - format(setting.helpSyntax) + " " + setting.helpDescription) - .mkString( - "Usage: scalac \n" + - "where possible options include: \n ", - "\n ", - "\n"); - } - - // initialization - var args = arguments; - var ok = true; - while (!args.isEmpty && ok) { - val args0 = args; - if (args.head.startsWith("-")) { - if (interactive) { - error("no options can be given in interactive mode"); - ok = false - } else { - for (val setting <- settings.allSettings) - args = setting.tryToSet(args); - if (args eq args0) { - error("unknown option: '" + args.head + "'"); - ok = false - } - } - } else if (args.head.endsWith(".scala")) { - fs = args.head :: fs; - args = args.tail - } else { - error("don't know what to do with " + args.head); - ok = false - } - } -} diff --git a/sources/scala/tools/nsc/CompilerRun.scala b/sources/scala/tools/nsc/CompilerRun.scala deleted file mode 100644 index 7677fc2cb8..0000000000 --- a/sources/scala/tools/nsc/CompilerRun.scala +++ /dev/null @@ -1,20 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -class CompilerRun { - def firstPhase: Phase = NoPhase; - def terminalPhase: Phase = NoPhase; - def namerPhase: Phase = NoPhase; - def typerPhase: Phase = NoPhase; - def refchecksPhase: Phase = NoPhase; - def explicitOuterPhase: Phase = NoPhase; - def erasurePhase: Phase = NoPhase; - def flattenPhase: Phase = NoPhase; - def mixinPhase: Phase = NoPhase; - def phaseNamed(name: String): Phase = NoPhase; -} - diff --git a/sources/scala/tools/nsc/EvalLoop.scala b/sources/scala/tools/nsc/EvalLoop.scala deleted file mode 100644 index 240547491a..0000000000 --- a/sources/scala/tools/nsc/EvalLoop.scala +++ /dev/null @@ -1,19 +0,0 @@ -package scala.tools.nsc; - -import java.io._; - -trait EvalLoop { - - def prompt: String; - - def loop(action: (String) => Unit): unit = { - val in = new BufferedReader(new InputStreamReader(System.in)); - System.out.print(prompt); - var line = in.readLine(); - while (line != null && line.length() > 0) { - action(line); - System.out.print(prompt); - line = in.readLine(); - } - } -} diff --git a/sources/scala/tools/nsc/FatalError.scala b/sources/scala/tools/nsc/FatalError.scala deleted file mode 100644 index aa849fa5d0..0000000000 --- a/sources/scala/tools/nsc/FatalError.scala +++ /dev/null @@ -1,8 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -case class FatalError(msg: String) extends Exception; diff --git a/sources/scala/tools/nsc/Global.scala b/sources/scala/tools/nsc/Global.scala deleted file mode 100644 index 75558c30b5..0000000000 --- a/sources/scala/tools/nsc/Global.scala +++ /dev/null @@ -1,518 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -import java.io._; -import java.nio.charset._; -import scala.tools.util.{SourceReader,ClassPath,AbstractFile}; -import scala.tools.nsc.util.{Position,SourceFile}; -import scala.tools.nsc.reporters._; - -import scala.collection.mutable.{HashSet,HashMap} - -import symtab._; -import symtab.classfile.{PickleBuffer, Pickler}; -import util.{ListBuffer, Statistics}; -import ast._; -import ast.parser._; -import typechecker._; -import matching.TransMatcher; -import transform._; -import backend.icode.{ICodes, GenICode, Checkers}; -import backend.ScalaPrimitives; -import backend.jvm.GenJVM; - -class Global(val settings: Settings, val reporter: Reporter) extends SymbolTable - with Trees - with CompilationUnits -{ - - // sub-components -------------------------------------------------- - - object treePrinters extends TreePrinters { - val global: Global.this.type = Global.this - } - val treePrinter = treePrinters.create(); - - object treeBrowsers extends TreeBrowsers { - val global: Global.this.type = Global.this - } - val treeBrowser = treeBrowsers.create(); - - object treeInfo extends TreeInfo { - val global: Global.this.type = Global.this - } - - object gen extends TreeGen { - val global: Global.this.type = Global.this - } - - object constfold extends ConstantFolder { - val global: Global.this.type = Global.this - } - - object checker extends TreeCheckers { - val global: Global.this.type = Global.this - } - - object icodes extends ICodes { - val global: Global.this.type = Global.this - } - - object checkers extends Checkers { - val global: Global.this.type = Global.this - } - - object statistics extends Statistics { - val global: Global.this.type = Global.this - } - - object overridingPairs extends OverridingPairs { - val global: Global.this.type = Global.this - } - - val copy = new LazyTreeCopier(); - -// reporting ------------------------------------------------------- - - def error(msg: String) = reporter.error(null, msg); - def warning(msg: String) = reporter.warning(null, msg); - def inform(msg: String) = System.err.println(msg); - - //reporter.info(null, msg, true); - - def informProgress(msg: String) = - if (settings.verbose.value) inform("[" + msg + "]"); - - def informTime(msg: String, start: long) = - informProgress(msg + " in " + (System.currentTimeMillis() - start) + "ms"); - - def log(msg: Object): unit = - if (settings.log contains phase.name) inform("[log " + phase + "] " + msg); - - def abort(msg: String) = throw new Error(msg); - -// file interface ------------------------------------------------------- - - private val reader: SourceReader = { - def stdCharset: Charset = { - settings.encoding.value = "ISO-8859-1"; // A mandatory charset - Charset.forName(settings.encoding.value); - } - val charset = - try { - Charset.forName(settings.encoding.value); - } catch { - case _: IllegalCharsetNameException => - error("illegal charset name '" + settings.encoding.value + "'"); - stdCharset - case _: UnsupportedCharsetException => - error("unsupported charset '" + settings.encoding.value + "'"); - stdCharset - } - new SourceReader(charset.newDecoder()); - } - - val classPath = new ClassPath( - settings.classpath.value, - settings.sourcepath.value, - settings.bootclasspath.value, - settings.extdirs.value); - - if (settings.verbose.value) { - System.err.println("classpath = " + classPath); - } - - def getSourceFile(f: AbstractFile): SourceFile = - new SourceFile(f, reader.read(f)); - - def getSourceFile(name: String): SourceFile = { - val f = AbstractFile.getFile(name); - if (f == null) throw new FileNotFoundException( - "source file '" + name + "' could not be found"); - getSourceFile(f) - } - - def getSourceFile(clazz: Symbol): SourceFile = { - val f = classPath.getRoot().lookupPath( - clazz.fullNameString(File.separatorChar) + ".scala", false); - if (f == null) throw new FileNotFoundException( - "source file for " + clazz + " could not be found"); - getSourceFile(f) - } - - object loaders extends SymbolLoaders { - val global: Global.this.type = Global.this - } - - def rootLoader: LazyType = new loaders.PackageLoader(classPath.getRoot()); - -// Phases ------------------------------------------------------------ - - var globalPhase: Phase = NoPhase; - - val MaxPhases = 64; - - val phaseWithId = new Array[Phase](MaxPhases); - { for (val i <- List.range(0, MaxPhases)) phaseWithId(i) = NoPhase } - - abstract class GlobalPhase(prev: Phase) extends Phase(prev) { - phaseWithId(id) = this; - def run: unit = currentRun.units foreach applyPhase; - - def apply(unit: CompilationUnit): unit; - private val isErased = prev.name == "erasure" || prev.erasedTypes; - override def erasedTypes: boolean = isErased; - private val isFlat = prev.name == "flatten" || prev.flatClasses; - override def flatClasses: boolean = isFlat; - final def applyPhase(unit: CompilationUnit): unit = { - if (settings.debug.value) inform("[running phase " + name + " on " + unit + "]"); - val unit0 = currentRun.currentUnit; - currentRun.currentUnit = unit; - apply(unit); - currentRun.advanceUnit; - assert(currentRun.currentUnit == unit); - currentRun.currentUnit = unit0; - } - } - - object syntaxAnalyzer extends SyntaxAnalyzer { - val global: Global.this.type = Global.this - } - - object analyzer extends Analyzer { - val global: Global.this.type = Global.this; - } - - object superAccessors extends SuperAccessors { - val global: Global.this.type = Global.this - } - - object pickler extends Pickler { - val global: Global.this.type = Global.this - } - - object refchecks extends RefChecks { - val global: Global.this.type = Global.this; - } - - object uncurry extends UnCurry { - val global: Global.this.type = Global.this; - } - - object tailCalls extends TailCalls { - val global: Global.this.type = Global.this; - } - - object transMatcher extends TransMatcher { - val global: Global.this.type = Global.this; - } - - object explicitOuter extends ExplicitOuter { - val global: Global.this.type = Global.this; - } - - object erasure extends Erasure { - val global: Global.this.type = Global.this; - } - - object lambdaLift extends LambdaLift { - val global: Global.this.type = Global.this; - } - - object constructors extends Constructors { - val global: Global.this.type = Global.this; - } - - object flatten extends Flatten { - val global: Global.this.type = Global.this; - } - - object mixin extends Mixin { - val global: Global.this.type = Global.this; - } - - object sampleTransform extends SampleTransform { - val global: Global.this.type = Global.this; - } - - object genicode extends GenICode { - val global: Global.this.type = Global.this; - } - - object icodePrinter extends backend.icode.Printers { - val global: Global.this.type = Global.this; - } - - object scalaPrimitives extends ScalaPrimitives { - val global: Global.this.type = Global.this; - } - - object genJVM extends GenJVM { - val global: Global.this.type = Global.this; - } - - object icodeChecker extends checkers.ICodeChecker(); - - object typer extends analyzer.Typer( - analyzer.NoContext.make(EmptyTree, Global.this.definitions.RootClass, new Scope())); - - def phaseDescriptors: List[SubComponent] = List( - analyzer.namerFactory, - analyzer.typerFactory, - superAccessors, - pickler, - refchecks, - uncurry, - tailCalls, - transMatcher, - explicitOuter, - erasure, - lambdaLift, - constructors, - flatten, - mixin, - genicode, - genJVM, - sampleTransform); - - private var curRun: Run = NoRun; - override def currentRun: Run = curRun; - - class TyperRun extends Run { - override val terminalPhase : Phase = typerPhase.next.next; - //override val terminalPhase : Phase = superAccessors.next; - } - - - - class Run extends CompilerRun { - var currentUnit : CompilationUnit = _; - curRun = this; - override val firstPhase = syntaxAnalyzer.newPhase(NoPhase); - phase = firstPhase; - definitions.init; // needs firstPhase and phase to be defined != NoPhase, - // that's why it is placed here. - icodes.init; - - private var p: Phase = firstPhase; - private var stopped = false; - for (val pd <- phaseDescriptors) { - if (!stopped) { - if (!(settings.skip contains pd.phaseName)) p = pd.newPhase(p); - stopped = settings.stop contains pd.phaseName; - } - } - - // progress tracking - def progress(current : Int, total : Int) : Unit = {} - private var phasec : Int = 0; - private var unitc : Int = 0; - def advancePhase : Unit = { - unitc = 0; - phasec = phasec + 1; - refreshProgress; - } - def advanceUnit : Unit = { - unitc = unitc + 1; - refreshProgress; - } - private def refreshProgress = if (fileset.size > 0) - progress((phasec * fileset.size) + unitc, - (phaseDescriptors.length+1) * fileset.size); - - - - override val terminalPhase : Phase = new GlobalPhase(p) { - def name = "terminal"; - def apply(unit: CompilationUnit): unit = {} - } - override def phaseNamed(name: String): Phase = { - var p: Phase = firstPhase; - while (p.next != p && p.name != name) p = p.next; - if (p.name != name) NoPhase else p - } - - override val namerPhase = phaseNamed("namer"); - override val typerPhase = phaseNamed("typer"); - override val refchecksPhase = phaseNamed("refchecks"); - override val explicitOuterPhase = phaseNamed("explicitouter"); - override val erasurePhase = phaseNamed("erasure"); - override val flattenPhase = phaseNamed("flatten"); - override val mixinPhase = phaseNamed("mixin"); - - private var unitbuf = new ListBuffer[CompilationUnit]; - private var fileset = new HashSet[AbstractFile]; - - private def addUnit(unit: CompilationUnit): unit = { - unitbuf += unit; - fileset += unit.source.getFile(); - } - - def units: Iterator[CompilationUnit] = unitbuf.elements; - - /** A map from compiled top-level symbols to their source files */ - val symSource = new HashMap[Symbol, AbstractFile]; - - /** A map from compiled top-level symbols to their picklers */ - val symData = new HashMap[Symbol, PickleBuffer]; - - def compileSources(sources: List[SourceFile]): unit = { - val startTime = System.currentTimeMillis(); - reporter.reset; - for (val source <- sources) - addUnit(new CompilationUnit(source)); - - globalPhase = firstPhase; - while (globalPhase != terminalPhase && reporter.errors == 0) { - val startTime = System.currentTimeMillis(); - phase = globalPhase; - globalPhase.run; - if (settings.print contains globalPhase.name) treePrinter.printAll(); - if (settings.browse contains globalPhase.name) treeBrowser.browse(units); - informTime(globalPhase.description, startTime); - globalPhase = globalPhase.next; - if (settings.check contains globalPhase.name) { - phase = globalPhase; - if (globalPhase.name == "jvm") icodeChecker.checkICodes; - else checker.checkTrees; - } - if (settings.statistics.value) statistics.print(phase); - advancePhase; - } - - if (settings.Xshowcls.value != "") showDef(newTermName(settings.Xshowcls.value), false); - if (settings.Xshowobj.value != "") showDef(newTermName(settings.Xshowobj.value), true); - if (settings.Xshowicode.value) writeICode(); - - if (reporter.errors == 0) { - assert(symData.isEmpty, symData.elements.toList); -/* - for (val Pair(sym, pickled) <- symData.elements.toList) { - sym setPos Position.NOPOS; -// if (symData contains sym) { -// symData -= sym; -// symData -= sym.linkedSym; -// writeSymblFile(sym, pickled) -// } -// } -*/ - for (val Pair(sym, file) <- symSource.elements) { - sym setPos Position.NOPOS; - if (sym.isTerm) sym.moduleClass setPos Position.NOPOS; - resetPackageClass(sym.owner); - } - } else { - for (val Pair(sym, file) <- symSource.elements) { - sym.reset(new loaders.SourcefileLoader(file)); - if (sym.isTerm) sym.moduleClass.reset(loaders.moduleClassLoader); - } - } - informTime("total", startTime); - } - - def compileLate(file: AbstractFile): unit = - if (fileset == null) - throw new FatalError("No class file for " + file + " was found\n(This file cannot be loaded as a source file)"); - else if (!(fileset contains file)) { - val unit = new CompilationUnit(getSourceFile(file)); - addUnit(unit); - var localPhase = firstPhase.asInstanceOf[GlobalPhase]; - while (localPhase.id < globalPhase.id || localPhase.id <= namerPhase.id) { - atPhase(localPhase)(localPhase.applyPhase(unit)); - localPhase = localPhase.next.asInstanceOf[GlobalPhase]; - } - refreshProgress; - } - - def compileFiles(files: List[AbstractFile]): unit = - try { - compileSources(files map getSourceFile) - } catch { - case ex: IOException => error(ex.getMessage()); - } - - def compile(filenames: List[String]): unit = - try { - compileSources(filenames map getSourceFile) - } catch { - case ex: IOException => error(ex.getMessage()); - } - - private def resetPackageClass(pclazz: Symbol): unit = { - assert(pclazz.isPackageClass, pclazz); - atPhase(firstPhase) { - pclazz.setInfo(atPhase(typerPhase)(pclazz.info)) - } - if (!pclazz.isRoot) resetPackageClass(pclazz.owner); - } - } - - def showDef(name: Name, module: boolean): unit = { - def getSym(name: Name, module: boolean): Symbol = { - var i = name.length - 1; - while (i != 0 && name(i) != '#' && name(i) != '.') i = i - 1; - if (i == 0) - definitions.getModule(name) - else { - val root = getSym(name.subName(0, i), name(i) == '.'); - var selector = name.subName(i+1, name.length); - if (module) selector = selector.toTypeName; - root.info.member(selector) - } - } - val sym = getSym(name, module); - System.err.println("" + sym.name + ":" + - (if (module) sym.tpe.symbol.info else sym.info)) - } - - /** Returns the file with the given suffix for the given class. */ - def getFile(clazz: Symbol, suffix: String) = { - val outdirname = settings.outdir.value; - var outdir = new File(if (outdirname == "") "." else outdirname); - val filename = clazz.fullNameString('.'); - var start = 0; - var end = filename.indexOf('.', start); - while (end >= start) { - outdir = new File(outdir, filename.substring(start, end)); - if (!outdir.exists()) outdir.mkdir(); - start = end + 1; - end = filename.indexOf('.', start); - } - new File(outdir, filename.substring(start) + suffix) - } - - private def writeSymblFile(clazz: Symbol, pickled: PickleBuffer) = { - val file = getFile(clazz, ".symbl"); - try { - val stream = new FileOutputStream(file); - stream.write(pickled.bytes, 0, pickled.writeIndex); - stream.close(); - informProgress("wrote " + file); - } catch { - case ex: IOException => - if (settings.debug.value) ex.printStackTrace(); - error("could not write file " + file); - } - } - - private def writeICode(): Unit = { - val printer = new icodePrinter.TextPrinter(null); - icodes.classes.foreach((cls) => { - val file = getFile(cls.symbol, ".icode"); - try { - val stream = new FileOutputStream(file); - printer.setWriter(new PrintWriter(stream, true)); - printer.printClass(cls); - informProgress("wrote " + file); - } catch { - case ex: IOException => - if (settings.debug.value) ex.printStackTrace(); - error("could not write file " + file); - } - }); - } -} diff --git a/sources/scala/tools/nsc/Interpreter.scala b/sources/scala/tools/nsc/Interpreter.scala deleted file mode 100644 index 847cdade6a..0000000000 --- a/sources/scala/tools/nsc/Interpreter.scala +++ /dev/null @@ -1,234 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -import scala.tools.nsc.reporters.Reporter; - -abstract class Interpreter { - import scala.collection.mutable.ListBuffer; - import symtab.Names; - - // list of names defined, for each line number - val prevDefines : ListBuffer[Pair[Int,ListBuffer[Names#Name]]] = new ListBuffer(); - - val compiler: Global; - - import scala.tools.nsc.ast.parser.SyntaxAnalyzer; - object syntaxAnalyzer extends SyntaxAnalyzer { - val global: compiler.type = compiler - } - - def interpret(line: String, reporter: Reporter): unit = { - import scala.tools.nsc.util.SourceFile; - - // convert input to a compilation unit, using SourceFile; - // and parse it, using syntaxAnalyzer, to get input ASTs - val inASTs = syntaxAnalyzer.interpreterParse( - new compiler.CompilationUnit( - //if SourceFile is not modified, then fix a bug - //here by adding an EOF character to the end of - //the 'line' - new SourceFile("",line.toCharArray()))); - - //todo: if (errors in parsing) after reporting them, exit method - - val dvt = new DefinedVarsTraverser; - dvt.traverseTrees(inASTs); - val definedVars = dvt.definedVars; - - val ivt = new ImportVarsTraverser(definedVars); - ivt.traverseTrees(inASTs); - val importVars = ivt.importVars; - - val lineno = prevDefines.length; - //todo: it is probably nice to include date & time, as well as a process id, in the filename - val filename = getTempPath().getPath()+java.io.File.separator+"InterpreterTempLine"+lineno+".scala"; - writeTempScalaFile(filename, line, lineno, definedVars, importVars); - - // first phase: compile auto-generated file - compiler.settings.outdir.value = getTempPath().getPath(); - val cr = new compiler.Run; - cr compile List(filename); - - //todo: if no errors in compilation then - // second phase: execute JVM, and print outcome - // else consider definition as if has not happened and exit method - //todo: use Scala's reflection API, which I designed, instead, for the following code - val cl = new java.net.URLClassLoader(Predef.Array(getTempPath().toURL())); - val interpreterResultObject: Class = Class.forName("InterpreterLine"+lineno+"Result",true,cl); - val resultValMethod: java.lang.reflect.Method = interpreterResultObject.getMethod("result",null); - var interpreterResultString: String = resultValMethod.invoke(interpreterResultObject,null).toString(); - - //var interpreterResultJavaTypeString: String = resultValMethod.getReturnType().getName(); - //Console.println(compiler.definitions.EmptyPackage.info.members); - val interpreterResultSym: compiler.Symbol = - compiler.definitions.getMember(compiler.definitions.EmptyPackage, - compiler.newTermName("InterpreterLine"+lineno+"Result")); - - def findSymbolWithName(ls: List[compiler.Symbol], name: compiler.Name): compiler.Symbol = - ls.find(s=>s.name == name) match { - case None => throw new IllegalStateException("Cannot find field '"+name+"' in InterpreterResult"); - case Some(s) => s; - } - - //var lastname: String = compiler.atPhase(cr.typerPhase.next){interpreterResultSym.info.decls.toList.last.name.toString()}; - //reporter.info(null,lastname,true); - //todo: similar to what I should be doing for Scala's reflection?? - var interpreterResultScalaTypeString: String = - compiler.atPhase(cr.typerPhase.next){ - findSymbolWithName(interpreterResultSym.info.decls.toList, - compiler.nme.getterToLocal(compiler.newTermName("result"))) - .tpe.toString() - }; - reporter.info(null,interpreterResultString+": "+interpreterResultScalaTypeString/*+" ("+interpreterResultJavaTypeString+")"*/,true); - -/* - val scalaInterpFile: File = ScalaInterpFile(filename); - scalaInterpFile.deleteOnExit(); - if(scalaInterpFile.exists()) - scalaInterpFile.delete(); - - getvalue of line#.last_var_defined_in_line (from defined_vars) - (works for 'it' as it was added as last val to definedvars) - and send it to reporter -*/ - - // book-keeping - //todo: if no errors in evaluation then - prevDefines += Pair(lineno,definedVars); - // else consider definition as if has not happened. - - // report some debug info - //reporter.info(null,"inASTs="+inASTs,true); - //reporter.info(null,"definedVars="+definedVars,true); - //reporter.info(null,"importVars="+importVars,true); - //reporter.info(null,"prevDefines="+prevDefines,true); - } - - import java.io.File; - def getTempPath(): File = { - val tempdir = { - val tempdir1 = System.getProperty("java.io.tmpdir"); - if (tempdir1 == null){ - val tempdir2 = System.getProperty("TEMP"); - if (tempdir2 == null){ - val tempdir3 = System.getProperty("TMP"); - if (tempdir3 == null) - throw new IllegalStateException("No temporary folder defined") - else tempdir3 } - else tempdir2 } - else tempdir1 - }; - val path = new File(tempdir); - if (!path.exists() || !path.isDirectory()) - throw new IllegalStateException("Invalid temporary directory") - else if (!path.canWrite()) - throw new IllegalStateException("Temporary directory not writable") - else path - }; - - def writeTempScalaFile(filename: String, line: String, lineno: Int, definedVars: ListBuffer[Names#Name], importVars: ListBuffer[Pair[Names#Name,Int]]) = { - import java.io.{File, PrintWriter, FileOutputStream}; - val scalaFile = new File(filename); - scalaFile.deleteOnExit(); - if(scalaFile.exists()) // to prevent old lingering files from having results from them reported! - scalaFile.delete(); - - val module = new PrintWriter(new FileOutputStream(scalaFile)); - //todo:"import "+LoadedModules?.getName - //module.println("\n"); - - for(val Pair(ivname,ivlineno) <- importVars.toList) yield - module.println("import line"+ivlineno+"."+ivname+";\n"); - - module.println("object line"+lineno+" {"); - var fullLine = line; - if(definedVars.length == 0) { // input is just an expression - fullLine = " var it = " + line; - definedVars += compiler.encode("it"); } - else fullLine = " " + line; - module.println(fullLine); - module.println("}"); - module.println(); - module.println("object InterpreterLine"+lineno+"Result "); - module.println("{ val result = (line"+lineno+"."+definedVars.toList.reverse.head+"); }"); - // reflection is used later (see above) to get the result value above - - module.flush(); - module.close(); - } - - import compiler.Traverser; - import compiler.Tree; - class DefinedVarsTraverser extends Traverser { - val definedVars = new ListBuffer[Names#Name]; - override def traverse(ast: Tree): unit = - if (!ast.isDef) () - else { - import compiler._; - ast match { - // only the outer level needed, so do not recurse to go deeper - // todo: combine similar cases in one case - case ClassDef(_,name,_,_,_) => definedVars += name - case ModuleDef(_, name,_) => definedVars += name - case ValDef(_, name,_,_) => definedVars += name - case DefDef(_,name,_,_,_,_) => definedVars += name - //todo:case Bind(name,_) => ((name != nme.WILDCARD) && (definedVars.elements forall (name !=))) definedVars += name - - //case Ident(name) => if (name...is defined) definedVars += name; - - //todo: - //case PackageDef(name, _) => throw new InterpIllegalDefException(name.toString()+": package definitions not allowed") - //case AbsTypeDef(_,name,_,_) => throw new InterpIllegalDefException(name.toString()+": absract type definitions not allowed") - //case AliasTypeDef(_,name,_,_) => throw new InterpIllegalDefException(name.toString()+": alias type definitions not allowed") - //case LabelDef(name,_,_) => throw new InterpIllegalDefException(name.toString()+": label definitions not allowed") - case _ => throw new InterpIllegalDefException("Unsupported interpreter definition. Contact Scala developers for adding interpreter support for it.")// () - } - } - } - case class InterpIllegalDefException(msg: String) extends RuntimeException(msg); - -// class ListTraverser extends Traverser { -// def traverse(trees: List[Tree]): Unit = -// trees foreach traverse; -// } -// -// class ListDefinedVarsTraverser extends DefinedVarsTraverser with ListTraverser; - - class ImportVarsTraverser(definedVars: ListBuffer[Names#Name]) extends Traverser { - val importVars = new ListBuffer[Pair[Names#Name,Int]]; - var curAST = 0; - import compiler.Ident; - override def traverse(ast: Tree): unit = ast match { - case Ident(name) => { - var lastPrevDefsIdx = -1; - //reporter.info(null,"name="+name,true); - for(val Pair(lineno,defs) <- prevDefines.toList) yield { - //reporter.info(null,"line#="+lineno+", defs="+defs,true); - if (defs.indexOf(name) != -1) lastPrevDefsIdx = lineno - } - val foundInPrevDefines = (lastPrevDefsIdx != -1); - //reporter.info(null,"lastPrevDefsIdx="+lastPrevDefsIdx,true); - if(foundInPrevDefines) { - val firstCurDefIdx = definedVars.indexOf(name); - val foundInDefinedVars = (firstCurDefIdx != -1); - if((!foundInDefinedVars || - (foundInDefinedVars && (firstCurDefIdx > curAST))) - && (importVars.indexOf(Pair(name,lastPrevDefsIdx)) == -1)) - // to prevent duplicate imports (todo: use find instead of indexOf?) - importVars += Pair(name,lastPrevDefsIdx); - } - } - case _ => { - // using case x, instead of case _, we can have: reporter.info(null,"x="+x,true); - super.traverse(ast) - } - } - override def traverseTrees(asts: List[Tree]): unit = - asts foreach { curAST = curAST+1; traverse; } - } - //todo: unit-test cases -} diff --git a/sources/scala/tools/nsc/Main.scala b/sources/scala/tools/nsc/Main.scala deleted file mode 100644 index 58b352db61..0000000000 --- a/sources/scala/tools/nsc/Main.scala +++ /dev/null @@ -1,71 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -import scala.tools.nsc.util.{Position}; -import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}; - -/** The main class for NSC, a compiler for the programming - * language Scala. - */ -object Main extends Object with EvalLoop { - - val PRODUCT: String = - System.getProperty("scala.product", "scalac"); - val VERSION: String = - System.getProperty("scala.version", "unknown version"); - val versionMsg = PRODUCT + " " + VERSION + " -- (c) 2002-05 LAMP/EPFL"; - val prompt = "\nnsc> "; - - private var reporter: ConsoleReporter = _; - - def error(msg: String): unit = - reporter.error(new Position(PRODUCT), - msg + "\n " + PRODUCT + " -help gives more information"); - - def errors() = reporter.errors; - - def resident(compiler: Global): unit = { - loop(line => { - val args = List.fromString(line, ' '); - val command = new CompilerCommand(args, error, true); - (new compiler.Run) compile command.files - }) - } - - def process(args: Array[String]): unit = { - reporter = new ConsoleReporter(); - val command = new CompilerCommand(List.fromArray(args), error, false); - reporter.prompt = command.settings.prompt.value; - if (command.settings.version.value) - reporter.info(null, versionMsg, true) - else if (command.settings.help.value) - reporter.info(null, command.usageMsg, true) - else { - try { - val compiler = new Global(command.settings, reporter); - if (command.settings.resident.value) - resident(compiler); - else if (command.files.isEmpty) - reporter.info(null, command.usageMsg, true) - else - (new compiler.Run) compile command.files; - } catch { - case ex @ FatalError(msg) => - if (command.settings.debug.value) - ex.printStackTrace(); - reporter.error(null, "fatal error: " + msg); - } - reporter.printSummary() - } - } - - def main(args: Array[String]): unit = { - process(args); - System.exit(if (reporter.errors > 0) 1 else 0); - } - -} diff --git a/sources/scala/tools/nsc/MainInterpreter.scala b/sources/scala/tools/nsc/MainInterpreter.scala deleted file mode 100644 index b1ea38e065..0000000000 --- a/sources/scala/tools/nsc/MainInterpreter.scala +++ /dev/null @@ -1,74 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author emir - */ -// $Id$ -package scala.tools.nsc; - -import java.io._; -import scala.tools.nsc.util.{Position}; -import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}; - -/** The main class for the new scala interpreter. - */ -object MainInterpreter extends Object with EvalLoop { - // lots of stuff duplicated from Main - val PRODUCT: String = - System.getProperty("scala.product", "scalaint"); - val VERSION: String = - System.getProperty("scala.version", "unknown version"); - val versionMsg = PRODUCT + " " + VERSION + " -- (c) 2002-05 LAMP/EPFL"; - val prompt = "\nnsc> "; - - private var reporter: ConsoleReporter = _; - - def error(msg: String): unit = - reporter.error(new Position(PRODUCT), - msg + "\n " + PRODUCT + " -help gives more information"); - - def errors() = reporter.errors; - - def interpret(gCompiler: Global): unit = { - val interpreter = new Interpreter { - val compiler: gCompiler.type = gCompiler - }; - loop(line => try { - interpreter.interpret(line.trim(), reporter) - } catch { - case e: Exception => { - reporter.info(null,e.getMessage(),true); - //e.printStackTrace(); - } - } - ) - } - - def process(args: Array[String]): unit = { - reporter = new ConsoleReporter(); - val command = new CompilerCommand(List.fromArray(args), error, false); - reporter.prompt = (command.settings.prompt.value); - if (command.settings.version.value) - reporter.info(null, versionMsg, true) - else if (command.settings.help.value) // 2do replace with InterpCommand - reporter.info(null, command.usageMsg, true) - - else { - try { - val compiler = new Global(command.settings, reporter); - interpret(compiler); - } catch { - case ex @ FatalError(msg) => - if (command.settings.debug.value) - ex.printStackTrace(); - reporter.error(null, "fatal error: " + msg); - } - reporter.printSummary() - } - } - - def main(args: Array[String]): unit = { - process(args); - System.exit(if (reporter.errors > 0) 1 else 0); - } - -} diff --git a/sources/scala/tools/nsc/MainTokenMetric.scala b/sources/scala/tools/nsc/MainTokenMetric.scala deleted file mode 100644 index df05b627e0..0000000000 --- a/sources/scala/tools/nsc/MainTokenMetric.scala +++ /dev/null @@ -1,61 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -import java.io._; -import scala.tools.nsc.reporters.{Reporter, ConsoleReporter}; - -/** The main class for NSC, a compiler for the programming - * language Scala. - */ -object MainTokenMetric { - - private var reporter: ConsoleReporter = _; - - def tokenMetric(compiler: Global, fnames: List[String]): unit = { - import compiler.CompilationUnit; - import compiler.syntaxAnalyzer.Scanner; - import ast.parser.Tokens.EOF; - var totale = 0; - for (val source <- fnames) { - val s = new Scanner(new CompilationUnit(compiler.getSourceFile(source))); - var i = 0; - while(s.token != EOF) { - i = i + 1; - s.nextToken() - } - var j = 0 ; while(j + Math.log(i)/ Math.log(10) < 7) { - j = j+1; - Console.print(' '); - } - Console.print(i.toString()); - Console.print(" "); - Console.println(source.toString()); - totale = totale + i; - } - Console.println(totale.toString()+" total"); - } - - def process(args: Array[String]): unit = { - val command = new CompilerCommand(List.fromArray(args), error, false); - reporter = new ConsoleReporter(); - try { - val compiler = new Global(command.settings, reporter); - tokenMetric(compiler, command.files); - } catch { - case ex @ FatalError(msg) => - if (command.settings.debug.value) - ex.printStackTrace(); - reporter.error(null, "fatal error: " + msg); - } - } - - def main(args: Array[String]): unit = { - process(args); - System.exit(if (reporter.errors > 0) 1 else 0); - } - -} diff --git a/sources/scala/tools/nsc/NoPhase.scala b/sources/scala/tools/nsc/NoPhase.scala deleted file mode 100644 index 342b022842..0000000000 --- a/sources/scala/tools/nsc/NoPhase.scala +++ /dev/null @@ -1,11 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -object NoPhase extends Phase(null) { - def name = ""; - def run: unit = throw new Error("NoPhase.run"); -} diff --git a/sources/scala/tools/nsc/Phase.scala b/sources/scala/tools/nsc/Phase.scala deleted file mode 100644 index 4ca3aa2e9c..0000000000 --- a/sources/scala/tools/nsc/Phase.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -import symtab.Flags; - -abstract class Phase(val prev: Phase) { - - type Id = int; - - val id: Id = if (prev == null) 0 else prev.id + 1; - - def newFlags: long = 0l; - private var fmask: long = - if (prev == null) Flags.InitialFlags else prev.flagMask | newFlags; - def flagMask: long = fmask; - - private var nx: Phase = this; - if (prev != null) prev.nx = this; - - def next: Phase = nx; - - def name: String; - def description: String = name; - def erasedTypes: boolean = false; - def flatClasses: boolean = false; - def run: unit; - - override def toString() = name; -} - - diff --git a/sources/scala/tools/nsc/Settings.scala b/sources/scala/tools/nsc/Settings.scala deleted file mode 100644 index a7a5dfe73c..0000000000 --- a/sources/scala/tools/nsc/Settings.scala +++ /dev/null @@ -1,166 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -class Settings(error: String => unit) { - - private var allsettings: List[Setting] = List(); - - val debuginfo = BooleanSetting("-g", "Generate debugging info"); - val nowarnings = BooleanSetting("-nowarn", "Generate no warnings"); - val noassertions = BooleanSetting("-noassert", "Generate no assertions and assumptions"); - val verbose = BooleanSetting("-verbose", "Output messages about what the compiler is doing"); - val classpath = StringSetting ("-classpath", "path", "Specify where to find user class files", - System.getProperty("scala.class.path", - System.getProperty("java.class.path", "."))); - val sourcepath = StringSetting ("-sourcepath", "path", "Specify where to find input source files", - System.getProperty("scala.source.path", - System.getProperty("java.source.path", "."))); - val bootclasspath = StringSetting ("-bootclasspath", "path", "Override location of bootstrap class files", - System.getProperty("sun.boot.class.path", "")); - val extdirs = StringSetting ("-extdirs", "dirs", "Override location of installed extensions", - System.getProperty("java.ext.dirs", "")); - val outdir = StringSetting ("-d", "directory", "Specify where to place generated class files", ""); - val encoding = StringSetting ("-encoding", "encoding", "Specify character encoding used by source files", "ISO-8859-1"); - val separate = ChoiceSetting ("-separate", "Read symbol files for separate compilation", List("yes","no"), "default"); - val target = ChoiceSetting ("-target", "Specify which backend to use", List("jvm", "msil"), "jvm"); - val debug = BooleanSetting("-debug", "Output debugging messages"); - val statistics = BooleanSetting("-statistics", "Print compiler statistics"); - val explaintypes = BooleanSetting("-explaintypes", "Explain type errors in more detail"); - val resident = BooleanSetting("-resident", "Compiler stays resident, files to compile are read from standard input"); - val uniqid = BooleanSetting("-uniqid", "Print identifiers with unique names (debugging option)"); - val printtypes = BooleanSetting("-printtypes", "Print tree types (debugging option)"); - val prompt = BooleanSetting("-prompt", "Display a prompt after each error (debugging option)"); - val noimports = BooleanSetting("-noimports", "Compile without any implicit imports"); - val nopredefs = BooleanSetting("-nopredefs", "Compile without any implicit predefined values"); - val skip = PhasesSetting ("-skip", "Skip"); - val check = PhasesSetting ("-check", "Check the tree at start of"); - val print = PhasesSetting ("-print", "Print out program after"); - val printer = ChoiceSetting ("-printer", "Printer to use", List("text", "html"), "text"); - val printfile = StringSetting ("-printfile", "file", "Specify file in which to print trees", "-"); - val graph = PhasesSetting ("-graph", "Graph the program after"); - val browse = PhasesSetting ("-browse", "Browse the abstract syntax tree after"); - val stop = PhasesSetting ("-stop", "Stop after phase"); - val log = PhasesSetting ("-log", "Log operations in"); - val version = BooleanSetting("-version", "Print product version and exit"); - val help = BooleanSetting("-help", "Print a synopsis of standard options"); - - val Xshowcls = StringSetting ("-Xshowcls", "class", "Show class info", ""); - val Xshowobj = StringSetting ("-Xshowobj", "object", "Show object info", ""); - val Xshowicode = BooleanSetting("-Xshowicode", "Print the generated ICode"); - val Xgadt = BooleanSetting("-Xgadt", "enable gadt for classes"); - - /** A list of all settings */ - def allSettings: List[Setting] = allsettings.reverse; - - /** A base class for settings of all types. - * Subclasses each define a `value' field of the appropriate type. - */ - abstract class Setting(name: String, descr: String) { - - /** If first arg defines this setting, consume it as well as all following - * args needed to define the setting. If this can be done without - * error, set value field and return suffix of args else - * issue error message and return empty. - * If first arg does not define this setting return args unchanged. - */ - def tryToSet(args: List[String]): List[String]; - - /** The syntax defining this setting in a help string */ - def helpSyntax: String = name; - - /** A description of the purpose of this setting in a help string */ - def helpDescription = descr; - - // initialization - allsettings = this :: allsettings; - } - - /** A setting represented by a boolean flag (false, unless set) */ - case class BooleanSetting(name: String, descr: String) - extends Setting(name, descr) { - var value: boolean = false; - - def tryToSet(args: List[String]): List[String] = args match { - case n :: rest if (n == name) => value = true; rest - case _ => args - } - } - - /** A setting represented by a string, (`default' unless set) */ - case class StringSetting(name: String, arg: String, descr: String, default: String) - extends Setting(name, descr) { - var value: String = default; - - def tryToSet(args: List[String]): List[String] = args match { - case n :: rest if (n == name) => - if (rest.isEmpty) { - error("missing argument"); - List() - } else { - value = rest.head; - rest.tail - } - case _ => args - } - - override def helpSyntax = name + " <" + arg + ">"; - } - - /** A setting represented by a string in a given set of `choices', - * (`default' unless set) - */ - case class ChoiceSetting(name: String, descr: String, choices: List[String], default: String) - extends Setting(name, descr + choices.mkString(" (", ",", ")")) { - var value: String = default; - - private def argument: String = name.substring(1); - - def tryToSet(args: List[String]): List[String] = args match { - case n :: rest if (n startsWith (name + ":")) => - val choice = n.substring(name.length() + 1); - if (!(choices contains choice)) { - error( - if (choice == "") "missing " + argument - else "unknown " + argument + " '" + choice + "'"); - List() - } else { - value = choice; - rest - } - case _ => args - } - - override def helpSyntax = name + ":<" + argument + ">"; - } - - /** A setting represented by a list of strings which should be prefixes of - * phase names. This is not checked here, however. - * (the empty list, unless set) - */ - case class PhasesSetting(name: String, descr: String) - extends Setting(name, descr + " (see below)") { - var value: List[String] = List(); - - def tryToSet(args: List[String]): List[String] = args match { - case n :: rest if (n startsWith (name + ":")) => - val phase = n.substring(name.length() + 1); - if (phase == "") { - error("missing phase"); - List() - } else { - value = value ::: List(phase); - rest - } - case _ => args - } - - override def helpSyntax = name + ":"; - - def contains(phasename: String): boolean = - value exists (str => phasename startsWith str) - } -} diff --git a/sources/scala/tools/nsc/SubComponent.scala b/sources/scala/tools/nsc/SubComponent.scala deleted file mode 100644 index 556b6538ad..0000000000 --- a/sources/scala/tools/nsc/SubComponent.scala +++ /dev/null @@ -1,29 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc; - -/** An nsc sub-component. - */ -abstract class SubComponent { - - /** The global environment; overridden by instantiation in Global. */ - val global: Global; - - /** The name of the phase */ - val phaseName: String; - - /** New flags defined by the phase which are not valid before */ - def phaseNewFlags: long = 0; - - /** The phase factory */ - def newPhase(prev: Phase): Phase; - - /** A standard phase template */ - abstract class StdPhase(prev: Phase) extends global.GlobalPhase(prev) { - def name = phaseName; - override def newFlags = phaseNewFlags; - } -} diff --git a/sources/scala/tools/nsc/ant/NSC.scala b/sources/scala/tools/nsc/ant/NSC.scala deleted file mode 100644 index 9010a92bf9..0000000000 --- a/sources/scala/tools/nsc/ant/NSC.scala +++ /dev/null @@ -1,645 +0,0 @@ -/* __ ______________ *\ -** / |/ / ____/ ____/ ** -** / | | /___ / /___ ** -** /_/|__/_____/_____/ Copyright 2005-2006 LAMP/EPFL ** -\* */ - -// $Id$ - - -package scala.tools.nsc.ant { - - import java.io.File; - import java.net.URL; - import java.net.URLClassLoader; - import java.util.ArrayList; - import java.util.Vector; - - import org.apache.tools.ant.AntClassLoader; - import org.apache.tools.ant.BuildException; - import org.apache.tools.ant.DirectoryScanner; - import org.apache.tools.ant.Project; - import org.apache.tools.ant.taskdefs.MatchingTask; - import org.apache.tools.ant.types.Path; - import org.apache.tools.ant.util.FileUtils; - import org.apache.tools.ant.util.GlobPatternMapper; - import org.apache.tools.ant.util.SourceFileScanner; - import org.apache.tools.ant.types.EnumeratedAttribute; - import org.apache.tools.ant.types.Reference; - - import scala.tools.nsc.reporters.{Reporter,ConsoleReporter}; - - /** - * An Ant task to compile with the new Scala compiler (NSC). - * This task can take the following parameters as attributes:
    - *
  • srcdir (mandatory),
  • - *
  • srcref,
  • - *
  • destdir,
  • - *
  • classpath,
  • - *
  • classpathref,
  • - *
  • sourcepath,
  • - *
  • sourcepathref,
  • - *
  • bootclasspath,
  • - *
  • bootclasspathref,
  • - *
  • extdirs,
  • - *
  • extdirsref,
  • - *
  • encoding,
  • - *
  • verbose,
  • - *
  • debug,
  • - *
  • usepredefs,
  • - *
  • useimports,
  • - *
  • force,
  • - *
  • stop,
  • - *
  • skip,
  • - *
  • check,
  • - *
  • print,
  • - *
  • showicode,
  • - *
  • log,
  • - *
  • debuginfo.
  • - *
- * It also takes the following parameters as nested elements:
    - *
  • src (for srcdir),
  • - *
  • classpath,
  • - *
  • sourcepath,
  • - *
  • bootclasspath,
  • - *
  • extdirs.
  • - *
- * - * @author Gilles Dubochet - */ - class NSC extends MatchingTask { - - private val SCALA_PRODUCT: String = - System.getProperty("scala.product", "Scalac Ant compiler"); - private val SCALA_VERSION: String = - System.getProperty("scala.version", "Unknown version"); - - /** The unique Ant file utilities instance to use in this task. */ - private val fileUtils = FileUtils.newFileUtils(); - - // ################################################################### - // ##### Ant Properties ##### - // ################################################################### - - abstract class PermissibleValue { - val values: List[String]; - def isPermissible(value: String): Boolean = ( - (value == "") || - values.exists(v: String => v startsWith value) - ) - } - - /** Defines valid values for the logging property. */ - object LoggingLevel extends PermissibleValue { - val values = List("none", "verbose", "debug"); - } - - /** Defines valid values for properties that refer to compiler phases. */ - object CompilerPhase extends PermissibleValue { - val values = List( - "namer", "typer", "pickler", "uncurry", "tailcalls", - "transmatch", "explicitouter", "erasure", "lambdalift", - "flatten", "constructors", "mixin", "icode", "jvm", "terminal"); - } - - /** The directories that contain source files to compile. */ - private var origin: Option[Path] = None; - /** The directory to put the compiled files in. */ - private var destination: Option[File] = None; - - /** The class path to use for this compilation. */ - private var classpath: Option[Path] = None; - /** The source path to use for this compilation. */ - private var sourcepath: Option[Path] = None; - /** The boot class path to use for this compilation. */ - private var bootclasspath: Option[Path] = None; - /** The external extensions path to use for this compilation. */ - private var extpath: Option[Path] = None; - - /** The text encoding of the files to compile. */ - private var encoding: Option[String] = None; - - /** How much logging output to print. Either none (default), verbose or debug. */ - private var logging: Option[String] = None; - /** Whether to use implicit predefined values or not. */ - private var usepredefs: Boolean = true; - /** Whether to implicitly import or not. */ - private var useimports: Boolean = true; - /** Whether to force compilation of all files or not. */ - private var force: Boolean = false; - /** After which phase the compilation should stop. */ - private var stop: Option[String] = None; - /** Which compilation phases should be skipped during compilation. */ - private var skip: List[String] = Nil; - /** Which compilation phases should be logged during compilation. */ - private var logPhase: List[String] = Nil; - /** Which compilation phases results should be checked for consistency. */ - private var check: List[String] = Nil; - /** Which compilation phases results should be printed-out. */ - private var print: List[String] = Nil; - /** Print ICode files along with class files (debug option). */ - private var showICode: Boolean = false; - - /** Instruct the compiler to generate debugging information (pass '-g') */ - private var debugInfo: Boolean = false; - - - // ################################################################### - // ##### Properties setters ##### - // ################################################################### - - /** - * Sets the srcdir attribute. Used by Ant. - * @param input The value of origin. - */ - def setSrcdir(input: Path) = - if (origin.isEmpty) - origin = Some(input); - else - origin.get.append(input); - - /** - * Sets the origin as a nested src Ant parameter. - * @return An origin path to be configured. - */ - def createSrc(): Path = { - if (origin.isEmpty) { - origin = Some(new Path(getProject())) - } - origin.get.createPath() - } - - /** - * Sets the origin as an external reference Ant parameter. - * @param input A reference to an origin path. - */ - def setSrcref(input: Reference) = - createSrc().setRefid(input); - - /** - * Gets the value of the origin attribute in a Scala-friendly form. - * @returns The origin path as a list of files. - */ - private def getOrigin: List[File] = - if (origin.isEmpty) - throw new ArrayIndexOutOfBoundsException("Member 'origin' is empty."); - else - List.fromArray(origin.get.list()).map(nameToFile("src")); - - /** - * Sets the destdir attribute. Used by Ant. - * @param input The value of destination. - */ - def setDestdir(input: File) = - destination = Some(input); - - /** - * Gets the value of the destination attribute in a Scala-friendly form. - * @returns The destination as a file. - */ - private def getDestination: File = - if (destination.isEmpty) - throw new ArrayIndexOutOfBoundsException("Member 'destination' is empty."); - else - testReadableFile("destdir")(getProject().resolveFile(destination.get.toString())); - - /** - * Sets the classpath attribute. Used by Ant. - * @param input The value of classpath. - */ - def setClasspath(input: Path) = - if (classpath.isEmpty) - classpath = Some(input); - else - classpath.get.append(input); - - /** - * Sets the classpath as a nested classpath Ant parameter. - * @return A class path to be configured. - */ - def createClasspath(): Path = { - if (classpath.isEmpty) { - classpath = Some(new Path(getProject())) - } - classpath.get.createPath() - } - - /** - * Sets the classpath as an external reference Ant parameter. - * @param input A reference to a class path. - */ - def setClasspathref(input: Reference) = - createClasspath().setRefid(input); - - /** - * Gets the value of the classpath attribute in a Scala-friendly form. - * @returns The class path as a list of files. - */ - private def getClasspath: List[File] = - if (classpath.isEmpty) - throw new ArrayIndexOutOfBoundsException("Member 'classpath' is empty."); - else - List.fromArray(classpath.get.list()).map(nameToFile("classpath")); - - /** - * Sets the sourcepath attribute. Used by Ant. - * @param input The value of sourcepath. - */ - def setSourcepath(input: Path) = - if (sourcepath.isEmpty) - sourcepath = Some(input); - else - sourcepath.get.append(input); - - /** - * Sets the sourcepath as a nested sourcepath Ant parameter. - * @return A source path to be configured. - */ - def createSourcepath(): Path = { - if (sourcepath.isEmpty) { - sourcepath = Some(new Path(getProject())) - } - sourcepath.get.createPath() - } - - /** - * Sets the sourcepath as an external reference Ant parameter. - * @param input A reference to a source path. - */ - def setSourcepathref(input: Reference) = - createSourcepath().setRefid(input); - - /** - * Gets the value of the sourcepath attribute in a Scala-friendly form. - * @returns The source path as a list of files. - */ - private def getSourcepath: List[File] = - if (sourcepath.isEmpty) - throw new ArrayIndexOutOfBoundsException("Member 'sourcepath' is empty."); - else - List.fromArray(sourcepath.get.list()).map(nameToFile("sourcepath")); - - /** - * Sets the boot classpath attribute. Used by Ant. - * @param input The value of bootclasspath. - */ - def setBootclasspath(input: Path) = - if (bootclasspath.isEmpty) - bootclasspath = Some(input); - else - bootclasspath.get.append(input); - - /** - * Sets the bootclasspath as a nested sourcepath Ant parameter. - * @return A source path to be configured. - */ - def createBootclasspath(): Path = { - if (bootclasspath.isEmpty) { - bootclasspath = Some(new Path(getProject())) - } - bootclasspath.get.createPath() - } - - /** - * Sets the bootclasspath as an external reference Ant parameter. - * @param input A reference to a source path. - */ - def setBootclasspathref(input: Reference) = - createBootclasspath().setRefid(input); - - /** - * Gets the value of the bootclasspath attribute in a Scala-friendly form. - * @returns The boot class path as a list of files. - */ - private def getBootclasspath: List[File] = - if (bootclasspath.isEmpty) - throw new ArrayIndexOutOfBoundsException("Member 'bootclasspath' is empty."); - else - List.fromArray(bootclasspath.get.list()).map(nameToFile("bootclasspath")); - - /** - * Sets the external extensions path attribute. Used by Ant. - * @param input The value of extpath. - */ - def setExtdirs(input: Path) = - if (extpath.isEmpty) - extpath = Some(input); - else - extpath.get.append(input); - - /** - * Sets the extpath as a nested sourcepath Ant parameter. - * @return An extensions path to be configured. - */ - def createExtdirs(): Path = { - if (extpath.isEmpty) { - extpath = Some(new Path(getProject())) - } - extpath.get.createPath() - } - - /** - * Sets the extpath as an external reference Ant parameter. - * @param input A reference to an extensions path. - */ - def setExtdirsref(input: Reference) = - createExtdirs().setRefid(input); - - /** - * Gets the value of the extpath attribute in a Scala-friendly form. - * @returns The extensions path as a list of files. - */ - private def getExtpath: List[File] = - if (extpath.isEmpty) - throw new ArrayIndexOutOfBoundsException("Member 'extdirs' is empty."); - else - List.fromArray(extpath.get.list()).map(nameToFile("extdirs")); - - /** - * Sets the encoding attribute. Used by Ant. - * @param input The value of encoding. - */ - def setEncoding(input: String): Unit = - encoding = Some(input); - - /** - * Sets the logging level attribute. Used by Ant. - * @param input The value for logging. - */ - def setLogging(input: String) = - if (LoggingLevel.isPermissible(input)) - logging = Some(input); - else - error("Logging level '" + input + "' does not exist."); - - /** - * Sets the use predefs attribute. Used by Ant. - * @param input The value for usepredefs. - */ - def setUsepredefs(input: Boolean): Unit = - usepredefs = input; - - /** - * Sets the use imports attribute. Used by Ant. - * @param input The value for useimport. - */ - def setUseimports(input: Boolean): Unit = - useimports = input; - - /** - * Sets the force attribute. Used by Ant. - * @param input The value for force. - */ - def setForce(input: Boolean): Unit = - force = input; - - /** - * Sets the force attribute. Used by Ant. - * @param input The value for force. - */ - def setStop(input: String) = - if (CompilerPhase.isPermissible(input)) { - if (input != "") - stop = Some(input); - } - else - error("Phase '" + input + "' in stop does not exist."); - - /** - * Sets the force attribute. Used by Ant. - * @param input The value for force. - */ - def setSkip(input: String) = { - skip = List.fromArray(input.split(",")).flatMap(s: String => { - val st = s.trim(); - if (CompilerPhase.isPermissible(st)) (if (input != "") List(st) else Nil) - else {error("Phase '" + st + "' in skip does not exist."); Nil} - }); - } - - /** - * Sets the log attribute. Used by Ant. - * @param input The value for logPhase. - */ - def setLog(input: String) = { - logPhase = List.fromArray(input.split(",")).flatMap(s: String => { - val st = s.trim(); - if (CompilerPhase.isPermissible(st)) (if (input != "") List(st) else Nil) - else {error("Phase " + st + " in log does not exist."); Nil} - }); - } - - /** - * Sets the check attribute. Used by Ant. - * @param input The value for check. - */ - def setCheck(input: String) = { - check = List.fromArray(input.split(",")).flatMap(s: String => { - val st = s.trim(); - if (CompilerPhase.isPermissible(st)) (if (input != "") List(st) else Nil) - else {error("Phase " + st + " in check does not exist."); Nil} - }); - } - - /** - * Sets the print attribute. Used by Ant. - * @param input The value for print. - */ - def setPrint(input: String) = { - print = List.fromArray(input.split(",")).flatMap(s: String => { - val st = s.trim(); - if (CompilerPhase.isPermissible(st)) (if (input != "") List(st) else Nil) - else {error("Phase " + st + " in print does not exist."); Nil} - }); - } - - def setShowicode(input: Boolean): Unit = - showICode = input; - - /** - * Set the debug info attribute. - */ - def setDebuginfo(input: Boolean): Unit = - debugInfo = input; - - // ################################################################### - // ##### Compilation and support methods ##### - // ################################################################### - - override protected def getDirectoryScanner (baseDir: java.io.File) = - super.getDirectoryScanner(baseDir); - - /** - * Creates a file from a given string. - * @param test A method to test whether the file is valid. - * @param name The path of the file as a string. - * @return The file corresponding to the provided name. - */ - private def nameToFile(test: File=>File)(name: String): File = - test(getProject().resolveFile(name)); - - /** - * Creates a file from a given string. - * @param test A method to test whether the file is valid. - * @param name The path of the file as a string. - * @return The file corresponding to the provided name. - */ - private def nameToFile(test: File=>File, origin: File)(name: String): File = - test(fileUtils.resolveFile(origin, name)); - - /** - * Creates a file from a given string and tests its validity using the testReadableFile method. - * @param pathName The name of the path in which the file is. - * @param name The path of the file as a string. - * @return The file corresponding to the provided name. - */ - private def nameToFile(pathName: String, origin: File)(name: String): File = { - nameToFile((f: File) => testReadableFile(pathName)(f), origin)(name); - } - - /** - * Creates a file from a given string and tests its validity using the testReadableFile method. - * @param pathName The name of the path in which the file is. - * @param name The path of the file as a string. - * @return The file corresponding to the provided name. - */ - private def nameToFile(pathName: String)(name: String): File = { - nameToFile((f: File) => testReadableFile(pathName)(f))(name); - } - - /** - * Tests whether a file is readable (if it does not exist, it is not readable. - * If it is not readable, prints a warning message. - * @param pathName The name of the path in which the file is (used for printing-out warning message). - * @param file The file to test. - * @return The same file as provided. - */ - private def testReadableFile(pathName: String)(file: File): File = { - if (!file.exists()) - log("Element '" + file.toString() + "' in " + pathName + " does not exist.", Project.MSG_WARN); - file - } - - private def asString(path: List[File]): String = { - path.map(file: File => asString(file)).mkString("", File.pathSeparator, "") - } - - private def asString(file: File): String = - file.getAbsolutePath(); - - /** - * Generates a build error. Error location will be the current task in the ant file. - * @param message The message of the error. This message should be end-user readable. - * @throws org.apache.tools.ant.BuildException The build error exception. Will be thrown in all conditions. - */ - private def error(message: String) = { - throw new BuildException(message, getLocation()); - } - - /** - * Performs the compilation. - */ - override def execute() = { - - // Tests if all mandatory attributes are set and valid. - if (origin.isEmpty) error("Attribute 'srcdir' is not set."); - if (getOrigin.isEmpty) error("Attribute 'srcdir' is not set."); - if (!destination.isEmpty && !destination.get.isDirectory()) - error("Attribute 'destdir' does not refer to an existing directory."); - if (destination.isEmpty) { - destination = Some(getOrigin.head); - } - - val mapper = new GlobPatternMapper(); - mapper.setTo("*.class"); - mapper.setFrom("*.scala"); - - // Scans source directories to build up a compile lists. - // If force is false, only files were the .class file in destination is older than - // the .scala file will be used. - val sourceFiles: List[File] = - for (val originDir <- getOrigin; - val originFile <- { - var includedFiles = getDirectoryScanner(originDir).getIncludedFiles(); - if (!force) { - includedFiles = new SourceFileScanner(this) - .restrict(includedFiles, originDir, destination.get, mapper) - } - (List.fromArray(includedFiles)).map(nameToFile("srcdir", originDir)) - } - ) yield { - log(originFile.toString(), Project.MSG_VERBOSE); - originFile - } - - if (sourceFiles.length == 0) - log("No files selected for compilation") - else - log("Compiling " + sourceFiles.length + " source file" - + (if (sourceFiles.length > 1) "s" else "") - + (" to " + getDestination.toString())); - - System.setProperty("scala.library.class.path", ""); - System.setProperty("scala.library.source.path", ""); - - // Builds-up the compilation settings for Scalac with the existing Ant parameters. - val reporter = new ConsoleReporter(); - val settings = new Settings(error); - settings.outdir.value = asString(destination.get); - if (!classpath.isEmpty) settings.classpath.value = asString(getClasspath); - if (!sourcepath.isEmpty) settings.sourcepath.value = asString(getSourcepath) - else if (origin.get.size() > 0) settings.sourcepath.value = origin.get.list()(0); - if (!bootclasspath.isEmpty) settings.bootclasspath.value = asString(getBootclasspath); - if (!extpath.isEmpty) settings.extdirs.value = asString(getExtpath); - if (!encoding.isEmpty) settings.encoding.value = encoding.get; - if (!logging.isEmpty && logging.get == "verbose") { - settings.verbose.value = true; - } - else if (!logging.isEmpty && logging.get == "debug") { - settings.verbose.value = true; - settings.debug.value = true; - } - settings.noimports.value = !useimports; - settings.nopredefs.value = !usepredefs; - if (!stop.isEmpty) settings.stop.value = List(stop.get); - if (!skip.isEmpty) settings.skip.value = skip; - if (!check.isEmpty) settings.check.value = check; - if (!print.isEmpty) settings.print.value = print; - settings.Xshowicode.value = showICode; - settings.debuginfo.value = debugInfo; - if (!logPhase.isEmpty) settings.log.value = logPhase; - - // Sets path properties to prevent ClassPath from being corrupted. - // It this isn't done, classpath will contain more than - //System.setProperty("scala.library.class.path", ""); - //System.setProperty("scala.library.source.path", ""); - - // Compiles the actual code - val compiler = new Global(settings, reporter); - try { - (new compiler.Run).compile(sourceFiles.map(f:File=>f.toString())); - if (reporter.errors > 0) - error("Compile failed with " - + reporter.errors + " error" - + (if (reporter.errors > 1) "s" else "") - + "; see the compiler error output for details."); - } - catch { - case exception @ FatalError(msg) => { - exception.printStackTrace(); - if (settings.debug.value) exception.printStackTrace(); - error("Compile failed because of an internal compiler error (" - + msg + "); see the error output for details."); - } - } - if (reporter.warnings > 0) - log("Compile suceeded with " - + reporter.errors + " warning" - + (if (reporter.warnings > 1) "s" else "") - + "; see the compiler output for details."); - reporter.printSummary() - } - - } - -} diff --git a/sources/scala/tools/nsc/ast/TreeBrowsers.scala b/sources/scala/tools/nsc/ast/TreeBrowsers.scala deleted file mode 100644 index 9e4821a734..0000000000 --- a/sources/scala/tools/nsc/ast/TreeBrowsers.scala +++ /dev/null @@ -1,631 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.ast; - -import scala.concurrent._; -import symtab.Flags._; - - -import java.lang.Math; -import java.util.HashMap; -import java.io.StringWriter; - -import javax.swing.tree._; -import javax.swing.event.TreeModelListener; -import javax.swing._; - -import java.awt.BorderLayout; -import java.awt.{List => awtList, _}; -import java.awt.event._; - -import scala.text._; - -/** - * Tree browsers can show the AST in a graphical and interactive - * way, useful for debugging and understanding. - */ -abstract class TreeBrowsers { - - val global: Global; - import global._; - import nme.EMPTY; - - /** Pseudo tree class, so that all JTree nodes are treated uniformly */ - case class ProgramTree(units: List[UnitTree]) extends Tree { - override def toString(): String = "Program"; - } - - /** Pseudo tree class, so that all JTree nodes are treated uniformly */ - case class UnitTree(unit: CompilationUnit) extends Tree { - override def toString(): String = unit.toString(); - } - - def create(): SwingBrowser = new SwingBrowser(); - - /** - * Java Swing pretty printer for Scala abstract syntax trees. - */ - class SwingBrowser { - - def browse(units: Iterator[CompilationUnit]): Unit = - browse(units.toList); - - /** print the whole program */ - def browse(units: List[CompilationUnit]): Unit = { - val phase: Phase = globalPhase; - var unitList: List[UnitTree] = Nil; - - - for (val i <- units) - unitList = UnitTree(i) :: unitList; - val tm = new ASTTreeModel(ProgramTree(unitList)); - - val frame = new BrowserFrame(); - frame.setTreeModel(tm); - - val lock = new Lock(); - frame.createFrame(lock); - - // wait for the frame to be closed - lock.acquire; - } - } - - /** Tree model for abstract syntax trees */ - class ASTTreeModel(val program: ProgramTree) extends TreeModel { - var listeners: List[TreeModelListener] = Nil; - - /** Add a listener to this tree */ - def addTreeModelListener(l : TreeModelListener): Unit = listeners = l :: listeners; - - /** Return the index'th child of parent */ - def getChild(parent: Any, index: Int): AnyRef = { - packChildren(parent).drop(index).head; - } - - /** Return the number of children this 'parent' has */ - def getChildCount(parent: Any): Int = - packChildren(parent).length; - - /** Return the index of the given child */ - def getIndexOfChild(parent: Any, child: Any): Int = - packChildren(parent).dropWhile(c => c != child).length; - - /** Return the root node */ - def getRoot(): AnyRef = program; - - /** Test whether the given node is a leaf */ - def isLeaf(node: Any): Boolean = packChildren(node).length == 0; - - def removeTreeModelListener(l: TreeModelListener): Unit = - listeners remove (x => x == l); - - /** we ignore this message for now */ - def valueForPathChanged(path: TreePath, newValue: Any) = (); - - /** - * Return a list of children for the given node. - */ - def packChildren(t: Any): List[AnyRef] = - TreeInfo.children(t.asInstanceOf[Tree]); - } - - - /** - * A window that can host the Tree widget and provide methods for - * displaying information - */ - class BrowserFrame { - val frame = new JFrame("Scala AST"); - val topLeftPane = new JPanel(new BorderLayout()); - val topRightPane = new JPanel(new BorderLayout()); - val bottomPane = new JPanel(new BorderLayout()); - var splitPane: JSplitPane = _; - var treeModel: TreeModel = _; - - val textArea: JTextArea = new JTextArea(20, 50); - val infoPanel = new TextInfoPanel(); - - - /** Create a frame that displays the AST. - * - * @param lock The lock is used in order to stop the compilation thread - * until the user is done with the tree inspection. Swing creates its - * own threads when the frame is packed, and therefore execution - * would continue. However, this is not what we want, as the tree and - * especially symbols/types would change while the window is visible. - */ - def createFrame(lock: Lock): Unit = { - lock.acquire; // keep the lock until the user closes the window - - frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); - - frame.addWindowListener(new WindowAdapter() { - /** Release the lock, so compilation may resume after the window is closed. */ - override def windowClosed(e: WindowEvent): Unit = lock.release; - }); - - val tree = new JTree(treeModel) { - /** Return the string for a tree node. */ - override def convertValueToText(value: Any, sel: Boolean, - exp: Boolean, leaf: Boolean, - row: Int, hasFocus: Boolean) = { - val Pair(cls, name) = TreeInfo.treeName(value.asInstanceOf[Tree]); - if (name != EMPTY) - cls + "[" + name.toString() + "]"; - else - cls; - - } - } - - tree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() { - def valueChanged(e: javax.swing.event.TreeSelectionEvent): Unit = { - textArea.setText(e.getPath().getLastPathComponent().toString()); - infoPanel.update(e.getPath().getLastPathComponent()); - } - }); - - val topSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, topLeftPane, topRightPane); - topSplitPane.setResizeWeight(0.5); - - topLeftPane.add(new JScrollPane(tree), BorderLayout.CENTER); - topRightPane.add(new JScrollPane(infoPanel), BorderLayout.CENTER); - - bottomPane.add(new JScrollPane(textArea), BorderLayout.CENTER); - textArea.setFont(new Font("monospaced", Font.PLAIN, 14)); - textArea.setEditable(false); - - splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topSplitPane, bottomPane); - frame.getContentPane().add(splitPane); - frame.pack(); - frame.setVisible(true); - } - - def setTreeModel(tm: TreeModel): Unit = treeModel = tm; - } - - /** - * Present detailed information about the selected tree node. - */ - class TextInfoPanel extends JTextArea(30, 40) { - - setFont(new Font("monospaced", Font.PLAIN, 12)); - - def update(v: AnyRef): Unit = { - val t: Tree = v.asInstanceOf[Tree]; - val str = new StringBuffer(); - var buf = new StringWriter(); - - t match { - case ProgramTree(_) => (); - case UnitTree(_) => (); - case _ => - str.append("Symbol: ").append(TreeInfo.symbolText(t)); - str.append("\nSymbol info: \n"); - TreeInfo.symbolTypeDoc(t).format(getWidth() / getColumnWidth(), buf); - str.append(buf.toString()); - str.append("\nSymbol tpe: \n"); - if (t.symbol != null) { - buf = new StringWriter(); - TypePrinter.toDocument(t.symbol.tpe).format(getWidth() / getColumnWidth(), buf); - str.append(buf.toString()); - } - str.append("\nSymbol Attributes: \n").append(TreeInfo.symbolAttributes(t)); - str.append("\nType: \n").append(if (t.tpe ne null) t.tpe.toString() else ""); - } - setText(str.toString()); - } - } - - - /** Computes different information about a tree node. It - * is used as central place to do all pattern matching against - * Tree. - */ - object TreeInfo { - - /** Return the case class name and the Name, if the node defines one */ - def treeName(t: Tree): Pair[String, Name] = t match { - case ProgramTree(units) => - Pair("Program", EMPTY); - - case UnitTree(unit) => - Pair("CompilationUnit", unit.toString()); - - case Attributed(attribute, definition) => - Pair("Attributed", EMPTY); - - case DocDef(comment, definition) => - Pair("DocDef", EMPTY); - - case ClassDef(mods, name, tparams, tpt, impl) => - Pair("ClassDef", name); - - case PackageDef(packaged, impl) => - Pair("PackageDef", EMPTY); - - case ModuleDef(mods, name, impl) => - Pair("ModuleDef", name); - - case ValDef(mods, name, tpe, rhs) => - Pair("ValDef", name); - - case DefDef(mods, name, tparams, vparams, tpe, rhs) => - Pair("DefDef", name); - - case AbsTypeDef(mods, name, rhs, lobound) => - Pair("AbsTypeDef", name); - - case AliasTypeDef(mods, name, tparams, rhs) => - Pair("AliasTypeDef", name); - - case Import(expr, selectors) => - Pair("Import", EMPTY); - - case CaseDef(pat, guard, body) => - Pair("CaseDef", EMPTY); - - case Template(parents, body) => - Pair("Template", EMPTY); - - case LabelDef(name, params, rhs) => - Pair("LabelDef", name); - - case Block(stats, expr) => - Pair("Block", EMPTY); - - case Sequence(trees) => - Pair("Sequence", EMPTY); - - case Alternative(trees) => - Pair("Alternative", EMPTY); - - case Bind(name, rhs) => - Pair("Bind", name); - - case Match(selector, cases) => - Pair("Visitor", EMPTY); - - case Function(vparams, body) => - Pair("Function", EMPTY); - - case Assign(lhs, rhs) => - Pair("Assign", EMPTY); - - case If(cond, thenp, elsep) => - Pair("If", EMPTY); - - case Return(expr) => - Pair("Return", EMPTY); - - case Throw(expr) => - Pair("Throw", EMPTY); - - case New(init) => - Pair("New", EMPTY); - - case Typed(expr, tpe) => - Pair("Typed", EMPTY); - - case TypeApply(fun, args) => - Pair("TypeApply", EMPTY); - - case Apply(fun, args) => - Pair("Apply", EMPTY); - - case Super(qualif, mixin) => - Pair("Super", qualif.toString() + ", mixin: " + mixin.toString()); - - case This(qualifier) => - Pair("This", qualifier); - - case Select(qualifier, selector) => - Pair("Select", selector); - - case Ident(name) => - Pair("Ident", name); - - case Literal(value) => - Pair("Literal", EMPTY); - - case TypeTree() => - Pair("TypeTree", EMPTY); - - case SingletonTypeTree(ref) => - Pair("SingletonType", EMPTY); - - case SelectFromTypeTree(qualifier, selector) => - Pair("SelectFromType", selector); - - case CompoundTypeTree(template) => - Pair("CompoundType", EMPTY); - - case AppliedTypeTree(tpe, args) => - Pair("AppliedType", EMPTY); - - case Try(block, catcher, finalizer) => - Pair("Try", EMPTY); - - case EmptyTree => - Pair("Empty", EMPTY); - - case ArrayValue(elemtpt, trees) => - Pair("ArrayValue", EMPTY); - } - - /** Return a list of children for the given tree node */ - def children(t: Tree): List[Tree] = t match { - case ProgramTree(units) => - units; - - case UnitTree(unit) => - List(unit.body); - - case Attributed(attribute, definition) => - List(attribute, definition); - - case DocDef(comment, definition) => - List(definition); - - case ClassDef(mods, name, tparams, tpt, impl) => { - var children: List[Tree] = List(); - children = tparams ::: children; - tpt :: impl :: children - } - - case PackageDef(name, stats) => - stats; - - case ModuleDef(mods, name, impl) => - List(impl); - - case ValDef(mods, name, tpe, rhs) => - List(tpe, rhs); - - case DefDef(mods, name, tparams, vparams, tpe, rhs) => { - var children: List[Tree] = List(); - children = tparams ::: children; - children = List.flatten(vparams) ::: children; - tpe :: rhs :: children - } - - case AbsTypeDef(mods, name, rhs, lobound) => - List(rhs, lobound); - - case AliasTypeDef(mods, name, tparams, rhs) => { - var children: List[Tree] = List(); - children = tparams ::: children; - rhs :: children - } - - case Import(expr, selectors) => { - var children: List[Tree] = List(expr); - children - } - - case CaseDef(pat, guard, body) => - List(pat, guard, body); - - case Template(parents, body) => - parents ::: body; - - case LabelDef(name, params, rhs) => - params ::: List(rhs); - - case Block(stats, expr) => - stats ::: List(expr); - - case Sequence(trees) => - trees; - - case Alternative(trees) => - trees; - - case Bind(name, rhs) => - List(rhs); - - case Match(selector, cases) => - selector :: cases; - - case Function(vparams, body) => - vparams ::: List(body); - - case Assign(lhs, rhs) => - List(lhs, rhs); - - case If(cond, thenp, elsep) => - List(cond, thenp, elsep); - - case Return(expr) => - List(expr); - - case Throw(expr) => - List(expr); - - case New(init) => - List(init); - - case Typed(expr, tpe) => - List(expr, tpe); - - case TypeApply(fun, args) => - List(fun) ::: args; - - case Apply(fun, args) => - List(fun) ::: args; - - case Super(qualif, mixin) => - Nil; - - case This(qualif) => - Nil - - case Select(qualif, selector) => - List(qualif); - - case Ident(name) => - Nil; - - case Literal(value) => - Nil; - - case TypeTree() => - Nil; - - case SingletonTypeTree(ref) => - List(ref); - - case SelectFromTypeTree(qualif, selector) => - List(qualif); - - case CompoundTypeTree(templ) => - List(templ); - - case AppliedTypeTree(tpe, args) => - tpe :: args; - - case Try(block, catches, finalizer) => - block :: catches ::: List(finalizer); - - case ArrayValue(elemtpt, elems) => - elemtpt :: elems; - - case EmptyTree => - Nil; - } - - /** Return a textual representation of this t's symbol */ - def symbolText(t: Tree): String = { - var prefix = ""; - - if (t.hasSymbol) - prefix = "[has] "; - if (t.isDef) - prefix = "[defines] "; - - prefix + t.symbol - } - - /** Return t's symbol type */ - def symbolTypeDoc(t: Tree): Document = { - val s = t.symbol; - if (s != null) - TypePrinter.toDocument(s.info); - else - DocNil; - } - - /** Return a textual representation of (some of) the symbol's - * attributes */ - def symbolAttributes(t: Tree): String = { - val s = t.symbol; - var att = ""; - - if (s != null) { - var str = flagsToString(s.flags); - if (s.hasFlag(STATIC) || s.hasFlag(STATICMEMBER)) - str = str + " isStatic "; - str - } - else ""; - } - } - - object TypePrinter { - - ///////////////// Document pretty printer //////////////// - - implicit def view(n: String): Document = DocText(n); - - def toDocument(sym: Symbol): Document = - toDocument(sym.info); - - def symsToDocument(syms: List[Symbol]): Document = syms match { - case Nil => DocNil; - case s :: Nil => Document.group(toDocument(s)); - case _ => - Document.group( - syms.tail.foldLeft (toDocument(syms.head) :: ", ") ( - (d: Document, s2: Symbol) => toDocument(s2) :: ", " :/: d) ); - } - - def toDocument(ts: List[Type]): Document = ts match { - case Nil => DocNil; - case t :: Nil => Document.group(toDocument(t)); - case _ => - Document.group( - ts.tail.foldLeft (toDocument(ts.head) :: ", ") ( - (d: Document, t2: Type) => toDocument(t2) :: ", " :/: d) ); - } - - def toDocument(t: Type): Document = t match { - case ErrorType => "ErrorType()"; - case WildcardType => "WildcardType()"; - case NoType => "NoType()"; - case NoPrefix => "NoPrefix()"; - case ThisType(s) => "ThisType(" + s.name + ")"; - - case SingleType(pre, sym) => - Document.group( - Document.nest(4, "SingleType(" :/: - toDocument(pre) :: ", " :/: sym.name.toString() :: ")") - ); - - case ConstantType(value) => - "ConstantType(" + value + ")"; - - case TypeRef(pre, sym, args) => - Document.group( - Document.nest(4, "TypeRef(" :/: - toDocument(pre) :: ", " :/: - sym.name.toString() :: ", " :/: - "[ " :: toDocument(args) ::"]" :: ")") - ); - - case TypeBounds(lo, hi) => - Document.group( - Document.nest(4, "TypeBounds(" :/: - toDocument(lo) :: ", " :/: - toDocument(hi) :: ")") - ); - - case RefinedType(parents, defs) => - Document.group( - Document.nest(4, "RefinedType(" :/: - toDocument(parents) :: ")") - ); - - case ClassInfoType(parents, defs, clazz) => - Document.group( - Document.nest(4,"ClassInfoType(" :/: - toDocument(parents) :: ", " :/: - clazz.name.toString() :: ")") - ); - - case MethodType(paramtypes, result) => - Document.group( - Document.nest(4, "MethodType(" :/: - Document.group("(" :/: - toDocument(paramtypes) :/: - "), ") :/: - toDocument(result) :: ")") - ); - - case PolyType(tparams, result) => - Document.group( - Document.nest(4,"PolyType(" :/: - Document.group("(" :/: - symsToDocument(tparams) :/: - "), ") :/: - toDocument(result) :: ")") - ); - - case _ => abort("Unknown case: " + t.toString()); - } - } - -} diff --git a/sources/scala/tools/nsc/ast/TreeGen.scala b/sources/scala/tools/nsc/ast/TreeGen.scala deleted file mode 100644 index 425cf9eac8..0000000000 --- a/sources/scala/tools/nsc/ast/TreeGen.scala +++ /dev/null @@ -1,158 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.ast; - -import scala.tools.nsc.util.Position; -import symtab.Flags._; - -abstract class TreeGen { - - val global: Global; - - import global._; - import definitions._; - import posAssigner.atPos; - - /** Builds a reference to value whose type is given stable prefix. - */ - def mkQualifier(tpe: Type): Tree = tpe match { - case NoPrefix => - EmptyTree - case ThisType(clazz) => - if (clazz.isRoot || clazz.isEmptyPackageClass) EmptyTree else This(clazz) - case SingleType(pre, sym) => - if (sym.isThisSkolem) { - mkQualifier(ThisType(sym.deSkolemize)) - } else { - val qual = mkStableRef(pre, sym); - qual.tpe match { - case MethodType(List(), restpe) => - Apply(qual, List()) setType restpe - case _ => - qual - } - } - case TypeRef(pre, sym, args) => - assert(phase.erasedTypes); - if (sym.isModuleClass && !sym.isRoot) { - val qual = Select(mkQualifier(sym.owner.tpe), sym.sourceModule); - qual.tpe match { - case MethodType(List(), restpe) => - Apply(qual, List()) setType restpe - case _ => - qual - } - } else This(sym) - } - - /** Builds a reference to given symbol with given stable prefix. */ - def mkRef(pre: Type, sym: Symbol): Tree = { - val qual = mkQualifier(pre); - if (qual == EmptyTree) Ident(sym) else Select(qual, sym) - } - - /** Builds a reference to given symbol. */ - def mkRef(sym: Symbol): Tree = - if (sym.owner.isClass) mkRef(sym.owner.thisType, sym) else Ident(sym); - - /** Replaces tree type with a stable type if possible */ - def stabilize(tree: Tree): Tree = tree match { - case Ident(_) => - if (tree.symbol.isStable) tree.setType(singleType(tree.symbol.owner.thisType, tree.symbol)) - else tree - case Select(qual, _) => - if (tree.symbol.isStable && qual.tpe.isStable) tree.setType(singleType(qual.tpe, tree.symbol)) - else tree - case _ => - tree - } - - /** Cast `tree' to type `pt' */ - def cast(tree: Tree, pt: Type): Tree = { - if (settings.debug.value) log("casting " + tree + ":" + tree.tpe + " to " + pt); - assert(!tree.tpe.isInstanceOf[MethodType], tree); - typer.typed { - atPos(tree.pos) { - Apply(TypeApply(Select(tree, Object_asInstanceOf), List(TypeTree(pt))), List()) - } - } - } - - /** Builds a reference with stable type to given symbol */ - def mkStableRef(pre: Type, sym: Symbol): Tree = stabilize(mkRef(pre, sym)); - def mkStableRef(sym: Symbol): Tree = stabilize(mkRef(sym)); - - def This(sym: Symbol): Tree = - global.This(sym.name) setSymbol sym setType sym.thisType; - - def Ident(sym: Symbol): Tree = { - assert(sym.isTerm); - global.Ident(sym.name) setSymbol sym setType sym.tpe; - } - - def Select(qual: Tree, sym: Symbol): Tree = - if (qual.symbol != null && - (qual.symbol.name.toTermName == nme.ROOT || - qual.symbol.name.toTermName == nme.EMPTY_PACKAGE_NAME)) { - this.Ident(sym) - } else { - assert(sym.isTerm); - val result = global.Select(qual, sym.name) setSymbol sym; - if (qual.tpe != null) result setType qual.tpe.memberType(sym); - result - } - - /** Builds an instance test with given value and type. */ - def mkIsInstanceOf(value: Tree, tpe: Type, erased: Boolean): Tree = { - val sym = - if(erased) - definitions.Any_isInstanceOfErased - else - definitions.Any_isInstanceOf; - Apply( - TypeApply( - Select(value, sym), - List(TypeTree(tpe))), - List()) - } - - def mkIsInstanceOf(value: Tree, tpe: Type): Tree = { - mkIsInstanceOf(value, tpe, global.phase.erasedTypes); - } - - /** Builds a cast with given value and type. */ - def mkAsInstanceOf(value: Tree, tpe: Type, erased: Boolean): Tree = { - val sym = - if(erased) - definitions.Any_asInstanceOfErased - else - definitions.Any_asInstanceOf; - - Apply( - TypeApply( - Select(value, sym), - List(TypeTree(tpe))), - List()) - } - - def mkAsInstanceOf(value: Tree, tpe: Type): Tree = { - mkAsInstanceOf(value, tpe, global.phase.erasedTypes); - } - - - /** Builds a list with given head and tail. */ - def mkNewCons(head: Tree, tail: Tree): Tree = - New(Apply(mkRef(definitions.ConsClass), List(head,tail))); - - /** Builds a list with given head and tail. */ - def mkNil: Tree = - mkRef(definitions.NilModule); - - /** Builds a pair */ - def mkNewPair(left: Tree, right: Tree) = - New(Apply(mkRef(definitions.TupleClass(2)), List(left,right))); - -} diff --git a/sources/scala/tools/nsc/ast/TreeInfo.scala b/sources/scala/tools/nsc/ast/TreeInfo.scala deleted file mode 100644 index dedfc6b03a..0000000000 --- a/sources/scala/tools/nsc/ast/TreeInfo.scala +++ /dev/null @@ -1,187 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.ast; - -import symtab.Flags._; - -abstract class TreeInfo { - - val global: Global; - import global._; - - def isTerm(tree: Tree): boolean = tree.isTerm; - def isType(tree: Tree): boolean = tree.isType; - - def isOwnerDefinition(tree: Tree): boolean = tree match { - case PackageDef(_, _) - | ClassDef(_, _, _, _, _) - | ModuleDef(_, _, _) - | DefDef(_, _, _, _, _, _) - | Import(_, _) => true - case _ => false - } - - def isDefinition(tree: Tree): boolean = tree.isDef; - - def isDeclaration(tree: Tree): boolean = tree match { - case DefDef(_, _, _, _, _, EmptyTree) - | ValDef(_, _, _, EmptyTree) - | AbsTypeDef(_, _, _, _) - | AliasTypeDef(_, _, _, _) => true - case _ => false - } - - /** Is tree legal as a member definition of an interface? - */ - def isInterfaceMember(tree: Tree): boolean = tree match { - case EmptyTree => true - case Import(_, _) => true - case AbsTypeDef(_, _, _, _) => true - case AliasTypeDef(_, _, _, _) => true - case DefDef(mods, _, _, _, _, __) => mods.hasFlag(DEFERRED) - case ValDef(mods, _, _, _) => mods.hasFlag(DEFERRED) - case DocDef(_, definition) => isInterfaceMember(definition) - case Attributed(_, definition) => isInterfaceMember(definition) - case _ => false - } - - - /** Is tree a pure definition? - */ - def isPureDef(tree: Tree): boolean = tree match { - case EmptyTree - | ClassDef(_, _, _, _, _) - | ModuleDef(_, _, _) - | AbsTypeDef(_, _, _, _) - | AliasTypeDef(_, _, _, _) - | Import(_, _) - | DefDef(_, _, _, _, _, _) => - true - case ValDef(mods, _, _, rhs) => - mods.hasFlag(MUTABLE) && isPureExpr(rhs) - case DocDef(_, definition) => - isPureDef(definition) - case Attributed(_, definition) => - isPureDef(definition) - case _ => - false - } - - /** Is tree a stable & pure expression? - */ - def isPureExpr(tree: Tree): boolean = tree match { - case EmptyTree - | This(_) - | Super(_, _) - | Literal(_) => - true - case Ident(_) => - tree.symbol.isStable - case Select(qual, _) => - tree.symbol.isStable && isPureExpr(qual) - case TypeApply(fn, _) => - isPureExpr(fn) - case Apply(fn, List()) => - isPureExpr(fn) - case Typed(expr, _) => - isPureExpr(expr) - case Block(stats, expr) => - (stats forall isPureDef) && isPureExpr(expr) - case _ => - false - } - - /** Is tree a self constructor call? - */ - def isSelfConstrCall(tree: Tree): boolean = tree match { - case Ident(nme.CONSTRUCTOR) => - true - case TypeApply(constr, _) => - isSelfConstrCall(constr) - case Apply(constr, _) => - isSelfConstrCall(constr) - case _ => - false - } - - /** Is tree a variable pattern */ - def isVarPattern(pat: Tree): boolean = pat match { - case Ident(name) => isVariableName(name) - case _ => false - } - - /** The longest statement suffix that starts with a constructor */ - def firstConstructor(stats: List[Tree]): Tree = stats.head match { - case constr @ DefDef(_, nme.CONSTRUCTOR, _, _, _, _) => constr - case _ => firstConstructor(stats.tail) - } - - /** Is name a left-associative operator? */ - def isLeftAssoc(operator: Name): boolean = - operator.length > 0 && operator(operator.length - 1) != ':'; - - /** Is name a variable name? */ - def isVariableName(name: Name): boolean = { - val first = name(0); - ((('a' <= first && first <= 'z') || first == '_') - && name != nme.false_ - && name != nme.true_ - && name != nme.null_) - } - - /** Is tree a this node which belongs to `enclClass'? */ - def isSelf(tree: Tree, enclClass: Symbol): boolean = tree match { - case This(_) => tree.symbol == enclClass - case _ => false - } - - /** Is this pattern node a catch-all (wildcard or variable) pattern? */ - def isDefaultCase(cdef: CaseDef) = cdef match { - case CaseDef(Ident(nme.WILDCARD), EmptyTree, _) => true - case CaseDef(Bind(_, Ident(nme.WILDCARD)), EmptyTree, _) => true - case _ => false - } - - /** Is this pattern node a catch-all or type-test pattern? */ - def isCatchCase(cdef: CaseDef) = cdef match { - case CaseDef(Typed(Ident(nme.WILDCARD), tpt), EmptyTree, _) => isSimple(tpt.tpe) - case CaseDef(Bind(_, Typed(Ident(nme.WILDCARD), tpt)), EmptyTree, _) => isSimple(tpt.tpe) - case _ => isDefaultCase(cdef) - } - - private def isSimple(tp: Type): boolean = true; - /* If we have run-time types, and these are used for pattern matching, - we should replace this by something like: - - tp match { - case TypeRef(pre, sym, args) => - args.isEmpty && (sym.owner.isPackageClass || isSimple(pre)) - case NoPrefix => - true - case _ => - false - } -*/ - - /** Is this pattern node a sequence-valued pattern? */ - def isSequenceValued(tree: Tree): boolean = tree match { - case Bind(_, body) => isSequenceValued(body) - case Sequence(_) => true - case ArrayValue(_, _) => true - case Star(_) => true - case Alternative(ts) => ts exists isSequenceValued - case _ => false - } - - /** The method part of an application node - */ - def methPart(tree: Tree): Tree = tree match { - case Apply(fn, _) => methPart(fn) - case TypeApply(fn, _) => methPart(fn) - case AppliedTypeTree(fn, _) => methPart(fn) - case _ => tree - } -} diff --git a/sources/scala/tools/nsc/ast/TreePrinters.scala b/sources/scala/tools/nsc/ast/TreePrinters.scala deleted file mode 100644 index 206fa58061..0000000000 --- a/sources/scala/tools/nsc/ast/TreePrinters.scala +++ /dev/null @@ -1,303 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.ast; - -import java.io._; -import symtab.Flags._; - -abstract class TreePrinters { - - val global: Global; - import global._; - - class TreePrinter(out: PrintWriter) { - protected var indentMargin = 0; - protected val indentStep = 2; - protected var indentString = " "; - - def flush = out.flush(); - - def indent = indentMargin = indentMargin + indentStep; - def undent = indentMargin = indentMargin - indentStep; - - def println = { - out.println(); - while (indentMargin > indentString.length()) - indentString = indentString + indentString; - if (indentMargin > 0) - out.write(indentString, 0, indentMargin); - } - - def printSeq[a](ls: List[a])(printelem: a => unit)(printsep: => unit): unit = ls match { - case List() => - case List(x) => printelem(x) - case x :: rest => printelem(x); printsep; printSeq(rest)(printelem)(printsep) - } - - def printColumn(ts: List[Tree], start: String, sep: String, end: String): unit = { - print(start); indent; println; - printSeq(ts){print}{print(sep); println}; undent; println; print(end) - } - - def printRow(ts: List[Tree], start: String, sep: String, end: String): unit = { - print(start); printSeq(ts){print}{print(sep)}; print(end) - } - - def printRow(ts: List[Tree], sep: String): unit = printRow(ts, "", sep, ""); - - def printTypeParams(ts: List[AbsTypeDef]): unit = - if (!ts.isEmpty) { - print("["); printSeq(ts){printParam}{print(", ")}; print("]") - } - - def printValueParams(ts: List[ValDef]): unit = { - print("("); - if (!ts.isEmpty) printFlags(ts.head.mods.flags & IMPLICIT, nme.EMPTY.toTypeName); - printSeq(ts){printParam}{print(", ")}; - print(")") - } - - def printParam(tree: Tree): unit = tree match { - case ValDef(mods, name, tp, rhs) => - print(symName(tree, name)); printOpt(": ", tp); - case AbsTypeDef(mods, name, lo, hi) => - print(symName(tree, name)); - printOpt(" >: ", lo); printOpt(" <: ", hi); - } - - def printBlock(tree: Tree): unit = tree match { - case Block(_, _) => print(tree) - case _ => printColumn(List(tree), "{", ";", "}") - } - - def symName(tree: Tree, name: Name): String = - if (tree.symbol != NoSymbol) tree.symbol.nameString else name.toString(); - - def printOpt(prefix: String, tree: Tree): unit = - if (!tree.isEmpty) { print(prefix); print(tree) } - - def printModifiers(tree: Tree, mods: Modifiers): unit = { - if (tree.symbol == NoSymbol) - printFlags(mods.flags, mods.privateWithin) - else if (tree.symbol.privateWithin == null) - printFlags(tree.symbol.flags, nme.EMPTY.toTypeName) - else - printFlags(tree.symbol.flags, tree.symbol.privateWithin.name) - } - - def printFlags(flags: long, privateWithin: Name): unit = { - val mask = if (settings.debug.value) -1 else PrintableFlags; - val suffixes: List[Pair[long, String]] = - if (privateWithin.isEmpty) List() else List(Pair(PRIVATE, privateWithin.toString())); - val s = flagsToString(flags & mask, suffixes); - if (s.length() != 0) print(s + " ") - } - - def print(str: String): unit = out.print(str); - def print(name: Name): unit = print(name.toString()); - - def printRaw(tree: Tree): unit = { - tree match { - case EmptyTree => - print(""); - - case ClassDef(mods, name, tparams, tp, impl) => - printModifiers(tree, mods); - print((if (mods.hasFlag(TRAIT)) "trait " else "class ") + symName(tree, name)); - printTypeParams(tparams); - printOpt(": ", tp); print(" extends "); print(impl); - - case PackageDef(packaged, stats) => - print("package "); print(packaged); printColumn(stats, " {", ";", "}") - - case ModuleDef(mods, name, impl) => - printModifiers(tree, mods); print("object " + symName(tree, name)); - print(" extends "); print(impl); - - case ValDef(mods, name, tp, rhs) => - printModifiers(tree, mods); - print(if (mods.hasFlag(MUTABLE)) "var " else "val "); - print(symName(tree, name)); - printOpt(": ", tp); - if (!mods.hasFlag(DEFERRED)) { - print(" = "); - if (rhs.isEmpty) print("_") else print(rhs) - } - - case DefDef(mods, name, tparams, vparamss, tp, rhs) => - printModifiers(tree, mods); - print("def " + symName(tree, name)); - printTypeParams(tparams); vparamss foreach printValueParams; - printOpt(": ", tp); printOpt(" = ", rhs); - - case AbsTypeDef(mods, name, lo, hi) => - printModifiers(tree, mods); print("type "); printParam(tree); - - case AliasTypeDef(mods, name, tparams, rhs) => - printModifiers(tree, mods); print("type " + symName(tree, name)); - printTypeParams(tparams); printOpt(" = ", rhs); - - case LabelDef(name, params, rhs) => - print(symName(tree, name)); printRow(params, "(", ",", ")"); printBlock(rhs); - - case Import(expr, selectors) => - def selectorToString(s: Pair[Name, Name]): String = - if (s._1 == nme.WILDCARD || s._1 == s._2) s._1.toString() - else s._1.toString() + "=>" + s._2.toString(); - print("import "); print(expr); - print(selectors.map(selectorToString).mkString(".{", ", ", "}")) - - case Attributed(attr, definition) => - print("["); print(attr); print("]"); println; print(definition); - - case DocDef(comment, definition) => - print(comment); println; print(definition); - - case Template(parents, body) => - printRow(parents, " with "); - if (!body.isEmpty) printColumn(body, " {", ";", "}") - - case Block(stats, expr) => - printColumn(stats ::: List(expr), "{", ";", "}") - - case Match(selector, cases) => - print(selector); printColumn(cases, " match {", "", "}") - - case CaseDef(pat, guard, body) => - print("case "); print(pat); printOpt(" if ", guard); - print(" => "); print(body) - - case Sequence(trees) => - printRow(trees, "[", ", ", "]") - - case Alternative(trees) => - printRow(trees, "(", "| ", ")") - - case Star(elem) => - print("("); print(elem); print(")*"); - - case Bind(name, t) => - print("("); print(symName(tree, name)); print(" @ "); print(t); print(")"); - - case ArrayValue(elemtpt, trees) => - print("Array["); print(elemtpt); printRow(trees, "]{", ", ", "}") - - case Function(vparams, body) => - print("("); printValueParams(vparams); print(" => "); print(body); print(")") - - case Assign(lhs, rhs) => - print(lhs); print(" = "); print(rhs) - - case If(cond, thenp, elsep) => - print("if ("); print(cond); print(")"); indent; println; - print(thenp); undent; - if (!elsep.isEmpty) { - println; print("else"); indent; println; print(elsep); undent - } - - case Return(expr) => - print("return "); print(expr) - - case Try(block, catches, finalizer) => - print("try "); printBlock(block); - if (!catches.isEmpty) printColumn(catches, " catch {", "", "}"); - printOpt(" finally ", finalizer) - - case Throw(expr) => - print("throw "); print(expr) - - case New(tpe) => - print("new "); print(tpe) - - case Typed(expr, tp) => - print("("); print(expr); print(") : "); print(tp); - - case TypeApply(fun, targs) => - print(fun); printRow(targs, "[", ", ", "]"); - - case Apply(fun, vargs) => - print(fun); printRow(vargs, "(", ", ", ")"); - - case Super(qual, mixin) => - if (!qual.isEmpty || tree.symbol != NoSymbol) print(symName(tree, qual) + "."); - print("super"); - if (!mixin.isEmpty) - print("[" + mixin + "]") - - case This(qual) => - if (!qual.isEmpty) print(symName(tree, qual) + "."); - print("this"); - - case Select(qualifier, name) => - print(qualifier); print("."); print(symName(tree, name)) - - case Ident(name) => - print(symName(tree, name)) - - case Literal(x) => - print(x.tag match { - case NullTag => "null" - case StringTag => "\"" + x.stringValue + "\"" - case CharTag => "\'" + x.charValue + "\'" - case LongTag => x.longValue.toString() + "L"; - case _ => x.value.toString() - }) - - case TypeTree() => - if (tree.tpe == null) print("") - else print(tree.tpe.toString()); - - case SingletonTypeTree(ref) => - print(ref); print(".type") - - case SelectFromTypeTree(qualifier, selector) => - print(qualifier); print("#"); print(symName(tree, selector)) - - case CompoundTypeTree(templ) => - print(templ) - - case AppliedTypeTree(tp, args) => - print(tp); printRow(args, "[", ", ", "]") - } - if (global.settings.printtypes.value && tree.isTerm && !tree.isEmpty) { - print("{"); print(if (tree.tpe == null) "" else tree.tpe.toString()); print("}") - } - } - - def print(tree: Tree): unit = - printRaw( - if (tree.isDef && tree.symbol != NoSymbol) { - tree match { - case ClassDef(_, _, _, _, impl) => ClassDef(tree.symbol, impl) - case ModuleDef(_, _, impl) => ModuleDef(tree.symbol, impl) -// case ValDef(_, _, _, rhs) => ValDef(tree.symbol, rhs) - case DefDef(_, _, _, vparamss, _, rhs) => DefDef(tree.symbol, vparamss, rhs) - case AbsTypeDef(_, _, _, _) => AbsTypeDef(tree.symbol) - case AliasTypeDef(_, _, _, rhs) => AliasTypeDef(tree.symbol, rhs) - case _ => tree - } - } else tree); - - def print(unit: CompilationUnit): unit = { - print("// Scala source: " + unit.source + "\n"); - if (unit.body != null) { - print(unit.body); println - } else { - print("") - } - println; flush - } - - def printAll(): unit = { - print("[[syntax trees at end of " + phase + "]]"); - for (val unit <- global.currentRun.units) print(unit) - } - } - - def create(writer: PrintWriter): TreePrinter = new TreePrinter(writer); - def create(stream: OutputStream): TreePrinter = create(new PrintWriter(stream)); - def create(): TreePrinter = create(System.out); -} diff --git a/sources/scala/tools/nsc/ast/Trees.scala b/sources/scala/tools/nsc/ast/Trees.scala deleted file mode 100644 index 92b147c947..0000000000 --- a/sources/scala/tools/nsc/ast/Trees.scala +++ /dev/null @@ -1,1251 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.ast; - -import scala.tools.nsc.symtab.Flags; -import java.io.StringWriter; -import java.io.PrintWriter; -import scala.tools.nsc.util.{Position,SourceFile}; -import symtab.Flags._; - -[_trait_] abstract class Trees: Global { - - //statistics - var nodeCount = 0; - - case class Modifiers(flags: int, privateWithin: Name) { - def isPrivate = ((flags & PRIVATE ) != 0); - def isProtected = ((flags & PROTECTED) != 0); - def isVariable = ((flags & MUTABLE) != 0); - def isPublic = !isPrivate && !isProtected; - def hasFlag(flag: int) = (flags & flag) != 0; - def | (flag: int): Modifiers = { - val flags1 = flags | flag; - if (flags1 == flags) this else Modifiers(flags1, privateWithin) - } - } - - def Modifiers(flags: int): Modifiers = Modifiers(flags, nme.EMPTY.toTypeName); - def Modifiers(flags: long): Modifiers = Modifiers(flags.asInstanceOf[int]); - - val NoMods = Modifiers(0); - - abstract class Tree { - - if (util.Statistics.enabled) nodeCount = nodeCount + 1; - - private var posx: int = Position.NOPOS; - - def pos = posx; - - var tpe: Type = _; - - def setPos(p: int): this.type = { posx = p; this } - def setType(tp: Type): this.type = { tpe = tp; this } - - def symbol: Symbol = null; - def symbol_=(sym: Symbol): unit = - throw new Error("symbol_= inapplicable for " + this); - def setSymbol(sym: Symbol): this.type = { symbol = sym; this } - - def hasSymbol = false; - def isDef = false; - def isTerm = false; - def isType = false; - def isEmpty = false; - - override def toString(): String = { - val buffer = new StringWriter(); - val printer = treePrinters.create(new PrintWriter(buffer)); - printer.print(this); printer.flush; - buffer.toString() - } - - override def hashCode(): int = super.hashCode(); - - override def equals(that: Any): boolean = that match { - case t: Tree => this eq t - case _ => false - } - - def duplicate: this.type = (duplicator transform this).asInstanceOf[this.type]; - - def copyAttrs(tree: Tree): this.type = { - posx = tree.posx; - tpe = tree.tpe; - if (hasSymbol) symbol = tree.symbol; - this - } - } - - [_trait_] abstract class SymTree extends Tree { - override def hasSymbol = true; - override var symbol: Symbol = NoSymbol; - } - - abstract class DefTree extends SymTree { - def name: Name; - override def isDef = true; - } - - trait TermTree extends Tree { - override def isTerm = true - } - - trait TypTree extends Tree { - override def isType = true - } - -// ----- auxiliary objects and methods ------------------------------ - - private val duplicator = new Transformer { - override val copy = new StrictTreeCopier; - } - - private def syntheticParams(owner: Symbol, formals: List[Type]): List[Symbol] = { - var cnt = 0; - def freshName() = { cnt = cnt + 1; newTermName("x$" + cnt) } - for (val formal <- formals) yield - owner.newValueParameter(owner.pos, freshName()).setInfo(formal); - } - - private def syntheticParams(owner: Symbol, mtp: Type): List[List[Symbol]] = mtp match { - case PolyType(_, restp) => - syntheticParams(owner, restp) - case MethodType(formals, restp) => - syntheticParams(owner, formals) :: syntheticParams(owner, restp) - case _ => - List() - } - -// def nextPhase = if (phase.id > globalPhase.id) phase else phase.next; - -// ----- tree node alternatives -------------------------------------- - - /** The empty tree */ - case object EmptyTree extends TermTree { - tpe = NoType; - override def isEmpty = true; - } - - abstract class MemberDef extends DefTree { - def mods: Modifiers; - def name: Name; - def keyword : String; - final def hasFlag(mask: long): boolean = (mods.flags & mask) != 0; - - def namePos(source : SourceFile) : Int = if (pos == Position.NOPOS) Position.NOPOS else { - assert(keyword != null); - if (!source.beginsWith(pos, keyword + " ")) { - val p = new Position(source, pos); - // System.err.println("SYM=" + symbol + " KW=" + keyword + " LINE=" + p.lineContent + " TEXT=" + source.content(pos) + source.content(pos + 1)); - if (true) return Position.NOPOS; - else throw new Error(); - } - source.skipWhitespace(pos + keyword.length() + 1); - } - } - - /** Package clause */ - case class PackageDef(name: Name, stats: List[Tree]) - extends MemberDef { - def mods = NoMods; - def keyword = "package"; - } - - def PackageDef(sym: Symbol, stats: List[Tree]): PackageDef = - PackageDef(sym.name, stats) setSymbol sym; - - - abstract class ImplDef extends MemberDef { - def impl: Template - } - - /** Class definition */ - case class ClassDef(mods: Modifiers, name: Name, tparams: List[AbsTypeDef], tpt: Tree, impl: Template) - extends ImplDef { - def keyword = "class"; - } - - def ClassDef(sym: Symbol, impl: Template): ClassDef = - posAssigner.atPos(sym.pos) { - ClassDef(Modifiers(sym.flags), - sym.name, - sym.typeParams map AbsTypeDef, - if (sym.thisSym == sym) EmptyTree else TypeTree(sym.typeOfThis), - impl) setSymbol sym - } - - /** Construct class definition with given class symbol, value parameters, supercall arguments - * and template body. - * @param sym the class symbol - * @param vparamss the value parameters -- if they have symbols they should be owned by `sym' - * @param argss the supercall arguments - * @param body the template statements without primary constructor and value parameter fields. - */ - def ClassDef(sym: Symbol, vparamss: List[List[ValDef]], argss: List[List[Tree]], body: List[Tree]): ClassDef = - ClassDef(sym, Template(sym.info.parents map TypeTree, vparamss, argss, body)); - - /** Singleton object definition */ - case class ModuleDef(mods: Modifiers, name: Name, impl: Template) - extends ImplDef { - def keyword = "object"; - } - - def ModuleDef(sym: Symbol, impl: Template): ModuleDef = - posAssigner.atPos(sym.pos) { - ModuleDef(Modifiers(sym.flags), sym.name, impl) - } - - - abstract class ValOrDefDef extends MemberDef { - def tpt: Tree; - def rhs: Tree; - } - - /** Value definition */ - case class ValDef(mods: Modifiers, name: Name, tpt: Tree, rhs: Tree) - extends ValOrDefDef { - assert(tpt.isType, tpt); - assert(rhs.isTerm, rhs); - def keyword = if (mods.isVariable) "var" else "val"; - override def namePos(source : SourceFile) = - if (pos == Position.NOPOS) Position.NOPOS; - else if (source.beginsWith(pos, "val ") || source.beginsWith(pos, "var ")) source.skipWhitespace(pos + ("val ").length()); - else if (source.content(pos) == ',') source.skipWhitespace(pos + 1); - else pos; - } - - - def ValDef(sym: Symbol, rhs: Tree): ValDef = { - posAssigner.atPos(sym.pos) { - ValDef(Modifiers(sym.flags), sym.name, TypeTree(sym.tpe), rhs) setSymbol sym - } - } - - def ValDef(sym: Symbol): ValDef = ValDef(sym, EmptyTree); - - /** Method definition */ - case class DefDef(mods: Modifiers, name: Name, tparams: List[AbsTypeDef], - vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree) - extends ValOrDefDef { - assert(tpt.isType); - assert(rhs.isTerm); - def keyword = "def"; - } - - def DefDef(sym: Symbol, vparamss: List[List[ValDef]], rhs: Tree): DefDef = - posAssigner.atPos(sym.pos) { - assert(sym != NoSymbol); - DefDef(Modifiers(sym.flags), - sym.name, - sym.typeParams map AbsTypeDef, - vparamss, - TypeTree(sym.tpe.finalResultType), - rhs) setSymbol sym - } - - def DefDef(sym: Symbol, rhs: List[List[Symbol]] => Tree): DefDef = { - val vparamss = syntheticParams(sym, sym.tpe); - DefDef(sym, vparamss map (.map(ValDef)), rhs(vparamss)); - } - - /** Abstract type or type parameter */ - case class AbsTypeDef(mods: Modifiers, name: Name, lo: Tree, hi: Tree) - extends DefTree { - def keyword = ""; - - override def setPos(pos : Int) : this.type = { - val ret = super.setPos(pos); - ret; - } - def namePos = pos - name.length; - } - - def AbsTypeDef(sym: Symbol): AbsTypeDef = - posAssigner.atPos(sym.pos) { - AbsTypeDef(Modifiers(sym.flags), sym.name, - TypeTree(sym.info.bounds.lo), TypeTree(sym.info.bounds.hi)) - } - - /** Type alias */ - case class AliasTypeDef(mods: Modifiers, name: Name, tparams: List[AbsTypeDef], rhs: Tree) - extends MemberDef { - def keyword = "type"; - } - - def AliasTypeDef(sym: Symbol, rhs: Tree): AliasTypeDef = - posAssigner.atPos(sym.pos) { - AliasTypeDef(Modifiers(sym.flags), sym.name, sym.typeParams map AbsTypeDef, rhs) - } - - /** Labelled expression - the symbols in the array (must be Idents!) - * are those the label takes as argument - * - * The symbol that is given to the labeldef should have a MethodType - * (as if it were a nested function) - * - * jumps are apply nodes attributed with label symbol, the arguements - * will get assigned to the idents. - * - * note: on 2005-06-09 Martin, Iuli, Burak agreed to have forward - * jumps within a Block. - */ - case class LabelDef(name: Name, params: List[Ident], rhs: Tree) - extends DefTree with TermTree { - assert(rhs.isTerm); - } - - def LabelDef(sym: Symbol, params: List[Symbol], rhs: Tree): LabelDef = - posAssigner.atPos(sym.pos) { - LabelDef(sym.name, params map Ident, rhs) setSymbol sym - } - - /** Import clause */ - case class Import(expr: Tree, selectors: List[Pair[Name, Name]]) - extends SymTree; - - /** Attribuetd definition */ - case class Attributed(attribute: Tree, definition: Tree) - extends Tree { - override def symbol: Symbol = definition.symbol; - override def symbol_=(sym: Symbol): unit = { definition.symbol = sym } - } - - /** Documented definition, eliminated by analyzer */ - case class DocDef(comment: String, definition: Tree) - extends Tree { - override def symbol: Symbol = definition.symbol; - override def symbol_=(sym: Symbol): unit = { definition.symbol = sym } - } - - /** Instantiation template */ - case class Template(parents: List[Tree], body: List[Tree]) - extends SymTree { - // System.err.println("TEMPLATE: " + parents); - } - - def Template(parents: List[Tree], vparamss: List[List[ValDef]], argss: List[List[Tree]], body: List[Tree]): Template = { - /** Add constructor to template */ - var vparamss1 = - vparamss map (.map (vd => - ValDef(Modifiers(vd.mods.flags & IMPLICIT | PARAM), vd.name, vd.tpt.duplicate, EmptyTree))); - if (vparamss1.isEmpty || - !vparamss1.head.isEmpty && (vparamss1.head.head.mods.flags & IMPLICIT) != 0) - vparamss1 = List() :: vparamss1; - val superRef: Tree = Select(Super(nme.EMPTY.toTypeName, nme.EMPTY.toTypeName), nme.CONSTRUCTOR); - val superCall = (superRef /: argss) (Apply); - val constr: Tree = DefDef(NoMods, nme.CONSTRUCTOR, List(), vparamss1, TypeTree(), superCall); - Template(parents, List.flatten(vparamss) ::: constr :: body) - } - - /** Block of expressions (semicolon separated expressions) */ - case class Block(stats: List[Tree], expr: Tree) - extends TermTree; - - /** Case clause in a pattern match, eliminated by TransMatch - * (except for occurences in switch statements) - */ - case class CaseDef(pat: Tree, guard: Tree, body: Tree) - extends Tree; - - /** casedef shorthand */ - def CaseDef(pat: Tree, body: Tree): CaseDef = CaseDef(pat, EmptyTree, body); - - /** Sequence of patterns (comma separated expressions), eliminated by TransMatch */ - case class Sequence(trees: List[Tree]) - extends TermTree; - - /** Alternatives of patterns, eliminated by TransMatch, except for - * occurences in encoded Switch stmt (=remaining Match(CaseDef(...)) - */ - case class Alternative(trees: List[Tree]) - extends TermTree; - - /** Repetition of pattern, eliminated by TransMatch */ - case class Star(elem: Tree) - extends TermTree; - - /** Bind of a variable to a rhs pattern, eliminated by TransMatch */ - case class Bind(name: Name, body: Tree) - extends DefTree; - - def Bind(sym: Symbol, body: Tree): Bind = - Bind(sym.name, body) setSymbol sym; - - /** Array of expressions, needs to be translated in backend, - */ - case class ArrayValue(elemtpt: Tree, elems: List[Tree]) - extends TermTree; - - /** Anonymous function, eliminated by analyzer */ - case class Function(vparams: List[ValDef], body: Tree) - extends TermTree with SymTree; - - /** Assignment */ - case class Assign(lhs: Tree, rhs: Tree) - extends TermTree; - - /** Conditional expression */ - case class If(cond: Tree, thenp: Tree, elsep: Tree) - extends TermTree; - - /** Pattern matching expression (before TransMatch) - * Switch statements (after TransMatch) - * - * after TM, cases will satisfy the following constraints: - * - all guards are EmptyTree, - * - all patterns will be either Literal(Constant(x:Int)) or Alternative(lit|...|lit) - * - except for an "otherwise" branch, which has pattern Ident(nme.WILDCARD) - */ - case class Match(selector: Tree, cases: List[CaseDef]) extends TermTree; - - /** Return expression */ - case class Return(expr: Tree) - extends TermTree with SymTree; - - case class Try(block: Tree, catches: List[CaseDef], finalizer: Tree) - extends TermTree; - - /** Throw expression */ - case class Throw(expr: Tree) - extends TermTree; - - /** Object instantiation - * @param tpt a class type - * one should always use factory method below to build a user level new. - */ - case class New(tpt: Tree) - extends TermTree { - assert(tpt.isType) - } - - /** Factory method for object creation */ - def New(tpt: Tree, argss: List[List[Tree]]): Tree = { - assert(!argss.isEmpty); - val superRef: Tree = Select(New(tpt), nme.CONSTRUCTOR); - (superRef /: argss) (Apply); - } - - /** Type annotation, eliminated by explicit outer */ - case class Typed(expr: Tree, tpt: Tree) - extends TermTree; - - abstract class GenericApply(val fun0: Tree, val args0: List[Tree]) extends TermTree; - - - /** Type application */ - case class TypeApply(fun: Tree, args: List[Tree]) - extends GenericApply(fun, args) { - override def symbol: Symbol = fun.symbol; - override def symbol_=(sym: Symbol): unit = { fun.symbol = sym } - } - - /** Value application */ - case class Apply(fun: Tree, args: List[Tree]) - extends GenericApply(fun, args) { - override def symbol: Symbol = fun.symbol; - override def symbol_=(sym: Symbol): unit = { fun.symbol = sym } - } - - /** Super reference */ - case class Super(qual: Name, mixin: Name) - extends TermTree with SymTree; - - def Super(sym: Symbol, mixin: Name): Tree = Super(sym.name, mixin) setSymbol sym; - - /** Self reference */ - case class This(qual: Name) - extends TermTree with SymTree; - - def This(sym: Symbol): Tree = This(sym.name) setSymbol sym; - - /** Designator */ - case class Select(qualifier: Tree, selector: Name) - extends SymTree { - override def isTerm = selector.isTermName; - override def isType = selector.isTypeName; - - override def setPos(pos : Int) : this.type = { - val ret = super.setPos(pos); - // System.err.println("SELECT_POS: " + pos + " " + this); - // if (pos == 74) Thread.dumpStack(); - ret; - } - - - } - - def Select(qualifier: Tree, sym: Symbol): Select = - Select(qualifier, sym.name) setSymbol sym; - - /** Identifier */ - case class Ident(name: Name) - extends SymTree { - override def isTerm = name.isTermName; - override def isType = name.isTypeName; - - override def setPos(p : Int) : this.type = { - val ret = super.setPos(p); - ret; - } - - } - - def Ident(sym: Symbol): Ident = - Ident(sym.name) setSymbol sym; - - /** Literal */ - case class Literal(value: Constant) - extends TermTree { - assert(value != null) - } - - def Literal(value: Any): Literal = - Literal(Constant(value)); - - /** General type term, introduced by RefCheck. */ - case class TypeTree() extends TypTree { - var original : Tree = _; - - def setOriginal(tree : Tree) : this.type = { - tree match { - case tt : TypeTree => - System.err.println("Illegal: " + this + " to " + tree); - Thread.dumpStack(); - case _ => - } - - original = tree; - setPos(tree.pos); - } - override def setPos(pos : Int) : this.type = { - val ret = super.setPos(pos); - if (false && pos == 151 && original == null) { - System.err.println("TYPE: " + this + " POS=" + pos + " TPE=" + tpe); - Thread.dumpStack(); - } - ret; - } - - - override def isEmpty = tpe == null || tpe == NoType; - } - - def TypeTree(tp: Type): TypeTree = TypeTree() setType tp; - // def TypeTree(tp: Type, tree : Tree): TypeTree = TypeTree(tree) setType tp; - - - /** Singleton type, eliminated by RefCheck */ - case class SingletonTypeTree(ref: Tree) - extends TypTree; - - /** Type selection, eliminated by RefCheck */ - case class SelectFromTypeTree(qualifier: Tree, selector: Name) - extends TypTree with SymTree; - - /** Intersection type, eliminated by RefCheck */ - case class CompoundTypeTree(templ: Template) - extends TypTree; - - /** Applied type, eliminated by RefCheck */ - case class AppliedTypeTree(tpt: Tree, args: List[Tree]) - extends TypTree { - override def symbol: Symbol = tpt.symbol; - override def symbol_=(sym: Symbol): unit = { tpt.symbol = sym } - } - -/* A standard pattern match - case EmptyTree => - case PackageDef(name, stats) => - case ClassDef(mods, name, tparams, tpt, impl) => - case ModuleDef(mods, name, impl) => (eliminated by refcheck) - case ValDef(mods, name, tpt, rhs) => - case DefDef(mods, name, tparams, vparamss, tpt, rhs) => - case AbsTypeDef(mods, name, lo, hi) => (eliminated by erasure) - case AliasTypeDef(mods, name, tparams, rhs) => (eliminated by erasure) - case LabelDef(name, params, rhs) => - case Import(expr, selectors) => (eliminated by typecheck) - case Attributed(attribute, definition) => (eliminated by typecheck) - case DocDef(comment, definition) => (eliminated by typecheck) - case Template(parents, body) => - case Block(stats, expr) => - case CaseDef(pat, guard, body) => (eliminated by transmatch) - case Sequence(trees) => (eliminated by transmatch) - case Alternative(trees) => (eliminated by transmatch) - case Star(elem) => (eliminated by transmatch) - case Bind(name, body) => (eliminated by transmatch) - case ArrayValue(elemtpt, trees) => (introduced by uncurry) - case Function(vparams, body) => (eliminated by typecheck) - case Assign(lhs, rhs) => - case If(cond, thenp, elsep) => - case Match(selector, cases) => - case Return(expr) => - case Try(block, catches, finalizer) => - case Throw(expr) => - case New(tpt) => - case Typed(expr, tpt) => (eliminated by erasure) - case TypeApply(fun, args) => - case Apply(fun, args) => - case Super(qual, mixin) => - case This(qual) => - case Select(qualifier, selector) => - case Ident(name) => - case Literal(value) => - case TypeTree() => - case SingletonTypeTree(ref) => (eliminated by typecheck) - case SelectFromTypeTree(qualifier, selector) => (eliminated by typecheck) - case CompoundTypeTree(templ: Template) => (eliminated by typecheck) - case AppliedTypeTree(tpt, args) => (eliminated by typecheck) -*/ - - trait TreeCopier { - def ClassDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[AbsTypeDef], tpt: Tree, impl: Template): ClassDef; - def PackageDef(tree: Tree, name: Name, stats: List[Tree]): PackageDef; - def ModuleDef(tree: Tree, mods: Modifiers, name: Name, impl: Template): ModuleDef; - def ValDef(tree: Tree, mods: Modifiers, name: Name, tpt: Tree, rhs: Tree): ValDef; - def DefDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[AbsTypeDef], vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree): DefDef; - def AbsTypeDef(tree: Tree, mods: Modifiers, name: Name, lo: Tree, hi: Tree): AbsTypeDef; - def AliasTypeDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[AbsTypeDef], rhs: Tree): AliasTypeDef; - def LabelDef(tree: Tree, name: Name, params: List[Ident], rhs: Tree): LabelDef; - def Import(tree: Tree, expr: Tree, selectors: List[Pair[Name, Name]]): Import; - def Attributed(tree: Tree, attribute: Tree, definition: Tree): Attributed; - def DocDef(tree: Tree, comment: String, definition: Tree): DocDef; - def Template(tree: Tree, parents: List[Tree], body: List[Tree]): Template; - def Block(tree: Tree, stats: List[Tree], expr: Tree): Block; - def CaseDef(tree: Tree, pat: Tree, guard: Tree, body: Tree): CaseDef; - def Sequence(tree: Tree, trees: List[Tree]): Sequence; - def Alternative(tree: Tree, trees: List[Tree]): Alternative; - def Star(tree: Tree, elem: Tree): Star; - def Bind(tree: Tree, name: Name, body: Tree): Bind; - def ArrayValue(tree: Tree, elemtpt: Tree, trees: List[Tree]): ArrayValue; - def Function(tree: Tree, vparams: List[ValDef], body: Tree): Function; - def Assign(tree: Tree, lhs: Tree, rhs: Tree): Assign; - def If(tree: Tree, cond: Tree, thenp: Tree, elsep: Tree): If; - def Match(tree: Tree, selector: Tree, cases: List[CaseDef]): Match; - def Return(tree: Tree, expr: Tree): Return; - def Try(tree: Tree, block: Tree, catches: List[CaseDef], finalizer: Tree): Try; - def Throw(tree: Tree, expr: Tree): Throw; - def New(tree: Tree, tpt: Tree): New; - def Typed(tree: Tree, expr: Tree, tpt: Tree): Typed; - def TypeApply(tree: Tree, fun: Tree, args: List[Tree]): TypeApply; - def Apply(tree: Tree, fun: Tree, args: List[Tree]): Apply; - def Super(tree: Tree, qual: Name, mixin: Name): Super; - def This(tree: Tree, qual: Name): This; - def Select(tree: Tree, qualifier: Tree, selector: Name): Select; - def Ident(tree: Tree, name: Name): Ident; - def Literal(tree: Tree, value: Constant): Literal; - def TypeTree(tree: Tree): TypeTree; - def SingletonTypeTree(tree: Tree, ref: Tree): SingletonTypeTree; - def SelectFromTypeTree(tree: Tree, qualifier: Tree, selector: Name): SelectFromTypeTree; - def CompoundTypeTree(tree: Tree, templ: Template): CompoundTypeTree; - def AppliedTypeTree(tree: Tree, tpt: Tree, args: List[Tree]): AppliedTypeTree; - } - - class StrictTreeCopier extends TreeCopier { - def ClassDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[AbsTypeDef], tpt: Tree, impl: Template) = - new ClassDef(mods, name, tparams, tpt, impl).copyAttrs(tree); - def PackageDef(tree: Tree, name: Name, stats: List[Tree]) = - new PackageDef(name, stats).copyAttrs(tree); - def ModuleDef(tree: Tree, mods: Modifiers, name: Name, impl: Template) = - new ModuleDef(mods, name, impl).copyAttrs(tree); - def ValDef(tree: Tree, mods: Modifiers, name: Name, tpt: Tree, rhs: Tree) = - new ValDef(mods, name, tpt, rhs).copyAttrs(tree); - def DefDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[AbsTypeDef], vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree) = - new DefDef(mods, name, tparams, vparamss, tpt, rhs).copyAttrs(tree); - def AbsTypeDef(tree: Tree, mods: Modifiers, name: Name, lo: Tree, hi: Tree) = - new AbsTypeDef(mods, name, lo, hi).copyAttrs(tree); - def AliasTypeDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[AbsTypeDef], rhs: Tree) = - new AliasTypeDef(mods, name, tparams, rhs).copyAttrs(tree); - def LabelDef(tree: Tree, name: Name, params: List[Ident], rhs: Tree) = - new LabelDef(name, params, rhs).copyAttrs(tree); - def Import(tree: Tree, expr: Tree, selectors: List[Pair[Name, Name]]) = - new Import(expr, selectors).copyAttrs(tree); - def Attributed(tree: Tree, attribute: Tree, definition: Tree) = - new Attributed(attribute, definition).copyAttrs(tree); - def DocDef(tree: Tree, comment: String, definition: Tree) = - new DocDef(comment, definition).copyAttrs(tree); - def Template(tree: Tree, parents: List[Tree], body: List[Tree]) = - new Template(parents, body).copyAttrs(tree); - def Block(tree: Tree, stats: List[Tree], expr: Tree) = - new Block(stats, expr).copyAttrs(tree); - def CaseDef(tree: Tree, pat: Tree, guard: Tree, body: Tree) = - new CaseDef(pat, guard, body).copyAttrs(tree); - def Sequence(tree: Tree, trees: List[Tree]) = - new Sequence(trees).copyAttrs(tree); - def Alternative(tree: Tree, trees: List[Tree]) = - new Alternative(trees).copyAttrs(tree); - def Star(tree: Tree, elem: Tree) = - new Star(elem).copyAttrs(tree); - def Bind(tree: Tree, name: Name, body: Tree) = - new Bind(name, body).copyAttrs(tree); - def ArrayValue(tree: Tree, elemtpt: Tree, trees: List[Tree]) = - new ArrayValue(elemtpt, trees).copyAttrs(tree); - def Function(tree: Tree, vparams: List[ValDef], body: Tree) = - new Function(vparams, body).copyAttrs(tree); - def Assign(tree: Tree, lhs: Tree, rhs: Tree) = - new Assign(lhs, rhs).copyAttrs(tree); - def If(tree: Tree, cond: Tree, thenp: Tree, elsep: Tree) = - new If(cond, thenp, elsep).copyAttrs(tree); - def Match(tree: Tree, selector: Tree, cases: List[CaseDef]) = - new Match(selector, cases).copyAttrs(tree); - def Return(tree: Tree, expr: Tree) = - new Return(expr).copyAttrs(tree); - def Try(tree: Tree, block: Tree, catches: List[CaseDef], finalizer: Tree) = - new Try(block, catches, finalizer).copyAttrs(tree); - def Throw(tree: Tree, expr: Tree) = - new Throw(expr).copyAttrs(tree); - def New(tree: Tree, tpt: Tree) = - new New(tpt).copyAttrs(tree); - def Typed(tree: Tree, expr: Tree, tpt: Tree) = - new Typed(expr, tpt).copyAttrs(tree); - def TypeApply(tree: Tree, fun: Tree, args: List[Tree]) = - new TypeApply(fun, args).copyAttrs(tree); - def Apply(tree: Tree, fun: Tree, args: List[Tree]) = - new Apply(fun, args).copyAttrs(tree); - def Super(tree: Tree, qual: Name, mixin: Name) = - new Super(qual, mixin).copyAttrs(tree); - def This(tree: Tree, qual: Name) = - new This(qual).copyAttrs(tree); - def Select(tree: Tree, qualifier: Tree, selector: Name) = - new Select(qualifier, selector).copyAttrs(tree); - def Ident(tree: Tree, name: Name) = - new Ident(name).copyAttrs(tree); - def Literal(tree: Tree, value: Constant) = - new Literal(value).copyAttrs(tree); - def TypeTree(tree: Tree) = - new TypeTree().copyAttrs(tree); - def SingletonTypeTree(tree: Tree, ref: Tree) = - new SingletonTypeTree(ref).copyAttrs(tree); - def SelectFromTypeTree(tree: Tree, qualifier: Tree, selector: Name) = - new SelectFromTypeTree(qualifier, selector).copyAttrs(tree); - def CompoundTypeTree(tree: Tree, templ: Template) = - new CompoundTypeTree(templ).copyAttrs(tree); - def AppliedTypeTree(tree: Tree, tpt: Tree, args: List[Tree]) = - new AppliedTypeTree(tpt, args).copyAttrs(tree) - } - - class LazyTreeCopier(copy: TreeCopier) extends TreeCopier { - def this() = this(new StrictTreeCopier); - def ClassDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[AbsTypeDef], tpt: Tree, impl: Template) = tree match { - case t @ ClassDef(mods0, name0, tparams0, tpt0, impl0) - if (mods0 == mods && (name0 == name) && (tparams0 == tparams) && (tpt0 == tpt) && (impl0 == impl)) => t - case _ => copy.ClassDef(tree, mods, name, tparams, tpt, impl) - } - def PackageDef(tree: Tree, name: Name, stats: List[Tree]) = tree match { - case t @ PackageDef(name0, stats0) - if ((name0 == name) && (stats0 == stats)) => t - case _ => copy.PackageDef(tree, name, stats) - } - def ModuleDef(tree: Tree, mods: Modifiers, name: Name, impl: Template) = tree match { - case t @ ModuleDef(mods0, name0, impl0) - if (mods0 == mods && (name0 == name) && (impl0 == impl)) => t - case _ => copy.ModuleDef(tree, mods, name, impl) - } - def ValDef(tree: Tree, mods: Modifiers, name: Name, tpt: Tree, rhs: Tree) = tree match { - case t @ ValDef(mods0, name0, tpt0, rhs0) - if (mods0 == mods && (name0 == name) && (tpt0 == tpt) && (rhs0 == rhs)) => t - case _ => copy.ValDef(tree, mods, name, tpt, rhs) - } - def DefDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[AbsTypeDef], vparamss: List[List[ValDef]], tpt: Tree, rhs: Tree) = tree match { - case t @ DefDef(mods0, name0, tparams0, vparamss0, tpt0, rhs0) - if (mods0 == mods && (name0 == name) && (tparams0 == tparams) && (vparamss0 == vparamss) && (tpt0 == tpt) && (rhs == rhs0)) => t - case _ => copy.DefDef(tree, mods, name, tparams, vparamss, tpt, rhs) - } - def AbsTypeDef(tree: Tree, mods: Modifiers, name: Name, lo: Tree, hi: Tree) = tree match { - case t @ AbsTypeDef(mods0, name0, lo0, hi0) - if (mods0 == mods && (name0 == name) && (lo0 == lo) && (hi0 == hi)) => t - case _ => copy.AbsTypeDef(tree, mods, name, lo, hi) - } - def AliasTypeDef(tree: Tree, mods: Modifiers, name: Name, tparams: List[AbsTypeDef], rhs: Tree) = tree match { - case t @ AliasTypeDef(mods0, name0, tparams0, rhs0) - if (mods0 == mods && (name0 == name) && (tparams0 == tparams) && (rhs0 == rhs)) => t - case _ => copy.AliasTypeDef(tree, mods, name, tparams, rhs) - } - def LabelDef(tree: Tree, name: Name, params: List[Ident], rhs: Tree) = tree match { - case t @ LabelDef(name0, params0, rhs0) - if ((name0 == name) && (params0 == params) && (rhs0 == rhs)) => t - case _ => copy.LabelDef(tree, name, params, rhs) - } - def Import(tree: Tree, expr: Tree, selectors: List[Pair[Name, Name]]) = tree match { - case t @ Import(expr0, selectors0) - if ((expr0 == expr) && (selectors0 == selectors)) => t - case _ => copy.Import(tree, expr, selectors) - } - def Attributed(tree: Tree, attribute: Tree, definition: Tree) = tree match { - case t @ Attributed(attribute0, definition0) - if ((attribute0 == attribute) && (definition0 == definition)) => t - case _ => copy.Attributed(tree, attribute, definition) - } - def DocDef(tree: Tree, comment: String, definition: Tree) = tree match { - case t @ DocDef(comment0, definition0) - if ((comment0 == comment) && (definition0 == definition)) => t - case _ => copy.DocDef(tree, comment, definition) - } - def Template(tree: Tree, parents: List[Tree], body: List[Tree]) = tree match { - case t @ Template(parents0, body0) - if ((parents0 == parents) && (body0 == body)) => t - case _ => copy.Template(tree, parents, body) - } - def Block(tree: Tree, stats: List[Tree], expr: Tree) = tree match { - case t @ Block(stats0, expr0) - if ((stats0 == stats) && (expr0 == expr)) => t - case _ => copy.Block(tree, stats, expr) - } - def CaseDef(tree: Tree, pat: Tree, guard: Tree, body: Tree) = tree match { - case t @ CaseDef(pat0, guard0, body0) - if ((pat0 == pat) && (guard0 == guard) && (body0 == body)) => t - case _ => copy.CaseDef(tree, pat, guard, body) - } - def Sequence(tree: Tree, trees: List[Tree]) = tree match { - case t @ Sequence(trees0) - if ((trees0 == trees)) => t - case _ => copy.Sequence(tree, trees) - } - def Alternative(tree: Tree, trees: List[Tree]) = tree match { - case t @ Alternative(trees0) - if ((trees0 == trees)) => t - case _ => copy.Alternative(tree, trees) - } - def Star(tree: Tree, elem: Tree) = tree match { - case t @ Star(elem0) - if ((elem0 == elem)) => t - case _ => copy.Star(tree, elem) - } - def Bind(tree: Tree, name: Name, body: Tree) = tree match { - case t @ Bind(name0, body0) - if ((name0 == name) && (body0 == body)) => t - case _ => copy.Bind(tree, name, body) - } - def ArrayValue(tree: Tree, elemtpt: Tree, trees: List[Tree]) = tree match { - case t @ ArrayValue(elemtpt0, trees0) - if ((elemtpt0 == elemtpt) && (trees0 == trees)) => t - case _ => copy.ArrayValue(tree, elemtpt, trees) - } - def Function(tree: Tree, vparams: List[ValDef], body: Tree) = tree match { - case t @ Function(vparams0, body0) - if ((vparams0 == vparams) && (body0 == body)) => t - case _ => copy.Function(tree, vparams, body) - } - def Assign(tree: Tree, lhs: Tree, rhs: Tree) = tree match { - case t @ Assign(lhs0, rhs0) - if ((lhs0 == lhs) && (rhs0 == rhs)) => t - case _ => copy.Assign(tree, lhs, rhs) - } - def If(tree: Tree, cond: Tree, thenp: Tree, elsep: Tree) = tree match { - case t @ If(cond0, thenp0, elsep0) - if ((cond0 == cond) && (thenp0 == thenp) && (elsep0 == elsep)) => t - case _ => copy.If(tree, cond, thenp, elsep) - } - def Match(tree: Tree, selector: Tree, cases: List[CaseDef]) = tree match { - case t @ Match(selector0, cases0) - if ((selector0 == selector) && (cases0 == cases)) => t - case _ => copy.Match(tree, selector, cases) - } - def Return(tree: Tree, expr: Tree) = tree match { - case t @ Return(expr0) - if ((expr0 == expr)) => t - case _ => copy.Return(tree, expr) - } - def Try(tree: Tree, block: Tree, catches: List[CaseDef], finalizer: Tree) = tree match { - case t @ Try(block0, catches0, finalizer0) - if ((block0 == block) && (catches0 == catches) && (finalizer0 == finalizer)) => t - case _ => copy.Try(tree, block, catches, finalizer) - } - def Throw(tree: Tree, expr: Tree) = tree match { - case t @ Throw(expr0) - if ((expr0 == expr)) => t - case _ => copy.Throw(tree, expr) - } - def New(tree: Tree, tpt: Tree) = tree match { - case t @ New(tpt0) - if ((tpt0 == tpt)) => t - case _ => copy.New(tree, tpt) - } - def Typed(tree: Tree, expr: Tree, tpt: Tree) = tree match { - case t @ Typed(expr0, tpt0) - if ((expr0 == expr) && (tpt0 == tpt)) => t - case _ => copy.Typed(tree, expr, tpt) - } - def TypeApply(tree: Tree, fun: Tree, args: List[Tree]) = tree match { - case t @ TypeApply(fun0, args0) - if ((fun0 == fun) && (args0 == args)) => t - case _ => copy.TypeApply(tree, fun, args) - } - def Apply(tree: Tree, fun: Tree, args: List[Tree]) = tree match { - case t @ Apply(fun0, args0) - if ((fun0 == fun) && (args0 == args)) => t - case _ => copy.Apply(tree, fun, args) - } - def Super(tree: Tree, qual: Name, mixin: Name) = tree match { - case t @ Super(qual0, mixin0) - if ((qual0 == qual) && (mixin0 == mixin)) => t - case _ => copy.Super(tree, qual, mixin) - } - def This(tree: Tree, qual: Name) = tree match { - case t @ This(qual0) - if ((qual0 == qual)) => t - case _ => copy.This(tree, qual) - } - def Select(tree: Tree, qualifier: Tree, selector: Name) = tree match { - case t @ Select(qualifier0, selector0) - if ((qualifier0 == qualifier) && (selector0 == selector)) => t - case _ => copy.Select(tree, qualifier, selector) - } - def Ident(tree: Tree, name: Name) = tree match { - case t @ Ident(name0) - if ((name0 == name)) => t - case _ => copy.Ident(tree, name) - } - def Literal(tree: Tree, value: Constant) = tree match { - case t @ Literal(value0) - if (value0 == value) => t - case _ => copy.Literal(tree, value) - } - def TypeTree(tree: Tree) = tree match { - case t @ TypeTree() => t - case _ => copy.TypeTree(tree) - } - def SingletonTypeTree(tree: Tree, ref: Tree) = tree match { - case t @ SingletonTypeTree(ref0) - if ((ref0 == ref)) => t - case _ => copy.SingletonTypeTree(tree, ref) - } - def SelectFromTypeTree(tree: Tree, qualifier: Tree, selector: Name) = tree match { - case t @ SelectFromTypeTree(qualifier0, selector0) - if ((qualifier0 == qualifier) && (selector0 == selector)) => t - case _ => copy.SelectFromTypeTree(tree, qualifier, selector) - } - def CompoundTypeTree(tree: Tree, templ: Template) = tree match { - case t @ CompoundTypeTree(templ0) - if (templ0 == templ) => t - case _ => copy.CompoundTypeTree(tree, templ) - } - def AppliedTypeTree(tree: Tree, tpt: Tree, args: List[Tree]) = tree match { - case t @ AppliedTypeTree(tpt0, args0) - if ((tpt0 == tpt) && (args0 == args)) => t - case _ => copy.AppliedTypeTree(tree, tpt, args) - } - } - - abstract class Transformer { - val copy: TreeCopier = new LazyTreeCopier; - protected var currentOwner: Symbol = definitions.RootClass; - def transform(tree: Tree): Tree = tree match { - case EmptyTree => - tree - case PackageDef(name, stats) => - atOwner(tree.symbol.moduleClass) { - copy.PackageDef(tree, name, transformStats(stats, currentOwner)) - } - case ClassDef(mods, name, tparams, tpt, impl) => - atOwner(tree.symbol) { - copy.ClassDef(tree, mods, name, transformAbsTypeDefs(tparams), transform(tpt), transformTemplate(impl)) - } - case ModuleDef(mods, name, impl) => - atOwner(tree.symbol.moduleClass) { - copy.ModuleDef(tree, mods, name, transformTemplate(impl)) - } - case ValDef(mods, name, tpt, rhs) => - atOwner(tree.symbol) { - copy.ValDef(tree, mods, name, transform(tpt), transform(rhs)) - } - case DefDef(mods, name, tparams, vparamss, tpt, rhs) => - atOwner(tree.symbol) { - copy.DefDef( - tree, mods, name, transformAbsTypeDefs(tparams), transformValDefss(vparamss), transform(tpt), transform(rhs)) - } - case AbsTypeDef(mods, name, lo, hi) => - atOwner(tree.symbol) { - copy.AbsTypeDef(tree, mods, name, transform(lo), transform(hi)) - } - case AliasTypeDef(mods, name, tparams, rhs) => - atOwner(tree.symbol) { - copy.AliasTypeDef(tree, mods, name, transformAbsTypeDefs(tparams), transform(rhs)) - } - case LabelDef(name, params, rhs) => - copy.LabelDef(tree, name, transformIdents(params), transform(rhs)) //bq: Martin, once, atOwner(...) works, also change `LamdaLifter.proxy' - case Import(expr, selectors) => - copy.Import(tree, transform(expr), selectors) - case Attributed(attribute, definition) => - copy.Attributed(tree, transform(attribute), transform(definition)) - case DocDef(comment, definition) => - copy.DocDef(tree, comment, transform(definition)) - case Template(parents, body) => - copy.Template(tree, transformTrees(parents), transformStats(body, tree.symbol)) - case Block(stats, expr) => - copy.Block(tree, transformStats(stats, currentOwner), transform(expr)) - case CaseDef(pat, guard, body) => - copy.CaseDef(tree, transform(pat), transform(guard), transform(body)) - case Sequence(trees) => - copy.Sequence(tree, transformTrees(trees)) - case Alternative(trees) => - copy.Alternative(tree, transformTrees(trees)) - case Star(elem) => - copy.Star(tree, transform(elem)) - case Bind(name, body) => - copy.Bind(tree, name, transform(body)) - case ArrayValue(elemtpt, trees) => - copy.ArrayValue(tree, transform(elemtpt), transformTrees(trees)) - case Function(vparams, body) => - copy.Function(tree, transformValDefs(vparams), transform(body)) - case Assign(lhs, rhs) => - copy.Assign(tree, transform(lhs), transform(rhs)) - case If(cond, thenp, elsep) => - copy.If(tree, transform(cond), transform(thenp), transform(elsep)) - case Match(selector, cases) => - copy.Match(tree, transform(selector), transformCaseDefs(cases)) - case Return(expr) => - copy.Return(tree, transform(expr)) - case Try(block, catches, finalizer) => - copy.Try(tree, transform(block), transformCaseDefs(catches), transform(finalizer)) - case Throw(expr) => - copy.Throw(tree, transform(expr)) - case New(tpt) => - copy.New(tree, transform(tpt)) - case Typed(expr, tpt) => - copy.Typed(tree, transform(expr), transform(tpt)) - case TypeApply(fun, args) => - copy.TypeApply(tree, transform(fun), transformTrees(args)) - case Apply(fun, args) => - copy.Apply(tree, transform(fun), transformTrees(args)) - case Super(qual, mixin) => - copy.Super(tree, qual, mixin) - case This(qual) => - copy.This(tree, qual) - case Select(qualifier, selector) => - copy.Select(tree, transform(qualifier), selector) - case Ident(name) => - copy.Ident(tree, name) - case Literal(value) => - copy.Literal(tree, value) - case TypeTree() => - copy.TypeTree(tree) - case SingletonTypeTree(ref) => - copy.SingletonTypeTree(tree, transform(ref)) - case SelectFromTypeTree(qualifier, selector) => - copy.SelectFromTypeTree(tree, transform(qualifier), selector) - case CompoundTypeTree(templ) => - copy.CompoundTypeTree(tree, transformTemplate(templ)) - case AppliedTypeTree(tpt, args) => - copy.AppliedTypeTree(tree, transform(tpt), transformTrees(args)) - } - - def transformTrees(trees: List[Tree]): List[Tree] = - List.mapConserve(trees)(transform); - def transformTemplate(tree: Template): Template = - transform(tree: Tree).asInstanceOf[Template]; - def transformAbsTypeDefs(trees: List[AbsTypeDef]): List[AbsTypeDef] = - List.mapConserve(trees)(tree => transform(tree).asInstanceOf[AbsTypeDef]); - def transformValDefs(trees: List[ValDef]): List[ValDef] = - List.mapConserve(trees)(tree => transform(tree).asInstanceOf[ValDef]); - def transformValDefss(treess: List[List[ValDef]]): List[List[ValDef]] = - List.mapConserve(treess)(tree => transformValDefs(tree)); - def transformCaseDefs(trees: List[CaseDef]): List[CaseDef] = - List.mapConserve(trees)(tree => transform(tree).asInstanceOf[CaseDef]); - def transformIdents(trees: List[Ident]): List[Ident] = - List.mapConserve(trees)(tree => transform(tree).asInstanceOf[Ident]); - def transformStats(stats: List[Tree], exprOwner: Symbol): List[Tree] = - List.mapConserve(stats)(stat => - if (exprOwner != currentOwner && stat.isTerm) atOwner(exprOwner)(transform(stat)) - else transform(stat)) filter (EmptyTree !=); - def transformUnit(unit: CompilationUnit): unit = { unit.body = transform(unit.body) } - - def atOwner[A](owner: Symbol)(trans: => A): A = { - val prevOwner = currentOwner; - currentOwner = owner; - val result = trans; - currentOwner = prevOwner; - result - } - } - - class Traverser { - protected var currentOwner: Symbol = definitions.RootClass; - def traverse(tree: Tree): unit = tree match { - case EmptyTree => - ; - case PackageDef(name, stats) => - atOwner(tree.symbol.moduleClass) { - traverseTrees(stats) - } - case ClassDef(mods, name, tparams, tpt, impl) => - atOwner(tree.symbol) { - traverseTrees(tparams); traverse(tpt); traverse(impl) - } - case ModuleDef(mods, name, impl) => - atOwner(tree.symbol.moduleClass) { - traverse(impl) - } - case ValDef(mods, name, tpt, rhs) => - atOwner(tree.symbol) { - traverse(tpt); traverse(rhs) - } - case DefDef(mods, name, tparams, vparamss, tpt, rhs) => - atOwner(tree.symbol) { - traverseTrees(tparams); traverseTreess(vparamss); traverse(tpt); traverse(rhs) - } - case AbsTypeDef(mods, name, lo, hi) => - atOwner(tree.symbol) { - traverse(lo); traverse(hi); - } - case AliasTypeDef(mods, name, tparams, rhs) => - atOwner(tree.symbol) { - traverseTrees(tparams); traverse(rhs) - } - case LabelDef(name, params, rhs) => - traverseTrees(params); traverse(rhs) - case Import(expr, selectors) => - traverse(expr) - case Attributed(attribute, definition) => - traverse(attribute); traverse(definition) - case DocDef(comment, definition) => - traverse(definition) - case Template(parents, body) => - traverseTrees(parents); traverseStats(body, tree.symbol) - case Block(stats, expr) => - traverseTrees(stats); traverse(expr) - case CaseDef(pat, guard, body) => - traverse(pat); traverse(guard); traverse(body) - case Sequence(trees) => - traverseTrees(trees) - case Alternative(trees) => - traverseTrees(trees) - case Star(elem) => - traverse(elem) - case Bind(name, body) => - traverse(body) - case ArrayValue(elemtpt, trees) => - traverse(elemtpt); traverseTrees(trees) - case Function(vparams, body) => - traverseTrees(vparams); traverse(body) - case Assign(lhs, rhs) => - traverse(lhs); traverse(rhs) - case If(cond, thenp, elsep) => - traverse(cond); traverse(thenp); traverse(elsep) - case Match(selector, cases) => - traverse(selector); traverseTrees(cases) - case Return(expr) => - traverse(expr) - case Try(block, catches, finalizer) => - traverse(block); traverseTrees(catches); traverse(finalizer) - case Throw(expr) => - traverse(expr) - case New(tpt) => - traverse(tpt) - case Typed(expr, tpt) => - traverse(expr); traverse(tpt) - case TypeApply(fun, args) => - traverse(fun); traverseTrees(args) - case Apply(fun, args) => - traverse(fun); traverseTrees(args) - case Super(_, _) => - ; - case This(_) => - ; - case Select(qualifier, selector) => - traverse(qualifier) - case Ident(_) => - ; - case Literal(_) => - ; - case TypeTree() => - ; - case SingletonTypeTree(ref) => - traverse(ref) - case SelectFromTypeTree(qualifier, selector) => - traverse(qualifier) - case CompoundTypeTree(templ) => - traverse(templ) - case AppliedTypeTree(tpt, args) => - traverse(tpt); traverseTrees(args) - } - - def traverseTrees(trees: List[Tree]): unit = - trees foreach traverse; - def traverseTreess(treess: List[List[Tree]]): unit = - treess foreach traverseTrees; - def traverseStats(stats: List[Tree], exprOwner: Symbol): unit = - stats foreach (stat => - if (exprOwner != currentOwner && stat.isTerm) atOwner(exprOwner)(traverse(stat)) - else traverse(stat)); - def apply[T <: Tree](tree: T): T = { traverse(tree); tree } - - def atOwner(owner: Symbol)(traverse: => unit): unit = { - val prevOwner = currentOwner; - currentOwner = owner; - traverse; - currentOwner = prevOwner; - } - } - - class TreeSubstituter(from: List[Symbol], to: List[Tree]) extends Transformer { - override def transform(tree: Tree): Tree = tree match { - case Ident(_) => - def subst(from: List[Symbol], to: List[Tree]): Tree = - if (from.isEmpty) tree - else if (tree.symbol == from.head) to.head - else subst(from.tail, to.tail); - subst(from, to) - case _ => - super.transform(tree) - } - } - - class TreeTypeSubstituter(from: List[Symbol], to: List[Type]) extends Traverser { - val typeSubst = new SubstTypeMap(from, to); - override def traverse(tree: Tree): unit = { - if (tree.tpe != null) tree.tpe = typeSubst(tree.tpe); - super.traverse(tree) - } - override def apply[T <: Tree](tree: T): T = super.apply(tree.duplicate) - } - - class TreeSymSubstituter(from: List[Symbol], to: List[Symbol]) extends Traverser { - val symSubst = new SubstSymMap(from, to); - override def traverse(tree: Tree): unit = { - def subst(from: List[Symbol], to: List[Symbol]): unit = { - if (!from.isEmpty) - if (tree.symbol == from.head) tree setSymbol to.head - else subst(from.tail, to.tail) - } - if (tree.tpe != null) tree.tpe = symSubst(tree.tpe); - if (tree.hasSymbol) subst(from, to); - super.traverse(tree) - } - override def apply[T <: Tree](tree: T): T = super.apply(tree.duplicate) - } - - class ChangeOwnerTraverser(val oldowner: Symbol, val newowner: Symbol) extends Traverser { - override def traverse(tree: Tree): unit = { - if ((tree.isDef || tree.isInstanceOf[Function]) && tree.symbol != NoSymbol && tree.symbol.owner == oldowner) - tree.symbol.owner = newowner; - super.traverse(tree) - } - } - - final class TreeList { - private var trees = List[Tree](); - def append(t: Tree): TreeList = { trees = t :: trees; this } - def append(ts: List[Tree]): TreeList = { trees = ts reverse_::: trees; this } - def toList: List[Tree] = trees.reverse; - } - - object posAssigner extends Traverser { - private var pos: int = _; - override def traverse(t: Tree): unit = - if (t != EmptyTree && t.pos == Position.NOPOS) { - t.setPos(pos); - super.traverse(t); - } - def atPos[T <: Tree](pos: int)(tree: T): T = { - this.pos = pos; - traverse(tree); - tree - } - } -} - diff --git a/sources/scala/tools/nsc/ast/parser/MarkupParsers.scala b/sources/scala/tools/nsc/ast/parser/MarkupParsers.scala deleted file mode 100644 index cf4244cb3f..0000000000 --- a/sources/scala/tools/nsc/ast/parser/MarkupParsers.scala +++ /dev/null @@ -1,583 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ -package scala.tools.nsc.ast.parser; - -//import java.lang.{Integer, Long, Float, Double}; - -//import scalac._; -//import scalac.ast._; -//import scalac.atree.AConstant; -//import scalac.symtab.Modifiers; - -import scala.Iterator; -import scala.collection.immutable.ListMap ; -import scala.collection.mutable; -//import scala.tools.scalac.util.NewArray; -import scala.tools.nsc.util.Position; -import scala.xml.{Text,TextBuffer}; - - -trait MarkupParsers: SyntaxAnalyzer { - - import global._ ; - import posAssigner.atPos; - -class MarkupParser(unit: CompilationUnit, s: Scanner, p: Parser, presWS: boolean) /*with scala.xml.parsing.MarkupParser[Tree,Tree] */{ - - import Tokens.{EMPTY, LBRACE, RBRACE}; - - final val preserveWS = presWS; - - import p.{symbXMLBuilder => handle}; - import s.token; - - /** the XML tree factory */ - //final val handle: SymbolicXMLBuilder = p.symbXMLBuilder; - //new SymbolicXMLBuilder(unit.global.make, unit.global.treeGen, p, presWS); - - /** holds the position in the source file */ - /*[Duplicate]*/ var pos: Int = _; - - /** holds temporary values of pos */ - /*[Duplicate]*/ var tmppos: Int = _; - - /** holds the next character */ - /*[Duplicate]*/ var ch: Char = _; - - /** character buffer, for names */ - /*[Duplicate]*/ protected val cbuf = new StringBuffer(); - - /** append Unicode character to name buffer*/ - /*[Duplicate]*/ protected def putChar(c: char) = cbuf.append( c ); - - /*[Duplicate]*/ var xEmbeddedBlock = false; - - /** munch expected XML token, report syntax error for unexpected */ - /*[Duplicate]*/ def xToken(that: Char): Unit = { - if( ch == that ) - nextch; - else - reportSyntaxError("'" + that + "' expected instead of '" + ch + "'"); - } - - var debugLastStartElement = new mutable.Stack[Pair[Int,String]]; - - /** checks whether next character starts a Scala block, if yes, skip it. - * @return true if next character starts a scala block - */ - /*[Duplicate]*/ def xCheckEmbeddedBlock:Boolean = { - xEmbeddedBlock = - enableEmbeddedExpressions && ( ch == '{' ) && { nextch;( ch != '{' ) }; - return xEmbeddedBlock; - } - - /** parse attribute and add it to listmap - * [41] Attributes ::= { S Name Eq AttValue } - * AttValue ::= `'` { _ } `'` - * | `"` { _ } `"` - * | `{` scalablock `}` - */ - /*[Duplicate]*/ def xAttributes = { - var aMap = new mutable.HashMap[String, Tree](); - while (xml.Parsing.isNameStart(ch)) { - val key = xName; - xEQ; - val delim = ch; - val pos1 = pos; - val value: /* AttribValue[*/Tree/*]*/ = ch match { - case '"' | '\'' => - nextch; - val tmp = xAttributeValue( delim ); - nextch; - Literal(Constant(tmp)); - case '{' if enableEmbeddedExpressions => - nextch; - xEmbeddedExpr; - case _ => - reportSyntaxError( "' or \" delimited attribute value or '{' scala-expr '}' expected" ); - Literal(Constant("")) - }; - // well-formedness constraint: unique attribute names - if( aMap.contains( key )) - reportSyntaxError( "attribute "+key+" may only be defined once" ); - aMap.update( key, value ); - if(( ch != '/' )&&( ch != '>' )) - xSpace; - }; - aMap - } - - /** attribute value, terminated by either ' or ". value may not contain <. - * @param endch either ' or " - */ - /*[Duplicate]*/ def xAttributeValue(endCh: char): String = { - while (ch != endCh) { - putChar(ch); - nextch; - }; - val str = cbuf.toString(); - cbuf.setLength(0); - // @todo: normalize attribute value - // well-formedness constraint - if (str.indexOf('<') != -1) { - reportSyntaxError( "'<' not allowed in attrib value" ); "" - } else { - str - } - } - - /** parse a start or empty tag. - * [40] STag ::= '<' Name { S Attribute } [S] - * [44] EmptyElemTag ::= '<' Name { S Attribute } [S] - */ - /*[Duplicate]*/ def xTag: Pair[String, mutable.Map[String, Tree]] = { - val elemName = xName; - xSpaceOpt; - val aMap = if (xml.Parsing.isNameStart(ch)) { - xAttributes; - } else { - new mutable.HashMap[String, Tree](); - } - Tuple2( elemName, aMap ); - } - - /* [42] '<' xmlEndTag ::= '<' '/' Name S? '>' */ - /*[Duplicate]*/ def xEndTag(n: String) = { - xToken('/'); - val m = xName; - if(n != m) reportSyntaxError( "expected closing tag of " + n/* +", not "+m*/); - xSpaceOpt; - xToken('>') - } - - /** '"{char} ) ']]>' - * - * see [15] - */ - /*[Duplicate]*/ def xCharData: Tree = { - xToken('['); - xToken('C'); - xToken('D'); - xToken('A'); - xToken('T'); - xToken('A'); - xToken('['); - val pos1 = pos; - val sb:StringBuffer = new StringBuffer(); - while (true) { - if (ch==']' && - { sb.append( ch ); nextch; ch == ']' } && - { sb.append( ch ); nextch; ch == '>' } ) { - sb.setLength( sb.length() - 2 ); - nextch; - return handle.charData( pos1, sb.toString() ); - } else sb.append( ch ); - nextch; - } - Predef.error("this cannot happen"); - }; - - /** CharRef ::= "&#" '0'..'9' {'0'..'9'} ";" - * | "&#x" '0'..'9'|'A'..'F'|'a'..'f' { hexdigit } ";" - * - * see [66] - */ - /*[Duplicate]*/ def xCharRef:String = { - val hex = ( ch == 'x' ) && { nextch; true }; - val base = if (hex) 16 else 10; - var i = 0; - while (ch != ';') { - ch match { - case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => - i = i * base + Character.digit( ch, base ); - case 'a' | 'b' | 'c' | 'd' | 'e' | 'f' - | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' => - if( !hex ) - reportSyntaxError("hex char not allowed in decimal char ref\n" - +"Did you mean to write &#x ?"); - else - i = i * base + Character.digit( ch, base ); - case _ => - reportSyntaxError("character '"+ch+" not allowed in char ref\n"); - } - nextch; - } - new String(Predef.Array(i.asInstanceOf[char])) - } -/** Comment ::= '' - * - * see [15] - */ - /*[Duplicate]*/ def xComment: Tree = { - val sb:StringBuffer = new StringBuffer(); - xToken('-'); - xToken('-'); - while (true) { - if( ch=='-' && { sb.append( ch ); nextch; ch == '-' } ) { - sb.setLength( sb.length() - 1 ); - nextch; - xToken('>'); - return handle.comment( pos, sb.toString() ); - } else sb.append( ch ); - nextch; - } - Predef.error("this cannot happen"); - }; - - /*[Duplicate]*/ def appendText(pos: int, ts:mutable.Buffer[Tree], txt:String):Unit = { - if( !preserveWS ) - for( val t <- TextBuffer.fromString( txt ).toText ) { - ts.append( handle.text( pos, t.text ) ); - } - else - ts.append( handle.text( pos, txt )); - } - - /*[Duplicate]*/ def content: mutable.Buffer[Tree] = { - var ts = new mutable.ArrayBuffer[Tree]; - var exit = false; - while( !exit ) { - if( xEmbeddedBlock ) { - ts.append( xEmbeddedExpr ); - } else { - tmppos = pos; - ch match { - case '<' => // another tag - nextch; - ch match { - case '/' => - exit = true; // end tag - case '!' => - nextch; - if( '[' == ch ) // CDATA - ts.append( xCharData ); - else // comment - ts.append( xComment ); - case '?' => // PI - nextch; - ts.append( xProcInstr ); - case _ => - ts.append( element ); // child - } - - case '{' => - if( xCheckEmbeddedBlock ) { - ts.append(xEmbeddedExpr); - } else { - val str = new StringBuffer("{"); - str.append( xText ); - appendText(tmppos, ts, str.toString()); - } - // postcond: xEmbeddedBlock == false! - case '&' => // EntityRef or CharRef - nextch; - ch match { - case '#' => // CharacterRef - nextch; - val theChar = handle.text( tmppos, xCharRef ); - xToken(';'); - ts.append( theChar ); - case _ => // EntityRef - val n = xName ; - xToken(';'); - ts.append( handle.entityRef( tmppos, n ) ); - } - case _ => // text content - appendText(tmppos, ts, xText); - // here xEmbeddedBlock might be true - } - } - } - ts - } /* end content */ - - /** '<' element ::= xmlTag1 '>' { xmlExpr | '{' simpleExpr '}' } ETag - * | xmlTag1 '/' '>' - */ - /*[Duplicate]*/ def element: Tree = { - val pos1 = pos; - val Tuple2(qname, attrMap) = xTag; - //Console.println("MarkupParser::element("+qname+","+attrMap+")"); - if (ch == '/') { // empty element - xToken('/'); - xToken('>'); - handle.element( pos1, qname, attrMap, new mutable.ListBuffer[Tree] ); - } - else { // handle content - xToken('>'); - debugLastStartElement.push(Pair(pos1,qname)); - val ts = content; - xEndTag( qname ); - debugLastStartElement.pop; - handle.element( pos1, qname, attrMap, ts ); - } - } - - - /** Name ::= (Letter | '_' | ':') (NameChar)* - * - * see [5] of XML 1.0 specification - */ - /*[Duplicate]*/ def xName: String = { - if( xml.Parsing.isNameStart( ch ) ) { - do { - putChar( ch ); - nextch; - } while( xml.Parsing.isNameChar( ch ) ); - val n = cbuf.toString().intern(); - cbuf.setLength( 0 ); - n - } else { - reportSyntaxError( "name expected, but char '"+ch+"' cannot start a name" ); - new String(); - } - } - - - /** scan [S] '=' [S]*/ - /*[Duplicate]*/ def xEQ = { xSpaceOpt; xToken('='); xSpaceOpt } - - /** skip optional space S? */ - /*[Duplicate]*/ def xSpaceOpt = { while( xml.Parsing.isSpace( ch ) ) { nextch; }} - - /** scan [3] S ::= (#x20 | #x9 | #xD | #xA)+ */ - /*[Duplicate]*/ def xSpace = { - if (xml.Parsing.isSpace(ch)) { - nextch; xSpaceOpt - } - else { - reportSyntaxError("whitespace expected"); - } - } - -/** '?' {Char})]'?>' - * - * see [15] - */ - /*[Duplicate]*/ def xProcInstr: Tree = { - val sb:StringBuffer = new StringBuffer(); - val n = xName; - if( xml.Parsing.isSpace( ch ) ) { - xSpace; - while( true ) { - if( ch=='?' && { sb.append( ch ); nextch; ch == '>' } ) { - sb.setLength( sb.length() - 1 ); - nextch; - return handle.procInstr(tmppos, n.toString(), sb.toString()); - } else - sb.append( ch ); - nextch; - } - }; - xToken('?'); - xToken('>'); - return handle.procInstr(tmppos, n.toString(), sb.toString()); - } - - /** parse character data. - * precondition: xEmbeddedBlock == false (we are not in a scala block) - */ - /*[Duplicate]*/ def xText: String = { - if( xEmbeddedBlock ) Predef.error("internal error: encountered embedded block"); // assert - - if( xCheckEmbeddedBlock ) - return "" - else { - var exit = false; - while( !exit ) { - putChar( ch ); - exit = { nextch; xCheckEmbeddedBlock }||( ch == '<' ) || ( ch == '&' ); - } - val str = cbuf.toString(); - cbuf.setLength( 0 ); - str - } - } - //override type Tree = handle.Tree; - //override type Tree = handle.Tree; - - final val PATTERN = true; - final val EXPR = false; - - val enableEmbeddedExpressions: Boolean = true; - - //val cbuf = new StringBuffer(); - - /** append Unicode character to name buffer*/ - //private def putChar(c: char) = cbuf.append( c ); - - /** xLiteral = element { element } - * @return Scala representation of this xml literal - * precondition: s.xStartsXML == true - */ - def xLiteral: Tree = try { - init; - handle.isPattern = false; - val pos = s.currentPos; - var tree = element; - xSpaceOpt; - // parse more XML ? - if (ch == '<') { - val ts = new mutable.ArrayBuffer[Tree](); - ts.append( tree ); - while( ch == '<' ) { - nextch; - //Console.println("DEBUG 1: I am getting char '"+ch+"'"); // DEBUG - ts.append( element ); - xSpaceOpt; - } - tree = handle.makeXMLseq( pos, ts ); - } - //Console.println("out of xLiteral, parsed:"+tree.toString()); - s.next.token = EMPTY; - s.nextToken(); /* s.fetchToken(); */ - tree - } - catch { - case _:ArrayIndexOutOfBoundsException => - s.syntaxError(debugLastStartElement.top._1, - "missing end tag in XML literal for <" - +debugLastStartElement.top._2+">"); - EmptyTree; - } - - /** @see xmlPattern. resynchronizes after succesful parse - * @return this xml pattern - * precondition: s.xStartsXML == true - */ - def xLiteralPattern:Tree = try { - init; - val oldMode = handle.isPattern; - handle.isPattern = true; - val pos = s.currentPos; - var tree = xPattern; xSpaceOpt; - //if (ch == '<') { - var ts: List[Tree] = List(); - ts = tree :: ts; - - s.next.token = EMPTY; s.nextToken(); /* ?????????? */ - while( token == Tokens.XMLSTART ) {// ??????????????????????????? - //while (ch == '<' /* && lookahead != '-'*/) { - nextch; - //Console.println("DEBUG 2: I am getting char '"+ch+"'"); // DEBUG - ts = xPattern :: ts; - //xSpaceOpt; // ???? - s.next.token = EMPTY; s.nextToken(); /* ?????????? */ - //Console.println("DEBUG 3: resync'ed, token = '"+s+"'"); // DEBUG - } - //Console.println("current token == "+s); - tree = handle.makeXMLseqPat( pos, ts.reverse ); - //} - handle.isPattern = oldMode; - //Console.println("out of xLiteralPattern, parsed:"+tree.toString()); - // s.next.token = EMPTY; // ?? - // s.nextToken(); /* s.fetchToken(); */ // ?? - tree - }catch { - case _:ArrayIndexOutOfBoundsException => - s.syntaxError(debugLastStartElement.top._1, - "missing end tag in XML literal for <" - +debugLastStartElement.top._2+">"); - EmptyTree; - } - - def xEmbeddedExpr:Tree = { - sync; - val b = p.expr(true,false); - if(/*s.*/token != RBRACE) - reportSyntaxError(" expected end of Scala block"); - init; - //Console.println("[out of xScalaExpr s.ch = "+s.ch+" ch="+ch+"]"); - return b - } - - /** xScalaPatterns ::= patterns - */ - def xScalaPatterns: List[Tree] = { - sync; - val b = p.patterns(); - if (/*s.*/token != RBRACE) - reportSyntaxError(" expected end of Scala patterns"); - init; - return b - } - - //var ch: Char = _; - - /** this method assign the next character to ch and advances in input */ - def nextch: Unit = { s.in.next; /*s.xNext;*/ ch = s.in.ch ; pos = s.currentPos; } - - //def lookahead = { s.xLookahead } - - def init: Unit = { - ch = s.in.ch; - pos = s.currentPos; - //Console.println("\ninit! ch = "+ch); - } - - def reportSyntaxError(str: String) = { - s.syntaxError("in XML literal: " + str); - nextch; - } - - def sync: Unit = { - xEmbeddedBlock = false; - s.xSync; - } - - /** '<' xPattern ::= Name [S] { xmlPattern | '{' pattern3 '}' } ETag - * | Name [S] '/' '>' - */ - def xPattern:Tree = { - //Console.println("xPattern"); - val pos1 = pos; - val qname = xName; - debugLastStartElement.push(Pair(pos1,qname)); - xSpaceOpt; - if( ch == '/' ) { // empty tag - nextch; - xToken('>'); - return handle.makeXMLpat( pos1, qname, new mutable.ArrayBuffer[Tree]() ); - }; - - // else: tag with content - xToken('>'); - var ts = new mutable.ArrayBuffer[Tree]; - var exit = false; - while (! exit) { - val pos2 = pos; - if( xEmbeddedBlock ) { - ts ++ xScalaPatterns; - } else - ch match { - case '<' => { // tag - nextch; - if( ch != '/' ) { //child - ts.append( xPattern ); - } else { - exit = true - } - } - case '{' => // embedded Scala patterns - while( ch == '{' ) { - s.in.next; - ts ++ xScalaPatterns; - } - // postcond: xEmbeddedBlock = false; - if (xEmbeddedBlock) Predef.error("problem with embedded block"); // assert - case _ => // teMaxt - appendText( pos2, ts, xText ); - // here xEmbeddedBlock might be true; - //if( xEmbeddedBlock ) throw new ApplicationError("after:"+text); // assert - } - } - xEndTag(qname); - debugLastStartElement.pop; - handle.makeXMLpat(pos1, qname, ts); - } - -} /* class MarkupParser */ -} diff --git a/sources/scala/tools/nsc/ast/parser/Parsers.scala b/sources/scala/tools/nsc/ast/parser/Parsers.scala deleted file mode 100644 index 0634ace4d0..0000000000 --- a/sources/scala/tools/nsc/ast/parser/Parsers.scala +++ /dev/null @@ -1,1808 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.ast.parser; - -import scala.tools.nsc.util.Position; -import util.ListBuffer; -import symtab.Flags; -import Tokens._; - -/** Performs the following context-free rewritings: - * (1) Places all pattern variables in Bind nodes. In a pattern, for identifiers `x': - * x => x @ _ - * x:T => x @ (_ : T) - * - * (2) Removes pattern definitions (PatDef's) as follows: - * If pattern is a simple (typed) identifier: - * val x = e ==> val x = e - * val x: T = e ==> val x: T = e - * - * if there are no variables in pattern - * val p = e ==> e.match (case p => ()) - * - * if there is exactly one variable in pattern - * val x_1 = e.match (case p => (x_1)) - * - * if there is more than one variable in pattern - * val p = e ==> private synthetic val t$ = e.match (case p => (x_1, ..., x_N)) - * val x_1 = t$._1 - * ... - * val x_N = t$._N - * - * (3) Removes function types as follows: - * (argtpes) => restpe ==> scala.Function_n[argtpes, restpe] - * - * (4) Wraps naked case definitions in a match as follows: - * { cases } ==> (x => x.match {cases}), except when already argument to match - */ -[_trait_] abstract class Parsers: SyntaxAnalyzer { - - import global._; - import posAssigner.atPos; - - class Parser(unit: CompilationUnit) { - - val in = new Scanner(unit); - - /** the markup parser */ - val xmlp = new MarkupParser(unit, in, Parser.this, true); - - object treeBuilder extends TreeBuilder { - val global: Parsers.this.global.type = Parsers.this.global; - def freshName(prefix: String): Name = unit.fresh.newName(prefix); - } - import treeBuilder._; - - object symbXMLBuilder extends SymbolicXMLBuilder(treeBuilder, Parser.this, true) { // DEBUG choices - val global: Parsers.this.global.type = Parsers.this.global; - def freshName(prefix: String): Name = unit.fresh.newName(prefix); - } - - /** this is the general parse method - */ - def parse(): Tree = { - val t = compilationUnit(); - accept(EOF); - t - } - -/////// ERROR HANDLING ////////////////////////////////////////////////////// - - private def skip(): unit = { - //System.out.println(" " + in.token2string(in.token));//DEBUG - var nparens = 0; - var nbraces = 0; - while (true) { - in.token match { - case EOF => - return; - case SEMI => - if (nparens == 0 && nbraces == 0) return; - case NEWLINE => - if (nparens == 0 && nbraces == 0) return; - case RPAREN => - nparens = nparens - 1; - case RBRACE => - if (nbraces == 0) return; - nbraces = nbraces - 1; - case LPAREN => - nparens = nparens + 1; - case LBRACE => - nbraces = nbraces + 1; - case _ => - } - in.nextToken(); - } - } - - def syntaxError(msg: String, skipIt: boolean): unit = - syntaxError(in.currentPos, msg, skipIt); - - def syntaxError(pos: int, msg: String, skipIt: boolean): unit = { - if (pos != in.errpos) { - unit.error(pos, msg); - in.errpos = pos; - } - if (skipIt) skip(); - } - - def accept(token: int): int = { - val pos = in.currentPos; - if (in.token != token) - syntaxError( - if (Position.line(unit.source, in.currentPos) > Position.line(unit.source, in.lastPos)) in.lastPos - else in.currentPos, - in.token2string(token) + " expected but " + - in.token2string(in.token) + " found.", true); - if (in.token == token) in.nextToken(); - pos; - } - - /** SEP = NL | `;' - * NL = `\n' // where allowed - */ - def acceptStatSep(): unit = if (in.token == NEWLINE) in.nextToken() else accept(SEMI); - - def errorTypeTree = TypeTree().setType(ErrorType).setPos(in.currentPos); - def errorTermTree = Literal(Constant(null)).setPos(in.currentPos); - def errorPatternTree = Ident(nme.WILDCARD).setPos(in.currentPos); - -/////// TOKEN CLASSES ////////////////////////////////////////////////////// - - def isModifier: boolean = in.token match { - case ABSTRACT | FINAL | SEALED | PRIVATE | PROTECTED | OVERRIDE | IMPLICIT => true - case _ => false - } - - def isLocalModifier: boolean = in.token match { - case ABSTRACT | FINAL | SEALED => true - case _ => false - } - - def isDefIntro: boolean = in.token match { - case VAL | VAR | DEF | TYPE | OBJECT | - CASEOBJECT | CLASS | CASECLASS | TRAIT => true - case _ => false - } - - def isDclIntro: boolean = in.token match { - case VAL | VAR | DEF | TYPE => true - case _ => false - } - - def isExprIntro: boolean = in.token match { - case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT | - STRINGLIT | SYMBOLLIT | TRUE | FALSE | NULL | IDENTIFIER | - THIS | SUPER | IF | FOR | NEW | USCORE | TRY | WHILE | - DO | RETURN | THROW | LPAREN | LBRACE | XMLSTART => true - case _ => false - } - -/////// COMMENT AND ATTRIBUTE COLLECTION ////////////////////////////////////// - - /** Join the comment associated with a definition - */ - def joinComment(trees: => List[Tree]): List[Tree] = { - val buf = in.docBuffer; - if (buf != null) { - in.docBuffer = null; - trees map (t => DocDef(buf.toString(), t) setPos t.pos) - } else trees - } - -/////// TREE CONSTRUCTION //////////////////////////////////////////////////// - - def scalaDot(name: Name): Tree = - Select(Ident(nme.scala_), name); - def scalaAnyRefConstr: Tree = - scalaDot(nme.AnyRef.toTypeName); - def scalaScalaObjectConstr: Tree = - scalaDot(nme.ScalaObject.toTypeName); - def caseClassConstr: Tree = - scalaDot(nme.CaseClass.toTypeName); - - /** Convert tree to formal parameter list - */ - def convertToParams(t: Tree): List[ValDef] = t match { - case Function(params, TypeTree()) => - params - case Ident(_) | Typed(Ident(_), _) => - List(convertToParam(t)); - case Literal(c) if c.tag == UnitTag => - Nil - case _ => - syntaxError(t.pos, "malformed formal parameter list", false); - Nil - } - - /** Convert tree to formal parameter - */ - def convertToParam(tree: Tree): ValDef = - atPos(tree.pos) { - tree match { - case Ident(name) => - ValDef(Modifiers(Flags.PARAM), name, TypeTree(), EmptyTree) - case Typed(Ident(name), tpe) => - ValDef(Modifiers(Flags.PARAM), name, tpe, EmptyTree) - case _ => - syntaxError(tree.pos, "not a legal formal parameter", false); - ValDef(Modifiers(Flags.PARAM), nme.ERROR, errorTypeTree, EmptyTree) - } - } - - /** Convert (qual)ident to type identifier - */ - def convertToTypeId(tree: Tree): Tree = tree match { - case Ident(name) => - Ident(name.toTypeName).setPos(tree.pos) - case Select(qual, name) => - Select(qual, name.toTypeName).setPos(tree.pos) - case _ => - System.out.println(tree);//debug - syntaxError(tree.pos, "identifier expected", false); - errorTypeTree - } - - /** make closure from tree */ - def makeClosure(tree: Tree): Tree = { - val pname: Name = unit.fresh.newName("x$"); - def insertParam(tree: Tree): Tree = tree match { - case Ident(name) => - Select(Ident(pname), name) - case Select(qual, name) => - Select(insertParam(qual), name) - case Apply(fn, args) => - Apply(insertParam(fn), args) - case TypeApply(fn, args) => - TypeApply(insertParam(fn), args) - case _ => - syntaxError(tree.pos, "cannot convert to closure", false); - errorTermTree - } - Function( - List(ValDef(Modifiers(Flags.PARAM), pname, TypeTree(), EmptyTree)), - insertParam(tree)) - } - -/////// OPERAND/OPERATOR STACK ///////////////////////////////////////////////// - - case class OpInfo(operand: Tree, operator: Name, pos: int); - var opstack: List[OpInfo] = Nil; - - def precedence(operator: Name): int = - if (operator eq nme.ERROR) -1 - else { - val firstCh = operator(0); - if (((firstCh >= 'A') && (firstCh <= 'Z')) || - ((firstCh >= 'a') && (firstCh <= 'z'))) - 1 - else - firstCh match { - case '|' => 2 - case '^' => 3 - case '&' => 4 - case '<' | '>' => 5 - case '=' | '!' => 6 - case ':' => 7 - case '+' | '-' => 8; - case '*' | '/' | '%' => 9; - case _ => 10; - } - } - - def reduceStack(isExpr: boolean, base: List[OpInfo], top0: Tree, prec: int, leftAssoc: boolean): Tree = { - var top = top0; - if (opstack != base && - precedence(opstack.head.operator) == prec && - treeInfo.isLeftAssoc(opstack.head.operator) != leftAssoc) { - syntaxError( - opstack.head.pos, - "left- and right-associative operators with same precedence may not be mixed", - false); - } - while (opstack != base && - (prec < precedence(opstack.head.operator) || - (leftAssoc && prec == precedence(opstack.head.operator)))) { - top = atPos(opstack.head.pos) { - makeBinop(isExpr, opstack.head.operand, opstack.head.operator, top) - } - opstack = opstack.tail; - } - top - } - -/////// IDENTIFIERS AND LITERALS //////////////////////////////////////////////////////////// - - final val MINUS: Name = "-"; - final val PLUS : Name = "+"; - final val BANG : Name = "!"; - final val TILDE: Name = "~"; - final val STAR : Name = "*"; - final val BAR : Name = "|"; - final val OPT : Name = "?"; - final val LT : Name = "<"; - - def ident(): Name = - if (in.token == IDENTIFIER) { - val name = in.name.encode; - in.nextToken(); - name - } else { - accept(IDENTIFIER); - nme.ERROR - } - - /** StableRef ::= StableId - * | [Ident `.'] this - * SimpleType ::= StableRef [`.' type] - */ - def stableRef(thisOK: boolean, typeOK: boolean): Tree = { - var t: Tree = null; - if (in.token == THIS) { - t = atPos(in.skipToken()) { This(nme.EMPTY.toTypeName) } - if (!thisOK || in.token == DOT) - t = { selectors(t, typeOK, accept(DOT)) } - } else if (in.token == SUPER) { - t = atPos(in.skipToken()) { - Super(nme.EMPTY.toTypeName, mixinQualifierOpt()) - } - t = atPos(accept(DOT)) { Select(t, ident()) } - if (in.token == DOT) - t = { selectors(t, typeOK, in.skipToken()) } - } else { - val i = atPos(in.currentPos) { Ident(ident()) } - t = i; - if (in.token == DOT) { - val pos = in.skipToken(); - if (in.token == THIS) { - in.nextToken(); - t = atPos(i.pos) { This(i.name.toTypeName) } - if (!thisOK || in.token == DOT) - t = { selectors(t, typeOK, accept(DOT)) } - } else if (in.token == SUPER) { - in.nextToken(); - t = atPos(i.pos) { Super(i.name.toTypeName, mixinQualifierOpt()) } - t = atPos(accept(DOT)) { Select(t, ident())} - if (in.token == DOT) - t = { selectors(t, typeOK, in.skipToken()) } - } else { - t = { selectors(t, typeOK, pos) } - } - } - } - t - } - - def selectors(t: Tree, typeOK: boolean, pos : Int): Tree = - if (typeOK && in.token == TYPE) { - in.nextToken(); - atPos(pos) { SingletonTypeTree(t) } - } else { - val t1 = atPos(pos) { Select(t, ident()); } - if (in.token == DOT) { selectors(t1, typeOK, in.skipToken()) } - else t1 - } - - /** MixinQualifier ::= `[' Id `]' - */ - def mixinQualifierOpt(): Name = - if (in.token == LBRACKET) { - in.nextToken(); - val name = ident().toTypeName; - accept(RBRACKET); - name - } else { - nme.EMPTY.toTypeName - } - - /** StableId ::= Id - * | StableRef `.' Id - * | [Id '.'] super [MixinQualifier] ` `.' Id - */ - def stableId(): Tree = - stableRef(false, false); - - /** QualId ::= Id {`.' Id} - */ - def qualId(): Tree = { - val id = atPos(in.currentPos) { Ident(ident()) } - if (in.token == DOT) { selectors(id, false, in.skipToken()) } - else id - } - - /** SimpleExpr ::= literal - * | symbol [ArgumentExprs] - * | null - */ - def literal(isPattern: boolean, isNegated: boolean): Tree = { - def litToTree() = atPos(in.currentPos) { - Literal( - in.token match { - case CHARLIT => - Constant(in.intVal.asInstanceOf[char]) - case INTLIT => - Constant(in.intVal(isNegated).asInstanceOf[int]) - case LONGLIT => - Constant(in.intVal(isNegated)) - case FLOATLIT => - Constant(in.floatVal(isNegated).asInstanceOf[float]) - case DOUBLELIT => - Constant(in.floatVal(isNegated)) - case STRINGLIT | SYMBOLLIT => - Constant(in.name.toString()) - case TRUE => - Constant(true) - case FALSE => - Constant(false) - case NULL => - Constant(null) - case _ => - syntaxError("illegal literal", true); - null - }) - } - - val isSymLit = in.token == SYMBOLLIT; - val t = litToTree(); - val pos = in.skipToken(); - if (isSymLit) { - atPos(pos) { - var symid = scalaDot(nme.Symbol); - if (isPattern) { symid = convertToTypeId(symid) } - Apply(symid, List(t)) - } - } else { - t - } - } - - def newLineOpt(): unit = if (in.token == NEWLINE) in.nextToken(); - -//////// TYPES /////////////////////////////////////////////////////////////// - - /** TypedOpt ::= [`:' Type] - */ - def typedOpt(): Tree = - if (in.token == COLON) { in.nextToken(); typ() } - else TypeTree(); - - /** RequiresTypedOpt ::= [`:' SimpleType | requires SimpleType] - */ - def requiresTypeOpt(): Tree = - if (in.token == COLON | in.token == REQUIRES) { in.nextToken(); simpleType() } - else TypeTree(); - - /** Types ::= Type {`,' Type} - */ - def types(): List[Tree] = { - val ts = new ListBuffer[Tree] + typ(); - while (in.token == COMMA) { - in.nextToken(); - ts += typ(); - } - ts.toList - } - - /** Type ::= Type1 `=>' Type - * | `(' [Types] `)' `=>' Type - * | Type1 - */ - def typ(): Tree = { - val t = - if (in.token == LPAREN) { - in.nextToken(); - if (in.token == RPAREN) { - in.nextToken(); - atPos(accept(ARROW)) { makeFunctionTypeTree(List(), typ()) } - } else { - val t0 = typ(); - if (in.token == COMMA) { - in.nextToken(); - val ts = new ListBuffer[Tree] + t0 ++ types(); - accept(RPAREN); - atPos (accept(ARROW)) { makeFunctionTypeTree(ts.toList, typ()) } - } else { - accept(RPAREN); t0 - } - } - } else { - type1() - } - if (in.token == ARROW) atPos(in.skipToken()) { - makeFunctionTypeTree(List(t), typ()) } - else t - } - - /** Type1 ::= SimpleType {with SimpleType} [Refinement] - */ - def type1(): Tree = { - val pos = in.currentPos; - var ts = new ListBuffer[Tree] + simpleType(); - while (in.token == WITH) { - in.nextToken(); ts += simpleType() - } - atPos(pos) { - if (in.token == LBRACE) CompoundTypeTree(Template(ts.toList, refinement())) - else makeIntersectionTypeTree(ts.toList) - } - } - - /** SimpleType ::= SimpleType TypeArgs - * | SimpleType `#' Id - * | StableId - * | StableRef `.' type - * | `(' Type `)' - */ - def simpleType(): Tree = { - val pos = in.currentPos; - var t: Tree = - if (in.token == LPAREN) { - in.nextToken(); - val t = typ(); - accept(RPAREN); - t - } else { - val r = stableRef(false, true); - val x = r match { - case SingletonTypeTree(_) => r - case _ => convertToTypeId(r); - } - // System.err.println("SIMPLE_TYPE: " + r.pos + " " + r + " => " + x.pos + " " + x); - x; - } - while (true) { - if (in.token == HASH) - t = atPos(in.skipToken()) { - SelectFromTypeTree(t, ident().toTypeName); - } - else if (in.token == LBRACKET) - t = atPos(pos) { AppliedTypeTree(t, typeArgs()) } - else - return t - } - null; //dummy - } - - /** TypeArgs ::= `[' Types `]' - */ - def typeArgs(): List[Tree] = { - accept(LBRACKET); - val ts = types(); - accept(RBRACKET); - ts - } - -//////// EXPRESSIONS //////////////////////////////////////////////////////// - - /** EqualsExpr ::= `=' Expr - */ - def equalsExpr(): Tree = { - accept(EQUALS); - expr() - } - - /** Exprs ::= Expr {`,' Expr} [ `:' `_' `*' ] - */ - def exprs(): List[Tree] = { - val ts = new ListBuffer[Tree] + expr(true, false); - while (in.token == COMMA) { - in.nextToken(); ts += expr(true, false) - } - ts.toList - } - - /** Expr ::= Bindings `=>' Expr - * | Expr1 - * ResultExpr ::= Bindings `=>' Block - * | Expr1 - * Expr1 ::= if (' Expr `)' [NL] Expr [[`;'] else Expr] - * | try `{' block `}' [catch `{' caseClauses `}'] [finally Expr] - * | while `(' Expr `)' [NL] Expr - * | do Expr [SEP] while `(' Expr `)' - * | for (`(' Enumerators `)' | '{' Enumerators '}') [NL] (yield) Expr - * | throw Expr - * | return [Expr] - * | [SimpleExpr `.'] Id `=' Expr - * | SimpleExpr ArgumentExprs `=' Expr - * | `.' SimpleExpr - * | PostfixExpr [`:' Type1] - * | PostfixExpr match `{' caseClauses `}' - * Bindings ::= Id [`:' Type1] - * | `(' [Binding {`,' Binding}] `)' - * Binding ::= Id [`:' Type] - */ - def expr(): Tree = - expr(false, false); - - def expr(isArgument: boolean, isInBlock: boolean): Tree = in.token match { - case IF => - val pos = in.skipToken(); - accept(LPAREN); - val cond = expr(); - accept(RPAREN); - newLineOpt(); - val thenp = expr(); - val elsep = - if (in.token == ELSE) { in.nextToken(); expr() } - else EmptyTree; - atPos(pos) { If(cond, thenp, elsep) } - case TRY => - atPos(in.skipToken()) { - accept(LBRACE); - val body = block(); - accept(RBRACE); - val catches = - if (in.token == CATCH) { - in.nextToken(); - accept(LBRACE); - val cases = caseClauses(); - accept(RBRACE); - cases - } else List(); - val finalizer = - if (in.token == FINALLY) { in.nextToken(); expr() } - else EmptyTree; - Try(body, catches, finalizer) - } - case WHILE => - val lname: Name = unit.fresh.newName("label$"); - val pos = in.skipToken(); - accept(LPAREN); - val cond = expr(); - accept(RPAREN); - newLineOpt(); - val body = expr(); - atPos(pos) { makeWhile(lname, cond, body) } - case DO => - val lname: Name = unit.fresh.newName("label$"); - val pos = in.skipToken(); - val body = expr(); - if (in.token == SEMI || in.token == NEWLINE) in.nextToken(); - accept(WHILE); - accept(LPAREN); - val cond = expr(); - accept(RPAREN); - atPos(pos) { makeDoWhile(lname, body, cond) } - case FOR => - atPos(in.skipToken()) { - val startToken = in.token; - accept(if (startToken == LBRACE) LBRACE else LPAREN); - val enums = enumerators(); - accept(if (startToken == LBRACE) RBRACE else RPAREN); - newLineOpt(); - if (in.token == YIELD) { - in.nextToken(); makeForYield(enums, expr()) - } else makeFor(enums, expr()) - } - case RETURN => - atPos(in.skipToken()) { - Return(if (isExprIntro) expr() else Literal(())) - } - case THROW => - atPos(in.skipToken()) { - Throw(expr()) - } - case DOT => - atPos(in.skipToken()) { - if (in.token == IDENTIFIER) makeClosure(simpleExpr()) - else { syntaxError("identifier expected", true); errorTermTree } - } - case _ => - var t = postfixExpr(); - if (in.token == EQUALS) { - t match { - case Ident(_) | Select(_, _) | Apply(_, _) => - t = atPos(in.skipToken()) { makeAssign(t, expr()) } - case _ => - } - } else if (in.token == COLON) { - val pos = in.skipToken(); - if (isArgument && in.token == USCORE) { - val pos1 = in.skipToken(); - if (in.token == IDENTIFIER && in.name == nme.STAR) { - in.nextToken(); - t = atPos(pos) { - Typed(t, atPos(pos1) { Ident(nme.WILDCARD_STAR.toTypeName) }) - } - } else { - syntaxError(in.currentPos, "`*' expected", true); - } - } else { - t = atPos(pos) { Typed(t, type1()) } - } - } else if (in.token == MATCH) { - t = atPos(in.skipToken()) { - accept(LBRACE); - val cases = caseClauses(); - accept(RBRACE); - Match(t, cases): Tree - } - } - if (in.token == ARROW) { - t = atPos(in.skipToken()) { - Function(convertToParams(t), if (isInBlock) block() else expr()) - } - } - t - } - - /** PostfixExpr ::= [`.'] InfixExpr [Id] - * InfixExpr ::= PrefixExpr - * | InfixExpr Id InfixExpr - */ - def postfixExpr(): Tree = { - val base = opstack; - var top = prefixExpr(); - while (in.token == IDENTIFIER) { - top = reduceStack( - true, base, top, precedence(in.name), treeInfo.isLeftAssoc(in.name)); - opstack = OpInfo(top, in.name, in.currentPos) :: opstack; - ident(); - if (isExprIntro) { - top = prefixExpr(); - } else { - val topinfo = opstack.head; - opstack = opstack.tail; - return Select( - reduceStack(true, base, topinfo.operand, 0, true), - topinfo.operator.encode).setPos(topinfo.pos); - } - } - reduceStack(true, base, top, 0, true) - } - - /** PrefixExpr ::= [`-' | `+' | `~' | `!'] SimpleExpr - */ - def prefixExpr(): Tree = - if (in.token == IDENTIFIER && in.name == MINUS) { - val name = ident(); - in.token match { - case INTLIT | LONGLIT | FLOATLIT | DOUBLELIT => literal(false, true) - case _ => atPos(in.currentPos) { Select(simpleExpr(), name) } - } - } else if (in.token == IDENTIFIER && (in.name == PLUS || in.name == TILDE || in.name == BANG)) { - val pos = in.currentPos; - val name = ident(); - atPos(pos) { Select(simpleExpr(), name) } - } else { - simpleExpr() - } - - /* SimpleExpr ::= new SimpleType {`(' [Exprs] `)'} {`with' SimpleType} [TemplateBody] - * | SimpleExpr1 - * SimpleExpr1 ::= literal - * | xLiteral - * | StableRef - * | `(' [Expr] `)' - * | BlockExpr - * | SimpleExpr `.' Id - * | SimpleExpr TypeArgs - * | SimpleExpr1 ArgumentExprs - */ - def simpleExpr(): Tree = { - var t: Tree = null; - var isNew = false; - in.token match { - case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT | STRINGLIT | - SYMBOLLIT | TRUE | FALSE | NULL => - t = literal(false, false); - case XMLSTART => - t = xmlp.xLiteral; - //Console.println("successfully parsed XML at "+t); // DEBUG - case IDENTIFIER | THIS | SUPER => - t = stableRef(true, false); - case LPAREN => - val pos = in.skipToken(); - if (in.token == RPAREN) { - in.nextToken(); - t = Literal(()).setPos(pos); - } else { - t = expr(); - if (in.token == COMMA) { - val commapos = in.skipToken(); - val ts = new ListBuffer[Tree] + t ++ exprs(); - accept(RPAREN); - if (in.token == ARROW) { - t = atPos(pos) { - Function(ts.toList map convertToParam, TypeTree()) - } - } else { - syntaxError(commapos, "`)' expected", false); - } - } else { - accept(RPAREN); - } - } - case LBRACE => - t = blockExpr() - case NEW => - t = atPos(in.skipToken()) { - val parents = new ListBuffer[Tree] + simpleType(); - val argss = new ListBuffer[List[Tree]]; - if (in.token == LPAREN) - do { argss += argumentExprs() } while (in.token == LPAREN) - else argss += List(); - while (in.token == WITH) { - in.nextToken(); - parents += simpleType() - } - val stats = if (in.token == LBRACE) templateBody() else List(); - makeNew(parents.toList, stats, argss.toList) - } - isNew = true - case _ => - syntaxError("illegal start of simple expression", true); - t = errorTermTree - } - while (true) { - in.token match { - case DOT => - t = atPos(in.skipToken()) { Select(t, ident()) } - case LBRACKET => - t match { - case Ident(_) | Select(_, _) => - t = atPos(in.currentPos) { TypeApply(t, typeArgs()) } - case _ => - return t; - } - case LPAREN | LBRACE if (!isNew) => - t = atPos(in.currentPos) { Apply(t, argumentExprs()) } - case _ => - return t - } - isNew = false - } - null;//dummy - } - - /** ArgumentExprs ::= `(' [Exprs] `)' - * | BlockExpr - */ - def argumentExprs(): List[Tree] = { - if (in.token == LBRACE) { - List(blockExpr()) - } else { - accept(LPAREN); - val ts = if (in.token == RPAREN) List() else exprs(); - accept(RPAREN); - ts - } - } - - /** BlockExpr ::= `{' CaseClauses | Block `}' - */ - def blockExpr(): Tree = { - val res = atPos(accept(LBRACE)) { - if (in.token == CASE) makeVisitor(caseClauses()) - else block() - } - accept(RBRACE); - res - } - - /** Block ::= BlockStatSeq - */ - def block(): Tree = makeBlock(blockStatSeq(new ListBuffer[Tree])); - - /** CaseClauses ::= CaseClause {CaseClause} - */ - def caseClauses(): List[CaseDef] = { - val ts = new ListBuffer[CaseDef]; - do { ts += caseClause(); - } while (in.token == CASE); - ts.toList - } - - /** caseClause : =>= case Pattern [if PostfixExpr] `=>' Block - */ - def caseClause(): CaseDef = - atPos(accept(CASE)) { - val pat = pattern(); - val guard = - if (in.token == IF) { in.nextToken(); postfixExpr() } - else EmptyTree; - makeCaseDef(pat, guard, atPos(accept(ARROW))(block())) - } - - /** Enumerators ::= Generator {SEP Enumerator} - * Enumerator ::= Generator - * | Expr - */ - def enumerators(): List[Tree] = { - val enums = new ListBuffer[Tree] + generator(); - while (in.token == SEMI || in.token == NEWLINE) { - in.nextToken(); - enums += (if (in.token == VAL) generator() else expr()) - } - enums.toList - } - - /** Generator ::= val Pattern1 `<-' Expr - */ - def generator(): Tree = - atPos(accept(VAL)) { - makeGenerator(pattern1(false), { accept(LARROW); expr() }) - } - -//////// PATTERNS //////////////////////////////////////////////////////////// - - /** Patterns ::= SeqPattern { , SeqPattern } */ - def patterns(): List[Tree] = { - val ts = new ListBuffer[Tree]; - ts += pattern(true); - while (in.token == COMMA) { - in.nextToken(); ts += pattern(true); - } - ts.toList - } - - /** Pattern ::= Pattern1 { `|' Pattern1 } - * SeqPattern ::= SeqPattern1 { `|' SeqPattern1 } - */ - def pattern(seqOK: boolean): Tree = { - val pos = in.currentPos; - val t = pattern1(seqOK); - if (in.token == IDENTIFIER && in.name == BAR) { - val ts = new ListBuffer[Tree] + t; - while (in.token == IDENTIFIER && in.name == BAR) { - in.nextToken(); ts += pattern1(seqOK); - } - atPos(pos) { makeAlternative(ts.toList) } - } else t - } - - def pattern(): Tree = pattern(false); - - /** Pattern1 ::= varid `:' Type1 - * | `_' `:' Type1 - * | Pattern2 - * SeqPattern1 ::= varid `:' Type1 - * | `_' `:' Type1 - * | [SeqPattern2] - */ - def pattern1(seqOK: boolean): Tree = - if (seqOK && !isExprIntro) { - atPos(in.currentPos) { Sequence(List()) } - } else { - val p = pattern2(seqOK); - p match { - case Ident(name) if (treeInfo.isVariableName(name) && in.token == COLON) => - atPos(in.skipToken()) { Typed(p, type1()) } - case _ => - p - } - } - - /* Pattern2 ::= varid [ @ Pattern3 ] - * | Pattern3 - * SeqPattern2 ::= varid [ @ SeqPattern3 ] - * | SeqPattern3 - */ - def pattern2(seqOK: boolean): Tree = { - val p = pattern3(seqOK); - if (in.token == AT) { - p match { - case Ident(name) => - if (name == nme.WILDCARD) { - in.nextToken(); pattern3(seqOK) - } else if (treeInfo.isVariableName(name)) { - atPos(in.skipToken()) { Bind(name, pattern3(seqOK)) } - } else { - p - } - case _ => - p - } - } else p - } - - /* Pattern3 ::= SimplePattern - * | SimplePattern {Id SimplePattern} - * SeqPattern3 ::= SeqSimplePattern [ '*' | '?' | '+' ] - * | SeqSimplePattern {Id SeqSimplePattern} - */ - def pattern3(seqOK: boolean): Tree = { - val base = opstack; - var top = simplePattern(seqOK); - if (seqOK && in.token == IDENTIFIER) { - if (in.name == STAR) - return atPos(in.skipToken())(Star(top)) - else if (in.name == PLUS) - return atPos(in.skipToken())(makePlus(top)) - else if (in.name == OPT) - return atPos(in.skipToken())(makeOpt(top)) - } - while (in.token == IDENTIFIER && in.name != BAR) { - top = reduceStack( - false, base, top, precedence(in.name), treeInfo.isLeftAssoc(in.name)); - opstack = OpInfo(top, in.name, in.currentPos) :: opstack; - ident(); - top = simplePattern(seqOK) - } - reduceStack(false, base, top, 0, true) - } - - /** SimplePattern ::= varid - * | `_' - * | literal - * | `<' xLiteralPattern - * | StableId [ `(' Patterns `)' ] - * | `(' [Pattern] `)' - * SimpleSeqPattern ::= varid - * | `_' - * | literal - * | `<' xLiteralPattern - * | StableId [ `(' Patterns `)' ] - * | `(' Patterns `)' - */ - def simplePattern(seqOK: boolean): Tree = in.token match { - case IDENTIFIER | THIS => - var t = stableId(); - in.token match { - case INTLIT | LONGLIT | FLOATLIT | DOUBLELIT => - t match { - case Ident(name) if name == nme.MINUS => - return literal(true, true); - case _ => - } - case _ => - } - if (in.token == LPAREN) { - atPos(in.skipToken()) { - val ps = if (in.token == RPAREN) List() else patterns(); - accept(RPAREN); - Apply(convertToTypeId(t), ps) - } - } else t - case USCORE => - atPos(in.skipToken()) { Ident(nme.WILDCARD) } - case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT | STRINGLIT | SYMBOLLIT | TRUE | FALSE | NULL => - literal(true, false) - case LPAREN => - val pos = in.skipToken(); - val p = - if (seqOK) atPos(pos) { makeSequence(patterns()) } - else if (in.token != RPAREN) pattern(false); - else Literal(()).setPos(pos); - accept(RPAREN); - p - case XMLSTART => - val r = xmlp.xLiteralPattern; - //Console.println("successfully parsed xml pattern "+r); DEBUG - r - case _ => - syntaxError("illegal start of simple pattern", true); - errorPatternTree - } - -////////// MODIFIERS //////////////////////////////////////////////////////////// - - /** Modifiers ::= {Modifier} - * Modifier ::= final - * | private [ "[" Id "]" ] - * | protected - * | override - * | abstract - */ - def modifiers(): Modifiers = { - def loop(mods: int): int = in.token match { - case ABSTRACT => - loop(addMod(mods, Flags.ABSTRACT)) - case FINAL => - loop(addMod(mods, Flags.FINAL)) - case SEALED => - loop(addMod(mods, Flags.SEALED)) - case PRIVATE => - loop(addMod(mods, Flags.PRIVATE)) - case PROTECTED => - loop(addMod(mods, Flags.PROTECTED)) - case OVERRIDE => - loop(addMod(mods, Flags.OVERRIDE)) - case IMPLICIT => - loop(addMod(mods, Flags.IMPLICIT)) - case _ => - mods - } - var mods = loop(0); - if ((mods & (Flags.ABSTRACT | Flags.OVERRIDE)) == (Flags.ABSTRACT | Flags.OVERRIDE)) - mods = mods & ~(Flags.ABSTRACT | Flags.OVERRIDE) | Flags.ABSOVERRIDE; - Modifiers(mods) - } - - /** LocalClassModifiers ::= {LocalClassModifier} - * LocalClassModifier ::= final - * | private - */ - def localClassModifiers(): Modifiers = { - def loop(mods: int): int = in.token match { - case ABSTRACT => - loop(addMod(mods, Flags.ABSTRACT)) - case FINAL => - loop(addMod(mods, Flags.FINAL)) - case SEALED => - loop(addMod(mods, Flags.SEALED)) - case _ => - mods - } - Modifiers(loop(0)) - } - - private def addMod(mods: int, mod: int): int = { - if ((mods & mod) != 0) - syntaxError(in.currentPos, "repeated modifier", false); - in.nextToken(); - mods | mod; - } - -//////// PARAMETERS ////////////////////////////////////////////////////////// - - /** ParamClauses ::= {`(' [Param {`,' Param}] ')'} - * [`(' implicit Param {`,' Param} `)'] - * Param ::= Id `:' ParamType - * ClassParamClauses ::= {`(' [ClassParam {`' ClassParam}] ')'} - * [`(' implicit ClassParam {`,' ClassParam} `)'] - * ClassParam ::= [[modifiers] (val | var)] Param - */ - def paramClauses(owner: Name, implicitViews: List[Tree], ofCaseClass: boolean): List[List[ValDef]] = { - var implicitmod = 0; - var caseParam = ofCaseClass; - def param(): ValDef = { - atPos(in.currentPos) { - var mods = Modifiers(Flags.PARAM); - if (owner.isTypeName) { - mods = modifiers() | Flags.PARAMACCESSOR; - if (in.token == VAL) { - in.nextToken() - } else if (in.token == VAR) { - mods = mods | Flags.MUTABLE; - in.nextToken() - } else { - if (mods.flags != Flags.PARAMACCESSOR) accept(VAL); - if (!(caseParam)) mods = mods | Flags.PRIVATE | Flags.LOCAL; - } - if (caseParam) mods = mods | Flags.CASEACCESSOR; - } - val name = ident(); - accept(COLON); - val bynamemod = if (in.token == ARROW) Flags.BYNAMEPARAM else 0; - ValDef(mods | implicitmod | bynamemod, name, paramType(), EmptyTree) - } - } - def paramClause(): List[ValDef] = { - val params = new ListBuffer[ValDef]; - if (in.token != RPAREN) { - if (in.token == IMPLICIT) { - if (!implicitViews.isEmpty) - syntaxError("cannot have both view bounds `<%' and implicit parameters", false); - in.nextToken(); - implicitmod = Flags.IMPLICIT - } - params += param(); - while (in.token == COMMA) { - in.nextToken(); params += param() - } - } - params.toList - } - val vds = new ListBuffer[List[ValDef]]; - val pos = in.currentPos; - while (implicitmod == 0 && in.token == LPAREN) { - in.nextToken(); - vds += paramClause(); - accept(RPAREN); - caseParam = false - } - val result = vds.toList; - if (owner == nme.CONSTRUCTOR && - (result.isEmpty || - (!result.head.isEmpty && result.head.head.mods.hasFlag(Flags.IMPLICIT)))) - if (in.token == LBRACKET) - syntaxError(pos, "no type parameters allowed here", false); - else - syntaxError(pos, "auxiliary constructor needs non-implicit parameter list", false); - addImplicitViews(owner, result, implicitViews) - } - - /** ParamType ::= Type | `=>' Type | Type `*' - */ - def paramType(): Tree = - if (in.token == ARROW) - atPos(in.skipToken()) { - AppliedTypeTree( - scalaDot(nme.BYNAME_PARAM_CLASS_NAME.toTypeName), List(typ())) - } - else { - val t = typ(); - if (in.token == IDENTIFIER && in.name == STAR) { - in.nextToken(); - atPos(t.pos) { - AppliedTypeTree( - scalaDot(nme.REPEATED_PARAM_CLASS_NAME.toTypeName), List(t)) - } - } else t - } - - /** TypeParamClauseOpt ::= [`[' TypeParam {`,' TypeParam} `]'] - * TypeParam ::= [`+' | `-'] FunTypeParam - * FunTypeParamClauseOpt ::= [`[' FunTypeParam {`,' FunTypeParam} `]'] - * FunTypeParam ::= Id TypeBounds - */ - def typeParamClauseOpt(owner: Name, implicitViews: ListBuffer[Tree]): List[AbsTypeDef] = { - def typeParam(): AbsTypeDef = { - var mods = Modifiers(Flags.PARAM); - if (owner.isTypeName && in.token == IDENTIFIER) { - if (in.name == PLUS) { - in.nextToken(); - mods = mods | Flags.COVARIANT; - } else if (in.name == MINUS) { - in.nextToken(); - mods = mods | Flags.CONTRAVARIANT; - } - } - val pname = ident(); - val param = atPos(in.currentPos) { typeBounds(mods, pname) } - if (in.token == VIEWBOUND && (implicitViews != null)) - implicitViews += atPos(in.skipToken()) { - makeFunctionTypeTree(List(Ident(pname.toTypeName)), typ()) - } - param - } - val params = new ListBuffer[AbsTypeDef]; - if (in.token == LBRACKET) { - in.nextToken(); - params += typeParam(); - while (in.token == COMMA) { - in.nextToken(); - params += typeParam(); - } - accept(RBRACKET); - } - params.toList - } - - /** TypeBounds ::= [`>:' Type] [`<:' Type] - */ - def typeBounds(mods: Modifiers, name: Name): AbsTypeDef = { - def bound(tok: int, default: Name): Tree = - if (in.token == tok) { in.nextToken(); typ() } - else scalaDot(default.toTypeName); - AbsTypeDef(mods, name.toTypeName, - bound(SUPERTYPE, nme.All), - bound(SUBTYPE, nme.Any)) - } - -//////// DEFS //////////////////////////////////////////////////////////////// - - - /** Import ::= import ImportExpr {`,' ImportExpr} - */ - def importClause(): List[Tree] = { - accept(IMPORT); - val ts = new ListBuffer[Tree] + importExpr(); - while (in.token == COMMA) { - in.nextToken(); ts += importExpr(); - } - ts.toList - } - - /** ImportRef ::= StableId `.' (Id | `_' | ImportSelectors) - */ - def importExpr(): Tree = - atPos(in.currentPos) { - var t: Tree = null; - var pos = 0; - if (in.token == THIS) { - t = atPos(in.currentPos) { This(nme.EMPTY.toTypeName) } - t = atPos(accept(DOT)) { Select(t, ident()) } - pos = accept(DOT); - } else { - val i = atPos(in.currentPos) { Ident(ident()) } - pos = accept(DOT); - if (in.token == THIS) { - in.nextToken(); - t = atPos(i.pos) { This(i.name.toTypeName) } - t = atPos(accept(DOT)) { Select(t, ident()) } - pos = accept(DOT); - } else { - t = i; - } - } - def loop: Tree = - if (in.token == USCORE) { - in.nextToken(); - Import(t, List(Pair(nme.WILDCARD, null))) - } else if (in.token == LBRACE) { - Import(t, importSelectors()) - } else { - val name = ident(); - if (in.token == DOT) { - t = atPos(pos) { Select(t, name) } - pos = accept(DOT); - loop - } else { - Import(t, List(Pair(name, name))); - } - } - loop - } - - /** ImportSelectors ::= `{' {ImportSelector `,'} (ImportSelector | `_') `}' - */ - def importSelectors(): List[Pair[Name, Name]] = { - val names = new ListBuffer[Pair[Name, Name]]; - accept(LBRACE); - var isLast = importSelector(names); - while (!isLast && in.token == COMMA) { - in.nextToken(); - isLast = importSelector(names); - } - accept(RBRACE); - names.toList - } - - /** ImportSelector ::= Id [`=>' Id | `=>' `_'] - */ - def importSelector(names: ListBuffer[Pair[Name, Name]]): boolean = - if (in.token == USCORE) { - in.nextToken(); names += Pair(nme.WILDCARD, null); true - } else { - val name = ident(); - names += Pair( - name, - if (in.token == ARROW) { - in.nextToken(); - if (in.token == USCORE) { in.nextToken(); nme.WILDCARD } else ident() - } else { - name - }); - false - } - - /** Def ::= val PatDef {`,' PatDef} - * | var VarDef {`,' VatDef} - * | def FunDef {`,' FunDef} - * | type TypeDef {`,' TypeDef} - * | TmplDef - * Dcl ::= val ValDcl {`,' ValDcl} - * | var ValDcl {`,' ValDcl} - * | def FunDcl {`,' FunDcl} - * | type TypeDcl {`,' TypeDcl} - */ - def defOrDcl(mods: Modifiers): List[Tree] = { - in.token match { - case VAL => - patDefOrDcl(mods); - case VAR => - varDefOrDcl(mods); - case DEF => - List(funDefOrDcl(mods)); - case TYPE => - in.nextToken(); - List(typeDefOrDcl(mods)) - case _ => - List(tmplDef(mods)) - } - } - - /** PatDef ::= Pattern2 {`,' Pattern2} [`:' Type] `=' Expr - * ValDcl ::= Id {`,' Id} `:' Type - */ - def patDefOrDcl(mods: Modifiers): List[Tree] = { - var newmods = mods; - var lhs = new ListBuffer[Tree]; - do { - in.nextToken(); - lhs += pattern2(false) - } while (in.token == COMMA); - val tp = typedOpt(); - val rhs = - if (tp.isEmpty || in.token == EQUALS) equalsExpr() - else { - newmods = newmods | Flags.DEFERRED; - EmptyTree - } - def mkDefs(p: Tree): List[Tree] = { - //Console.println("DEBUG: p = "+p.toString()); // DEBUG - val trees = - makePatDef(newmods, - if (tp.isEmpty) - p - else - Typed(p, tp), - rhs.duplicate) map atPos(p.pos); - if (rhs == EmptyTree) { - trees match { - case List(ValDef(_, _, _, EmptyTree)) => - case _ => syntaxError(p.pos, "pattern definition may not be abstract", false); - } - } - trees - } - for (val p <- lhs.toList; val d <- mkDefs(p)) yield d - } - - /** VarDef ::= Id {`,' Id} [`:' Type] `=' Expr - * | Id {`,' Id} `:' Type `=' `_' - * VarDcl ::= Id {`,' Id} `:' Type - */ - def varDefOrDcl(mods: Modifiers): List[Tree] = { - var newmods = mods | Flags.MUTABLE; - val lhs = new ListBuffer[Pair[Int, Name]]; - do { - lhs += Pair(in.skipToken(), ident()) - } while (in.token == COMMA); - val tp = typedOpt(); - val rhs = if (tp.isEmpty || in.token == EQUALS) { - accept(EQUALS); - if (tp != EmptyTree && in.token == USCORE) { - in.nextToken(); - EmptyTree - } else - expr(); - } else { - newmods = newmods | Flags.DEFERRED; - EmptyTree - } - for (val Pair(pos, name) <- lhs.toList) yield - atPos(pos) { ValDef(newmods, name, tp.duplicate, rhs.duplicate) } - } - - /** FunDef ::= FunSig `:' Type `=' Expr - * | this ParamClause ParamClauses `=' ConstrExpr - * FunDcl ::= FunSig `:' Type - * FunSig ::= id [FunTypeParamClause] ParamClauses - */ - def funDefOrDcl(mods: Modifiers): Tree = - atPos(in.skipToken()) { - if (in.token == THIS) { - in.nextToken(); - val vparamss = paramClauses(nme.CONSTRUCTOR, List(), false); - accept(EQUALS); - DefDef(mods, nme.CONSTRUCTOR, List(), vparamss, TypeTree(), constrExpr()) - } else { - var newmods = mods; - val name = ident(); - val implicitViews = new ListBuffer[Tree]; - val tparams = typeParamClauseOpt(name, implicitViews); - val vparamss = paramClauses(name, implicitViews.toList, false); - val restype = typedOpt(); - val rhs = - if (restype.isEmpty || in.token == EQUALS) equalsExpr(); - else { - newmods = newmods | Flags.DEFERRED; - EmptyTree - } - DefDef(newmods, name, tparams, vparamss, restype, rhs) - } - } - - /** ConstrExpr ::= SelfInvocation - * | `{' SelfInvocation {SEP BlockStat} `}' - * SelfInvocation ::= this ArgumentExpr - */ - def constrExpr(): Tree = - if (in.token == LBRACE) { - atPos(in.skipToken()) { - val statlist = new ListBuffer[Tree]; - statlist += selfInvocation(); - val stats = - if (in.token == SEMI || in.token == NEWLINE) { in.nextToken(); blockStatSeq(statlist) } - else statlist.toList; - accept(RBRACE); - makeBlock(stats) - } - } else selfInvocation(); - - /** SelfInvocation ::= this ArgumentExprs - */ - def selfInvocation(): Tree = - atPos(accept(THIS)) { Apply(Ident(nme.CONSTRUCTOR), argumentExprs()) } - - /** TypeDef ::= Id `=' Type - * TypeDcl ::= Id TypeBounds - */ - def typeDefOrDcl(mods: Modifiers): Tree = - atPos(in.currentPos) { - val name = ident().toTypeName; - in.token match { - case LBRACKET => - val tparams = typeParamClauseOpt(name, null); - accept(EQUALS); - AliasTypeDef(mods, name, tparams, typ()) - case EQUALS => - in.nextToken(); - AliasTypeDef(mods, name, List(), typ()) - case SUPERTYPE | SUBTYPE | SEMI | NEWLINE | COMMA | RBRACE => - typeBounds(mods | Flags.DEFERRED, name) - case _ => - syntaxError("`=', `>:', or `<:' expected", true); - EmptyTree - } - } - - /** TmplDef ::= ([case] class | trait) ClassDef - * | [case] object ObjectDef - */ - def tmplDef(mods: Modifiers): Tree = in.token match { - case TRAIT => - classDef(mods | Flags.TRAIT | Flags.ABSTRACT); - case CLASS => - classDef(mods); - case CASECLASS => - classDef(mods | Flags.CASE); - case OBJECT => - objectDef(mods); - case CASEOBJECT => - objectDef(mods | Flags.CASE); - case _ => - syntaxError("illegal start of definition", true); - EmptyTree - } - - /** ClassDef ::= ClassSig RequiresTypeOpt ClassTemplate - * ClassSig ::= Id [TypeParamClause] {ClassParamClause} - */ - def classDef(mods: Modifiers): Tree = - atPos(in.skipToken()) { - val name = ident().toTypeName; - val implicitViews = new ListBuffer[Tree]; - val tparams = typeParamClauseOpt(name, implicitViews); - if (mods.hasFlag(Flags.CASE) && in.token != LPAREN) accept(LPAREN); - val vparamss = paramClauses(name, implicitViews.toList, mods.hasFlag(Flags.CASE)); - val thistpe = requiresTypeOpt(); - val template = classTemplate(mods, name, vparamss); - val mods1 = if (mods.hasFlag(Flags.TRAIT) && (template.body forall treeInfo.isInterfaceMember)) - mods | Flags.INTERFACE - else mods; - ClassDef(mods1, name, tparams, thistpe, template) - } - - /** ObjectDef ::= Id ClassTemplate - */ - def objectDef(mods: Modifiers): Tree = - atPos(in.skipToken()) { - val name = ident(); - val template = classTemplate(mods, name, List()); - ModuleDef(mods, name, template) - } - - /** ClassTemplate ::= [`extends' TemplateParents] [[NL] TemplateBody] - * TemplateParents ::= SimpleType {`(' [Exprs] `)'} {`with' SimpleType} - */ - def classTemplate(mods: Modifiers, name: Name, vparamss: List[List[ValDef]]): Template = { - val ret = atPos(in.currentPos) { - val parents = new ListBuffer[Tree]; - val argss = new ListBuffer[List[Tree]]; - if (in.token == EXTENDS) { - in.nextToken(); - val parent = simpleType(); - // System.err.println("classTempl: " + parent); - parents += parent; - if (in.token == LPAREN) - do { argss += argumentExprs() } while (in.token == LPAREN) - else argss += List(); - while (in.token == WITH) { - in.nextToken(); - parents += simpleType() - } - } else argss += List(); - if (name != nme.ScalaObject.toTypeName) - parents += scalaScalaObjectConstr; - if (mods.hasFlag(Flags.CASE)) parents += caseClassConstr; - val ps = parents.toList; - if (in.token == NEWLINE && in.next.token == LBRACE) in.nextToken(); - var body = - if (in.token == LBRACE) { - templateBody() - } else { - if (!(in.token == SEMI || in.token == NEWLINE || in.token == COMMA || in.token == RBRACE)) - syntaxError("`extends' or `{' expected", true); - List() - } - if (!mods.hasFlag(Flags.TRAIT)) Template(ps, vparamss, argss.toList, body) - else Template(ps, body) - } - ret; - } - -////////// TEMPLATES //////////////////////////////////////////////////////////// - - /** TemplateBody ::= `{' [TemplateStat {SEP TemplateStat}] `}' - */ - def templateBody(): List[Tree] = { - accept(LBRACE); - var body = templateStatSeq(); - if (body.isEmpty) body = List(EmptyTree); - accept(RBRACE); - body - } - - /** Refinement ::= `{' [RefineStat {SEP RefineStat}] `}' - */ - def refinement(): List[Tree] = { - accept(LBRACE); - val body = refineStatSeq(); - accept(RBRACE); - body - } - -/////// STATSEQS ////////////////////////////////////////////////////////////// - - /** Packaging ::= package QualId `{' TopStatSeq `}' - */ - def packaging(): Tree = { - atPos(accept(PACKAGE)) { - val pkg = qualId(); - accept(LBRACE); - val stats = topStatSeq(); - accept(RBRACE); - makePackaging(pkg, stats) - } - } - - /** TopStatSeq ::= [TopStat {SEP TopStat}] - * TopStat ::= AttributeClauses Modifiers ClsDef - * | Packaging - * | Import - * | - */ - def topStatSeq(): List[Tree] = { - val stats = new ListBuffer[Tree]; - while (in.token != RBRACE && in.token != EOF) { - if (in.token == PACKAGE) { - stats += packaging() - } else if (in.token == IMPORT) { - stats ++= importClause() - } else if (in.token == CLASS || - in.token == CASECLASS || - in.token == TRAIT || - in.token == OBJECT || - in.token == CASEOBJECT || - in.token == LBRACKET || - isModifier) { - val attrs = attributeClauses(); - (stats ++ - joinAttributes(attrs, joinComment(List(tmplDef(modifiers() | traitAttribute(attrs)))))) - } else if (in.token != SEMI && in.token != NEWLINE) { - syntaxError("illegal start of class or object definition", true); - } - if (in.token != RBRACE && in.token != EOF) acceptStatSep(); - } - stats.toList - } - - /** TemplateStatSeq ::= TemplateStat {SEP TemplateStat} - * TemplateStat ::= Import - * | AttributeClauses Modifiers Def - * | AttributeClauses Modifiers Dcl - * | Expr - * | - */ - def templateStatSeq(): List[Tree] = { - val stats = new ListBuffer[Tree]; - while (in.token != RBRACE && in.token != EOF) { - if (in.token == IMPORT) { - stats ++= importClause() - } else if (isExprIntro) { - stats += expr() - } else if (isDefIntro || isModifier || in.token == LBRACKET) { - val attrs = attributeClauses(); - (stats ++ - joinAttributes(attrs, joinComment(defOrDcl(modifiers() | traitAttribute(attrs))))) - } else if (in.token != SEMI && in.token != NEWLINE) { - syntaxError("illegal start of definition", true); - } - if (in.token != RBRACE) acceptStatSep(); - } - stats.toList - } - - /** AttributeClauses ::= {AttributeClause} - * AttributeClause ::= `[' Attribute {`,' Attribute} `]' [NL] - */ - def attributeClauses(): List[Tree] = { - var attrs = new ListBuffer[Tree]; - while (in.token == LBRACKET) { - in.nextToken(); - attrs += attribute(); - while (in.token == COMMA) { - in.nextToken(); - attrs += attribute() - } - accept(RBRACKET); - newLineOpt(); - } - attrs.toList - } - - /** Attribute ::= StableId [TypeArgs] [`(' [Exprs] `)'] - */ - def attribute(): Tree = { - val pos = in.currentPos; - var t: Tree = convertToTypeId(stableId()); - if (in.token == LBRACKET) - t = atPos(in.currentPos)(AppliedTypeTree(t, typeArgs())); - val args = if (in.token == LPAREN) argumentExprs() else List(); - atPos(pos) { New(t, List(args)) } - } - - def traitAttribute(attrs: List[Tree]) = { - def isTraitAttribute(attr: Tree) = attr match { - case Apply(Select(New(Ident(name)), constr), List()) if (name.toString() == "_trait_") => - true - case _ => - false - } - if (attrs exists isTraitAttribute) Flags.TRAIT else 0 - } - - def joinAttributes(attrs: List[Tree], defs: List[Tree]): List[Tree] = - defs map (defn => - (attrs :\ defn) ((attr, tree) => Attributed(attr, tree) setPos attr.pos)); - - /** RefineStatSeq ::= RefineStat {SEP RefineStat} - * RefineStat ::= Dcl - * | type TypeDef - * | - */ - def refineStatSeq(): List[Tree] = { - val stats = new ListBuffer[Tree]; - while (in.token != RBRACE && in.token != EOF) { - if (isDclIntro) { - stats ++= joinComment(defOrDcl(NoMods)) - } else if (in.token != SEMI && in.token != NEWLINE) { - syntaxError("illegal start of declaration", true); - } - if (in.token != RBRACE) acceptStatSep(); - } - stats.toList - } - - /** BlockStatSeq ::= { BlockStat SEP } [Expr] - * BlockStat ::= Import - * | Def - * | LocalModifiers TmplDef - * | Expr - * | - */ - def blockStatSeq(stats: ListBuffer[Tree]): List[Tree] = { - while ((in.token != RBRACE) && (in.token != EOF) && (in.token != CASE)) { - if (in.token == IMPORT) { - stats ++= importClause(); - acceptStatSep(); - } else if (isExprIntro) { - stats += expr(false, true); - if (in.token != RBRACE && in.token != CASE) acceptStatSep(); - } else if (isDefIntro) { - stats ++= defOrDcl(NoMods); - acceptStatSep(); - if (in.token == RBRACE || in.token == CASE) { - stats += Literal(()).setPos(in.currentPos) - } - } else if (isLocalModifier) { - stats += tmplDef(localClassModifiers()); - acceptStatSep(); - if (in.token == RBRACE || in.token == CASE) { - stats += Literal(()).setPos(in.currentPos) - } - } else if (in.token == SEMI || in.token == NEWLINE) { - in.nextToken(); - } else { - syntaxError("illegal start of statement", true); - } - } - stats.toList - } - - /** CompilationUnit ::= package QualId SEP TopStatSeq - * | package QualId `{' TopStatSeq `}' - * | TopStatSeq - */ - def compilationUnit(): Tree = - atPos(in.currentPos) { - if (in.token == PACKAGE) { - in.nextToken(); - val pkg = qualId(); - if (in.token == SEMI || in.token == NEWLINE) { - in.nextToken(); - makePackaging(pkg, topStatSeq()) - } else { - accept(LBRACE); - val t = makePackaging(pkg, topStatSeq()); - accept(RBRACE); - if (in.token == SEMI || in.token == NEWLINE) in.nextToken(); - t - } - } else { - makePackaging(Ident(nme.EMPTY_PACKAGE_NAME), topStatSeq()) - } - } - } -} - - - -// LocalWords: SOcos diff --git a/sources/scala/tools/nsc/ast/parser/Scanners.scala b/sources/scala/tools/nsc/ast/parser/Scanners.scala deleted file mode 100644 index 5fbf54834e..0000000000 --- a/sources/scala/tools/nsc/ast/parser/Scanners.scala +++ /dev/null @@ -1,908 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.ast.parser; - -import Tokens._; -import scala.tools.nsc.util.{Position, SourceFile} -import SourceFile.{LF, FF, CR, SU} -import scala.tools.nsc.util.CharArrayReader; - -[_trait_] abstract class Scanners: SyntaxAnalyzer { - - import global._; - - /** A class for representing a token's data. */ - class TokenData { - - /** the next token */ - var token: int = EMPTY; - - /** the token's position */ - protected var pos: int = 0; - - /** the first character position after the previous token */ - var lastPos: int = 0; - - def currentPos = pos - 1; - - - /** the name of an identifier or token */ - var name: Name = null; - - /** the base of a number */ - var base: int = 0; - - def copyFrom(td: TokenData) = { - this.token = td.token; - this.pos = td.pos; - this.lastPos = td.lastPos; - this.name = td.name; - this.base = td.base; - } - } - - /** A scanner for the programming language Scala. - * - * @author Matthias Zenger, Martin Odersky, Burak Emir - * @version 1.1 - */ - class Scanner(unit: CompilationUnit) extends TokenData { - - import Tokens._; - import java.lang.{Integer, Long, Float, Double, Character} - - /** Character input reader - */ - val in = new CharArrayReader(unit.source.getContent(), true, syntaxError); - - /** character buffer for literals - */ - val cbuf = new StringBuffer(); - - /** append Unicode character to "lit" buffer - */ - protected def putChar(c: char) = cbuf.append(c); - - /** Clear buffer and set name */ - private def setName = { - name = newTermName(cbuf.toString()); - cbuf.setLength(0) - } - - /** buffer for the documentation comment - */ - var docBuffer: StringBuffer = null; - - /** add the given character to the documentation buffer - */ - protected def putDocChar(c: char): unit = - if (docBuffer != null) docBuffer.append(c); - - /** we need one token lookahead - */ - val next = new TokenData(); - val prev = new TokenData(); - - /** the last error position - */ - var errpos = -1; - - /** a stack which indicates whether line-ends can be statement separators - */ - var sepRegions: List[int] = List(); - -// Get next token ------------------------------------------------------------ - - /** read next token and return last position - */ - def skipToken(): int = { - val p = pos; nextToken(); - // XXX: account for off by one error //??? - p - 1 - } - - def nextToken(): unit = { - if (token == LPAREN) { - sepRegions = RPAREN :: sepRegions - } else if (token == LBRACKET) { - sepRegions = RBRACKET :: sepRegions - } else if (token == LBRACE) { - sepRegions = RBRACE :: sepRegions - } else if (token == CASE) { - sepRegions = ARROW :: sepRegions - } else if (token == RBRACE) { - while (!sepRegions.isEmpty && sepRegions.head != RBRACE) - sepRegions = sepRegions.tail; - if (!sepRegions.isEmpty) - sepRegions = sepRegions.tail - } else if (token == RBRACKET || token == RPAREN || token == ARROW) { - if (!sepRegions.isEmpty && sepRegions.head == token) - sepRegions = sepRegions.tail - } - - val lastToken = token; - if (next.token == EMPTY) { - fetchToken(); - } else { - this.copyFrom(next); - next.token = EMPTY - } - - if (token == CASE) { - prev.copyFrom(this); - fetchToken(); - if (token == CLASS) { - token = CASECLASS; - lastPos = prev.lastPos; - } else if (token == OBJECT) { - token = CASEOBJECT; - lastPos = prev.lastPos; - } else { - next.copyFrom(this); - this.copyFrom(prev); - } - } else if (token == SEMI) { - prev.copyFrom(this); - fetchToken(); - if (token != ELSE) { - next.copyFrom(this); - this.copyFrom(prev); - } - } - - if (afterLineEnd() && inLastOfStat(lastToken) && inFirstOfStat(token) && - (sepRegions.isEmpty || sepRegions.head == RBRACE)) { - next.copyFrom(this); - pos = in.lineStartPos; - token = NEWLINE -/* - } else if (lastToken == RBRACE) { - System.out.println("failing to insert NL after RBRACE: " + sepRegions + " " + - lastPos + " " + in.lineStartPos + " " + pos); -*/ - } -// System.out.println("token: " + toString());//DEBUG - } - - private def afterLineEnd() = ( - lastPos < in.lineStartPos && - (in.lineStartPos <= pos || - lastPos < in.lastLineStartPos && in.lastLineStartPos <= pos) - ); - - /** read next token - */ - private def fetchToken(): unit = { - if (token == EOF) return; - lastPos = in.cpos - 1; // Position.encode(in.cline, in.ccol); - //var index = bp; - while (true) { - in.ch match { - case ' ' | '\t' | CR | LF | FF => - in.next; - case _ => - pos = in.cpos; // Position.encode(in.cline, in.ccol); - in.ch match { - case '\u21D2' => - in.next; token = ARROW; - return; - case 'A' | 'B' | 'C' | 'D' | 'E' | - 'F' | 'G' | 'H' | 'I' | 'J' | - 'K' | 'L' | 'M' | 'N' | 'O' | - 'P' | 'Q' | 'R' | 'S' | 'T' | - 'U' | 'V' | 'W' | 'X' | 'Y' | - 'Z' | '$' | '_' | - 'a' | 'b' | 'c' | 'd' | 'e' | - 'f' | 'g' | 'h' | 'i' | 'j' | - 'k' | 'l' | 'm' | 'n' | 'o' | - 'p' | 'q' | 'r' | 's' | 't' | - 'u' | 'v' | 'w' | 'x' | 'y' | // scala-mode: need to understand multi-line case patterns - 'z' => - putChar(in.ch); - in.next; - getIdentRest; // scala-mode: wrong indent for multi-line case blocks - return; - - case '<' => // is XMLSTART? - val last = in.last; - in.next; - last match { - case ' '|'\t'|'\n'|'{'|'('|'>' if xml.Parsing.isNameStart(in.ch) => - token = XMLSTART; - case _ => - // Console.println("found '<', but last is '"+in.last+"'"); // DEBUG - putChar('<'); - getOperatorRest; - } - return; - - case '~' | '!' | '@' | '#' | '%' | - '^' | '*' | '+' | '-' | /*'<' | */ - '>' | '?' | ':' | '=' | '&' | - '|' | '\\' => - putChar(in.ch); - in.next; - getOperatorRest; // XXX - return; - case '/' => - in.next; - if (!skipComment()) { - putChar('/'); - getOperatorRest; - return; - } - - case '0' => - putChar(in.ch); - in.next; - if (in.ch == 'x' || in.ch == 'X') { - in.next; - base = 16 - } else { - base = 8; - } - getNumber; - return; // scala-mode: return is a keyword - case '1' | '2' | '3' | '4' | - '5' | '6' | '7' | '8' | '9' => - base = 10; - getNumber; - return; - case '`' => //" scala-mode: need to understand literals - getStringLit('`'); - token = IDENTIFIER; - return; - case '\"' => //" scala-mode: need to understand literals - getStringLit('\"'); - return; - case '\'' => - in.next; - in.ch match { - case 'A' | 'B' | 'C' | 'D' | 'E' | - 'F' | 'G' | 'H' | 'I' | 'J' | - 'K' | 'L' | 'M' | 'N' | 'O' | - 'P' | 'Q' | 'R' | 'S' | 'T' | - 'U' | 'V' | 'W' | 'X' | 'Y' | - 'Z' | '$' | '_' | - 'a' | 'b' | 'c' | 'd' | 'e' | - 'f' | 'g' | 'h' | 'i' | 'j' | - 'k' | 'l' | 'm' | 'n' | 'o' | - 'p' | 'q' | 'r' | 's' | 't' | - 'u' | 'v' | 'w' | 'x' | 'y' | - 'z' => - putChar(in.ch); - in.next; - if (in.ch != '\'') { - getIdentRest; - token = SYMBOLLIT; - return; - } - case _ => - if (Character.isUnicodeIdentifierStart(in.ch)) { - putChar(in.ch); - in.next; - if (in.ch != '\'') { - getIdentRest; - token = SYMBOLLIT; - return; - } - } else { - getlitch() - } - } - if (in.ch == '\'') { - in.next; - token = CHARLIT; - setName - } else { - syntaxError("unclosed character literal"); - } - return; - case '.' => - in.next; - if ('0' <= in.ch && in.ch <= '9') { - putChar('.'); getFraction; - } else { - token = DOT - } - return; - case ';' => - in.next; token = SEMI; - return; - case ',' => - in.next; token = COMMA; - return; - case '(' => //scala-mode: need to understand character quotes - in.next; token = LPAREN; - return; - case '{' => - in.next; token = LBRACE; - return; - case ')' => - in.next; token = RPAREN; - return; - case '}' => - in.next; token = RBRACE; - return; - case '[' => - in.next; token = LBRACKET; - return; - case ']' => - in.next; token = RBRACKET; - return; - case SU => - if (!in.hasNext) token = EOF; - else { - syntaxError("illegal character"); - in.next - } - return; - case _ => - if (Character.isUnicodeIdentifierStart(in.ch)) { - putChar(in.ch); - in.next; - getIdentRest; - } else if (isSpecial(in.ch)) { - putChar(in.ch); - getOperatorRest; - } else { - syntaxError("illegal character"); - in.next; - } - return; - } - } - } - } - - private def skipComment(): boolean = - if (in.ch == '/') { - do { - in.next; - } while ((in.ch != CR) && (in.ch != LF) && (in.ch != SU)); - true - } else if (in.ch == '*') { - docBuffer = null; - var openComments = 1; - in.next; - if (in.ch == '*') docBuffer = new StringBuffer("/**"); - while (openComments > 0) { - do { - do { - if (in.ch == '/') { - in.next; putDocChar(in.ch); - if (in.ch == '*') { - in.next; putDocChar(in.ch); - openComments = openComments + 1; - } - } - in.next; putDocChar(in.ch); - } while (in.ch != '*' && in.ch != SU); - while (in.ch == '*') { - in.next; putDocChar(in.ch); - } - } while (in.ch != '/' && in.ch != SU); - if (in.ch == '/') in.next; - else syntaxError("unclosed comment"); - openComments = openComments - 1; - } - true - } else { - false - } - - def inFirstOfStat(token: int) = token match { - case EOF | ELSE | CASE | EXTENDS | WITH | YIELD | CATCH | FINALLY | MATCH | - REQUIRES | COMMA | SEMI | NEWLINE | DOT | USCORE | COLON | EQUALS | ARROW | - LARROW | SUBTYPE | VIEWBOUND | SUPERTYPE | HASH | AT | - RPAREN | RBRACKET | RBRACE => - false - case _ => - true - } - - def inLastOfStat(token: int) = token match { - case CHARLIT | INTLIT | LONGLIT | FLOATLIT | DOUBLELIT | STRINGLIT | SYMBOLLIT | - IDENTIFIER | THIS | NULL | TRUE | FALSE | RETURN | USCORE | - RPAREN | RBRACKET | RBRACE => - true - case _ => - false - } - -// Identifiers --------------------------------------------------------------- - - def isIdentStart(c: char): boolean = ( - ('A' <= c && c <= 'Z') || - ('a' <= c && c <= 'a') || - (c == '_') || (c == '$') || - Character.isUnicodeIdentifierStart(c) - ); - - def isIdentPart(c: char) = ( - isIdentStart(c) || - ('0' <= c && c <= '9') || - Character.isUnicodeIdentifierPart(c) - ); - - def isSpecial(c: char) = { - val chtp = Character.getType(c); - chtp == Character.MATH_SYMBOL || chtp == Character.OTHER_SYMBOL; - } - - private def getIdentRest: unit = - while (true) { - in.ch match { - case 'A' | 'B' | 'C' | 'D' | 'E' | - 'F' | 'G' | 'H' | 'I' | 'J' | - 'K' | 'L' | 'M' | 'N' | 'O' | - 'P' | 'Q' | 'R' | 'S' | 'T' | - 'U' | 'V' | 'W' | 'X' | 'Y' | - 'Z' | '$' | - 'a' | 'b' | 'c' | 'd' | 'e' | - 'f' | 'g' | 'h' | 'i' | 'j' | - 'k' | 'l' | 'm' | 'n' | 'o' | - 'p' | 'q' | 'r' | 's' | 't' | - 'u' | 'v' | 'w' | 'x' | 'y' | - 'z' | - '0' | '1' | '2' | '3' | '4' | - '5' | '6' | '7' | '8' | '9' => - putChar(in.ch); - in.next; - case '_' => - putChar(in.ch); - in.next; - getIdentOrOperatorRest; - return; - case SU => - setName; - token = name2token(name); - return; - case _ => - if(java.lang.Character.isUnicodeIdentifierPart(in.ch)) { - putChar(in.ch); - in.next - } else { - setName; - token = name2token(name); - return - } - } - } - - private def getOperatorRest: unit = - while (true) { - in.ch match { - case '~' | '!' | '@' | '#' | '%' | - '^' | '*' | '+' | '-' | '<' | - '>' | '?' | ':' | '=' | '&' | - '|' | '\\' => - putChar(in.ch); - in.next - case '/' => - in.next; - if (skipComment()) { - setName; - token = name2token(name); - return; - } else { - putChar('/'); - } - case _ => - if (isSpecial(in.ch)) { - putChar(in.ch); - in.next; - } else { - setName; - token = name2token(name); - return; - } - } - } - - private def getIdentOrOperatorRest: unit = - if (isIdentPart(in.ch)) - getIdentRest - else in.ch match { - case '~' | '!' | '@' | '#' | '%' | - '^' | '*' | '+' | '-' | '<' | - '>' | '?' | ':' | '=' | '&' | - '|' | '\\' | '/' => - getOperatorRest; - case _ => - if (isSpecial(in.ch)) getOperatorRest - else { - setName; - token = name2token(name) - } - } - - private def getStringLit(delimiter: char): unit = { - in.next; - while (in.ch != delimiter && (in.isUnicode || in.ch != CR && in.ch != LF && in.ch != SU)) { - getlitch(); - } - if (in.ch == delimiter) { - token = STRINGLIT; - setName; - in.next - } else { - syntaxError("unclosed string literal"); - } - } - -// Literals ----------------------------------------------------------------- - - /** read next character in character or string literal: - */ - protected def getlitch() = - if (in.ch == '\\') { - in.next; - if ('0' <= in.ch && in.ch <= '7') { - val leadch: char = in.ch; - var oct: int = in.digit2int(in.ch, 8); - in.next; - if ('0' <= in.ch && in.ch <= '7') { - oct = oct * 8 + in.digit2int(in.ch, 8); - in.next; - if (leadch <= '3' && '0' <= in.ch && in.ch <= '7') { - oct = oct * 8 + in.digit2int(in.ch, 8); - in.next; - } - } - putChar(oct.asInstanceOf[char]); - } else { - in.ch match { - case 'b' => putChar('\b') - case 't' => putChar('\t') - case 'n' => putChar('\n') - case 'f' => putChar('\f') - case 'r' => putChar('\r') - case '\"' => putChar('\"') - case '\'' => putChar('\'') - case '\\' => putChar('\\') - case _ => - syntaxError(in.cpos - 1, // Position.encode(in.cline, in.ccol - 1), - "invalid escape character"); - putChar(in.ch); - } - in.next - } - } else { - putChar(in.ch); - in.next; - } - - /** read fractional part and exponent of floating point number - * if one is present. - */ - protected def getFraction = { - token = DOUBLELIT; - while ('0' <= in.ch && in.ch <= '9') { - putChar(in.ch); - in.next; - } - if (in.ch == 'e' || in.ch == 'E') { - val lookahead = in.copy; - lookahead.next; - if (lookahead.ch == '+' || lookahead.ch == '-') { - lookahead.next; - } - if ('0' <= lookahead.ch && lookahead.ch <= '9') { - putChar(in.ch); - in.next; - if (in.ch == '+' || in.ch == '-') { - putChar(in.ch); - in.next; - } - while ('0' <= in.ch && in.ch <= '9') { - putChar(in.ch); - in.next; - } - } - token = DOUBLELIT; - } - if ((in.ch == 'd') || (in.ch == 'D')) { - putChar(in.ch); - in.next; - token = DOUBLELIT; - } else if ((in.ch == 'f') || (in.ch == 'F')) { - putChar(in.ch); - in.next; - token = FLOATLIT; - } - setName - } - - /** convert name to long value - */ - def intVal(negated: boolean): long = { - if (token == CHARLIT && !negated) { - if (name.length > 0) name(0) else 0 - } else { - var value: long = 0; - val divider = if (base == 10) 1 else 2; - val limit: long = - if (token == LONGLIT) Long.MAX_VALUE else Integer.MAX_VALUE; - var i = 0; - val len = name.length; - while (i < len) { - val d = in.digit2int(name(i), base); - if (d < 0) { - syntaxError("malformed integer number"); - return 0; - } - if (value < 0 || - limit / (base / divider) < value || - limit - (d / divider) < value * (base / divider) && - !(negated && limit == value * base - 1 + d)) { - syntaxError("integer number too large"); - return 0; - } - value = value * base + d; - i = i + 1; - } - if (negated) -value else value - } - } - - def intVal: long = intVal(false); - - /** convert name, base to double value - */ - def floatVal(negated: boolean): double = { - val limit: double = - if (token == DOUBLELIT) Double.MAX_VALUE else Float.MAX_VALUE; - try { - val value = Double.valueOf(name.toString()).doubleValue(); - if (value > limit) - syntaxError("floating point number too large"); - if (negated) -value else value - } catch { - case _: NumberFormatException => - syntaxError("malformed floating point number"); - 0.0 - } - } - - def floatVal: double = floatVal(false); - - /** read a number into name and set base - */ - protected def getNumber:unit = { - while (in.digit2int(in.ch, if (base < 10) 10 else base) >= 0) { - putChar(in.ch); - in.next; - } - token = INTLIT; - if (base <= 10 && in.ch == '.') { - val lookahead = in.copy; - lookahead.next; - lookahead.ch match { - case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | - '8' | '9' | 'd' | 'D' | 'e' | 'E' | 'f' | 'F' => - putChar(in.ch); - in.next; - return getFraction - case _ => - if (!isIdentStart(lookahead.ch)) { - putChar(in.ch); - in.next; - return getFraction - } - } - } - if (base <= 10 && - (in.ch == 'e' || in.ch == 'E' || - in.ch == 'f' || in.ch == 'F' || - in.ch == 'd' || in.ch == 'D')) { - return getFraction - } - setName; - if (in.ch == 'l' || in.ch == 'L') { - in.next; - token = LONGLIT; - } - } - -// XML lexing---------------------------------------------------------------- - def xSync = { - token = NEWLINE; // avoid getting NEWLINE from nextToken if last was RBRACE - //in.next; - nextToken(); - } - -// Errors ----------------------------------------------------------------- - - /** generate an error at the given position - */ - def syntaxError(pos: int, msg: String): unit = { - unit.error(pos, msg); - token = ERROR; - errpos = pos; - } - - /** generate an error at the current token position - */ - def syntaxError(msg: String): unit = syntaxError(pos, msg); - -// Keywords ----------------------------------------------------------------- - - /** Keyword array; maps from name indices to tokens */ - private var key: Array[byte] = _; - private var maxKey = 0; - private var tokenName = new Array[Name](128); - - { - var tokenCount = 0; - - // Enter keywords - - def enterKeyword(n: Name, tokenId: int): unit = { - while (tokenId >= tokenName.length) { - val newTokName = new Array[Name](tokenName.length * 2); - System.arraycopy(tokenName, 0, newTokName, 0, newTokName.length); - tokenName = newTokName; - } - tokenName(tokenId) = n; - if (n.start > maxKey) maxKey = n.start; - if (tokenId >= tokenCount) tokenCount = tokenId + 1; - } - - enterKeyword(nme.ABSTRACTkw, ABSTRACT); - enterKeyword(nme.CASEkw, CASE); - enterKeyword(nme.CATCHkw, CATCH); - enterKeyword(nme.CLASSkw, CLASS); - enterKeyword(nme.DEFkw, DEF); - enterKeyword(nme.DOkw, DO); - enterKeyword(nme.ELSEkw, ELSE); - enterKeyword(nme.EXTENDSkw, EXTENDS); - enterKeyword(nme.FALSEkw, FALSE); - enterKeyword(nme.FINALkw, FINAL); - enterKeyword(nme.FINALLYkw, FINALLY); - enterKeyword(nme.FORkw, FOR); - enterKeyword(nme.IFkw, IF); - enterKeyword(nme.IMPLICITkw, IMPLICIT); - enterKeyword(nme.IMPORTkw, IMPORT); - enterKeyword(nme.MATCHkw, MATCH); - enterKeyword(nme.REQUIRESkw, REQUIRES); - enterKeyword(nme.NEWkw, NEW); - enterKeyword(nme.NULLkw, NULL); - enterKeyword(nme.OBJECTkw, OBJECT); - enterKeyword(nme.OVERRIDEkw, OVERRIDE); - enterKeyword(nme.PACKAGEkw, PACKAGE); - enterKeyword(nme.PRIVATEkw, PRIVATE); - enterKeyword(nme.PROTECTEDkw, PROTECTED); - enterKeyword(nme.RETURNkw, RETURN); - enterKeyword(nme.SEALEDkw, SEALED); - enterKeyword(nme.SUPERkw, SUPER); - enterKeyword(nme.THISkw, THIS); - enterKeyword(nme.THROWkw, THROW); - enterKeyword(nme.TRAITkw, TRAIT); - enterKeyword(nme.TRUEkw, TRUE); - enterKeyword(nme.TRYkw, TRY); - enterKeyword(nme.TYPEkw, TYPE); - enterKeyword(nme.VALkw, VAL); - enterKeyword(nme.VARkw, VAR); - enterKeyword(nme.WHILEkw, WHILE); - enterKeyword(nme.WITHkw, WITH); - enterKeyword(nme.YIELDkw, YIELD); - enterKeyword(nme.DOTkw, DOT); - enterKeyword(nme.USCOREkw, USCORE); - enterKeyword(nme.COLONkw, COLON); - enterKeyword(nme.EQUALSkw, EQUALS); - enterKeyword(nme.ARROWkw, ARROW); - enterKeyword(nme.LARROWkw, LARROW); - enterKeyword(nme.SUBTYPEkw, SUBTYPE); - enterKeyword(nme.VIEWBOUNDkw, VIEWBOUND); - enterKeyword(nme.SUPERTYPEkw, SUPERTYPE); - enterKeyword(nme.HASHkw, HASH); - enterKeyword(nme.ATkw, AT); - - // Build keyword array - key = new Array[byte](maxKey+1); - for (val i <- Iterator.range(0, maxKey + 1)) - key(i) = IDENTIFIER; - for (val j <- Iterator.range(0, tokenCount)) - if (tokenName(j) != null) - key(tokenName(j).start) = j.asInstanceOf[byte]; - - } - -// Token representation ----------------------------------------------------- - - /** Convert name to token */ - def name2token(name: Name): int = - if (name.start <= maxKey) key(name.start) else IDENTIFIER; - - /** Returns the string representation of given token. */ - def token2string(token: int): String = token match { - case IDENTIFIER => - "identifier"/* + \""+name+"\""*/ - case CHARLIT => - "character literal" - case INTLIT => - "integer literal" - case LONGLIT => - "long literal" - case FLOATLIT => - "float literal" - case DOUBLELIT => - "double literal" - case STRINGLIT => - "string literal" - case SYMBOLLIT => - "symbol literal" - case LPAREN => - "'('" - case RPAREN => - "')'" - case LBRACE => - "'{'" - case RBRACE => - "'}'" - case LBRACKET => - "'['" - case RBRACKET => - "']'" - case EOF => - "eof" - case ERROR => - "something" - case SEMI => - "';'" - case NEWLINE => - "';'" - case COMMA => - "','" - case CASECLASS => - "case class" - case CASEOBJECT => - "case object" - case XMLSTART => - "$XMLSTART$<" - case _ => - try { - "'" + tokenName(token) + "'" - } catch { - case _: ArrayIndexOutOfBoundsException => - "'<" + token + ">'" - case _: NullPointerException => - "'<(" + token + ")>'" - } - } - - override def toString() = token match { - case IDENTIFIER => - "id(" + name + ")" - case CHARLIT => - "char(" + intVal + ")" - case INTLIT => - "int(" + intVal + ")" - case LONGLIT => - "long(" + intVal + ")" - case FLOATLIT => - "float(" + floatVal + ")" - case DOUBLELIT => - "double(" + floatVal + ")" - case STRINGLIT => - "string(" + name + ")" - case SEMI => - ";" - case NEWLINE => - ";" - case COMMA => - "," - case _ => - token2string(token) - } - - /** INIT: read lookahead character and token. - */ - in.next; - nextToken(); - } -} diff --git a/sources/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala b/sources/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala deleted file mode 100644 index 4fc234bead..0000000000 --- a/sources/scala/tools/nsc/ast/parser/SymbolicXMLBuilder.scala +++ /dev/null @@ -1,349 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ -package scala.tools.nsc.ast.parser; - -import scala.tools.nsc.util.Position; -import scala.Iterator; -import scala.collection.immutable.{ Map, ListMap }; -import scala.collection.mutable; -import scala.xml.{Text,TextBuffer}; - -import symtab.Flags.MUTABLE; - -/** this class builds instance of Tree that represent XML */ -abstract class SymbolicXMLBuilder(make: TreeBuilder, p: Parsers # Parser, preserveWS: Boolean ) { - - val global: Global; - import global._; - import posAssigner.atPos; - - //import scala.tools.scalac.ast.{TreeList => myTreeList} - - var isPattern:Boolean = _; - - import nme.{ - _Attribute , - _MetaData , - _NamespaceBinding , - _NodeBuffer , - - _Null , - - _PrefixedAttribute , - _UnprefixedAttribute , - _Elem , - _Seq , - _immutable , - _mutable , - _append , - _plus , - _collection , - _toList , - _xml , - _Comment , - _CharData , - _Node , - _ProcInstr , - _Text , - _EntityRef , - _md, - _scope, - _tmpscope}; - - - // convenience methods - private def LL[A](x:A*):List[List[A]] = List(List(x:_*)); - - private def _scala(name: Name) = Select(Ident(nme.scala_), name); - - private def _scala_Seq = _scala( _Seq ); - private def _scala_xml(name: Name) = Select( _scala(_xml), name ); - - private def _scala_xml_MetaData = _scala_xml( _MetaData ); - private def _scala_xml_NamespaceBinding = _scala_xml( _NamespaceBinding ); - private def _scala_xml_Null = _scala_xml( _Null ); - private def _scala_xml_PrefixedAttribute = _scala_xml(_PrefixedAttribute); - private def _scala_xml_UnprefixedAttribute= _scala_xml(_UnprefixedAttribute); - private def _scala_xml_Node = _scala_xml( _Node ); - private def _scala_xml_NodeBuffer = _scala_xml( _NodeBuffer ); - private def _scala_xml_EntityRef = _scala_xml( _EntityRef ); - private def _scala_xml_Comment = _scala_xml( _Comment ); - private def _scala_xml_CharData = _scala_xml( _CharData ); - private def _scala_xml_ProcInstr = _scala_xml( _ProcInstr ); - private def _scala_xml_Text = _scala_xml( _Text ); - private def _scala_xml_Elem = _scala_xml( _Elem ); - private def _scala_xml_Attribute = _scala_xml( _Attribute ); - - - private def bufferToArray(buf: mutable.Buffer[Tree]): Array[Tree] = { - val arr = new Array[Tree]( buf.length ); - var i = 0; - for (val x <- buf.elements) { arr(i) = x; i = i + 1; } - arr; - } - - // create scala xml tree - - /** - * @arg namespace: a Tree of type defs.STRING_TYPE - * @arg label: a Tree of type defs.STRING_TYPE - * @todo map: a map of attributes !!! - */ - - protected def mkXML(pos: int, isPattern: boolean, pre: Tree, label: Tree, attrs: /*Array[*/Tree/*]*/ , scope:Tree, children: mutable.Buffer[Tree]): Tree = { - if( isPattern ) { - //val ts = new mutable.ArrayBuffer[Tree](); - convertToTextPat( children ); - atPos (pos) { - Apply( _scala_xml_Elem, List( - pre, label, Ident( nme.WILDCARD ) /* attributes? */ , Ident( nme.WILDCARD )) /* scope? */ ::: children.toList ) - } - } else { - var ab = List(pre, label, attrs, scope); - if(( children.length ) > 0 ) - ab = ab ::: List(Typed(makeXMLseq(pos, children), Ident(nme.WILDCARD_STAR.toTypeName))); - atPos(pos) { New( _scala_xml_Elem, List(ab) )} - } - } - - final def entityRef( pos:int, n: String ) = { - atPos(pos) { New( _scala_xml_EntityRef, LL(Literal(Constant( n )))) }; - - }; - // create scala.xml.Text here <: scala.xml.Node - final def text( pos: Int, txt:String ):Tree = { - //makeText( isPattern, gen.mkStringLit( txt )); - val txt1 = Literal(Constant(txt)); - atPos(pos) { - if( isPattern ) - makeTextPat( txt1 ); - else - makeText1( txt1 ); - } - } - - // create scala.xml.Text here <: scala.xml.Node - def makeTextPat(txt:Tree ) = Apply(_scala_xml_Text, List(txt)); - def makeText1(txt:Tree ) = New( _scala_xml_Text, LL( txt )); - - // create - def comment( pos: int, text: String ):Tree = - atPos(pos) { Comment( Literal(Constant(text))) }; - - // create - def charData( pos: int, txt: String ):Tree = - atPos(pos) { CharData( Literal(Constant(txt))) }; - - // create scala.xml.Text here <: scala.xml.Node - def procInstr( pos: int, target: String, txt: String ) = - atPos(pos) { ProcInstr(Literal(Constant(target)), Literal(Constant(txt))) }; - - protected def CharData(txt: Tree) = New( _scala_xml_CharData, LL(txt)); - protected def Comment(txt: Tree) = New( _scala_xml_Comment, LL(txt)); - protected def ProcInstr(target: Tree, txt: Tree) = - New(_scala_xml_ProcInstr, LL( target, txt )); - - - /** @todo: attributes */ - def makeXMLpat(pos: int, n: String, args: mutable.Buffer[Tree]): Tree = - mkXML(pos, - true, - Ident( nme.WILDCARD ), - Literal(Constant(n)), - null, //Predef.Array[Tree](), - null, - args); - - protected def convertToTextPat(t: Tree): Tree = t match { - case _:Literal => makeTextPat(t); - case _ => t - } - - protected def convertToTextPat(buf: mutable.Buffer[Tree]): Unit = { - var i = 0; while( i < buf.length ) { - val t1 = buf( i ); - val t2 = convertToTextPat( t1 ); - if (!t1.eq(t2)) { - buf.remove(i); - buf.insert(i,t2); - } - i = i + 1; - } - } - - def freshName(prefix:String): Name; - - def isEmptyText(t:Tree) = t match { - case Literal(Constant("")) => true; - case _ => false; - } - def makeXMLseq( pos:int, args:mutable.Buffer[Tree] ) = { - var _buffer = New( _scala_xml_NodeBuffer, List(Nil)); - val it = args.elements; - while( it.hasNext ) { - val t = it.next; - if( !isEmptyText( t )) { - _buffer = Apply(Select(_buffer, _plus), List( t )); - } - } - atPos(pos) { Select(_buffer, _toList) }; - } - - def makeXMLseqPat( pos:int, args:List[Tree] ) = atPos(pos) {Apply( _scala_Seq, args )}; - - - /** returns Some(prefix) if pre:name, None otherwise */ - def getPrefix( name:String ):Option[String] = { - val i = name.indexOf(':'); - if( i != -1 ) Some( name.substring(0, i) ) else None - } - - /** splits */ - protected def qualifiedAttr( pos:Int, namespace:String, name:String ):Pair[String,String] = { - getPrefix( name ) match { - case Some( pref ) => - val newLabel = name.substring( pref.length()+1, name.length() ); - // if( newLabel.indexOf(':') != -1 ) syntaxError - Pair( "namespace$"+pref, newLabel ); - case None => - Pair( namespace, name ); - } - } - protected def qualified( pos:Int, name:String ):Pair[String,String] = - getPrefix( name ) match { - case Some( pref ) => - val newLabel = name.substring( pref.length()+1, name.length() ); - // if( newLabel.indexOf(':') != -1 ) syntaxError - Pair( "namespace$"+pref, newLabel ); - case None => - Pair( "namespace$default", name ); - } - - - /** makes an element */ - def element(pos: int, qname: String, attrMap: mutable.Map[String,Tree], args: mutable.Buffer[Tree]): Tree = { - //Console.println("SymbolicXMLBuilder::element("+pos+","+qname+","+attrMap+","+args+")"); - var setNS = new mutable.HashMap[String, Tree]; - - var tlist: List[Tree] = List(); - - /* pre can be null */ - def handleNamespaceBinding(pre:String , uri:Tree): Unit = { - val t = Assign(Ident(_tmpscope), New( _scala_xml_NamespaceBinding, - LL(Literal(Constant(pre)), uri, Ident( _tmpscope)))); - tlist = t :: tlist; - //Console.println("SymbolicXMLBuilder::handleNamespaceBinding:"); - //Console.println(t.toString()); - } - - /* DEBUG */ - val attrIt = attrMap.keys; - while( attrIt.hasNext ) { - val z = attrIt.next; - if( z.startsWith("xmlns") ) { // handle namespace - val i = z.indexOf(':'); - if( i == -1 ) - handleNamespaceBinding(null, attrMap( z )); - //setNS.update("default", attrMap( z ) ); - else { - val zz = z.substring( i+1, z.length() ); - //setNS.update( zz, attrMap( z ) ); - handleNamespaceBinding(zz, attrMap( z )); - } - attrMap -= z; - } - } - - val moreNamespaces = (0 < tlist.length); - - /* */ - val i = qname.indexOf(':'); - - var newlabel = qname; - val pre = getPrefix(qname) match { - case Some(p) => - newlabel = qname.substring(p.length()+1, qname.length()); - p; - case None => - null - } - var tlist2: List[Tree] = List(); - - // make attributes - - def handlePrefixedAttribute(pre:String, key:String, value:Tree): Unit = { - val t = atPos(pos) { - Assign(Ident(_md), New( _scala_xml_PrefixedAttribute, - LL( - Literal(Constant(pre)), - Literal(Constant(key)), - value, - Ident(_md) - )))}; - tlist2 = t :: tlist2; - // Console.println("SymbolicXMLBuilder::handlePrefixed :"); - // Console.println(t.toString()); - } - - def handleUnprefixedAttribute(key:String, value:Tree): Unit = { - val t = atPos(pos) { - Assign(Ident(_md), New(_scala_xml_UnprefixedAttribute, - LL(Literal(Constant(key)),value,Ident(_md)) - ))}; - tlist2 = t :: tlist2; - } - - var it = attrMap.elements; - while (it.hasNext) { - val ansk = it.next; - getPrefix(ansk._1) match { - case Some(pre) => - val key = ansk._1.substring(pre.length()+1, ansk._1.length()); - handlePrefixedAttribute(pre, key, ansk._2); - case None => - handleUnprefixedAttribute(ansk._1, ansk._2); - } - } - // attrs - - - val moreAttributes = (0 < tlist2.length); - - var ts: List[Tree] = tlist; - var ts2: List[Tree] = List(); - - if(moreAttributes) { - ts2 = atPos(pos) {ValDef(Modifiers(MUTABLE), - _md, - _scala_xml_MetaData, - _scala_xml_Null)} :: tlist2; - } - if(moreNamespaces) { - ts = atPos(pos) { - ValDef(Modifiers(MUTABLE), - _tmpscope, - _scala_xml_NamespaceBinding, - Ident(_scope))} :: ts; - - ts2 = ValDef(NoMods, _scope, _scala_xml_NamespaceBinding, Ident(_tmpscope)) :: ts2; - } - - val makeSymbolicAttrs = { - if (moreAttributes) Ident(_md) else _scala_xml_Null; - } - - var t = mkXML(pos, - false, - Literal(Constant(pre)) /* can be null */ , - Literal(Constant(newlabel)):Tree, - makeSymbolicAttrs, - Ident(_scope), - args); - - atPos(pos) { Block(ts, Block( ts2, t)) } - } -} - diff --git a/sources/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala b/sources/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala deleted file mode 100644 index b4a3b507b3..0000000000 --- a/sources/scala/tools/nsc/ast/parser/SyntaxAnalyzer.scala +++ /dev/null @@ -1,25 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.ast.parser; - -/** An nsc sub-component. - */ -abstract class SyntaxAnalyzer extends SubComponent with Parsers with MarkupParsers with Scanners { - val phaseName = "parser"; - def newPhase(prev: Phase): StdPhase = new ParserPhase(prev); - class ParserPhase(prev: scala.tools.nsc.Phase) extends StdPhase(prev) { - def apply(unit: global.CompilationUnit): unit = { - global.informProgress("parsing " + unit); - unit.body = new Parser(unit).parse(); - } - } - //Moez addition. I wished not to add/modify here, but the fact that Parsers - // are NOT accessible (because of Parsers' self type) except in SyntaxAnalyzer - // had bitten me, and thus I had to add the following code here. - def interpreterParse(unit: global.CompilationUnit): List[global.Tree] = - new Parser(unit).templateStatSeq() -} - diff --git a/sources/scala/tools/nsc/ast/parser/Tokens.scala b/sources/scala/tools/nsc/ast/parser/Tokens.scala deleted file mode 100644 index b99ee08811..0000000000 --- a/sources/scala/tools/nsc/ast/parser/Tokens.scala +++ /dev/null @@ -1,97 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.ast.parser; - -object Tokens { - - /** special tokens */ - final val EMPTY = -3; - final val UNDEF = -2; - final val ERROR = -1; - final val EOF = 0; - - /** literals */ - final val CHARLIT = 1; - final val INTLIT = 2; - final val LONGLIT = 3; - final val FLOATLIT = 4; - final val DOUBLELIT = 5; - final val STRINGLIT = 6; - final val SYMBOLLIT = 7; - - /** identifier */ - final val IDENTIFIER = 10; - - /** keywords */ - final val IF = 20; - final val FOR = 21; - final val ELSE = 22; - final val THIS = 23; - final val NULL = 24; - final val NEW = 25; - final val WITH = 26; - final val SUPER = 27; - final val CASE = 28; - final val CASECLASS = 29; - final val CASEOBJECT = 30; - final val VAL = 31; - final val ABSTRACT = 32; - final val FINAL = 33; - final val PRIVATE = 34; - final val PROTECTED = 35; - final val OVERRIDE = 36; - final val IMPLICIT = 37; - final val VAR = 38; - final val DEF = 39; - final val TYPE = 40; - final val EXTENDS = 41; - final val TRUE = 42; - final val FALSE = 43; - final val OBJECT = 44; - final val CLASS = 45; - - final val IMPORT = 46; - final val PACKAGE = 47; - final val YIELD = 48; - final val DO = 49; - final val TRAIT = 50; - final val SEALED = 51; - final val THROW = 52; - final val TRY = 53; - final val CATCH = 54; - final val FINALLY = 55; - final val WHILE = 56; - final val RETURN = 57; - final val MATCH = 58; - final val REQUIRES = 59; - - /** special symbols */ - final val COMMA = 61; - final val SEMI = 62; - final val DOT = 63; - final val USCORE = 64; - final val COLON = 65; - final val EQUALS = 66; - final val LARROW = 67; - final val ARROW = 68; - final val NEWLINE = 69; - final val SUBTYPE = 70; - final val SUPERTYPE = 71; - final val HASH = 72; - final val AT = 73; - final val VIEWBOUND = 74; - - /** parenthesis */ - final val LPAREN = 90; - final val RPAREN = 91; - final val LBRACKET = 92; - final val RBRACKET = 93; - final val LBRACE = 94; - final val RBRACE = 95; - - /** XML mode */ - final val XMLSTART = 96; -} diff --git a/sources/scala/tools/nsc/ast/parser/TreeBuilder.scala b/sources/scala/tools/nsc/ast/parser/TreeBuilder.scala deleted file mode 100644 index 70355350a7..0000000000 --- a/sources/scala/tools/nsc/ast/parser/TreeBuilder.scala +++ /dev/null @@ -1,289 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.ast.parser; - -import symtab.Flags._; -import util.ListBuffer; - -abstract class TreeBuilder { - - val global: Global; - import global._; - import posAssigner.atPos; - - def freshName(prefix: String): Name; - - def freshName(): Name = freshName("x$"); - - private object patvarTransformer extends Transformer { - override def transform(tree: Tree): Tree = tree match { - case Ident(name) if (treeInfo.isVariableName(name) && name != nme.WILDCARD) => - atPos(tree.pos)(Bind(name, Ident(nme.WILDCARD))) - case Typed(id @ Ident(name), tpt) if (treeInfo.isVariableName(name) && name != nme.WILDCARD) => - Bind(name, atPos(tree.pos)(Typed(Ident(nme.WILDCARD), tpt))) setPos id.pos - case Apply(fn @ Apply(_, _), args) => - copy.Apply(tree, transform(fn), transformTrees(args)) - case Apply(fn, args) => - copy.Apply(tree, fn, transformTrees(args)) - case Typed(expr, tpt) => - copy.Typed(tree, transform(expr), tpt) - case Bind(name, body) => - copy.Bind(tree, name, transform(body)) - case Sequence(_) | Alternative(_) | Star(_) => - super.transform(tree) - case _ => - tree - } - } - - /** Traverse pattern and collect all variable names in buffer */ - private object getvarTraverser extends Traverser { - val buf = new ListBuffer[Name]; - def init: Traverser = { buf.clear; this } - override def traverse(tree: Tree): unit = tree match { - case Bind(name, tpe) => - if ((name != nme.WILDCARD) && (buf.elements forall (name !=))) buf += name; - traverse(tpe) - case _ => super.traverse(tree) - } - } - - /** Returns list of all pattern variables without duplicates */ - private def getVariables(tree: Tree): List[Name] = { - getvarTraverser.init.traverse(tree); - getvarTraverser.buf.toList - } - - private def mkTuple(trees: List[Tree]): Tree = trees match { - case List() => Literal(()) - case List(tree) => tree - case _ => Apply(Select(Ident(nme.scala_), newTermName("Tuple" + trees.length)), trees) - } - - /** If tree is a variable pattern, return Some("its name and type"). - * Otherwise return none */ - private def matchVarPattern(tree: Tree): Option[Pair[Name, Tree]] = tree match { - case Ident(name) => Some(Pair(name, TypeTree())) - case Bind(name, Ident(nme.WILDCARD)) => Some(Pair(name, TypeTree())) - case Typed(Ident(name), tpt) => Some(Pair(name, tpt)) - case Bind(name, Typed(Ident(nme.WILDCARD), tpt)) => Some(Pair(name, tpt)) - case _ => None - } - - /** Create tree representing (unencoded) binary operation expression or pattern. */ - def makeBinop(isExpr: boolean, left: Tree, op: Name, right: Tree): Tree = { - if (isExpr) { - if (treeInfo.isLeftAssoc(op)) { - Apply(Select(left, op.encode), List(right)) - } else { - val x = freshName(); - Block( - List(ValDef(Modifiers(SYNTHETIC), x, TypeTree(), left)), - Apply(Select(right, op.encode), List(Ident(x)))) - } - } else { - Apply(Ident(op.encode.toTypeName), List(left, right)) - } - } - - /** Create tree representing an object creation */ - def makeNew(parents: List[Tree], stats: List[Tree], argss: List[List[Tree]]): Tree = - if (parents.tail.isEmpty && stats.isEmpty) - New(parents.head, argss) - else { - val x = nme.ANON_CLASS_NAME.toTypeName; - Block( - List(ClassDef( - Modifiers(FINAL | SYNTHETIC), x, List(), TypeTree(), - Template(parents, List(List()), argss, stats))), - New(Ident(x), List(List()))) - } - - /** Create a tree represeting an assignment */ - def makeAssign(lhs: Tree, rhs: Tree): Tree = lhs match { - case Apply(fn, args) => Apply(Select(fn, nme.update), args ::: List(rhs)) - case _ => Assign(lhs, rhs) - } - - /** A type tree corresponding to (possibly unary) intersection type */ - def makeIntersectionTypeTree(tps: List[Tree]): Tree = { - if (tps.tail.isEmpty) tps.head else CompoundTypeTree(Template(tps, List())) - } - - /** Create tree representing a while loop */ - def makeWhile(lname: Name, cond: Tree, body: Tree): Tree = { - val continu = Apply(Ident(lname), List()); - val rhs = If(cond, Block(List(body), continu), Literal(())); - LabelDef(lname, Nil, rhs) - } - - /** Create tree representing a do-while loop */ - def makeDoWhile(lname: Name, body: Tree, cond: Tree): Tree = { - val continu = Apply(Ident(lname), List()); - val rhs = Block(List(body), If(cond, continu, Literal(()))); - LabelDef(lname, Nil, rhs) - } - - /** Create block of statements `stats' */ - def makeBlock(stats: List[Tree]): Tree = { - if (stats.isEmpty) Literal(()) - else if (!stats.last.isTerm) Block(stats, Literal(())); - else if (stats.length == 1) stats(0) - else Block(stats.init, stats.last) - } - - /** Create tree for for-comprehension generator */ - def makeGenerator(pat: Tree, rhs: Tree): Tree = { - val pat1 = patvarTransformer.transform(pat); - val rhs1 = matchVarPattern(pat1) match { - case Some(_) => - rhs - case None => - Apply( - Select(rhs, nme.filter), - List(makeVisitor(List( - CaseDef(pat1.duplicate, EmptyTree, Literal(true)), - CaseDef(Ident(nme.WILDCARD), EmptyTree, Literal(false)))))) - } - CaseDef(pat1, EmptyTree, rhs1) - } - - /** Create tree for for-comprehension or - * where mapName and flatMapName are chosen - * corresponding to whether this is a for-do or a for-yield. - */ - private def makeFor(mapName: Name, flatMapName: Name, enums: List[Tree], body: Tree): Tree = { - - def makeCont(pat: Tree, body: Tree): Tree = matchVarPattern(pat) match { - case Some(Pair(name, tpt)) => - Function(List(ValDef(Modifiers(PARAM), name, tpt, EmptyTree)), body) - case None => - makeVisitor(List(CaseDef(pat, EmptyTree, body))) - } - - def makeBind(meth: Name, qual: Tree, pat: Tree, body: Tree): Tree = - Apply(Select(qual, meth), List(makeCont(pat, body))); - - atPos(enums.head.pos) { - enums match { - case CaseDef(pat, g, rhs) :: Nil => - makeBind(mapName, rhs, pat, body) - case CaseDef(pat, g, rhs) :: (rest @ (CaseDef(_, _, _) :: _)) => - makeBind(flatMapName, rhs, pat, makeFor(mapName, flatMapName, rest, body)) - case CaseDef(pat, g, rhs) :: test :: rest => - makeFor(mapName, flatMapName, - CaseDef(pat, g, makeBind(nme.filter, rhs, pat.duplicate, test)) :: rest, - body) - } - } - } - - /** Create tree for for-do comprehension */ - def makeFor(enums: List[Tree], body: Tree): Tree = - makeFor(nme.foreach, nme.foreach, enums, body); - - /** Create tree for for-yield comprehension */ - def makeForYield(enums: List[Tree], body: Tree): Tree = - makeFor(nme.map, nme.flatMap, enums, body); - - /** Create tree for a pattern alternative */ - def makeAlternative(ts: List[Tree]): Tree = { - def alternatives(t: Tree): List[Tree] = t match { - case Alternative(ts) => ts - case _ => List(t) - } - Alternative(for (val t <- ts; val a <- alternatives(t)) yield a) - } - - /** Create tree for a pattern sequence */ - def makeSequence(ts: List[Tree]): Tree = { - def elements(t: Tree): List[Tree] = t match { - case Sequence(ts) => ts - case _ => List(t) - } - Sequence(for (val t <- ts; val e <- elements(t)) yield e) - } - - /** Create tree for the p+ regex pattern, becomes p p* */ - def makePlus(p: Tree): Tree = - makeSequence(List(p, Star(p.duplicate))); - - /** Create tree for the p? regex pattern, becomes (p| ) */ - def makeOpt(p: Tree): Tree = - makeAlternative(List(p, Sequence(List()))); - - /** Create visitor x match cases> */ - def makeVisitor(cases: List[CaseDef]): Tree = { - val x = freshName(); - Function(List(ValDef(Modifiers(PARAM | SYNTHETIC), x, TypeTree(), EmptyTree)), Match(Ident(x), cases)) - } - - /** Create tree for case definition rhs> */ - def makeCaseDef(pat: Tree, guard: Tree, rhs: Tree): CaseDef = { - CaseDef(patvarTransformer.transform(pat), guard, rhs); - } - - /** Create tree for pattern definition */ - def makePatDef(mods: Modifiers, pat: Tree, rhs: Tree): List[Tree] = matchVarPattern(pat) match { - case Some(Pair(name, tpt)) => - List(ValDef(mods, name, tpt, rhs)) - - case None => - // in case there are no variables in pattern - // val p = e ==> e.match (case p => ()) - // - // in case there is exactly one variable in pattern - // val x_1 = e.match (case p => (x_1)) - // - // in case there are more variables in pattern - // val p = e ==> private synthetic val t$ = e.match (case p => (x_1, ..., x_N)) - // val x_1 = t$._1 - // ... - // val x_N = t$._N - val pat1 = patvarTransformer.transform(pat); - val vars = getVariables(pat1); - val matchExpr = atPos(pat1.pos){ - Match(rhs, List(CaseDef(pat1, EmptyTree, mkTuple(vars map Ident)))) - } - vars match { - case List() => - List(matchExpr) - case List(vname) => - List(ValDef(mods, vname, TypeTree(), matchExpr)) - case _ => - val tmp = freshName(); - val firstDef = ValDef(Modifiers(PRIVATE | LOCAL | SYNTHETIC), tmp, TypeTree(), matchExpr); - var cnt = 0; - val restDefs = for (val v <- vars) yield { - cnt = cnt + 1; - ValDef(mods, v, TypeTree(), Select(Ident(tmp), newTermName("_" + cnt))) - } - firstDef :: restDefs - } - } - - /** Create a tree representing a function type */ - def makeFunctionTypeTree(argtpes: List[Tree], restpe: Tree): Tree = - AppliedTypeTree( - Select(Ident(nme.scala_), newTypeName("Function" + argtpes.length)), - argtpes ::: List(restpe)); - - /** Append implicit view section if for `implicitViews' if nonempty */ - def addImplicitViews(owner: Name, vparamss: List[List[ValDef]], implicitViews: List[Tree]): List[List[ValDef]] = { - val mods = Modifiers(if (owner.isTypeName) PARAMACCESSOR | LOCAL | PRIVATE else PARAM); - def makeViewParam(tpt: Tree) = ValDef(mods | IMPLICIT, freshName("view$"), tpt, EmptyTree); - if (implicitViews.isEmpty) vparamss - else vparamss ::: List(implicitViews map makeViewParam) - } - - /** Create a tree representing a packaging */ - def makePackaging(pkg: Tree, stats: List[Tree]): PackageDef = pkg match { - case Ident(name) => - PackageDef(name, stats) - case Select(qual, name) => - makePackaging(qual, List(PackageDef(name, stats))) - } -} diff --git a/sources/scala/tools/nsc/backend/ScalaPrimitives.scala b/sources/scala/tools/nsc/backend/ScalaPrimitives.scala deleted file mode 100644 index 91dad33b05..0000000000 --- a/sources/scala/tools/nsc/backend/ScalaPrimitives.scala +++ /dev/null @@ -1,736 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend; - -import scala.tools.nsc.backend.icode._; - -import scala.collection.mutable.{Map, HashMap}; - -/** - * Scala primitive operations are represented as methods in Any and - * AnyVal subclasses. Here we demultiplex them by providing a mapping - * from their symbols to integers. Different methods exist for - * different value types, but with the same meaning (like plus, minus, - * etc.). They will all be mapped to the same int. - * - * Note: The three equal methods have the following semantics: - * - "==" checks for null, and if non-null, calls java.lang.Object.equals - * (class: Any; modifier: final). Primitive: EQ - * - "eq" usual reference comparison - * (class: AnyRef; modifier: final). Primitive: ID - * - "equals" user-defined equality (Java semantics) - * (class: Object; modifier: none). Primitive: EQUALS - * - * Inspired from the scalac compiler. - */ -abstract class ScalaPrimitives { - val global: Global; - - import global._; - import definitions._; - import global.icodes._; - - // Arithmetic unary operations - final val POS = 1; // +x - final val NEG = 2; // -x - final val NOT = 3; // ~x - - // Arithmetic binary operations - final val ADD = 10; // x + y - final val SUB = 11; // x - y - final val MUL = 12; // x * y - final val DIV = 13; // x / y - final val MOD = 14; // x % y - - // Bitwise operations - final val OR = 20; // x | y - final val XOR = 21; // x ^ y - final val AND = 22; // x & y - - // Shift operations - final val LSL = 30; // x << y - final val LSR = 31; // x >>> y - final val ASR = 32; // x >> y - - // Comparison operations - final val ID = 40; // x eq y - final val NI = 41; // x ne y - final val EQ = 42; // x == y - final val NE = 43; // x != y - final val LT = 44; // x < y - final val LE = 45; // x <= y - final val GE = 46; // x > y - final val GT = 47; // x >= y - - // Boolean unary operations - final val ZNOT = 50; // !x - - // Boolean binary operations - final val ZOR = 60; // x || y - final val ZAND = 61; // x && y - - // Array operations - final val LENGTH = 70; // x.length - final val APPLY = 71; // x(y) - final val UPDATE = 72; // x(y) = z - - // Any operations - final val IS = 80; // x.is[y] - final val AS = 81; // x.as[y] - final val EQUALS = 82; // x.equals(y) - final val HASHCODE = 83; // x.hashcode() - final val TOSTRING = 84; // x.toString() - final val ISERASED = 85; // x.is$erased[y] - final val ASERASED = 86; // x.as$erased[y] - - // AnyRef operations - final val SYNCHRONIZED = 90; // x.synchronized(y) - - // String operations - final val CONCAT = 100; // String.valueOf(x)+String.valueOf(y) - - // coercions - final val COERCE = 101; - - // RunTime operations - final val BOX = 110; // RunTime.box_(x) - final val UNBOX = 111; // RunTime.unbox_(x) - final val NEW_ZARRAY = 112; // RunTime.zarray(x) - final val NEW_BARRAY = 113; // RunTime.barray(x) - final val NEW_SARRAY = 114; // RunTime.sarray(x) - final val NEW_CARRAY = 115; // RunTime.carray(x) - final val NEW_IARRAY = 116; // RunTime.iarray(x) - final val NEW_LARRAY = 117; // RunTime.larray(x) - final val NEW_FARRAY = 118; // RunTime.farray(x) - final val NEW_DARRAY = 119; // RunTime.darray(x) - final val NEW_OARRAY = 120; // RunTime.oarray(x) - - final val ZARRAY_LENGTH = 131; // RunTime.zarray_length(x) - final val BARRAY_LENGTH = 132; // RunTime.barray_length(x) - final val SARRAY_LENGTH = 133; // RunTime.sarray_length(x) - final val CARRAY_LENGTH = 134; // RunTime.carray_length(x) - final val IARRAY_LENGTH = 135; // RunTime.iarray_length(x) - final val LARRAY_LENGTH = 136; // RunTime.larray_length(x) - final val FARRAY_LENGTH = 137; // RunTime.farray_length(x) - final val DARRAY_LENGTH = 138; // RunTime.darray_length(x) - final val OARRAY_LENGTH = 139; // RunTime.oarray_length(x) - - final val ZARRAY_GET = 140; // RunTime.zarray_get(x,y) - final val BARRAY_GET = 141; // RunTime.barray_get(x,y) - final val SARRAY_GET = 142; // RunTime.sarray_get(x,y) - final val CARRAY_GET = 143; // RunTime.carray_get(x,y) - final val IARRAY_GET = 144; // RunTime.iarray_get(x,y) - final val LARRAY_GET = 145; // RunTime.larray_get(x,y) - final val FARRAY_GET = 146; // RunTime.farray_get(x,y) - final val DARRAY_GET = 147; // RunTime.darray_get(x,y) - final val OARRAY_GET = 148; // RunTime.oarray_get(x,y) - - final val ZARRAY_SET = 150; // RunTime.zarray(x,y,z) - final val BARRAY_SET = 151; // RunTime.barray(x,y,z) - final val SARRAY_SET = 152; // RunTime.sarray(x,y,z) - final val CARRAY_SET = 153; // RunTime.carray(x,y,z) - final val IARRAY_SET = 154; // RunTime.iarray(x,y,z) - final val LARRAY_SET = 155; // RunTime.larray(x,y,z) - final val FARRAY_SET = 156; // RunTime.farray(x,y,z) - final val DARRAY_SET = 157; // RunTime.darray(x,y,z) - final val OARRAY_SET = 158; // RunTime.oarray(x,y,z) - - final val B2B = 200; // RunTime.b2b(x) - final val B2S = 201; // RunTime.b2s(x) - final val B2C = 202; // RunTime.b2c(x) - final val B2I = 203; // RunTime.b2i(x) - final val B2L = 204; // RunTime.b2l(x) - final val B2F = 205; // RunTime.b2f(x) - final val B2D = 206; // RunTime.b2d(x) - - final val S2B = 210; // RunTime.s2b(x) - final val S2S = 211; // RunTime.s2s(x) - final val S2C = 212; // RunTime.s2c(x) - final val S2I = 213; // RunTime.s2i(x) - final val S2L = 214; // RunTime.s2l(x) - final val S2F = 215; // RunTime.s2f(x) - final val S2D = 216; // RunTime.s2d(x) - - final val C2B = 220; // RunTime.c2b(x) - final val C2S = 221; // RunTime.c2s(x) - final val C2C = 222; // RunTime.c2c(x) - final val C2I = 223; // RunTime.c2i(x) - final val C2L = 224; // RunTime.c2l(x) - final val C2F = 225; // RunTime.c2f(x) - final val C2D = 226; // RunTime.c2d(x) - - final val I2B = 230; // RunTime.i2b(x) - final val I2S = 231; // RunTime.i2s(x) - final val I2C = 232; // RunTime.i2c(x) - final val I2I = 233; // RunTime.i2i(x) - final val I2L = 234; // RunTime.i2l(x) - final val I2F = 235; // RunTime.i2f(x) - final val I2D = 236; // RunTime.i2d(x) - - final val L2B = 240; // RunTime.l2b(x) - final val L2S = 241; // RunTime.l2s(x) - final val L2C = 242; // RunTime.l2c(x) - final val L2I = 243; // RunTime.l2i(x) - final val L2L = 244; // RunTime.l2l(x) - final val L2F = 245; // RunTime.l2f(x) - final val L2D = 246; // RunTime.l2d(x) - - final val F2B = 250; // RunTime.f2b(x) - final val F2S = 251; // RunTime.f2s(x) - final val F2C = 252; // RunTime.f2c(x) - final val F2I = 253; // RunTime.f2i(x) - final val F2L = 254; // RunTime.f2l(x) - final val F2F = 255; // RunTime.f2f(x) - final val F2D = 256; // RunTime.f2d(x) - - final val D2B = 260; // RunTime.d2b(x) - final val D2S = 261; // RunTime.d2s(x) - final val D2C = 262; // RunTime.d2c(x) - final val D2I = 263; // RunTime.d2i(x) - final val D2L = 264; // RunTime.d2l(x) - final val D2F = 265; // RunTime.d2f(x) - final val D2D = 266; // RunTime.d2d(x) - - - private var primitives: Map[Symbol, Int] = _; - - /** Initialize the primitive map */ - def init: Unit = { - primitives = new HashMap(); - - // scala.Any - addPrimitive(Any_==, EQ); - addPrimitive(Any_!=, NE); - addPrimitive(Any_equals, EQUALS); - addPrimitive(Any_hashCode, HASHCODE); - addPrimitive(Any_toString, TOSTRING); - addPrimitive(Any_isInstanceOf, IS); - addPrimitive(Any_asInstanceOf, AS); - addPrimitive(Any_isInstanceOfErased, ISERASED); - addPrimitive(Any_asInstanceOfErased, ASERASED); - - // java.lang.Object - addPrimitive(Object_eq, ID); - addPrimitive(Object_ne, NI); - addPrimitive(Object_==, EQ); - addPrimitive(Object_!=, NE); - addPrimitive(Object_synchronized, SYNCHRONIZED); - addPrimitive(Object_isInstanceOf, IS); - addPrimitive(Object_asInstanceOf, AS); - addPrimitive(Object_equals, EQUALS); - addPrimitive(Object_hashCode, HASHCODE); - addPrimitive(Object_toString, TOSTRING); - - // java.lang.String - addPrimitive(String_+, CONCAT); - - // scala.Array - addPrimitives(ArrayClass, nme.length, LENGTH); - addPrimitives(ArrayClass, nme.apply, APPLY); - addPrimitives(ArrayClass, nme.update, UPDATE); - - // scala.Unit - addPrimitives(UnitClass, nme.EQ, EQ); - addPrimitives(UnitClass, nme.NE, NE); - addPrimitives(UnitClass, nme.equals_, EQUALS); - addPrimitives(UnitClass, nme.hashCode_, HASHCODE); - addPrimitives(UnitClass, nme.toString_, TOSTRING); - - // scala.Boolean - addPrimitives(BooleanClass, nme.EQ, EQ); - addPrimitives(BooleanClass, nme.NE, NE); - addPrimitives(BooleanClass, nme.equals_, EQUALS); - addPrimitives(BooleanClass, nme.hashCode_, HASHCODE); - addPrimitives(BooleanClass, nme.toString_, TOSTRING); - addPrimitive(Boolean_not, ZNOT); - addPrimitive(Boolean_or, ZOR); - addPrimitive(Boolean_and, ZAND); - addPrimitives(BooleanClass, nme.OR, OR); - addPrimitives(BooleanClass, nme.AND, AND); - addPrimitives(BooleanClass, nme.XOR, XOR); - addPrimitives(BooleanClass, nme.ADD, CONCAT); - - // scala.Byte - addCoercions(ByteClass); - addPrimitives(ByteClass, nme.EQ, EQ); - addPrimitives(ByteClass, nme.NE, NE); - addPrimitives(ByteClass, nme.equals_, EQUALS); - addPrimitives(ByteClass, nme.hashCode_, HASHCODE); - addPrimitives(ByteClass, nme.toString_, TOSTRING); - addPrimitives(ByteClass, nme.NOT, NOT); - addPrimitives(ByteClass, nme.ADD, ADD); - addPrimitives(ByteClass, nme.SUB, SUB); - addPrimitives(ByteClass, nme.MUL, MUL); - addPrimitives(ByteClass, nme.DIV, DIV); - addPrimitives(ByteClass, nme.MOD, MOD); - addPrimitives(ByteClass, nme.LT, LT); - addPrimitives(ByteClass, nme.LE, LE); - addPrimitives(ByteClass, nme.GT, GT); - addPrimitives(ByteClass, nme.GE, GE); - addPrimitives(ByteClass, nme.XOR, XOR); - addPrimitives(ByteClass, nme.OR, OR); - addPrimitives(ByteClass, nme.AND, AND); - addPrimitives(ByteClass, nme.LSL, LSL); - addPrimitives(ByteClass, nme.LSR, LSR); - addPrimitives(ByteClass, nme.ASR, ASR); - // conversions - addPrimitives(ByteClass, nme.toByte, B2B); - addPrimitives(ByteClass, nme.toShort, B2S); - addPrimitives(ByteClass, nme.toChar, B2C); - addPrimitives(ByteClass, nme.toInt, B2I); - addPrimitives(ByteClass, nme.toLong, B2L); - addPrimitives(ByteClass, nme.toFloat, B2F); - addPrimitives(ByteClass, nme.toDouble, B2D); - - // scala.Short - addCoercions(ShortClass); - addPrimitives(ShortClass, nme.EQ, EQ); - addPrimitives(ShortClass, nme.NE, NE); - addPrimitives(ShortClass, nme.equals_, EQUALS); - addPrimitives(ShortClass, nme.hashCode_, HASHCODE); - addPrimitives(ShortClass, nme.toString_, TOSTRING); - addPrimitives(ShortClass, nme.NOT, NOT); - addPrimitives(ShortClass, nme.ADD, ADD); - addPrimitives(ShortClass, nme.SUB, SUB); - addPrimitives(ShortClass, nme.MUL, MUL); - addPrimitives(ShortClass, nme.DIV, DIV); - addPrimitives(ShortClass, nme.MOD, MOD); - addPrimitives(ShortClass, nme.LT, LT); - addPrimitives(ShortClass, nme.LE, LE); - addPrimitives(ShortClass, nme.GT, GT); - addPrimitives(ShortClass, nme.GE, GE); - addPrimitives(ShortClass, nme.XOR, XOR); - addPrimitives(ShortClass, nme.OR, OR); - addPrimitives(ShortClass, nme.AND, AND); - addPrimitives(ShortClass, nme.LSL, LSL); - addPrimitives(ShortClass, nme.LSR, LSR); - addPrimitives(ShortClass, nme.ASR, ASR); - // conversions - addPrimitives(ShortClass, nme.toByte, S2B); - addPrimitives(ShortClass, nme.toShort, S2S); - addPrimitives(ShortClass, nme.toChar, S2C); - addPrimitives(ShortClass, nme.toInt, S2I); - addPrimitives(ShortClass, nme.toLong, S2L); - addPrimitives(ShortClass, nme.toFloat, S2F); - addPrimitives(ShortClass, nme.toDouble, S2D); - - // scala.Char - addCoercions(CharClass); - addPrimitives(CharClass, nme.EQ, EQ); - addPrimitives(CharClass, nme.NE, NE); - addPrimitives(CharClass, nme.equals_, EQUALS); - addPrimitives(CharClass, nme.hashCode_, HASHCODE); - addPrimitives(CharClass, nme.toString_, TOSTRING); - addPrimitives(CharClass, nme.NOT, NOT); - addPrimitives(CharClass, nme.ADD, ADD); - addPrimitives(CharClass, nme.SUB, SUB); - addPrimitives(CharClass, nme.MUL, MUL); - addPrimitives(CharClass, nme.DIV, DIV); - addPrimitives(CharClass, nme.MOD, MOD); - addPrimitives(CharClass, nme.LT, LT); - addPrimitives(CharClass, nme.LE, LE); - addPrimitives(CharClass, nme.GT, GT); - addPrimitives(CharClass, nme.GE, GE); - addPrimitives(CharClass, nme.XOR, XOR); - addPrimitives(CharClass, nme.OR, OR); - addPrimitives(CharClass, nme.AND, AND); - addPrimitives(CharClass, nme.LSL, LSL); - addPrimitives(CharClass, nme.LSR, LSR); - addPrimitives(CharClass, nme.ASR, ASR); - // conversions - addPrimitives(CharClass, nme.toByte, C2B); - addPrimitives(CharClass, nme.toShort, C2S); - addPrimitives(CharClass, nme.toChar, C2C); - addPrimitives(CharClass, nme.toInt, C2I); - addPrimitives(CharClass, nme.toLong, C2L); - addPrimitives(CharClass, nme.toFloat, C2F); - addPrimitives(CharClass, nme.toDouble, C2D); - - // scala.Int - addCoercions(IntClass); - addPrimitives(IntClass, nme.EQ, EQ); - addPrimitives(IntClass, nme.NE, NE); - addPrimitives(IntClass, nme.equals_, EQUALS); - addPrimitives(IntClass, nme.hashCode_, HASHCODE); - addPrimitives(IntClass, nme.toString_, TOSTRING); - addPrimitives(IntClass, nme.NOT, NOT); - addPrimitives(IntClass, nme.ADD, ADD); - addPrimitives(IntClass, nme.SUB, SUB); - addPrimitives(IntClass, nme.MUL, MUL); - addPrimitives(IntClass, nme.DIV, DIV); - addPrimitives(IntClass, nme.MOD, MOD); - addPrimitives(IntClass, nme.LT, LT); - addPrimitives(IntClass, nme.LE, LE); - addPrimitives(IntClass, nme.GT, GT); - addPrimitives(IntClass, nme.GE, GE); - addPrimitives(IntClass, nme.XOR, XOR); - addPrimitives(IntClass, nme.OR, OR); - addPrimitives(IntClass, nme.AND, AND); - addPrimitives(IntClass, nme.LSL, LSL); - addPrimitives(IntClass, nme.LSR, LSR); - addPrimitives(IntClass, nme.ASR, ASR); - // conversions - addPrimitives(IntClass, nme.toByte, I2B); - addPrimitives(IntClass, nme.toShort, I2S); - addPrimitives(IntClass, nme.toChar, I2C); - addPrimitives(IntClass, nme.toInt, I2I); - addPrimitives(IntClass, nme.toLong, I2L); - addPrimitives(IntClass, nme.toFloat, I2F); - addPrimitives(IntClass, nme.toDouble, I2D); - - // scala.Long - addCoercions(LongClass); - addPrimitives(LongClass, nme.EQ, EQ); - addPrimitives(LongClass, nme.NE, NE); - addPrimitives(LongClass, nme.equals_, EQUALS); - addPrimitives(LongClass, nme.hashCode_, HASHCODE); - addPrimitives(LongClass, nme.toString_, TOSTRING); - addPrimitives(LongClass, nme.NOT, NOT); - addPrimitives(LongClass, nme.ADD, ADD); - addPrimitives(LongClass, nme.SUB, SUB); - addPrimitives(LongClass, nme.MUL, MUL); - addPrimitives(LongClass, nme.DIV, DIV); - addPrimitives(LongClass, nme.MOD, MOD); - addPrimitives(LongClass, nme.LT, LT); - addPrimitives(LongClass, nme.LE, LE); - addPrimitives(LongClass, nme.GT, GT); - addPrimitives(LongClass, nme.GE, GE); - addPrimitives(LongClass, nme.XOR, XOR); - addPrimitives(LongClass, nme.OR, OR); - addPrimitives(LongClass, nme.AND, AND); - addPrimitives(LongClass, nme.LSL, LSL); - addPrimitives(LongClass, nme.LSR, LSR); - addPrimitives(LongClass, nme.ASR, ASR); - // conversions - addPrimitives(LongClass, nme.toByte, L2B); - addPrimitives(LongClass, nme.toShort, L2S); - addPrimitives(LongClass, nme.toChar, L2C); - addPrimitives(LongClass, nme.toInt, L2I); - addPrimitives(LongClass, nme.toLong, L2L); - addPrimitives(LongClass, nme.toFloat, L2F); - addPrimitives(LongClass, nme.toDouble, L2D); - - // scala.Float - addCoercion(FloatClass); - addPrimitives(FloatClass, nme.EQ, EQ); - addPrimitives(FloatClass, nme.NE, NE); - addPrimitives(FloatClass, nme.equals_, EQUALS); - addPrimitives(FloatClass, nme.hashCode_, HASHCODE); - addPrimitives(FloatClass, nme.toString_, TOSTRING); - addPrimitives(FloatClass, nme.ADD, ADD); - addPrimitives(FloatClass, nme.SUB, SUB); - addPrimitives(FloatClass, nme.MUL, MUL); - addPrimitives(FloatClass, nme.DIV, DIV); - addPrimitives(FloatClass, nme.MOD, MOD); - addPrimitives(FloatClass, nme.LT, LT); - addPrimitives(FloatClass, nme.LE, LE); - addPrimitives(FloatClass, nme.GT, GT); - addPrimitives(FloatClass, nme.GE, GE); - // conversions - addPrimitives(FloatClass, nme.toByte, F2B); - addPrimitives(FloatClass, nme.toShort, F2S); - addPrimitives(FloatClass, nme.toChar, F2C); - addPrimitives(FloatClass, nme.toInt, F2I); - addPrimitives(FloatClass, nme.toLong, F2L); - addPrimitives(FloatClass, nme.toFloat, F2F); - addPrimitives(FloatClass, nme.toDouble, F2D); - - // scala.Double - addPrimitives(DoubleClass, nme.EQ, EQ); - addPrimitives(DoubleClass, nme.NE, NE); - addPrimitives(DoubleClass, nme.equals_, EQUALS); - addPrimitives(DoubleClass, nme.hashCode_, HASHCODE); - addPrimitives(DoubleClass, nme.toString_, TOSTRING); - addPrimitives(DoubleClass, nme.ADD, ADD); - addPrimitives(DoubleClass, nme.SUB, SUB); - addPrimitives(DoubleClass, nme.MUL, MUL); - addPrimitives(DoubleClass, nme.DIV, DIV); - addPrimitives(DoubleClass, nme.MOD, MOD); - addPrimitives(DoubleClass, nme.LT, LT); - addPrimitives(DoubleClass, nme.LE, LE); - addPrimitives(DoubleClass, nme.GT, GT); - addPrimitives(DoubleClass, nme.GE, GE); - // conversions - addPrimitives(DoubleClass, nme.toByte, D2B); - addPrimitives(DoubleClass, nme.toShort, D2S); - addPrimitives(DoubleClass, nme.toChar, D2C); - addPrimitives(DoubleClass, nme.toInt, D2I); - addPrimitives(DoubleClass, nme.toLong, D2L); - addPrimitives(DoubleClass, nme.toFloat, D2F); - addPrimitives(DoubleClass, nme.toDouble, D2D); - - // and the type map! - initPrimitiveTypeMap; - } - - /** Add a primitive operation to the map */ - def addPrimitive(s: Symbol, code: Int): Unit = { - assert(!(primitives contains s), "Duplicate primitive " + s); - primitives += s -> code; - } - - def addPrimitives(cls: Symbol, method: Name, code: Int): Unit = { - val tpe = cls.info; - val sym = tpe.member(method); - sym.info match { - case OverloadedType(pre, alternatives) => - log("Adding " + alternatives.length + " overloads for " + sym.fullNameString); - code match { - case SUB => - alternatives foreach ((s) => - if (s.info.paramTypes.length == 0) - addPrimitive(s, NEG); // unary - else - addPrimitive(s, code)); - - case ADD => - alternatives foreach ((s) => - if (s.info.paramTypes.length == 0) - addPrimitive(s, POS); // unary - else if (s.info.paramTypes.head == definitions.StringClass.tpe) - addPrimitive(s, CONCAT); // string concatenation - else - addPrimitive(s, code)); - - case _ => - alternatives foreach ((s) => addPrimitive(s, code)); - } - - case _ => - addPrimitive(sym, code); - } - } - - def addCoercion(cls: Symbol) = { - assert(cls == FloatClass, - "Only scala.Double has non-overloaded 'coerce'"); - val method = cls.info.member(nme.coerce); - addPrimitive(method, F2D); - } - - def addCoercions(cls: Symbol): Unit = { - val OverloadedType(_, coercions) = cls.info.member(nme.coerce).info; - if (cls == ByteClass) - coercions foreach ((m) => - if (m.info.resultType == ShortClass.tpe) - addPrimitive(m, B2S) - else if (m.info.resultType == IntClass.tpe) - addPrimitive(m, B2I) - else if (m.info.resultType == LongClass.tpe) - addPrimitive(m, B2L) - else if (m.info.resultType == FloatClass.tpe) - addPrimitive(m, B2F) - else if (m.info.resultType == DoubleClass.tpe) - addPrimitive(m, B2D) - else - abort("Unknown coercion method: " + m.info) - ) - else if (cls == ShortClass) - coercions foreach ((m) => - if (m.info.resultType == IntClass.tpe) - addPrimitive(m, S2I) - else if (m.info.resultType == LongClass.tpe) - addPrimitive(m, S2L) - else if (m.info.resultType == FloatClass.tpe) - addPrimitive(m, S2F) - else if (m.info.resultType == DoubleClass.tpe) - addPrimitive(m, S2D) - else - abort("Unknown coercion method: " + m.fullNameString) - ) - else if (cls == CharClass) - coercions foreach ((m) => - if (m.info.resultType == IntClass.tpe) - addPrimitive(m, C2I) - else if (m.info.resultType == LongClass.tpe) - addPrimitive(m, C2L) - else if (m.info.resultType == FloatClass.tpe) - addPrimitive(m, C2F) - else if (m.info.resultType == DoubleClass.tpe) - addPrimitive(m, C2D) - else - abort("Unknown coercion method: " + m.fullNameString) - ) - else if (cls == IntClass) - coercions foreach ((m) => - if (m.info.resultType == LongClass.tpe) - addPrimitive(m, I2L) - else if (m.info.resultType == FloatClass.tpe) - addPrimitive(m, I2F) - else if (m.info.resultType == DoubleClass.tpe) - addPrimitive(m, I2D) - else - abort("Unknown coercion method: " + m.fullNameString) - ) - else if (cls == LongClass) - coercions foreach ((m) => - if (m.info.resultType == FloatClass.tpe) - addPrimitive(m, L2F) - else if (m.info.resultType == DoubleClass.tpe) - addPrimitive(m, L2D) - else - abort("Unknown coercion method: " + m.fullNameString) - ) - else if (cls == FloatClass) - coercions foreach ((m) => - if (m.info.resultType == DoubleClass.tpe) - addPrimitive(m, F2D) - else - abort("Unknown coercion method: " + m.fullNameString) - ) - else - abort("Unknown value type: " + cls.fullNameString); - } - - def isCoercion(code: Int): Boolean = (code >= B2B) && (code <= D2D); - - /** Check whether the given operation code is an array operation. */ - def isArrayOp(code: Int): Boolean = - isArrayNew(code) | isArrayLength(code) | isArrayGet(code) | isArraySet(code); - - def isArrayNew(code: Int): Boolean = code match { - case NEW_ZARRAY | NEW_BARRAY | NEW_SARRAY | NEW_CARRAY | - NEW_IARRAY | NEW_LARRAY | NEW_FARRAY | NEW_DARRAY | - NEW_OARRAY => true; - case _ => false; - } - - def isArrayLength(code: Int): Boolean = code match { - case ZARRAY_LENGTH | BARRAY_LENGTH | SARRAY_LENGTH | CARRAY_LENGTH | - IARRAY_LENGTH | LARRAY_LENGTH | FARRAY_LENGTH | DARRAY_LENGTH | - OARRAY_LENGTH | LENGTH => true; - case _ => false; - } - - def isArrayGet(code: Int): Boolean = code match { - case ZARRAY_GET | BARRAY_GET | SARRAY_GET | CARRAY_GET | - IARRAY_GET | LARRAY_GET | FARRAY_GET | DARRAY_GET | - OARRAY_GET | APPLY => true; - case _ => false; - } - - def isArraySet(code: Int): Boolean = code match { - case ZARRAY_SET | BARRAY_SET | SARRAY_SET | CARRAY_SET | - IARRAY_SET | LARRAY_SET | FARRAY_SET | DARRAY_SET | - OARRAY_SET | UPDATE => true; - case _ => false; - } - - /** Check whether the given code is a comparison operator */ - def isComparisonOp(code: Int): Boolean = code match { - case ID | NI | EQ | NE | - LT | LE | GT | GE => true; - - case _ => false; - } - - def isArithmeticOp(code: Int): Boolean = code match { - case POS | NEG | NOT => true; // unary - case ADD | SUB | MUL | - DIV | MOD => true; // binary - case OR | XOR | AND | - LSL | LSR | ASR => true; // bitwise - case _ => false; - } - - def isLogicalOp(code: Int): Boolean = code match { - case ZNOT | ZAND | ZOR => true; - case _ => false; - } - - def isShiftOp(code: Int): Boolean = code match { - case LSL | LSR | ASR => true; - case _ => false; - } - - def isBitwiseOp(code: Int): Boolean = code match { - case OR | XOR | AND => true; - case _ => false; - } - - def isPrimitive(sym: Symbol): Boolean = primitives contains sym; - - /** Return the code for the givem symbol. */ - def getPrimitive(sym: Symbol): Int = { - assert(isPrimitive(sym), "Unkown primitive " + sym); - primitives(sym); - } - - /** - * Return the primitive code of the given operation. If the - * operation is an array get/set, we inspect the type of the receiver - * to demux the operation. - * - * @param fun The method symbol - * @param tpe The type of the receiver object. It is used only for array - * operations - */ - def getPrimitive(fun: Symbol, tpe: Type): Int = { - import definitions._; - val code = getPrimitive(fun); - - var elem: Type = null; - tpe match { - case TypeRef(_, sym, _elem :: Nil) - if (sym == ArrayClass) => elem = _elem; - case _ => (); - } - - code match { - - case APPLY => - toTypeKind(elem) match { - case BOOL => ZARRAY_GET; - case BYTE => BARRAY_GET; - case SHORT => SARRAY_GET; - case CHAR => CARRAY_GET; - case INT => IARRAY_GET; - case LONG => LARRAY_GET; - case FLOAT => FARRAY_GET; - case DOUBLE => DARRAY_GET; - case REFERENCE(_) | ARRAY(_) => OARRAY_GET; - case _ => - abort("Unexpected array element type: " + elem); - } - - case UPDATE => - toTypeKind(elem) match { - case BOOL => ZARRAY_SET; - case BYTE => BARRAY_SET; - case SHORT => SARRAY_SET; - case CHAR => CARRAY_SET; - case INT => IARRAY_SET; - case LONG => LARRAY_SET; - case FLOAT => FARRAY_SET; - case DOUBLE => DARRAY_SET; - case REFERENCE(_) | ARRAY(_) => OARRAY_SET; - case _ => - abort("Unexpected array element type: " + elem); - } - - case LENGTH => - toTypeKind(elem) match { - case BOOL => ZARRAY_LENGTH; - case BYTE => BARRAY_LENGTH; - case SHORT => SARRAY_LENGTH; - case CHAR => CARRAY_LENGTH; - case INT => IARRAY_LENGTH; - case LONG => LARRAY_LENGTH; - case FLOAT => FARRAY_LENGTH; - case DOUBLE => DARRAY_LENGTH; - case REFERENCE(_) | ARRAY(_) => OARRAY_LENGTH; - case _ => - abort("Unexpected array element type: " + elem); - } - - case _ => - code; - } - } - -} diff --git a/sources/scala/tools/nsc/backend/WorklistAlgorithm.scala b/sources/scala/tools/nsc/backend/WorklistAlgorithm.scala deleted file mode 100644 index 6676c820bc..0000000000 --- a/sources/scala/tools/nsc/backend/WorklistAlgorithm.scala +++ /dev/null @@ -1,50 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend; - -import scala.tools.nsc.ast._; -import scala.collection.mutable.MutableList; - -/** - * Simple implementation of a worklist algorithm. A processing - * function is applied repeatedly to the first element in the - * worklist, as long as the stack is not empty. - * - * The client class should mix-in this trait and initialize the - * worklist field and define the processElement method. Then call - * the 'run' method providing a function that initializes the - * worklist. - * - * @see scala.tools.nsc.backend.icode.Linearizers - */ -trait WorklistAlgorithm { - type Elem; - type WList <: MutableList[Elem]; - - val worklist: WList; - - /** - * Run the iterative algorithm until the worklist - * remains empty. The initializer is run once before - * the loop starts and should initialize the worklist. - */ - def run(initWorklist: => Unit) = { - initWorklist; - - while (!(worklist.length == 0)) - processElement(dequeue); - } - - /** - * Process the current element from the worklist. - */ - def processElement(e: Elem): Unit; - - /** Remove and return the first element to be processed from the worklist. */ - def dequeue: Elem; -} diff --git a/sources/scala/tools/nsc/backend/icode/BasicBlocks.scala b/sources/scala/tools/nsc/backend/icode/BasicBlocks.scala deleted file mode 100644 index 6fdbe98c57..0000000000 --- a/sources/scala/tools/nsc/backend/icode/BasicBlocks.scala +++ /dev/null @@ -1,269 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -import scala.tools.nsc.ast._; -import scala.collection.mutable.Map; -import scala.tools.nsc.util.Position; - -trait BasicBlocks: ICodes { - import opcodes._; - - /** This class represents a basic block. Each - * basic block contains a list of instructions that are - * either executed all, or none. No jumps - * to/from the "middle" of the basic block are allowed. - */ - class BasicBlock (theLabel: int, val code: Code) { - - /** The type stack at the begining of the block */ - var initialStack : TypeStack = null; - - /** The label of the block */ - val label = theLabel; - - /** The substitute variables of the block - * in the case of a recursive method */ - var substituteVars : List[Symbol] = null; - - /** The stack at the end of the block */ - var endStack : TypeStack = null; - - /** When set, the 'emit' methods will be ignored. */ - var ignore: Boolean = false; - - var preds: List[BasicBlock] = null; - - /** ICode instructions, used as temporary storage while emitting code. - * Once closed is called, only the `instrs' array should be used. - */ - private var instructionList: List[Instruction] = Nil; - - private var _lastInstruction: Instruction = null; - - private var closed: boolean = false; - - private var instrs: Array[Instruction] = _; - - // public: - - /** Compute an hashCode for the block */ - override def hashCode() = label; - - /** Apply a function to all the instructions of the block. */ - def traverse(f: Instruction => unit) = { - assert(closed, "Traversing an open block!: "); - instrs foreach f; - } - - def traverseBackwards(f: Instruction => Unit) = { - var i = instrs.length - 1; - while (i >= 0) { - f(instrs(i)); - i = i - 1 - } - } - - /** The number of instructions in this basic block so far. */ - def size: Int = - if (isClosed) - instrs.length; - else - instructionList.length; - - /** Initialize the stack of the block, must be done before evaluation - * the type stack */ - def initStack(stack : TypeStack) = { - if (initialStack == null) { - initialStack = stack; - endStack = null; - } - } - - ///////////////////// Substitutions /////////////////////// - - /** - * Replace the instruction at the given position. Used by labels when - * they are anchored. - */ - def replaceInstruction(pos: Int, instr: Instruction): Boolean = { - assert(closed, "Instructions can be replaced only after the basic block is closed"); - - instrs(pos) = instr; - true - } - - /** - * Replace the given instruction with the new one. - * Returns `true' if it actually changed something. - */ - def replaceInstruction(oldInstr: Instruction, newInstr: Instruction): Boolean = { - assert(closed, "Instructions can be replaced only after the basic block is closed"); - - var i = 0; - var changed = false; - while (i < instrs.length && !changed) { - if (instrs(i) == oldInstr) { - instrs(i) = newInstr; - changed = true; - } - i = i + 1; - } - changed - } - - /** Replace all instructions found in the map. */ - def subst(map: Map[Instruction, Instruction]) = - if (!closed) substOnList(map) else { - var i = 0; - while (i < instrs.length) { - map get instrs(i) match { - case Some(instr) => replaceInstruction(i, instr); - case None => (); - } - i = i + 1; - } - } - - private def substOnList(map: Map[Instruction, Instruction]): Unit = { - def subst(l: List[Instruction]): List[Instruction] = l match { - case Nil => Nil - case x :: xs => - map.get(x) match { - case Some(newInstr) => newInstr :: subst(xs); - case None => x :: subst(xs); - } - } - - instructionList = subst(instructionList); - } - - ////////////////////// Emit ////////////////////// - - - /** Add a new instruction at the end of the block, - * using the same source position as the last emitted instruction - */ - def emit(instr: Instruction): Unit = { - if (!instructionList.isEmpty) - emit(instr, instructionList.head.pos); - else - emit(instr, Position.NOPOS); - } - - def emit(instr: Instruction, pos: Int) = { - assert (!closed || ignore, "BasicBlock closed"); - - if (!ignore) { -// Console.println("block " + label + ": " + instr); - instr.pos = pos; - instructionList = instr :: instructionList; - _lastInstruction = instr; - } - } - - /** Close the block */ - def close = { - assert(instructionList.length > 0, - "Empty block."); - closed = true; - instrs = toInstructionArray(instructionList.reverse); - } - - def isEmpty: Boolean = instructionList.isEmpty; - - /** Enter ignore mode: new 'emit'ted instructions will not be - * added to this basic block. It makes the generation of THROW - * and RETURNs easier. - */ - def enterIgnoreMode = ignore = true; - - def exitIgnoreMode = { - assert(ignore, "Exit ignore mode when not in ignore mode."); - ignore = false; - } - - /** Return the last instruction of this basic block. */ - def lastInstruction = - if (closed) - instrs(instrs.length - 1) - else - instructionList.head; - - def firstInstruction = - if (closed) - instrs(0) - else - instructionList.last; - - /** Convert the list to an array */ - def toInstructionArray(l: List[Instruction]): Array[Instruction] = { - var array = new Array[Instruction](l.length); - var i: Int = 0; - - l foreach (x => { array(i) = x; i = i + 1 }); - array - } - - def isClosed = closed; - - // TODO: Take care of exception handlers! - def successors : List[BasicBlock] = if (isEmpty) Nil else - lastInstruction match { - case JUMP (where) => List(where); - case CJUMP(success, failure, _, _) => failure::success::Nil; - case CZJUMP(success, failure, _, _) => failure::success::Nil; - case SWITCH(_,labels) => labels; - case RETURN(_) => Nil; - case THROW() => Nil; - case _ => - if (isClosed) - global.abort("The last instruction is not a control flow instruction: " + lastInstruction); - else Nil; - } - - /** Returns the precessors of this block, in the current 'code' chunk. - * This is signifficant only if there are exception handlers, which live - * in different code 'chunks' than the rest of the method. - */ - def predecessors: List[BasicBlock] = { - if (preds == null) - preds = code.blocks.elements.filter (p => (p.successors contains this)).toList; - preds - } - - override def equals(other: Any): Boolean = ( - other.isInstanceOf[BasicBlock] && - other.asInstanceOf[BasicBlock].label == label && - other.asInstanceOf[BasicBlock].code == code - ); - - // Instead of it, rather use a printer - def print() : unit = print(System.out); - - def print(out: java.io.PrintStream) : unit = { - out.println("block #"+label+" :"); - instructionList.reverse.foreach( - (i: Instruction) => out.println(" "+i)); - out.print("Successors: "); - successors.foreach((x: BasicBlock) => out.print(" "+x.label.toString())); - out.println(); - } - - def fullString: String = { - val buf = new StringBuffer(); - buf.append("Block ").append(label.toString()); - buf.append("\nSuccessors: ").append(successors); - buf.append("\nPredecessors: ").append(predecessors); - buf.toString() - } - - override def toString(): String = "" + label; - } - -} diff --git a/sources/scala/tools/nsc/backend/icode/CheckerError.scala b/sources/scala/tools/nsc/backend/icode/CheckerError.scala deleted file mode 100644 index da1232b6e9..0000000000 --- a/sources/scala/tools/nsc/backend/icode/CheckerError.scala +++ /dev/null @@ -1,11 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -class CheckerError(s: String) extends Exception(s); - diff --git a/sources/scala/tools/nsc/backend/icode/Checkers.scala b/sources/scala/tools/nsc/backend/icode/Checkers.scala deleted file mode 100644 index 8aba76fa97..0000000000 --- a/sources/scala/tools/nsc/backend/icode/Checkers.scala +++ /dev/null @@ -1,591 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -import scala.collection.mutable.{Buffer, ListBuffer, Map, HashMap}; -import scala.tools.nsc.symtab._; - -abstract class Checkers { - val global: Global; - import global._; - import global.icodes.toTypeKind; - - /** - * This class performs a set of checks similar to what the bytecode - * verifier does. For each basic block, it checks that: - * - * - for primitive operations: the type and numer of operands match - * the type of the operation - * - * - for method calls: the method exists in the type of the receiver - * and the number and type of arguments match the declared type of - * the method. - * - * - for object creation: the constructor can be called. - * - * - for load/stores: the field/local/param exists and the type - * of the value matches that of the target. - * - * For a control flow graph it checks that type stacks at entry to - * each basic block 'agree': - * - * - they have the same length - * - there exists a lub for all types at the same position in stacks. - * - * TODO: Better checks for MONITOR_ENTER/EXIT - * Better checks for local var initializations - */ - class ICodeChecker { - import icodes._; - import opcodes._; - - var clasz: IClass = _; - var method: IMethod = _; - var code: Code = _; - - val in: Map[BasicBlock, TypeStack] = new HashMap(); - val out: Map[BasicBlock, TypeStack] = new HashMap(); - - val emptyStack = new TypeStack(); - - val STRING = REFERENCE(definitions.StringClass); - val SCALA_ALL = REFERENCE(definitions.AllClass); - val SCALA_ALL_REF = REFERENCE(definitions.AllRefClass); - val CASE_CLASS = REFERENCE(definitions.getClass("scala.CaseClass")); - - def checkICodes: Unit = { - Console.println("[[consistency check at beginning of phase " + globalPhase.name + "]]"); - classes foreach check; - } - - def check(cls: IClass): Unit = { - log("Checking class " + cls); - clasz = cls; - - for (val f1 <- cls.fields; val f2 <- cls.fields; f1 ne f2) - if (f1.symbol.name == f2.symbol.name) - Checkers.this.global.error("Repetitive field name: " + - f1.symbol.fullNameString); - - for (val m1 <- cls.methods; val m2 <- cls.methods; m1 ne m2) - if (m1.symbol.name == m2.symbol.name && - m1.symbol.tpe =:= m2.symbol.tpe) - Checkers.this.global.error("Repetitive method: " + - m1.symbol.fullNameString); - clasz.methods.foreach(check); - } - - /** Apply the give funtion to each pair of the cartesian product of - * l1 x l2. - */ - def pairwise[a](l1: List[a], l2: List[a])(f: (a, a) => Unit) = - l1 foreach { x => - l2 foreach { y => f(x, y) } - } - - def check(m: IMethod): Unit = { - log("Checking method " + m); - method = m; - if (!m.isDeferred) - check(m.code); - } - - def check(c: Code): Unit = { - var worklist: Buffer[BasicBlock] = new ListBuffer(); - - def append(elems: List[BasicBlock]) = elems foreach appendBlock; - def appendBlock(bl: BasicBlock) = - if ( !worklist.exists(bl.==) ) - worklist + bl; - - in.clear; out.clear; - code = c; - worklist + c.startBlock; - c.blocks foreach ( bl => { in += bl -> emptyStack; - out += bl -> emptyStack } ); - - while (worklist.length > 0) { - val block = worklist(0); worklist.trimStart(1); - val output = check(block, in(block)); - if (output != out(block) || - (out(block) eq emptyStack)) { - log("Output changed for block: " + block.fullString); - out(block) = output; - append(block.successors); - block.successors foreach meet; - } - } - } - - /** - * Apply the meet operator of the stack lattice on bl's predecessors. - * :-). Compute the input to bl by checking that all stacks have the - * same length, and taking the lub of types at the same positions. - */ - def meet(bl: BasicBlock): Unit = { - val preds = bl.predecessors; - - def meet2(s1: TypeStack, s2: TypeStack): TypeStack = { - if (s1 eq emptyStack) s2 - else if (s2 eq emptyStack) s1 - else { - if (s1.length != s2.length) - throw new CheckerError("Incompatible stacks: " + s1 + " and " + s2 + " in " + method + " at entry to block: " + bl); - new TypeStack(List.map2(s1.types, s2.types) (lub)) - } - } - - if (preds != Nil) { - in(bl) = (preds map out.apply) reduceLeft meet2; - log("Input changed for block: " + bl +" to: " + in(bl)); - } - } - - - private var typeStack: TypeStack = null; - private var instruction: Instruction = null; - private var basicBlock: BasicBlock = null; - - /** - * Check the basic block to be type correct and return the - * produced type stack. - */ - def check(b: BasicBlock, initial: TypeStack): TypeStack = { - log("** Checking block:\n" + b.fullString + " with initial stack:\n" + initial); - var stack = new TypeStack(initial); - - this.typeStack = stack; - this.basicBlock = b; - - def typeError(k1: TypeKind, k2: TypeKind): Unit = - error(" expected: " + k1 + " but " + k2 + " found"); - - b traverse (instr => { - - def checkStack(len: Int) = - if (stack.length < len) - ICodeChecker.this.error("Expected at least " + len + " elements on the stack", stack); - else - (); - - def checkLocal(local: Local) = - method.lookupLocal(local.sym.name) match { - case None => error(" " + local + " is not defined in method " + method); - case _ => () - } - - def checkField(obj: TypeKind, field: Symbol) = - obj match { - case REFERENCE(sym) => - if (sym.info.member(field.name) == NoSymbol) - error(" " + field + " is not defined in class " + clasz); - case _ => - error(" expected reference type, but " + obj + " found"); - } - - /** Checks that tpe is a subtype of one of the allowed types */ - def checkType(tpe: TypeKind, allowed: TypeKind*) = - if (isOneOf(tpe, allowed: _*)) - () - else - error(tpe.toString() + " is not one of: " + allowed); - - /** Checks that the 2 topmost elements on stack are of the - * kind TypeKind. - */ - def checkBinop(kind: TypeKind) = { - val Pair(a, b) = stack.pop2; - checkType(a, kind); - checkType(b, kind); - } - - /** Check that arguments on the stack match method params. */ - def checkMethodArgs(method: Symbol) = { - val params = method.info.paramTypes; - checkStack(params.length); - params.reverse.foreach( (tpe) => checkType(stack.pop, toTypeKind(tpe))); - } - - /** Checks that the object passed as receiver has a method - * 'method' and that it is callable from the current method. - */ - def checkMethod(receiver: TypeKind, method: Symbol) = - receiver match { - case REFERENCE(sym) => - checkBool(sym.info.member(method.name) != NoSymbol, - "Method " + method + " does not exist in " + sym.fullNameString); - if (method hasFlag Flags.PRIVATE) - checkBool(method.owner == clasz.symbol, - "Cannot call private method of " + method.owner.fullNameString - + " from " + clasz.symbol.fullNameString); - else if (method hasFlag Flags.PROTECTED) - checkBool(clasz.symbol isSubClass method.owner, - "Cannot call protected method of " + method.owner.fullNameString - + " from " + clasz.symbol.fullNameString); - - case ARRAY(_) => - checkBool(receiver.toType.member(method.name) != NoSymbol, - "Method " + method + " does not exist in " + receiver); - - case t => - error("Not a reference type: " + t); - } - - def checkBool(cond: Boolean, msg: String) = - if (cond) () else error(msg); - - this.instruction = instr; - - if (settings.debug.value) { - log("PC: " + instr); - log("stack: " + stack); - log("================"); - } - instr match { - case THIS(clasz) => - stack push toTypeKind(clasz.tpe); - - case CONSTANT(const) => - stack push toTypeKind(const.tpe); - - case LOAD_ARRAY_ITEM(kind) => - checkStack(2); - stack.pop2 match { - case Pair(INT, ARRAY(elem)) => - if (!(elem <:< kind)) - typeError(kind, elem); - stack.push(elem); - case Pair(a, b) => - error(" expected and INT and a array reference, but " + - a + ", " + b + " found"); - } - - case LOAD_LOCAL(local, isArg) => - checkLocal(local); - stack.push(local.kind); - - case LOAD_FIELD(field, isStatic) => - if (isStatic) { - // the symbol's owner should contain it's field, but - // this is already checked by the type checker, no need - // to redo that here - } else { - checkStack(1); - val obj = stack.pop; - checkField(obj, field); - } - stack.push(toTypeKind(field.tpe)); - - case LOAD_MODULE(module) => - checkBool((module.isModule || module.isModuleClass), - "Expected module: " + module + " flags: " + Flags.flagsToString(module.flags)); - stack.push(toTypeKind(module.tpe)); - - case STORE_ARRAY_ITEM(kind) => - checkStack(3); - stack.pop3 match { - case Triple(k, INT, ARRAY(elem)) => - if (!(k <:< kind)) - typeError(kind, k); - if (!(k <:< elem)) - typeError(elem, k); - case Triple(a, b, c) => - error(" expected and array reference, and int and " + kind + - " but " + a + ", " + b + ", " + c + " found"); - } - - case STORE_LOCAL(local, isArg) => - checkLocal(local); - checkStack(1); - - val actualType = stack.pop; - if (!(actualType <:< local.kind) && - actualType != CASE_CLASS && - local.kind != SCALA_ALL_REF) - typeError(local.kind, actualType); - - case STORE_FIELD(field, isStatic) => - if (isStatic) { - checkStack(1); - val fieldType = toTypeKind(field.tpe); - val actualType = stack.pop; - if (!(actualType <:< fieldType)) - typeError(fieldType, actualType); - } else { - checkStack(2); - stack.pop2 match { - case Pair(value, obj) => - checkField(obj, field); - val fieldType = toTypeKind(field.tpe); - if (fieldType != SCALA_ALL_REF && !(value <:< fieldType)) - typeError(fieldType, value); - } - } - - case CALL_PRIMITIVE(primitive) => - checkStack(instr.consumed); - primitive match { - case Negation(kind) => - checkType(kind, BOOL, BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE); - checkType(stack.pop, kind); - stack push kind; - - case Test(op, kind, zero) => - if (zero) { - val actualType = stack.pop; - checkType(actualType, kind); - } else - checkBinop(kind); - stack push BOOL; - - case Comparison(op, kind) => - checkType(kind, BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE); - checkBinop(kind); - stack push INT; - - case Arithmetic(op, kind) => - checkType(kind, BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE); - if (op == NOT) - checkType(stack.pop, kind) - else - checkBinop(kind); - stack push kind; - - case Logical(op, kind) => - checkType(kind, BOOL, BYTE, CHAR, SHORT, INT, LONG); - checkBinop(kind); - stack push kind; - - case Shift(op, kind) => - checkType(kind, BYTE, CHAR, SHORT, INT, LONG); - val Pair(a, b) = stack.pop2; - checkType(a, INT); - checkType(b, kind); - stack push kind; - - case Conversion(src, dst) => - checkType(src, BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE); - checkType(dst, BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE); - checkType(stack.pop, src); - stack push dst; - - case ArrayLength(kind) => - val arr = stack.pop; - arr match { - case ARRAY(elem) => - checkType(elem, kind); - case _ => - error(" array reference expected, but " + arr + " found"); - } - stack push INT; - - case StartConcat => - stack.push(ConcatClass); - - case EndConcat => - checkType(stack.pop, ConcatClass); - stack.push(STRING); - - case StringConcat(el) => - checkType(stack.pop, el); - checkType(stack.pop, ConcatClass); - stack push ConcatClass; - } - - case CALL_METHOD(method, style) => - style match { - case Dynamic => - checkStack(1 + method.info.paramTypes.length); - checkMethodArgs(method); - checkMethod(stack.pop, method); - stack.push(toTypeKind(method.info.resultType)); - - case Static(onInstance) => - if (onInstance) { - checkStack(1 + method.info.paramTypes.length); - checkBool(method.hasFlag(Flags.PRIVATE) || method.isConstructor, - "Static call to non-private method."); - checkMethodArgs(method); - checkMethod(stack.pop, method); - if (!method.isConstructor) - stack.push(toTypeKind(method.info.resultType)); - } else { - checkStack(method.info.paramTypes.length); - checkMethodArgs(method); - stack.push(toTypeKind(method.info.resultType)); - } - - case SuperCall(mixin) => - checkStack(1 + method.info.paramTypes.length); - checkMethodArgs(method); - checkMethod(stack.pop, method); - stack.push(toTypeKind(method.info.resultType)); - - } - - case NEW(kind) => - kind match { - case REFERENCE(cls) => - stack.push(kind); - - case _ => error("NEW call to non-reference type: " + kind); - } - - case CREATE_ARRAY(elem) => - checkStack(1); - checkType(stack.pop, INT); - stack.push(ARRAY(elem)); - - case IS_INSTANCE(tpe) => - val ref = stack.pop; - checkBool(ref.isReferenceType || ref.isArrayType, - "IS_INSTANCE on primitive type: " + ref); - checkBool(tpe.isReferenceType || tpe.isArrayType, - "IS_INSTANCE to primitive type: " + tpe); - stack.push(BOOL); - - case CHECK_CAST(tpe) => - val ref = stack.pop; - checkBool(ref.isReferenceType || ref.isArrayType, - "CHECK_CAST on primitive type: " + ref); - checkBool(tpe.isReferenceType || tpe.isArrayType, - "CHECK_CAST to primitive type: " + tpe); - stack.push(tpe); - - case SWITCH(tags, labels) => - checkType(stack.pop, INT); - checkBool(tags.length == labels.length - 1, - "The number of tags and labels does not coincide."); - checkBool(labels forall (b => code.blocks contains b), - "Switch target cannot be found in code."); - - case JUMP(where) => - checkBool(code.blocks contains where, - "Jump to non-existant block " + where); - - case CJUMP(success, failure, cond, kind) => - checkBool(code.blocks contains success, - "Jump to non-existant block " + success); - checkBool(code.blocks contains failure, - "Jump to non-existant block " + failure); - checkBinop(kind); - - case CZJUMP(success, failure, cond, kind) => - checkBool(code.blocks contains success, - "Jump to non-existant block " + success); - checkBool(code.blocks contains failure, - "Jump to non-existant block " + failure); - checkType(stack.pop, kind); - - case RETURN(kind) => - kind match { - case UNIT => (); - - case REFERENCE(_) | ARRAY(_) => - checkStack(1); - val top = stack.pop; - checkBool(top.isReferenceType || top.isArrayType, - "" + kind + " is a reference type, but " + top + " is not"); - case _ => - checkStack(1); - val top = stack.pop; - checkType(top, kind); - } - - case THROW() => - val thrown = stack.pop; - checkBool(thrown.toType <:< definitions.ThrowableClass.tpe, - "Element on top of stack should implement 'Throwable': " + thrown); - stack.push(SCALA_ALL); - - case DROP(kind) => - checkType(stack.pop, kind); - - case DUP(kind) => - val top = stack.pop; - checkType(top, kind); - stack.push(top); - stack.push(top); - - case MONITOR_ENTER() => - checkStack(1); - checkBool(stack.pop.isReferenceType, - "MONITOR_ENTER on non-reference type"); - - case MONITOR_EXIT() => - checkStack(1); - checkBool(stack.pop.isReferenceType, - "MONITOR_EXIT on non-reference type"); - - case _ => abort("Unknown instruction: " + instr); - } - }); - stack - } - - //////////////// Error reporting ///////////////////////// - - def error(msg: String): Unit = { - System.out.println(method.toString() + " in block: " + basicBlock.label); - printLastIntructions; - - Checkers.this.global.error("ICode checker: " + method + ": " + msg); - } - - /** Prints the last 4 instructions. */ - def printLastIntructions = { - var printed = 0; - var buf: List[Instruction] = Nil; - - basicBlock.traverseBackwards( (i) => - if (i == instruction || (printed > 0 && printed < 3)) { - buf = i :: buf; - printed = printed + 1; - }); - buf foreach System.out.println; - Console.println("at: " + clasz.cunit.position(buf.head.pos)); - } - - def error(msg: String, stack: TypeStack): Unit = { - error(msg + "\n type stack: " + stack); - } - - - //////////////////// Checking ///////////////////////////// - - /** Return true if k1 is a subtype of any of the following types. */ - def isOneOf(k1: TypeKind, kinds: TypeKind*) = - kinds.exists( k => k1 <:< k); - - - /** - * Dummy TypeKind to represent the ConcatClass in a platform-independent - * way. For JVM it would have been a REFERENCE to 'StringBuffer'. - */ - case object ConcatClass extends TypeKind { - override def toString() = "ConcatClass"; - - /** - * Approximate `lub'. The common type of two references is - * always AnyRef. For 'real' least upper bound wrt to subclassing - * use method 'lub'. - */ - override def maxType(other: TypeKind): TypeKind = - other match { - case REFERENCE(_) => REFERENCE(definitions.AnyRefClass); - case _ => - abort("Uncomparbale type kinds: ConcatClass with " + other); - } - - /** Checks subtyping relationship. */ - override def <:<(other: TypeKind): Boolean = (this eq other); - - override def isReferenceType: Boolean = false; - } - } -} diff --git a/sources/scala/tools/nsc/backend/icode/ExceptionHandlers.scala b/sources/scala/tools/nsc/backend/icode/ExceptionHandlers.scala deleted file mode 100644 index 126e20ebef..0000000000 --- a/sources/scala/tools/nsc/backend/icode/ExceptionHandlers.scala +++ /dev/null @@ -1,49 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -import scala.collection.mutable.HashMap; -import scala.collection.mutable.HashSet; - -/** - * Exception handlers are pieces of code that `handle' exceptions on - * the covered basic blocks. Since Scala's exception handling uses - * pattern matching instead of just class names to identify handlers, - * all our handlers will catch `Throwable' and rely on proper ordering - * in the generated code to preserve nesting. - */ -trait ExceptionHandlers: ICodes { - import global.{Symbol, NoSymbol}; - - class ExceptionHandler(val method: IMethod, label: String, val cls: Symbol) { - private var coveredBlocks: List[BasicBlock] = Nil; - private var _startBlock: BasicBlock = _; - var finalizer: Finalizer = _; - - def setStartBlock(b: BasicBlock) = _startBlock = b; - def startBlock = _startBlock; - - def addBlock(b: BasicBlock): ExceptionHandler = { - coveredBlocks = b :: coveredBlocks; - this - } - - def covered: List[BasicBlock] = coveredBlocks; - - override def toString() = "exh_" + label + "(" + cls.simpleName + ")"; - } - - class Finalizer(method: IMethod, label: String) extends ExceptionHandler(method, label, NoSymbol) { - override def toString() = "finalizer_" + label; - } - - object NoFinalizer extends Finalizer(null, "") { - override def startBlock: BasicBlock = error("NoFinalizer cannot have a start block."); - override def setStartBlock(b: BasicBlock): Unit = error("NoFinalizer cannot have a start block."); - } -} diff --git a/sources/scala/tools/nsc/backend/icode/GenICode.scala b/sources/scala/tools/nsc/backend/icode/GenICode.scala deleted file mode 100644 index a7940cd66a..0000000000 --- a/sources/scala/tools/nsc/backend/icode/GenICode.scala +++ /dev/null @@ -1,1672 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -import scala.collection.mutable.{Map, HashMap}; -import scala.tools.nsc.symtab._; - - -/** - * TODO: - * - switches with alternatives - */ -abstract class GenICode extends SubComponent { - import global._; - import icodes._; - import icodes.opcodes._; - - val phaseName = "icode"; - - override def newPhase(prev: Phase) = new ICodePhase(prev); - - class ICodePhase(prev: Phase) extends StdPhase(prev) { - override def name = "icode"; - - override def description = "Generate ICode from the AST"; - - var unit: CompilationUnit = _; - - // We assume definitions are alread initialized - val STRING = REFERENCE(definitions.StringClass); - - // this depends on the backend! should be changed. - val ANY_REF_CLASS = REFERENCE(definitions.ObjectClass); - - val SCALA_ALL = REFERENCE(definitions.AllClass); - val SCALA_ALLREF = REFERENCE(definitions.AllRefClass); - val THROWABLE = REFERENCE(definitions.ThrowableClass); - - /////////////////////////////////////////////////////////// - - override def run: Unit = { - scalaPrimitives.init; - super.run - } - - override def apply(unit: CompilationUnit): Unit = { - this.unit = unit; - log("Generating icode for " + unit); - gen(unit.body); - } - - def gen(tree: Tree): Context = gen(tree, new Context()); - - def gen(trees: List[Tree], ctx: Context): Context = { - var ctx1 = ctx; - for (val t <- trees) - ctx1 = gen(t, ctx1); - - ctx1 - } - - /////////////////// Code generation /////////////////////// - - def gen(tree: Tree, ctx: Context): Context = tree match { - case EmptyTree => ctx; - - case PackageDef(name, stats) => gen(stats, ctx setPackage name); - - case ClassDef(mods, name, tparams, tpt, impl) => - log("Generating class: " + tree.symbol.fullNameString); - ctx setClass (new IClass(tree.symbol) setCompilationUnit unit); - addClassFields(ctx, tree.symbol); - classes = ctx.clazz :: classes; - gen(impl, ctx); - ctx setClass null; - - // !! modules should be eliminated by refcheck... or not? - case ModuleDef(mods, name, impl) => - abort("Modules should not reach backend!"); - - log("Generating module: " + tree.symbol.fullNameString); - ctx setClass (new IClass(tree.symbol) setCompilationUnit unit); - addClassFields(ctx, tree.symbol); - classes = ctx.clazz :: classes; - gen(impl, ctx); - ctx setClass null; - - case ValDef(mods, name, tpt, rhs) => ctx; // we use the symbol to add fields - - case DefDef(mods, name, tparams, vparamss, tpt, rhs) => - if (settings.debug.value) - log("Entering method " + name); - val m = new IMethod(tree.symbol); - m.sourceFile = unit.source.toString(); - m.returnType = if (tree.symbol.isConstructor) UNIT - else toTypeKind(tree.symbol.info.resultType); - ctx.clazz.addMethod(m); - - var ctx1 = ctx.enterMethod(m, tree.asInstanceOf[DefDef]); - addMethodParams(ctx1, vparamss); - - if (!m.isDeferred) { - ctx1 = genLoad(rhs, ctx1, m.returnType); - - // reverse the order of the local variables, to match the source-order - m.locals = m.locals.reverse; - - rhs match { - case Block(_, Return(_)) => (); - case Return(_) => (); - case _ => if (ctx1.bb.isEmpty) - ctx1.bb.emit(RETURN(m.returnType), rhs.pos); - else - ctx1.bb.emit(RETURN(m.returnType)); - } - ctx1.bb.close; - prune(ctx1.method); - } else - ctx1.method.setCode(null); - ctx1; - - case Template(parents, body) => - gen(body, ctx); - - case _ => - abort("Illegal tree in gen: " + tree); - } - - private def genStat(trees: List[Tree], ctx: Context): Context = { - var currentCtx = ctx; - - for (val t <- trees) - currentCtx = genStat(t, currentCtx); - - currentCtx - } - - /** - * Generate code for the given tree. The trees should contain statements - * and not produce any value. Use genLoad for expressions which leave - * a value on top of the stack. - * - * @return a new context. This is necessary for control flow instructions - * which may change the current basic block. - */ - private def genStat(tree: Tree, ctx: Context): Context = tree match { - case Assign(lhs @ Select(_, _), rhs) => - if (isStaticSymbol(lhs.symbol)) { - val ctx1 = genLoad(rhs, ctx, toTypeKind(lhs.symbol.info)); - ctx1.bb.emit(STORE_FIELD(lhs.symbol, true), tree.pos); - ctx1 - } else { - var ctx1 = genLoadQualifier(lhs, ctx); - ctx1 = genLoad(rhs, ctx1, toTypeKind(lhs.symbol.info)); - ctx1.bb.emit(STORE_FIELD(lhs.symbol, false), tree.pos); - ctx1 - } - - case Assign(lhs, rhs) => -// assert(ctx.method.locals.contains(lhs.symbol) | ctx.clazz.fields.contains(lhs.symbol), -// "Assignment to inexistent local or field: " + lhs.symbol); - val ctx1 = genLoad(rhs, ctx, toTypeKind(lhs.symbol.info)); - val Some(l) = ctx.method.lookupLocal(lhs.symbol); - ctx1.bb.emit(STORE_LOCAL(l, lhs.symbol.isValueParameter), tree.pos); - ctx1 - - case _ => - if (settings.debug.value) - log("Passing " + tree + " to genLoad"); - genLoad(tree, ctx, UNIT); - } - - /** - * Generate code for trees that produce values on the stack - * - * @param tree The tree to be translated - * @param ctx The current context - * @param expectedType The type of the value to be generated on top of the - * stack. - * @return The new context. The only thing that may change is the current - * basic block (as the labels map is mutable). - */ - private def genLoad(tree: Tree, ctx: Context, expectedType: TypeKind): Context = { - var generatedType = expectedType; - - /** - * Generate code for primitive arithmetic operations. - */ - def genArithmeticOp(tree: Tree, ctx: Context, code: Int): Context = { - val Apply(fun @ Select(larg, _), args) = tree; - var ctx1 = ctx; - var resKind = toTypeKind(larg.tpe); - - assert(args.length <= 1, - "Too many arguments for primitive function: " + fun.symbol); - assert(resKind.isNumericType | resKind == BOOL, - resKind.toString() + " is not a numeric or boolean type [operation: " + fun.symbol + "]"); - - args match { - // unary operation - case Nil => - ctx1 = genLoad(larg, ctx1, resKind); - code match { - case scalaPrimitives.POS => (); // nothing - case scalaPrimitives.NEG => ctx1.bb.emit(CALL_PRIMITIVE(Negation(resKind)), larg.pos); - case scalaPrimitives.NOT => ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(NOT, resKind)), larg.pos); - case _ => abort("Unknown unary operation: " + fun.symbol.fullNameString + " code: " + code); - } - generatedType = resKind; - - // binary operation - case rarg :: Nil => - resKind = getMaxType(larg.tpe :: rarg.tpe :: Nil); - if (scalaPrimitives.isShiftOp(code) || scalaPrimitives.isBitwiseOp(code)) - assert(resKind.isIntType | resKind == BOOL, - resKind.toString() + " incompatible with arithmetic modulo operation: " + ctx1); - - ctx1 = genLoad(larg, ctx1, resKind); - ctx1 = genLoad(rarg, - ctx1, // check .NET size of shift arguments! - if (scalaPrimitives.isShiftOp(code)) INT else resKind); - - generatedType = resKind; - code match { - case scalaPrimitives.ADD => ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(ADD, resKind)), tree.pos); - case scalaPrimitives.SUB => ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(SUB, resKind)), tree.pos); - case scalaPrimitives.MUL => ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(MUL, resKind)), tree.pos); - case scalaPrimitives.DIV => ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(DIV, resKind)), tree.pos); - case scalaPrimitives.MOD => ctx1.bb.emit(CALL_PRIMITIVE(Arithmetic(REM, resKind)), tree.pos); - case scalaPrimitives.OR => ctx1.bb.emit(CALL_PRIMITIVE(Logical(OR, resKind)), tree.pos); - case scalaPrimitives.XOR => ctx1.bb.emit(CALL_PRIMITIVE(Logical(XOR, resKind)), tree.pos); - case scalaPrimitives.AND => ctx1.bb.emit(CALL_PRIMITIVE(Logical(AND, resKind)), tree.pos); - case scalaPrimitives.LSL => ctx1.bb.emit(CALL_PRIMITIVE(Shift(LSL, resKind)), tree.pos); - generatedType = resKind; - case scalaPrimitives.LSR => ctx1.bb.emit(CALL_PRIMITIVE(Shift(LSR, resKind)), tree.pos); - generatedType = resKind; - case scalaPrimitives.ASR => ctx1.bb.emit(CALL_PRIMITIVE(Shift(ASR, resKind)), tree.pos); - generatedType = resKind; - case _ => abort("Unknown primitive: " + fun.symbol + "[" + code + "]"); - } - - case _ => abort("Too many arguments for primitive function: " + tree); - } - ctx1 - } - - /** Generate primitive array operations. */ - def genArrayOp(tree: Tree, ctx: Context, code: Int): Context = { - import scalaPrimitives._; - val Apply(Select(arrayObj, _), args) = tree; - val k = toTypeKind(arrayObj.tpe); - val ARRAY(elem) = k; - var ctx1 = genLoad(arrayObj, ctx, k); - - if (scalaPrimitives.isArrayGet(code)) { - // load argument on stack - assert(args.length == 1, - "Too many arguments for array get operation: " + tree); - ctx1 = genLoad(args.head, ctx1, INT); - generatedType = elem; - } else if (scalaPrimitives.isArraySet(code)) { - assert(args.length == 2, - "Too many arguments for array set operation: " + tree); - ctx1 = genLoad(args.head, ctx1, INT); - ctx1 = genLoad(args.tail.head, ctx1, toTypeKind(args.tail.head.tpe)); - // the following line should really be here, but because of bugs in erasure - // we pretend we generate whatever type is expected from us. - //generatedType = UNIT; - } else - generatedType = INT; - - code match { - case ZARRAY_LENGTH => - ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(BOOL)), tree.pos); - case BARRAY_LENGTH => - ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(BYTE)), tree.pos); - case SARRAY_LENGTH => - ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(SHORT)), tree.pos); - case CARRAY_LENGTH => - ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(CHAR)), tree.pos); - case IARRAY_LENGTH => - ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(INT)), tree.pos); - case LARRAY_LENGTH => - ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(LONG)), tree.pos); - case FARRAY_LENGTH => - ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(FLOAT)), tree.pos); - case DARRAY_LENGTH => - ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(DOUBLE)), tree.pos); - case OARRAY_LENGTH => - ctx1.bb.emit(CALL_PRIMITIVE(ArrayLength(ANY_REF_CLASS)), tree.pos); - - case ZARRAY_GET => - ctx1.bb.emit(LOAD_ARRAY_ITEM(BOOL), tree.pos); - case BARRAY_GET => - ctx1.bb.emit(LOAD_ARRAY_ITEM(BYTE), tree.pos); - case SARRAY_GET => - ctx1.bb.emit(LOAD_ARRAY_ITEM(SHORT), tree.pos); - case CARRAY_GET => - ctx1.bb.emit(LOAD_ARRAY_ITEM(CHAR), tree.pos); - case IARRAY_GET => - ctx1.bb.emit(LOAD_ARRAY_ITEM(INT), tree.pos); - case LARRAY_GET => - ctx1.bb.emit(LOAD_ARRAY_ITEM(LONG), tree.pos); - case FARRAY_GET => - ctx1.bb.emit(LOAD_ARRAY_ITEM(FLOAT), tree.pos); - case DARRAY_GET => - ctx1.bb.emit(LOAD_ARRAY_ITEM(DOUBLE), tree.pos); - case OARRAY_GET => - ctx1.bb.emit(LOAD_ARRAY_ITEM(ANY_REF_CLASS), tree.pos); - - case ZARRAY_SET => - ctx1.bb.emit(STORE_ARRAY_ITEM(BOOL), tree.pos); - case BARRAY_SET => - ctx1.bb.emit(STORE_ARRAY_ITEM(BYTE), tree.pos); - case SARRAY_SET => - ctx1.bb.emit(STORE_ARRAY_ITEM(SHORT), tree.pos); - case CARRAY_SET => - ctx1.bb.emit(STORE_ARRAY_ITEM(CHAR), tree.pos); - case IARRAY_SET => - ctx1.bb.emit(STORE_ARRAY_ITEM(INT), tree.pos); - case LARRAY_SET => - ctx1.bb.emit(STORE_ARRAY_ITEM(LONG), tree.pos); - case FARRAY_SET => - ctx1.bb.emit(STORE_ARRAY_ITEM(FLOAT), tree.pos); - case DARRAY_SET => - ctx1.bb.emit(STORE_ARRAY_ITEM(DOUBLE), tree.pos); - case OARRAY_SET => - ctx1.bb.emit(STORE_ARRAY_ITEM(ANY_REF_CLASS), tree.pos); - - case _ => - abort("Unknown operation on arrays: " + tree + " code: " + code); - } - ctx1 - } - - // genLoad - val resCtx: Context = tree match { - case LabelDef(name, params, rhs) => - val ctx1 = ctx.newBlock; - ctx1.labels.get(tree.symbol) match { - case Some(label) => - label.anchor(ctx1.bb); - label.patch(ctx.method.code); - - case None => - ctx1.labels += tree.symbol -> (new Label(tree.symbol) anchor ctx1.bb setParams (params map (.symbol))); - ctx.method.addLocals(params map (p => new Local(p.symbol, toTypeKind(p.symbol.info)))); - if (settings.debug.value) - log("Adding label " + tree.symbol); - } - -// if (!isTailCallLabel(tree.asInstanceOf[LabelDef], ctx)) { -// log("Non-tail call label found (" + tree.symbol + "), initializing arguments to default values."); -// genLoadLabelArguments(params map { p => zeroOf(toTypeKind(p.symbol.tpe)) }, -// ctx1.labels(tree.symbol), -// ctx); -// } - - ctx.bb.emit(JUMP(ctx1.bb), tree.pos); - ctx.bb.close; - genLoad(rhs, ctx1, expectedType /*toTypeKind(tree.symbol.info.resultType)*/); - - case ValDef(_, _, _, rhs) => - val sym = tree.symbol; - val local = new Local(sym, toTypeKind(sym.info)); - ctx.method.addLocal(local); - - if (rhs == EmptyTree) { - if (settings.debug.value) - log("Uninitialized variable " + tree + " at: " + unit.position(tree.pos)); - ctx.bb.emit(getZeroOf(local.kind)); - } - - var ctx1 = ctx; - if (rhs != EmptyTree) - ctx1 = genLoad(rhs, ctx, local.kind); - - ctx1.bb.emit(STORE_LOCAL(local, false), tree.pos); - generatedType = UNIT; - ctx1 - - case If(cond, thenp, elsep) => - var thenCtx = ctx.newBlock; - var elseCtx = ctx.newBlock; - val contCtx = ctx.newBlock; - genCond(cond, ctx, thenCtx, elseCtx); - val ifKind = toTypeKind(tree.tpe); - - val thenKind = toTypeKind(thenp.tpe); - val elseKind = if (elsep == EmptyTree) UNIT else toTypeKind(elsep.tpe); - - generatedType = ifKind; - - // we need to drop unneeded results, if one branch gives - // unit and the other gives something on the stack, because - // the type of 'if' is scala.Any, and its erasure would be Object. - // But unboxed units are not Objects... - if (thenKind == UNIT || elseKind == UNIT) { - if (settings.debug.value) - log("Will drop result from an if branch"); - thenCtx = genLoad(thenp, thenCtx, UNIT); - elseCtx = genLoad(elsep, elseCtx, UNIT); - assert(expectedType == UNIT, "I produce UNIT in a context where " + expectedType + " is expected!"); - generatedType = UNIT; - } else { - thenCtx = genLoad(thenp, thenCtx, ifKind); - elseCtx = genLoad(elsep, elseCtx, ifKind); - } - - thenCtx.bb.emit(JUMP(contCtx.bb)); - thenCtx.bb.close; - elseCtx.bb.emit(JUMP(contCtx.bb)); - elseCtx.bb.close; - - contCtx; - - case Return(expr) => - val returnedKind = toTypeKind(expr.tpe); - val ctx1 = genLoad(expr, ctx, returnedKind); - ctx1.bb.emit(RETURN(returnedKind), tree.pos); - ctx1.bb.enterIgnoreMode; - generatedType = expectedType; - ctx1 - - case Try(block, catches, finalizer) => - val kind = toTypeKind(tree.tpe); - var handlers = for (val CaseDef(pat, _, body) <- catches.reverse) - yield pat match { - case Typed(Ident(nme.WILDCARD), tpt) => Pair(tpt.tpe.symbol, { - ctx: Context => - ctx.bb.emit(DROP(REFERENCE(tpt.tpe.symbol))); - val ctx1 = genLoad(finalizer, ctx, UNIT); - genLoad(body, ctx1, kind); - }) - - case Ident(nme.WILDCARD) => Pair(definitions.ThrowableClass, { - ctx: Context => - ctx.bb.emit(DROP(REFERENCE(definitions.ThrowableClass))); - val ctx1 = genLoad(finalizer, ctx, UNIT); - genLoad(body, ctx1, kind) - }) - - case Bind(name, _) => - val exception = new Local(pat.symbol, toTypeKind(pat.symbol.tpe)); - ctx.method.addLocal(exception); - - Pair(pat.symbol.tpe.symbol, { - ctx: Context => - ctx.bb.emit(STORE_LOCAL(exception, false), pat.pos); - val ctx1 = genLoad(finalizer, ctx, UNIT); - genLoad(body, ctx1, kind) - }) - } - - if (finalizer != EmptyTree) - handlers = Pair(NoSymbol, { - ctx: Context => - val ctx1 = genLoad(finalizer, ctx, UNIT); - ctx1.bb.emit(THROW()); - ctx1 - }) :: handlers; - - ctx.Try( - bodyCtx => { - generatedType = toTypeKind(block.tpe); - val ctx1 = genLoad(block, bodyCtx, generatedType); - genLoad(finalizer, ctx1, UNIT) - }, - handlers) - - case Throw(expr) => - val ctx1 = genLoad(expr, ctx, THROWABLE); - ctx1.bb.emit(THROW(), tree.pos); - ctx1.bb.enterIgnoreMode; - generatedType = SCALA_ALL; - ctx1; - - case New(tpt) => - abort("Unexpected New"); - - case Apply(TypeApply(fun, targs), _) => - val sym = fun.symbol; - var ctx1 = ctx; - var cast = false; - - if (sym == definitions.Object_isInstanceOf) - cast = false - else if (sym == definitions.Object_asInstanceOf) - cast = true - else - abort("Unexpected type application " + fun + "[sym: " + sym + "]"); - - val Select(obj, _) = fun; - val l = toTypeKind(obj.tpe); - val r = toTypeKind(targs.head.tpe); - - ctx1 = genLoadQualifier(fun, ctx); - - if (l.isValueType && r.isValueType) - genConversion(l, r, ctx1, cast) - else if (l.isValueType) { - ctx1.bb.emit(DROP(l), fun.pos); - if (cast) { - ctx1.bb.emit(NEW(REFERENCE(definitions.getClass("ClassCastException")))); - ctx1.bb.emit(DUP(ANY_REF_CLASS)); - ctx1.bb.emit(THROW()); - } else - ctx1.bb.emit(CONSTANT(Constant(false))) - } - else if (r.isValueType /*|| r.isArrayType */) - genBoxedConversion(l, r, ctx1, cast) - else - genCast(l, r, ctx1, cast); - - generatedType = if (cast) r else BOOL; - ctx1 - - // 'super' call: Note: since constructors are supposed to - // return an instance of what they construct, we have to take - // special care. On JVM they are 'void', and Scala forbids (syntactically) - // to call super constructors explicitly and/or use their 'returned' value. - // therefore, we can ignore this fact, and generate code that leaves nothing - // on the stack (contrary to what the type in the AST says). - case Apply(fun @ Select(Super(_, mixin), _), args) => - if (settings.debug.value) - log("Call to super: " + tree); - val invokeStyle = SuperCall(mixin); -// if (fun.symbol.isConstructor) Static(true) else SuperCall(mixin); - - ctx.bb.emit(THIS(ctx.clazz.symbol), tree.pos); - val ctx1 = genLoadArguments(args, fun.symbol.info.paramTypes, ctx); - - ctx1.bb.emit(CALL_METHOD(fun.symbol, invokeStyle), tree.pos); - generatedType = if (fun.symbol.isConstructor) - UNIT - else - toTypeKind(fun.symbol.info.resultType); - ctx1 - - // 'new' constructor call: Note: since constructors are - // thought to return an instance of what they construct, - // we have to 'simulate' it by DUPlicating the freshly created - // instance (on JVM, methods return VOID). - case Apply(fun @ Select(New(tpt), nme.CONSTRUCTOR), args) => - val ctor = fun.symbol; - assert(ctor.isClassConstructor, - "'new' call to non-constructor: " + tree); - - generatedType = toTypeKind(tpt.tpe); - assert(generatedType.isReferenceType || generatedType.isArrayType, - "Non reference type cannot be instantiated: " + generatedType); - - var ctx1 = ctx; - - generatedType match { - case ARRAY(elem) => - ctx1 = genLoadArguments(args, ctor.info.paramTypes, ctx); - ctx1.bb.emit(CREATE_ARRAY(elem), tree.pos); - - case REFERENCE(cls) => - assert(ctor.owner == cls, - "Symbol " + ctor.owner.fullNameString + "is different than " + tpt); - ctx1.bb.emit(NEW(generatedType), tree.pos); - ctx1.bb.emit(DUP(generatedType)); - ctx1 = genLoadArguments(args, ctor.info.paramTypes, ctx); - - ctx1.bb.emit(CALL_METHOD(ctor, Static(true)), tree.pos); - - case _ => - abort("Cannot instantiate " + tpt + "of kind: " + generatedType); - } - ctx1 - - case Apply(fun, args) => - val sym = fun.symbol; - - if (sym.isLabel) { // jump to a label - val label = ctx.labels.get(sym) match { - case Some(l) => l; - - // it is a forward jump, scan for labels - case None => - log("Performing scan for label because of forward jump."); - scanForLabels(ctx.defdef, ctx); - ctx.labels.get(sym) match { - case Some(l) => - log("Found label: " + l); - l - case _ => abort("Unknown label target: " + sym + " at: " + unit.position(fun.pos) + ": ctx: " + ctx); - } - } - val ctx1 = genLoadLabelArguments(args, label, ctx); - if (label.anchored) - ctx1.bb.emit(JUMP(label.block), tree.pos); - else - ctx1.bb.emit(PJUMP(label), tree.pos); - - ctx1.bb.close; - ctx1.newBlock; - } else if (isPrimitive(fun.symbol)) { // primitive method call - val Select(receiver, _) = fun; - - val code = scalaPrimitives.getPrimitive(fun.symbol, receiver.tpe); - var ctx1 = ctx; - - if (scalaPrimitives.isArithmeticOp(code)) { - ctx1 = genArithmeticOp(tree, ctx1, code); - } else if (code == scalaPrimitives.CONCAT) { - ctx1 = genStringConcat(tree, ctx1); - generatedType = STRING; - } else if (scalaPrimitives.isArrayOp(code)) { - ctx1 = genArrayOp(tree, ctx1, code); - } else if (scalaPrimitives.isLogicalOp(code) || - scalaPrimitives.isComparisonOp(code)) { - - val trueCtx = ctx1.newBlock; - val falseCtx = ctx1.newBlock; - val afterCtx = ctx1.newBlock; - if (settings.debug.value) - log("Passing " + tree + " to genCond"); - genCond(tree, ctx1, trueCtx, falseCtx); - trueCtx.bb.emit(CONSTANT(Constant(true)), tree.pos); - trueCtx.bb.emit(JUMP(afterCtx.bb)); - trueCtx.bb.close; - falseCtx.bb.emit(CONSTANT(Constant(false)), tree.pos); - falseCtx.bb.emit(JUMP(afterCtx.bb)); - falseCtx.bb.close; - generatedType = BOOL; - ctx1 = afterCtx; - } else if (code == scalaPrimitives.SYNCHRONIZED) { - val monitor = new Local(ctx.method.symbol.newVariable(tree.pos, unit.fresh.newName("monitor")).setInfo(definitions.ObjectClass.tpe), - ANY_REF_CLASS); - ctx.method.addLocal(monitor); - - ctx1 = genLoadQualifier(fun, ctx1); - ctx1.bb.emit(DUP(ANY_REF_CLASS)); - ctx1.bb.emit(STORE_LOCAL(monitor, false)); - ctx1.bb.emit(MONITOR_ENTER(), tree.pos); - - if (settings.debug.value) - log("synchronized block start"); - ctx1 = ctx1.Try( - bodyCtx => { - val ctx1 = genLoad(args.head, bodyCtx, toTypeKind(tree.tpe.resultType)); - ctx1.bb.emit(LOAD_LOCAL(monitor, false)); - ctx1.bb.emit(MONITOR_EXIT(), tree.pos); - ctx1 - }, List( - Pair(NoSymbol, exhCtx => { - exhCtx.bb.emit(LOAD_LOCAL(monitor, false)); - exhCtx.bb.emit(MONITOR_EXIT(), tree.pos); - exhCtx.bb.emit(THROW()); - exhCtx - }))); - if (settings.debug.value) - log("synchronized block end with block " + ctx1.bb + " closed=" + ctx1.bb.isClosed); - } else if (scalaPrimitives.isCoercion(code)) { - ctx1 = genLoad(receiver, ctx1, toTypeKind(receiver.tpe)); - genCoercion(tree, ctx1, code); - } else - abort("Primitive operation not handled yet: " + - fun.symbol.fullNameString + "(" + fun.symbol.simpleName + ") " - + " at: " + unit.position(tree.pos)); - ctx1 - } else { // normal method call - if (settings.debug.value) - log("Gen CALL_METHOD with sym: " + sym + " isStaticSymbol: " + isStaticSymbol(sym)); - var invokeStyle = - if (isStaticSymbol(sym)) - Static(false) - else if (sym.hasFlag(Flags.PRIVATE) || sym.isClassConstructor) - Static(true) - else - Dynamic; - - var ctx1 = if (invokeStyle.hasInstance) - genLoadQualifier(fun, ctx); - else - ctx; - - ctx1 = genLoadArguments(args, fun.symbol.info.paramTypes, ctx1); - - ctx1.bb.emit(CALL_METHOD(sym, invokeStyle), tree.pos); - generatedType = if (sym.isClassConstructor) UNIT else toTypeKind(sym.info.resultType); - ctx1 - } - - case This(qual) => - assert(tree.symbol == ctx.clazz.symbol || tree.symbol.isModuleClass, - "Trying to access the this of another class: " + - "tree.symbol = " + tree.symbol + ", ctx.clazz.symbol = " + ctx.clazz.symbol); - if (tree.symbol.isModuleClass && tree.symbol != ctx.clazz.symbol) { - if (settings.debug.value) - log("LOAD_MODULE from 'This': " + tree.symbol); - ctx.bb.emit(LOAD_MODULE(tree.symbol), tree.pos); - generatedType = REFERENCE(tree.symbol); - } else { - ctx.bb.emit(THIS(ctx.clazz.symbol), tree.pos); - generatedType = REFERENCE(ctx.clazz.symbol); - } - ctx; - - case Select(Ident(nme.EMPTY_PACKAGE_NAME), module) => - assert(tree.symbol.isModule, - "Selection of non-module from empty package: " + tree.toString() + - " sym: " + tree.symbol + - " at: " + unit.position(tree.pos)); - if (settings.debug.value) - log("LOAD_MODULE from Select(): " + tree.symbol); - ctx.bb.emit(LOAD_MODULE(tree.symbol), tree.pos); - ctx - - case Select(qualifier, selector) => - val sym = tree.symbol; - generatedType = toTypeKind(sym.info); - - if (sym.isModule) { - if (settings.debug.value) - log("LOAD_MODULE from Select(qualifier, selector): " + sym); - ctx.bb.emit(LOAD_MODULE(sym), tree.pos); - ctx - } else if (isStaticSymbol(sym)) { - ctx.bb.emit(LOAD_FIELD(sym, true), tree.pos); - ctx - } else { - val ctx1 = genLoadQualifier(tree, ctx); - ctx1.bb.emit(LOAD_FIELD(sym, false), tree.pos); - ctx1 - } - - case Ident(name) => - if (!tree.symbol.isPackage) { - if (tree.symbol.isModule) { - if (settings.debug.value) - log("LOAD_MODULE from Ident(name): " + tree.symbol); - ctx.bb.emit(LOAD_MODULE(tree.symbol), tree.pos); - generatedType = toTypeKind(tree.symbol.info); - } else { - val Some(l) = ctx.method.lookupLocal(tree.symbol); - ctx.bb.emit(LOAD_LOCAL(l, tree.symbol.isValueParameter), tree.pos); - generatedType = l.kind; - } - } - ctx - - case Literal(value) => - if (value.tag != UnitTag) - ctx.bb.emit(CONSTANT(value), tree.pos); - generatedType = toTypeKind(value.tpe); - ctx - - case Block(stats, expr) => - assert(!(ctx.method eq null), "Block outside method"); - val ctx1 = genStat(stats, ctx); - genLoad(expr, ctx1, expectedType); - - case Typed(expr, _) => - genLoad(expr, ctx, expectedType); - - case Assign(_, _) => - generatedType = UNIT; - genStat(tree, ctx); - - case ArrayValue(tpt @ TypeTree(), elems) => - var ctx1 = ctx; - val elmKind = toTypeKind(tpt.tpe); - generatedType = ARRAY(elmKind); - - ctx1.bb.emit(CONSTANT(new Constant(elems.length)), tree.pos); - ctx1.bb.emit(CREATE_ARRAY(elmKind)); - // inline array literals - var i = 0; - while (i < elems.length) { - ctx1.bb.emit(DUP(generatedType), tree.pos); - ctx1.bb.emit(CONSTANT(new Constant(i))); - ctx1 = genLoad(elems(i), ctx1, elmKind); - ctx1.bb.emit(STORE_ARRAY_ITEM(elmKind)); - i = i + 1; - } - ctx1 - - case Match(selector, cases) => - if (settings.debug.value) - log("Generating SWITCH statement."); - var ctx1 = genLoad(selector, ctx, INT); - val afterCtx = ctx1.newBlock; - var caseCtx: Context = null; - val kind = toTypeKind(tree.tpe); - - var targets: List[BasicBlock] = Nil; - var tags: List[Int] = Nil; - var default: BasicBlock = afterCtx.bb; - - for (val caze <- cases) - caze match { - case CaseDef(Literal(value), EmptyTree, body) => - tags = value.intValue :: tags; - val tmpCtx = ctx1.newBlock; - targets = tmpCtx.bb :: targets; - - caseCtx = genLoad(body, tmpCtx , kind); - caseCtx.bb.emit(JUMP(afterCtx.bb), caze.pos); - caseCtx.bb.close; - - case CaseDef(Ident(nme.WILDCARD), EmptyTree, body) => - val tmpCtx = ctx1.newBlock; - default = tmpCtx.bb; - - caseCtx = genLoad(body, tmpCtx , kind); - caseCtx.bb.emit(JUMP(afterCtx.bb), caze.pos); - caseCtx.bb.close; - - case _ => abort("Invalid case statement in switch-like pattern match: " + - tree + " at: " + unit.position(tree.pos)); - } - ctx1.bb.emit(SWITCH(tags.reverse map (x => List(x)), - (default :: targets).reverse), tree.pos); - ctx1.bb.close; - afterCtx - - case EmptyTree => ctx; - - case _ => abort("Unexpected tree in genLoad: " + tree + " at: " + unit.position(tree.pos)); - } - - // emit conversion - if (generatedType != expectedType) - adapt(generatedType, expectedType, resCtx, tree); - - resCtx; - } - - private def adapt(from: TypeKind, to: TypeKind, ctx: Context, tree: Tree): Unit = { - if (!(from <:< to) && !(from == SCALA_ALLREF && to == SCALA_ALL)) { - to match { - case UNIT => - ctx.bb.emit(DROP(from), tree.pos); - if (settings.debug.value) - log("Dropped an " + from); - - case _ => - assert(from != UNIT, "Can't convert from UNIT to " + to + - tree + " at: " + unit.position(tree.pos)); - ctx.bb.emit(CALL_PRIMITIVE(Conversion(from, to)), tree.pos); - } - } else if (from == SCALA_ALL) { - ctx.bb.emit(DROP(from)); - ctx.bb.emit(getZeroOf(ctx.method.returnType)); - ctx.bb.emit(RETURN(ctx.method.returnType)); - ctx.bb.enterIgnoreMode; - } else if (from == SCALA_ALLREF) { - ctx.bb.emit(DROP(from)); - ctx.bb.emit(CONSTANT(Constant(null))); - } - } - - /** Load the qualifier of `tree' on top of the stack. */ - private def genLoadQualifier(tree: Tree, ctx: Context): Context = - tree match { - case Select(qualifier, _) => - genLoad(qualifier, ctx, ANY_REF_CLASS); // !! - case _ => - abort("Unknown qualifier " + tree); - } - - /** Is this symbol static in the Java sense? */ - def isStaticSymbol(s: Symbol): Boolean = - s.hasFlag(Flags.STATIC) || s.hasFlag(Flags.STATICMEMBER) || s.owner.isImplClass; - - /** - * Generate code that loads args into label parameters. - */ - private def genLoadLabelArguments(args: List[Tree], label: Label, ctx: Context): Context = { - assert(args.length == label.params.length, - "Wrong number of arguments in call to label " + label.symbol); - var ctx1 = ctx; - var arg = args; - var param = label.params; - - // store arguments in reverse order on the stack - while (arg != Nil) { - val Some(l) = ctx.method.lookupLocal(param.head); - ctx1 = genLoad(arg.head, ctx1, l.kind); - arg = arg.tail; - param = param.tail; - } - - // store arguments in the right variables - arg = args.reverse; param = label.params.reverse; - while (arg != Nil) { - val Some(l) = ctx.method.lookupLocal(param.head); - ctx1.bb.emit(STORE_LOCAL(l, param.head.isValueParameter), arg.head.pos); - arg = arg.tail; - param = param.tail; - } - - ctx1 - } - - private def genLoadArguments(args: List[Tree], tpes: List[Type], ctx: Context): Context = { - assert(args.length == tpes.length, "Wrong number of arguments in call " + ctx); - - var ctx1 = ctx; - var arg = args; - var tpe = tpes; - while (arg != Nil) { - ctx1 = genLoad(arg.head, ctx1, toTypeKind(tpe.head)); - arg = arg.tail; - tpe = tpe.tail; - } - ctx1 - } - - def genConversion(from: TypeKind, to: TypeKind, ctx: Context, cast: Boolean) = { - if (cast) - ctx.bb.emit(CALL_PRIMITIVE(Conversion(from, to))); - else { - ctx.bb.emit(DROP(from)); - ctx.bb.emit(CONSTANT(Constant(from == to))); - } - } - - /** Generate a conversion from a reference type to a value type, like in - * Any -> Array[Int] or Any -> Int - */ - def genBoxedConversion(from: TypeKind, to: TypeKind, ctx: Context, cast: Boolean) = { - assert(to.isValueType || to.isArrayType, "Expecting conversion to value type: " + to); - - val boxedCls = to match { - case ARRAY(ARRAY(_)) | ARRAY(REFERENCE(_)) => - definitions.BoxedObjectArrayClass; - case ARRAY(elem) => - definitions.boxedArrayClass(elem.toType.symbol) - case _ => - definitions.boxedClass(to.toType.symbol); - } - - if (cast) { - ctx.bb.emit(CHECK_CAST(REFERENCE(boxedCls))); - ctx.bb.emit(CONSTANT(Constant(definitions.signature(to.toType)))); - ctx.bb.emit(CALL_METHOD(definitions.getMember(boxedCls, "unbox"), - Dynamic)); - } else { - ctx.bb.emit(IS_INSTANCE(REFERENCE(boxedCls))); - } - } - - def genCast(from: TypeKind, to: TypeKind, ctx: Context, cast: Boolean) = { - if (cast) - ctx.bb.emit(CHECK_CAST(to)); - else - ctx.bb.emit(IS_INSTANCE(to)); - } - - def zeroOf(k: TypeKind): Tree = k match { - case UNIT => Literal(()); - case BOOL => Literal(false); - case BYTE => Literal(0: Byte); - case SHORT => Literal(0: Short); - case CHAR => Literal(0: Char); - case INT => Literal(0: Int); - case LONG => Literal(0: Long); - case FLOAT => Literal(0.0f); - case DOUBLE => Literal(0.0d); - case REFERENCE(cls) => Literal(null: Any); - case ARRAY(elem) => Literal(null: Any); - } - - def getZeroOf(k: TypeKind): Instruction = k match { - case UNIT => CONSTANT(Constant(())); - case BOOL => CONSTANT(Constant(false)); - case BYTE => CONSTANT(Constant(0: Byte)); - case SHORT => CONSTANT(Constant(0: Short)); - case CHAR => CONSTANT(Constant(0: Char)); - case INT => CONSTANT(Constant(0: Int)); - case LONG => CONSTANT(Constant(0: Long)); - case FLOAT => CONSTANT(Constant(0.0f)); - case DOUBLE => CONSTANT(Constant(0.0d)); - case REFERENCE(cls) => CONSTANT(Constant(null: Any)); - case ARRAY(elem) => CONSTANT(Constant(null: Any)); - } - - - /** Is the given symbol a primitive operation? */ - def isPrimitive(fun: Symbol): Boolean = { - import scalaPrimitives._; - - if (scalaPrimitives.isPrimitive(fun)) - scalaPrimitives.getPrimitive(fun) match { - case EQUALS | HASHCODE | TOSTRING => false; - case _ => true; - } - else - false; - } - - def genCoercion(tree: Tree, ctx: Context, code: Int) = { - import scalaPrimitives._; - code match { - case B2B => (); - case B2C => ctx.bb.emit(CALL_PRIMITIVE(Conversion(BYTE, CHAR)), tree.pos); - case B2S => ctx.bb.emit(CALL_PRIMITIVE(Conversion(BYTE, SHORT)), tree.pos); - case B2I => ctx.bb.emit(CALL_PRIMITIVE(Conversion(BYTE, INT)), tree.pos); - case B2L => ctx.bb.emit(CALL_PRIMITIVE(Conversion(BYTE, LONG)), tree.pos); - case B2F => ctx.bb.emit(CALL_PRIMITIVE(Conversion(BYTE, FLOAT)), tree.pos); - case B2D => ctx.bb.emit(CALL_PRIMITIVE(Conversion(BYTE, DOUBLE)), tree.pos); - - case S2B => ctx.bb.emit(CALL_PRIMITIVE(Conversion(SHORT, BYTE)), tree.pos); - case S2S => (); - case S2C => ctx.bb.emit(CALL_PRIMITIVE(Conversion(SHORT, CHAR)), tree.pos); - case S2I => ctx.bb.emit(CALL_PRIMITIVE(Conversion(SHORT, INT)), tree.pos); - case S2L => ctx.bb.emit(CALL_PRIMITIVE(Conversion(SHORT, LONG)), tree.pos); - case S2F => ctx.bb.emit(CALL_PRIMITIVE(Conversion(SHORT, FLOAT)), tree.pos); - case S2D => ctx.bb.emit(CALL_PRIMITIVE(Conversion(SHORT, DOUBLE)), tree.pos); - - case C2B => ctx.bb.emit(CALL_PRIMITIVE(Conversion(CHAR, BYTE)), tree.pos); - case C2S => ctx.bb.emit(CALL_PRIMITIVE(Conversion(CHAR, SHORT)), tree.pos); - case C2C => (); - case C2I => ctx.bb.emit(CALL_PRIMITIVE(Conversion(CHAR, INT)), tree.pos); - case C2L => ctx.bb.emit(CALL_PRIMITIVE(Conversion(CHAR, LONG)), tree.pos); - case C2F => ctx.bb.emit(CALL_PRIMITIVE(Conversion(CHAR, FLOAT)), tree.pos); - case C2D => ctx.bb.emit(CALL_PRIMITIVE(Conversion(CHAR, DOUBLE)), tree.pos); - - case I2B => ctx.bb.emit(CALL_PRIMITIVE(Conversion(INT, BYTE)), tree.pos); - case I2S => ctx.bb.emit(CALL_PRIMITIVE(Conversion(INT, SHORT)), tree.pos); - case I2C => ctx.bb.emit(CALL_PRIMITIVE(Conversion(INT, CHAR)), tree.pos); - case I2I => (); - case I2L => ctx.bb.emit(CALL_PRIMITIVE(Conversion(INT, LONG)), tree.pos); - case I2F => ctx.bb.emit(CALL_PRIMITIVE(Conversion(INT, FLOAT)), tree.pos); - case I2D => ctx.bb.emit(CALL_PRIMITIVE(Conversion(INT, DOUBLE)), tree.pos); - - case L2B => ctx.bb.emit(CALL_PRIMITIVE(Conversion(LONG, BYTE)), tree.pos); - case L2S => ctx.bb.emit(CALL_PRIMITIVE(Conversion(LONG, SHORT)), tree.pos); - case L2C => ctx.bb.emit(CALL_PRIMITIVE(Conversion(LONG, CHAR)), tree.pos); - case L2I => ctx.bb.emit(CALL_PRIMITIVE(Conversion(LONG, INT)), tree.pos); - case L2L => (); - case L2F => ctx.bb.emit(CALL_PRIMITIVE(Conversion(LONG, FLOAT)), tree.pos); - case L2D => ctx.bb.emit(CALL_PRIMITIVE(Conversion(LONG, DOUBLE)), tree.pos); - - case F2B => ctx.bb.emit(CALL_PRIMITIVE(Conversion(FLOAT, BYTE)), tree.pos); - case F2S => ctx.bb.emit(CALL_PRIMITIVE(Conversion(FLOAT, SHORT)), tree.pos); - case F2C => ctx.bb.emit(CALL_PRIMITIVE(Conversion(FLOAT, CHAR)), tree.pos); - case F2I => ctx.bb.emit(CALL_PRIMITIVE(Conversion(FLOAT, INT)), tree.pos); - case F2L => ctx.bb.emit(CALL_PRIMITIVE(Conversion(FLOAT, LONG)), tree.pos); - case F2F => (); - case F2D => ctx.bb.emit(CALL_PRIMITIVE(Conversion(FLOAT, DOUBLE)), tree.pos); - - case D2B => ctx.bb.emit(CALL_PRIMITIVE(Conversion(DOUBLE, BYTE)), tree.pos); - case D2S => ctx.bb.emit(CALL_PRIMITIVE(Conversion(DOUBLE, SHORT)), tree.pos); - case D2C => ctx.bb.emit(CALL_PRIMITIVE(Conversion(DOUBLE, CHAR)), tree.pos); - case D2I => ctx.bb.emit(CALL_PRIMITIVE(Conversion(DOUBLE, INT)), tree.pos); - case D2L => ctx.bb.emit(CALL_PRIMITIVE(Conversion(DOUBLE, LONG)), tree.pos); - case D2F => ctx.bb.emit(CALL_PRIMITIVE(Conversion(DOUBLE, FLOAT)), tree.pos); - case D2D => (); - - case _ => abort("Unknown coercion primitive: " + code); - } - } - - /** Generate string concatenation. */ - def genStringConcat(tree: Tree, ctx: Context): Context = { - val Apply(Select(larg, _), rarg) = tree; - var ctx1 = ctx; - - assert(rarg.length == 1, - "Too many parameters for string concatenation"); - - val concatenations = liftStringConcat(tree); - if (settings.debug.value) - log("Lifted string concatenations for " + tree + "\n to: " + concatenations); - - ctx1.bb.emit(CALL_PRIMITIVE(StartConcat), tree.pos); - for (val elem <- concatenations) { - val kind = toTypeKind(elem.tpe); - ctx1 = genLoad(elem, ctx1, kind); - ctx1.bb.emit(CALL_PRIMITIVE(StringConcat(kind)), elem.pos); - } - ctx1.bb.emit(CALL_PRIMITIVE(EndConcat), tree.pos); - - ctx1; - } - - /** - * Returns a list of trees that each should be concatenated, from - * left to right. It turns a chained call like "a".+("b").+("c") into - * a list of arguments. - */ - def liftStringConcat(tree: Tree): List[Tree] = tree match { - case Apply(fun @ Select(larg, method), rarg) => - if (isPrimitive(fun.symbol) && - scalaPrimitives.getPrimitive(fun.symbol) == scalaPrimitives.CONCAT) - liftStringConcat(larg) ::: rarg - else - List(tree); - case _ => - List(tree); - } - - - /** - * Traverse the tree and store label stubs in the contxt. This is - * necessary to handle forward jumps, because at a label application - * with arguments, the symbols of the corresponding LabelDef parameters - * are not yet known. - * - * Since it is expensive to traverse each method twice, this method is called - * only when forward jumps really happen, and then it re-traverses the whole - * method, scanning for LabelDefs. - * - * TODO: restrict the scanning to smaller subtrees than the whole method. - * It is sufficient to scan the trees of the innermost enclosing block. - */ - private def scanForLabels(tree: Tree, ctx: Context): Unit = - new Traverser() { - override def traverse(tree: Tree): Unit = tree match { - - case LabelDef(name, params, rhs) => - if (!ctx.labels.contains(tree.symbol)) { - ctx.labels += tree.symbol -> (new Label(tree.symbol) setParams(params map (.symbol))); - ctx.method.addLocals(params map (p => new Local(p.symbol, toTypeKind(p.symbol.info)))); - } - super.traverse(rhs); - - case _ => super.traverse(tree); - } - } traverse(tree); - - /** - * Generate code for conditional expressions. The two basic blocks - * represent the continuation in case of success/failure of the - * test. - */ - private def genCond(tree: Tree, - ctx: Context, - thenCtx: Context, - elseCtx: Context): Unit = - { - def genComparisonOp(l: Tree, r: Tree, code: Int): Unit = { - val op: TestOp = code match { - case scalaPrimitives.LT => LT; - case scalaPrimitives.LE => LE; - case scalaPrimitives.GT => GT; - case scalaPrimitives.GE => GE; - case scalaPrimitives.ID | scalaPrimitives.EQ => EQ; - case scalaPrimitives.NI | scalaPrimitives.NE => NE; - - case _ => abort("Unknown comparison primitive: " + code); - }; - - val kind = getMaxType(l.tpe :: r.tpe :: Nil); - var ctx1 = genLoad(l, ctx, kind); - ctx1 = genLoad(r, ctx1, kind); - ctx1.bb.emit(CJUMP(thenCtx.bb, elseCtx.bb, op, kind), r.pos); - ctx1.bb.close; - } - - if (settings.debug.value) - log("Entering genCond with tree: " + tree); - - tree match { - case Apply(fun, args) - if isPrimitive(fun.symbol) => - assert(args.length <= 1, - "Too many arguments for primitive function: " + fun.symbol); - val code = scalaPrimitives.getPrimitive(fun.symbol); - - if (code == scalaPrimitives.ZNOT) { - val Select(leftArg, _) = fun; - genCond(leftArg, ctx, elseCtx, thenCtx); - } else if ((code == scalaPrimitives.EQ || - code == scalaPrimitives.NE)) { - val Select(leftArg, _) = fun; - if (toTypeKind(leftArg.tpe).isReferenceType) { - if (code == scalaPrimitives.EQ) - genEqEqPrimitive(leftArg, args.head, ctx, thenCtx, elseCtx); - else - genEqEqPrimitive(leftArg, args.head, ctx, elseCtx, thenCtx); - } - else - genComparisonOp(leftArg, args.head, code); - } else if (scalaPrimitives.isComparisonOp(code)) { - val Select(leftArg, _) = fun; - genComparisonOp(leftArg, args.head, code); - } else { - code match { - case scalaPrimitives.ZAND => - val Select(leftArg, _) = fun; - - val ctxInterm = ctx.newBlock; - genCond(leftArg, ctx, ctxInterm, elseCtx); - genCond(args.head, ctxInterm, thenCtx, elseCtx); - - case scalaPrimitives.ZOR => - val Select(leftArg, _) = fun; - - val ctxInterm = ctx.newBlock; - genCond(leftArg, ctx, thenCtx, ctxInterm); - genCond(args.head, ctxInterm, thenCtx, elseCtx); - - case _ => - var ctx1 = genLoad(tree, ctx, BOOL); - ctx1.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL), tree.pos); - ctx1.bb.close; - } - } - - case _ => - var ctx1 = genLoad(tree, ctx, BOOL); - ctx1.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL), tree.pos); - ctx1.bb.close; - } - } - - val eqEqTemp: Name = "eqEqTemp$"; - - - /** - * Generate the "==" code for object references. It is equivalent of - * if (l == null) then r == null else l.equals(r); - */ - def genEqEqPrimitive(l: Tree, r: Tree, ctx: Context, thenCtx: Context, elseCtx: Context): Unit = { - var eqEqTempVar: Symbol = null; - var eqEqTempLocal: Local = null; - - ctx.method.lookupLocal(eqEqTemp) match { - case Some(local) => eqEqTempVar = local.sym; eqEqTempLocal = local; - case None => - eqEqTempVar = ctx.method.symbol.newVariable(l.pos, eqEqTemp); - eqEqTempVar.setInfo(definitions.AnyRefClass.typeConstructor); - eqEqTempLocal = new Local(eqEqTempVar, REFERENCE(definitions.AnyRefClass)); - ctx.method.addLocal(eqEqTempLocal); - } - - var ctx1 = genLoad(l, ctx, ANY_REF_CLASS); - ctx1 = genLoad(r, ctx1, ANY_REF_CLASS); - val tmpNullCtx = ctx1.newBlock; - val tmpNonNullCtx = ctx1.newBlock; - ctx1.bb.emit(STORE_LOCAL(eqEqTempLocal, false), l.pos); - ctx1.bb.emit(DUP(ANY_REF_CLASS)); - ctx1.bb.emit(CZJUMP(tmpNullCtx.bb, tmpNonNullCtx.bb, EQ, ANY_REF_CLASS)); - ctx1.bb.close; - - tmpNullCtx.bb.emit(DROP(ANY_REF_CLASS), l.pos); // type of AnyRef - tmpNullCtx.bb.emit(LOAD_LOCAL(eqEqTempLocal, false)); - tmpNullCtx.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, EQ, ANY_REF_CLASS)); - tmpNullCtx.bb.close; - - tmpNonNullCtx.bb.emit(LOAD_LOCAL(eqEqTempLocal, false), l.pos); - tmpNonNullCtx.bb.emit(CALL_METHOD(definitions.Object_equals, Dynamic)); - tmpNonNullCtx.bb.emit(CZJUMP(thenCtx.bb, elseCtx.bb, NE, BOOL)); - tmpNonNullCtx.bb.close; - } - - /** - * Add all fields of the given class symbol to the current ICode - * class. - */ - private def addClassFields(ctx: Context, cls: Symbol): Unit = { - assert(ctx.clazz.symbol eq cls, - "Classes are not the same: " + ctx.clazz.symbol + ", " + cls); - - for (val f <- cls.info.decls.elements) - if (!f.isMethod && f.isTerm) - ctx.clazz.addField(new IField(f)); - } - - /** - * Add parameters to the current ICode method. It is assumed the methods - * have been uncurried, so the list of lists contains just one list. - */ - private def addMethodParams(ctx: Context, vparamss: List[List[ValDef]]): Unit = - vparamss match { - case Nil => () - - case vparams :: Nil => - for (val p <- vparams) - ctx.method.addParam(new Local(p.symbol, toTypeKind(p.symbol.info))); - ctx.method.params = ctx.method.params.reverse; - - case _ => - abort("Malformed parameter list: " + vparamss); - } - - /** - * If the block consists of a single unconditional jump, prune - * it by replacing the instructions in the predecessor to jump - * directly to the JUMP target of the block. - */ - def prune(method: IMethod) = { - var changed = false; - var n = 0; - - def prune0(block: BasicBlock): Unit = { - val optCont = block.lastInstruction match { - case JUMP(b) if (b != block) => Some(b); - case _ => None - } - if (block.size == 1 && optCont != None) { - val Some(cont) = optCont; - val pred = block.predecessors; - log("Preds: " + pred + " of " + block); - pred foreach { p => - p.lastInstruction match { - case CJUMP(succ, fail, cond, kind) => - if (settings.debug.value) - log("Pruning empty if branch."); - changed = true; - p.replaceInstruction(p.lastInstruction, - if (block == succ) - CJUMP(cont, fail, cond, kind) - else if (block == fail) - CJUMP(succ, cont, cond, kind) - else - abort("Could not find block in preds")); - - case CZJUMP(succ, fail, cond, kind) => - if (settings.debug.value) - log("Pruning empty if branch."); - changed = true; - p.replaceInstruction(p.lastInstruction, - if (block == succ) - CZJUMP(cont, fail, cond, kind) - else if (block == fail) - CZJUMP(succ, cont, cond, kind) - else - abort("Could not find block in preds")); - - case JUMP(b) => - if (settings.debug.value) - log("Pruning empty if branch."); - changed = true; - p.replaceInstruction(p.lastInstruction, JUMP(cont)); - - case SWITCH(tags, labels) => - if (settings.debug.value) - log("Pruning empty if branch."); - changed = true; - p.replaceInstruction(p.lastInstruction, - SWITCH(tags, labels map (l => if (l == block) cont else l))); - } - } - if (changed) - method.code.removeBlock(block); - } - } - - do { - changed = false; - n = n + 1; - method.code traverse prune0; - } while (changed); - - if (settings.debug.value) - log("Prune fixpoint reached in " + n + " iterations."); - } - - def getMaxType(ts: List[Type]): TypeKind = { - def maxType(a: TypeKind, b: TypeKind): TypeKind = - a maxType b; - - val kinds = ts map toTypeKind; - kinds reduceLeft maxType; - } - - /** Check weather a given label definition is introduced by the tail call phase - * It is considered to be so if all value parameters of the label are the - * same as the value parameters of the current method. - */ - def isTailCallLabel(tree: LabelDef, ctx: Context) = ( - tree.params.length == ctx.defdef.vparamss.head && - List.forall2(tree.params, ctx.defdef.vparamss.head) - { (x, y) => x.symbol == y.symbol } - ); - - - /////////////////////// Context //////////////////////////////// - - - /** - * The Context class keeps information relative to the current state - * in code generation - */ - class Context { - - /** The current package. */ - var packg: Name = _; - - /** The current class. */ - var clazz: IClass = _; - - /** The current method. */ - var method: IMethod = _; - - /** The current basic block. */ - var bb: BasicBlock = _; - - /** Map from label symbols to label objects. */ - var labels: HashMap[Symbol, Label] = new HashMap(); - - /** Current method definition. */ - var defdef: DefDef = _; - - /** current exception handlers */ - var handlers: List[ExceptionHandler] = Nil; - - var handlerCount = 0; - - override def toString(): String = { - val buf = new StringBuffer(); - buf.append("\tpackage: ").append(packg).append('\n'); - buf.append("\tclazz: ").append(clazz).append('\n'); - buf.append("\tmethod: ").append(method).append('\n'); - buf.append("\tbb: ").append(bb).append('\n'); - buf.append("\tlabels: ").append(labels).append('\n'); - buf.append("\texception handlers: ").append(handlers).append('\n'); - buf.toString() - } - - - def this(other: Context) = { - this(); - this.packg = other.packg; - this.clazz = other.clazz; - this.method = other.method; - this.bb = other.bb; - this.labels = other.labels; - this.defdef = other.defdef; - this.handlers = other.handlers; - this.handlerCount = other.handlerCount; - } - - def setPackage(p: Name): this.type = { - this.packg = p; - this - } - - def setClass(c: IClass): this.type = { - this.clazz = c; - this - } - - def setMethod(m: IMethod): this.type = { - this.method = m; - this - } - - def setBasicBlock(b: BasicBlock): this.type = { - this.bb = b; - this - } - - /** Prepare a new context upon entry into a method */ - def enterMethod(m: IMethod, d: DefDef): Context = { - val ctx1 = new Context(this) setMethod(m); - ctx1.labels = new HashMap(); - ctx1.method.code = new Code(m.symbol.simpleName.toString()); - ctx1.bb = ctx1.method.code.startBlock; - ctx1.defdef = d; - ctx1 - } - - /** Return a new context for a new basic block. */ - def newBlock: Context = { - val block = method.code.newBlock; - handlers foreach (h => h addBlock block); - new Context(this) setBasicBlock block; - } - - /** Create a new exception handler and adds it in the list - * of current exception handlers. - */ - def newHandler(cls: Symbol): ExceptionHandler = { - handlerCount = handlerCount + 1; - val exh = new ExceptionHandler(method, "" + handlerCount, cls); - method.addHandler(exh); - handlers = exh :: handlers; - if (settings.debug.value) - log("added handler: " + exh); - - exh - } - - /** Return a new context for generating code for the given - * exception handler. - */ - def enterHandler(exh: ExceptionHandler): Context = { - val ctx = newBlock; - exh.setStartBlock(ctx.bb); - ctx - } - - def exitHandler(exh: ExceptionHandler): Unit = { - assert(handlerCount > 0 && handlers.head == exh, - "Wrong nesting of exception handlers." + this + " for " + exh); - handlerCount = handlerCount - 1; - handlers = handlers.tail; - if (settings.debug.value) - log("removed handler: " + exh); - - } - - /** Clone the current context */ - def dup: Context = new Context(this); - - /** - * Generate exception handlers for the body. Body is evaluated - * with a context where all the handlers are active. Handlers are - * evaluated in the 'outer' context. - * - * It returns the resulting context, with the same active handlers as - * before the call. Use it like: - * - * ctx.Try( ctx => { - * ctx.bb.emit(...) // protected block - * }, Pair(definitions.ThrowableClass, - * ctx => { - * ctx.bb.emit(...); // exception handler - * }), Pair(AnotherExceptionClass, - * ctx => {... - * } )) - */ - def Try(body: Context => Context, - handlers: List[Pair[Symbol, (Context => Context)]]) = { - val outerCtx = this.dup; - val afterCtx = outerCtx.newBlock; - - val exhs = handlers.map { handler => - val exh = this.newHandler(handler._1); - val ctx1 = handler._2(outerCtx.enterHandler(exh)); - ctx1.bb.emit(JUMP(afterCtx.bb)); - ctx1.bb.close; - exh - } - val bodyCtx = this.newBlock; - - val finalCtx = body(bodyCtx); - - outerCtx.bb.emit(JUMP(bodyCtx.bb)); - outerCtx.bb.close; - - exhs.reverse foreach finalCtx.exitHandler; - - finalCtx.bb.emit(JUMP(afterCtx.bb)); - finalCtx.bb.close; - - afterCtx - } - } - } - - /** - * Represent a label in the current method code. In order - * to support forward jumps, labels can be created without - * having a deisgnated target block. They can later be attached - * by calling `anchor'. - */ - class Label(val symbol: Symbol) { - var anchored = false; - var block: BasicBlock = _; - var params: List[Symbol] = _; - - private var toPatch: List[Instruction] = Nil; - - /** Fix this label to the given basic block. */ - def anchor(b: BasicBlock): Label = { - assert(!anchored, "Cannot anchor an already anchored label!"); - anchored = true; - this.block = b; - this - } - - def setParams(p: List[Symbol]): Label = { - assert(params == null, "Cannot set label parameters twice!"); - params = p; - this - } - - /** Add an instruction that refers to this label. */ - def addCallingInstruction(i: Instruction) = - toPatch = i :: toPatch; - - /** - * Patch the code by replacing pseudo call instructions with - * jumps to the given basic block. - */ - def patch(code: Code): Unit = { - def substMap: Map[Instruction, Instruction] = { - val map = new HashMap[Instruction, Instruction](); - - toPatch foreach (i => map += i -> patch(i)); - map - } - - val map = substMap; - code traverse (.subst(map)); - } - - /** - * Return the patched instruction. If the given instruction - * jumps to this label, replace it with the basic block. Otherwise, - * return the same instruction. Conditional jumps have more than one - * label, so they are replaced only if all labels are anchored. - */ - def patch(instr: Instruction): Instruction = { - assert(anchored, "Cannot patch until this label is anchored: " + this); - - instr match { - case PJUMP(self) - if (self == this) => JUMP(block); - - case PCJUMP(self, failure, cond, kind) - if (self == this && failure.anchored) => - CJUMP(block, failure.block, cond, kind); - - case PCJUMP(success, self, cond, kind) - if (self == this && success.anchored) => - CJUMP(success.block, block, cond, kind); - - case PCZJUMP(self, failure, cond, kind) - if (self == this && failure.anchored) => - CZJUMP(block, failure.block, cond, kind); - - case PCZJUMP(success, self, cond, kind) - if (self == this && success.anchored) => - CZJUMP(success.block, block, cond, kind); - - case _ => instr; - } - } - } - - ///////////////// Fake instructions ////////////////////////// - - /** - * Pseudo jump: it takes a Label instead of a basick block. - * It is used temporarily during code generation. It is replaced - * by a real JUMP instruction when all labels are resolved. - */ - abstract class PseudoJUMP(label: Label) extends Instruction { - override def toString(): String ="PJUMP " + label.symbol.simpleName; - - override def consumed = 0; - override def produced = 0; - - // register with the given label - if (!label.anchored) - label.addCallingInstruction(this); - } - - case class PJUMP(where: Label) extends PseudoJUMP(where); - - case class PCJUMP(success: Label, failure: Label, cond: TestOp, kind: TypeKind) - extends PseudoJUMP(success) { - - if (!failure.anchored) - failure.addCallingInstruction(this); - } - - case class PCZJUMP(success: Label, failure: Label, cond: TestOp, kind: TypeKind) - extends PseudoJUMP(success) { - - if (!failure.anchored) - failure.addCallingInstruction(this); - } - -} - diff --git a/sources/scala/tools/nsc/backend/icode/ICodes.scala b/sources/scala/tools/nsc/backend/icode/ICodes.scala deleted file mode 100644 index d29a8b5433..0000000000 --- a/sources/scala/tools/nsc/backend/icode/ICodes.scala +++ /dev/null @@ -1,31 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -import scala.tools.nsc.symtab._; - -/** Glue together ICode parts. - */ -abstract class ICodes extends AnyRef - with Members - with BasicBlocks - with Opcodes - with TypeStacks - with TypeKinds - with ExceptionHandlers - with Primitives - with Linearizers -{ - val global: Global; - - /** The ICode representation of classes */ - var classes: List[IClass] = _; - - def init = { classes = Nil } -} - diff --git a/sources/scala/tools/nsc/backend/icode/Linearizers.scala b/sources/scala/tools/nsc/backend/icode/Linearizers.scala deleted file mode 100644 index 7a0b77f6fa..0000000000 --- a/sources/scala/tools/nsc/backend/icode/Linearizers.scala +++ /dev/null @@ -1,89 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -import scala.tools.nsc.ast._; -import scala.collection.mutable.Stack; - -trait Linearizers: ICodes { - import opcodes._; - - trait Linearizer { - def linearize(c: IMethod): List[BasicBlock]; - } - - /** - * A simple linearizer which predicts all branches to - * take the 'success' branch and tries to schedule those - * blocks immediately after the test. This is in sync with - * how 'while' statements are translated (if the test is - * 'true', the loop continues). - */ - class NormalLinearizer extends Linearizer with WorklistAlgorithm { - type Elem = BasicBlock; - type WList = Stack[Elem]; - - val worklist: WList = new Stack(); - - var blocks: List[BasicBlock] = Nil; - - def linearize(m: IMethod): List[BasicBlock] = { - val b = m.code.startBlock; - blocks = Nil; - - run { - worklist ++= (m.exh map (.startBlock)); - worklist.push(b); - } - - blocks.reverse; - } - - /** Linearize another subtree and append it to the existing blocks. */ - def linearize(startBlock: BasicBlock): List[BasicBlock] = { - //blocks = startBlock :: Nil; - run( { worklist.push(startBlock); } ); - blocks.reverse; - } - - def processElement(b: BasicBlock) = - if (b.size > 0) { - add(b); - b.lastInstruction match { - case JUMP(where) => - add(where); - case CJUMP(success, failure, _, _) => - add(success); - add(failure); - case CZJUMP(success, failure, _, _) => - add(success); - add(failure); - case SWITCH(_, labels) => - add(labels); - case RETURN(_) => (); - case THROW() => (); - } - } - - def dequeue: Elem = worklist.pop; - - /** - * Prepend b to the list, if not already scheduled. - * TODO: use better test than linear search - */ - def add(b: BasicBlock) = - if (blocks.contains(b)) - () - else { - blocks = b :: blocks; - worklist push b; - } - - def add(bs: List[BasicBlock]): Unit = bs foreach add; - } -} diff --git a/sources/scala/tools/nsc/backend/icode/Members.scala b/sources/scala/tools/nsc/backend/icode/Members.scala deleted file mode 100644 index f12c4ef62c..0000000000 --- a/sources/scala/tools/nsc/backend/icode/Members.scala +++ /dev/null @@ -1,241 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -import scala.collection.mutable.HashMap; -import scala.collection.mutable.{Set, HashSet}; -import scala.{Symbol => scala_Symbol}; - -import scala.tools.nsc.symtab.Flags; - -trait Members: ICodes { - import global._; - - /** - * This class represents the intermediate code of a method or - * other multi-block piece of code, like exception handlers. - */ - class Code(label: String) { - - /** The set of all blocks */ - val blocks: HashSet[BasicBlock] = new HashSet; - - /** The start block of the method */ - var startBlock: BasicBlock = null; - - /** The stack produced by this method */ - var producedStack: TypeStack = null; - - private var currentLabel: int = 0; - - // Constructor code - startBlock = newBlock; - startBlock.initStack(new TypeStack); - - - def removeBlock(b: BasicBlock) = { - if (settings.debug.value) { - assert(blocks.forall(p => !(p.successors.contains(b))), - "Removing block that is still referenced in method code " + label); - if (b == startBlock) - assert(b.successors.length == 1, - "Removing start block with more than one successor."); - } - - if (b == startBlock) - startBlock = b.successors.head; - blocks -= b; - } - - /** - * Apply a function to all basic blocks, for side-effects. It starts at - * the given startBlock and checks that are no predecessors of the given node. - * Only blocks that are reachable via a path from startBlock are ever visited. - */ - def traverseFrom(startBlock: BasicBlock, f: BasicBlock => Unit) = { - val visited: Set[BasicBlock] = new HashSet(); - - def traverse0(toVisit: List[BasicBlock]): Unit = toVisit match { - case Nil => (); - case b :: bs => if (!visited.contains(b)) { - f(b); - visited += b; - traverse0(bs ::: b.successors); - } else - traverse0(bs); - } - assert(startBlock.predecessors == Nil, - "Starting traverse from a block with predecessors: " + this); - traverse0(startBlock :: Nil) - } - - def traverse(f: BasicBlock => Unit) = blocks foreach f; - - /* This method applies the given function to each basic block. */ - def traverseFeedBack(f: (BasicBlock, HashMap[BasicBlock, Boolean]) => Unit) = { - val visited : HashMap[BasicBlock, Boolean] = new HashMap; - visited ++= blocks.elements.map(x => Pair(x, false)); - - var blockToVisit : List[BasicBlock] = startBlock::Nil; - - while (!blockToVisit.isEmpty) { - blockToVisit match { - case b::xs => - if (!visited(b)) { - f(b, visited); - blockToVisit = b.successors ::: xs; - visited += b -> true; - } else - blockToVisit = xs; - } - } - } - - /** This methods returns a string representation of the ICode */ - override def toString() : String = "ICode '" + label + "'"; - - /** This method print the code */ -// def print() : unit = print(System.out); - -// def print(out: java.io.PrintStream) : unit = { -// traverse((bb: BasicBlock) => { -// out.println("Block #" + bb.label); -// out.println("Substituable variables : "); -// if (bb.substituteVars != null) -// bb.substituteVars.foreach(out.print); -// else -// out.println(" {Empty} "); -// out.println("Instructions:"); -// bb.traverse((ici: Instruction) => -// out.println(" "+ici.toString())); -// out.print ("Successors: "); -// bb.successors.foreach((bb: BasicBlock) => out.print(bb.label+", ")); -// out.println (""); // ?? Del -// out.println (); -// }); -// } - - /* Compute a unique new label */ - def nextLabel = { - currentLabel = currentLabel + 1; - currentLabel; - } - - /* Create a new block and append it to the list - */ - def newBlock: BasicBlock = { - val block = new BasicBlock(nextLabel, this); - blocks += block; - block; - } - } - - /** Represent a class in ICode */ - class IClass(val symbol: Symbol) { - var fields: List[IField] = Nil; - var methods: List[IMethod] = Nil; - var cunit: CompilationUnit = _; - - def addField(f: IField): this.type = { - fields = f :: fields; - this - } - - def addMethod(m: IMethod): this.type = { - methods = m :: methods; - this - } - - def setCompilationUnit(unit: CompilationUnit): this.type = { - this.cunit = unit; - this - } - - override def toString() = symbol.fullNameString; - - def lookupField(s: Symbol) = fields find ((f) => f.symbol == s); - } - - /** Represent a field in ICode */ - class IField(val symbol: Symbol) { - } - - /** - * Represents a method in ICode. Local variables contain - * both locals and parameters, similar to the way the JVM - * 'sees' them. - * - * Locals and parameters are added in reverse order, as they - * are kept in cons-lists. The 'builder' is responsible for - * reversing them and putting them back, when the generation is - * finished (GenICode does that). - */ - class IMethod(val symbol: Symbol) { - var code: Code = null; - var exh: List[ExceptionHandler] = Nil; - var sourceFile: String = _; - var returnType: TypeKind = _; - - /** local variables and method parameters */ - var locals: List[Local] = Nil; - - /** method parameters */ - var params: List[Local] = Nil; - - def setCode(code: Code): IMethod = { - this.code = code; - this - } - - def addLocal(l: Local): Unit = - if (!(locals contains l)) - locals = l :: locals; - - def addLocals(ls: List[Local]): Unit = - ls foreach addLocal; - - def addParam(p: Local): Unit = - if (!(params contains p)) { - params = p :: params; - locals = p :: locals; - } - - def addParams(as: List[Local]): Unit = - as foreach addParam; - - def lookupLocal(n: Name): Option[Local] = - locals find ((l) => l.sym.name == n); - - def lookupLocal(sym: Symbol): Option[Local] = - locals find ((l) => l.sym == sym); - - def addHandler(e: ExceptionHandler): Unit = - exh = e :: exh; - - /** Is this method deferred ('abstract' in Java sense) */ - def isDeferred = ( - symbol.hasFlag(Flags.DEFERRED) || - symbol.owner.hasFlag(Flags.INTERFACE) - ); - - override def toString() = symbol.fullNameString; - } - - /** Represent local variables and parameters */ - class Local(val sym: Symbol, val kind: TypeKind) { - var index: Int = -1; - - override def equals(other: Any): Boolean = ( - other.isInstanceOf[Local] && - other.asInstanceOf[Local].sym == this.sym - ); - - override def toString(): String = sym.toString(); - } - -} diff --git a/sources/scala/tools/nsc/backend/icode/Opcodes.scala b/sources/scala/tools/nsc/backend/icode/Opcodes.scala deleted file mode 100644 index 24eb1132f6..0000000000 --- a/sources/scala/tools/nsc/backend/icode/Opcodes.scala +++ /dev/null @@ -1,473 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - - -package scala.tools.nsc.backend.icode; - -import scala.tools.nsc.ast._; -import scala.tools.nsc.util.Position; - -/* - A pattern match - - case THIS(clasz) => - case CONSTANT(const) => - case LOAD_ARRAY_ITEM(kind) => - case LOAD_LOCAL(local, isArg) => - case LOAD_FIELD(field, isStatic) => - case LOAD_MODULE(module) => - case STORE_ARRAY_ITEM(kind) => - case STORE_LOCAL(local, isArg) => - case STORE_FIELD(field, isStatic) => - case CALL_PRIMITIVE(primitive) => - case CALL_METHOD(method, style) => - case NEW(kind) => - case CREATE_ARRAY(elem) => - case IS_INSTANCE(tpe) => - case CHECK_CAST(tpe) => - case SWITCH(tags, labels) => - case JUMP(where) => - case CJUMP(success, failure, cond, kind) => - case CZJUMP(success, failure, cond, kind) => - case RETURN(kind) => - case THROW() => - case DROP(kind) => - case DUP(kind) => - case MONITOR_ENTER() => - case MONITOR_EXIT() => -*/ - - -/** - * The ICode intermediate representation. It is a stack-based - * representation, very close to the JVM and .NET. It uses the - * erased types of Scala and references Symbols to refer named entities - * in the source files. - */ -[_trait_] abstract class Opcodes: ICodes { - import global.{Symbol, NoSymbol, Type, Name, Constant}; - - /** This class represents an instruction of the intermediate code. - * Each case subclass will represent a specific operation. - */ - abstract class Instruction { - - /** This abstract method returns the number of used elements on the stack */ - def consumed : Int = 0; - - /** This abstract method returns the number of produced elements on the stack */ - def produced : Int = 0; - - /** This method returns the difference of size of the stack when the instruction is used */ - def difference = produced-consumed; - - /** The corresponding position in the source file */ - var pos: Int = Position.NOPOS; - } - - object opcodes { - - /** Loads the "this" references on top of the stack. - * Stack: ... - * ->: ...:ref - */ - case class THIS(clasz: Symbol) extends Instruction { - /** Returns a string representation of this constant */ - override def toString(): String = "THIS"; - - override def consumed = 0; - override def produced = 1; - } - - /** Loads a constant on the stack. - * Stack: ... - * ->: ...:constant - */ - case class CONSTANT(constant: Constant) extends Instruction{ - /** Returns a string representation of this constant */ - override def toString(): String = "CONSTANT ("+constant.toString()+")"; - - override def consumed = 0; - override def produced = 1; - } - - /** Loads an element of an array. The array and the index should - * be on top of the stack. - * Stack: ...:array[a](Ref):index(Int) - * ->: ...:element(a) - */ - case class LOAD_ARRAY_ITEM(kind: TypeKind) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String = "LOAD_ARRAY_ITEM (" + kind + ")"; - - override def consumed = 2; - override def produced = 1; - } - - /** Load a local variable on the stack. It can be a method argument. - * Stack: ... - * ->: ...:value - */ - case class LOAD_LOCAL(local: Local, isArgument: boolean) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String = "LOAD_LOCAL "+local.toString(); //+isArgument?" (argument)":""; - - override def consumed = 0; - override def produced = 1; - } - - /** Load a field on the stack. The object to which it refers should be - * on the stack. - * Stack: ...:ref - * ->: ...:value - */ - case class LOAD_FIELD(field: Symbol, isStatic: boolean) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String = - "LOAD_FIELD " + (if (isStatic) field.fullNameString else field.toString()); - - override def consumed = 1; - override def produced = 1; - } - - case class LOAD_MODULE(module: Symbol) extends Instruction { - assert(module != NoSymbol, - "Invalid module symbol"); - /** Returns a string representation of this instruction */ - override def toString(): String = - "LOAD_MODULE " + module.toString(); - - override def consumed = 0; - override def produced = 1; - } - - /** Store a value into an array at a specified index. - * Stack: ...:array[a](Ref):index(Int):value(a) - * ->: ... - */ - case class STORE_ARRAY_ITEM(kind: TypeKind) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String = "STORE_ARRAY_ITEM (" + kind + ")"; - - override def consumed = 3; - override def produced = 0; - } - - /** Store a value into a local variable. It can be an argument. - * Stack: ...:value - * ->: ... - */ - case class STORE_LOCAL(local: Local, isArgument: boolean) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String = "STORE_LOCAL "+local.toString(); //+isArgument?" (argument)":""; - - override def consumed = 1; - override def produced = 0; - } - - /** Store a value into a field. - * Stack: ...:ref:value - * ->: ... - */ - case class STORE_FIELD(field: Symbol, isStatic: boolean) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String = "STORE_FIELD "+field.toString(); //+isStatic?" (static)":""; - - override def consumed = 2; - override def produced = 0; - } - - /** Call a primitive function. - * Stack: ...:arg1:arg2:...:argn - * ->: ...:result - */ - case class CALL_PRIMITIVE(primitive: Primitive) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String ="CALL_PRIMITIVE "+primitive.toString(); - - override def consumed = primitive match { - case Negation(_) => 1; - case Test(_,_,true) => 1; - case Test(_,_,false) => 2; - case Comparison(_,_) => 2; - case Arithmetic(_,_) => 2; - case Logical(_,_) => 2; - case Shift(_,_) => 2; - case Conversion(_,_) => 1; - case ArrayLength(_) => 1; - case StringConcat(_) => 2; - case StartConcat => 0; - case EndConcat => 1; - } - override def produced = 1; - } - - /** This class represents a CALL_METHOD instruction - * STYLE: dynamic / static(StaticInstance) - * Stack: ...:ref:arg1:arg2:...:argn - * ->: ...:result - * - * STYLE: static(StaticClass) - * Stack: ...:arg1:arg2:...:argn - * ->: ...:result - * - */ - case class CALL_METHOD(method: Symbol, style: InvokeStyle) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String = - "CALL_METHOD " + method.fullNameString +" ("+style.toString()+")"; - - override def consumed = { - var result = method.tpe.paramTypes.length; - result = result + (style match { - case Dynamic => 1 - case Static(true) => 1 - case _ => 0 - }); - - result; - } - override def produced = 1; - } - - /** Create a new instance of a class through the specified constructor - * Stack: ...:arg1:arg2:...:argn - * ->: ...:ref - */ - case class NEW(kind: TypeKind) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String = "NEW "+ kind; - - override def consumed = 0; - override def produced = 1; - } - - - /** This class represents a CREATE_ARRAY instruction - * Stack: ...:size(int) - * ->: ...:arrayref - */ - case class CREATE_ARRAY(element: TypeKind) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String ="CREATE_ARRAY "+element.toString(); - - override def consumed = 1; - override def produced = 1; - } - - /** This class represents a IS_INSTANCE instruction - * Stack: ...:ref - * ->: ...:result(boolean) - */ - case class IS_INSTANCE(typ: TypeKind) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String ="IS_INSTANCE "+typ.toString(); - - override def consumed = 1; - override def produced = 1; - } - - /** This class represents a CHECK_CAST instruction - * Stack: ...:ref(oldtype) - * ->: ...:ref(typ <=: oldtype) - */ - case class CHECK_CAST(typ: TypeKind) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String ="CHECK_CAST "+typ.toString(); - - override def consumed = 1; - override def produced = 1; - } - - /** This class represents a SWITCH instruction - * Stack: ...:index(int) - * ->: ...: - * - * The tags array contains one entry per label, each entry consisting of - * an array of ints, any of which will trigger the jump to the corresponding label. - * labels should contain an extra label, which is the 'default' jump. - */ - case class SWITCH(tags: List[List[Int]], labels: List[BasicBlock]) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String ="SWITCH ..."; - - override def consumed = 1; - override def produced = 0; - } - - /** This class represents a JUMP instruction - * Stack: ... - * ->: ... - */ - case class JUMP(where: BasicBlock) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String ="JUMP "+where.label; - - override def consumed = 0; - override def produced = 0; - } - - /** This class represents a CJUMP instruction - * It compares the two values on the stack with the 'cond' test operator - * Stack: ...:value1:value2 - * ->: ... - */ - case class CJUMP(successBlock: BasicBlock, - failureBlock: BasicBlock, - cond: TestOp, - kind: TypeKind) extends Instruction - { - - /** Returns a string representation of this instruction */ - override def toString(): String = ( - "CJUMP (" + kind + ")" + - cond.toString()+" ? "+successBlock.label+" : "+failureBlock.label - ); - - override def consumed = 2; - override def produced = 0; - } - - /** This class represents a CZJUMP instruction - * It compares the one value on the stack and zero with the 'cond' test operator - * Stack: ...:value: - * ->: ... - */ - case class CZJUMP(successBlock: BasicBlock, - failureBlock: BasicBlock, - cond: TestOp, - kind: TypeKind) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String = ( - "CZJUMP (" + kind + ")" + - cond.toString()+" ? "+successBlock.label+" : "+failureBlock.label - ); - - override def consumed = 1; - override def produced = 0; - } - - - /** This class represents a RETURN instruction - * Stack: ... - * ->: ... - */ - case class RETURN(kind: TypeKind) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String ="RETURN (" + kind + ")"; - - override def consumed = 0; - override def produced = 0; - } - - /** This class represents a THROW instruction - * Stack: ...:Throwable(Ref) - * ->: ...: - */ - case class THROW() extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String ="THROW"; - - override def consumed = 1; - override def produced = 0; - } - - /** This class represents a DROP instruction - * Stack: ...:something - * ->: ... - */ - case class DROP (typ: TypeKind) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String ="DROP "+typ.toString(); - - override def consumed = 1; - override def produced = 0; - } - - /** This class represents a DUP instruction - * Stack: ...:something - * ->: ...:something:something - */ - case class DUP (typ: TypeKind) extends Instruction { - /** Returns a string representation of this instruction */ - override def toString(): String ="DUP"; - - override def consumed = 1; - override def produced = 2; - } - - /** This class represents a MONITOR_ENTER instruction - * Stack: ...:object(ref) - * ->: ...: - */ - case class MONITOR_ENTER() extends Instruction { - - /** Returns a string representation of this instruction */ - override def toString(): String ="MONITOR_ENTER"; - - override def consumed = 1; - override def produced = 0; - } - - /** This class represents a MONITOR_EXIT instruction - * Stack: ...:object(ref) - * ->: ...: - */ - case class MONITOR_EXIT() extends Instruction { - - /** Returns a string representation of this instruction */ - override def toString(): String ="MONITOR_EXIT"; - - override def consumed = 1; - override def produced = 0; - } - - /** This class represents a method invocation style. */ - trait InvokeStyle { - - /** Is this a dynamic method call? */ - def isDynamic: Boolean = this match { - case Dynamic => true; - case _ => false; - } - - /** Is this a static method call? */ - def isStatic: Boolean = this match { - case Static(_) => true; - case _ => false; - } - - /** Is this an instance method call? */ - def hasInstance: Boolean = this match { - case Dynamic => true; - case Static(onInstance) => onInstance; - case SuperCall(_) => true; - case _ => false; - } - - /** Returns a string representation of this style. */ - override def toString(): String = this match { - case Dynamic => "dynamic"; - case Static(false) => "static-class"; - case Static(true) => "static-instance"; - case SuperCall(mixin) => "super(" + mixin + ")"; - } - } - - case object Dynamic extends InvokeStyle; - - /** - * Special invoke. Static(true) is used for calls to private - * members. - */ - case class Static(onInstance: Boolean) extends InvokeStyle; - - /** Call through super[mixin]. */ - case class SuperCall(mixin: Name) extends InvokeStyle; - - } -} diff --git a/sources/scala/tools/nsc/backend/icode/Primitives.scala b/sources/scala/tools/nsc/backend/icode/Primitives.scala deleted file mode 100644 index 5cebb0edaf..0000000000 --- a/sources/scala/tools/nsc/backend/icode/Primitives.scala +++ /dev/null @@ -1,239 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -import java.io.PrintWriter; - -[_trait_] abstract class Primitives: ICodes { - - /** This class represents a primitive operation. */ - class Primitive { - } - - - // type : (type) => type - // range: type <- { BOOL, Ix, Ux, Rx } - // jvm : {i, l, f, d}neg - case class Negation(kind: TypeKind) extends Primitive; - - // type : zero ? (type) => BOOL : (type,type) => BOOL - // range: type <- { BOOL, Ix, Ux, Rx, REF } - // jvm : if{eq, ne, lt, ge, le, gt}, if{null, nonnull} - // if_icmp{eq, ne, lt, ge, le, gt}, if_acmp{eq,ne} - case class Test(op: TestOp, kind: TypeKind, zero: boolean) extends Primitive; - - // type : (type,type) => I4 - // range: type <- { Ix, Ux, Rx } - // jvm : lcmp, {f, d}cmp{l, g} - case class Comparison(op: ComparisonOp, kind: TypeKind) extends Primitive; - - // type : (type,type) => type - // range: type <- { Ix, Ux, Rx } - // jvm : {i, l, f, d}{add, sub, mul, div, rem} - case class Arithmetic(op: ArithmeticOp, kind: TypeKind) extends Primitive; - - // type : (type,type) => type - // range: type <- { BOOL, Ix, Ux } - // jvm : {i, l}{and, or, xor} - case class Logical(op: LogicalOp, kind: TypeKind) extends Primitive; - - // type : (type,I4) => type - // range: type <- { Ix, Ux } - // jvm : {i, l}{shl, ushl, shr} - case class Shift(op: ShiftOp, kind: TypeKind) extends Primitive; - - // type : (src) => dst - // range: src,dst <- { Ix, Ux, Rx } - // jvm : i2{l, f, d}, l2{i, f, d}, f2{i, l, d}, d2{i, l, f}, i2{b, c, s} - case class Conversion(src: TypeKind, dst: TypeKind) extends Primitive; - - // type : (Array[REF]) => I4 - // range: type <- { BOOL, Ix, Ux, Rx, REF } - // jvm : arraylength - case class ArrayLength(kind: TypeKind) extends Primitive; - - // type : (buf,el) => buf - // range: lf,rg <- { BOOL, Ix, Ux, Rx, REF, STR } - // jvm : It should call the appropiate 'append' method on StringBuffer - case class StringConcat(el: TypeKind) extends Primitive; - - /** Signals the beginning of a series of concatenations. - * On the JVM platform, it should create a new StringBuffer - */ - case object StartConcat extends Primitive; - - /** - * type: (buf) => STR - * jvm : It should turn the StringBuffer into a String. - */ - case object EndConcat extends Primitive; - - /** Pretty printer for primitives */ - class PrimitivePrinter(out: PrintWriter) { - - def print(s: String): PrimitivePrinter = { - out.print(s); - this - } - - def print(o: AnyRef): PrimitivePrinter = print(o.toString()); - - def printPrimitive(prim: Primitive) = prim match { - case Negation(kind) => - print("!"); - - case Test(op, kind, zero) => - print(op).print(kind); - - case Comparison(op, kind) => - print(op).print("(").print(kind); - - } - } - - /** This class represents a comparison operation. */ - class ComparisonOp { - - /** Returns a string representation of this operation. */ - override def toString(): String = this match { - case CMPL => "CMPL"; - case CMP => "CMP"; - case CMPG => "CMPG"; - case _ => throw new RuntimeException("ComparisonOp unknown case"); - } - } - - /** A comparison operation with -1 default for NaNs */ - case object CMPL extends ComparisonOp; - - /** A comparison operation with no default for NaNs */ - case object CMP extends ComparisonOp; - - /** A comparison operation with +1 default for NaNs */ - case object CMPG extends ComparisonOp; - - - /** This class represents a test operation. */ - class TestOp { - - /** Returns the negation of this operation. */ - def negate(): TestOp = this match { - case EQ => NE; - case NE => EQ; - case LT => GE; - case GE => LT; - case LE => GT; - case GT => LE; - case _ => throw new RuntimeException("TestOp unknown case"); - } - - /** Returns a string representation of this operation. */ - override def toString(): String = this match { - case EQ => "EQ"; - case NE => "NE"; - case LT => "LT"; - case GE => "GE"; - case LE => "LE"; - case GT => "GT"; - case _ => throw new RuntimeException("TestOp unknown case"); - } - } - /** An equality test */ - case object EQ extends TestOp; - - /** A non-equality test */ - case object NE extends TestOp; - - /** A less-than test */ - case object LT extends TestOp; - - /** A greater-than-or-equal test */ - case object GE extends TestOp; - - /** A less-than-or-equal test */ - case object LE extends TestOp; - - /** A greater-than test */ - case object GT extends TestOp; - - /** This class represents an arithmetic operation. */ - class ArithmeticOp { - - /** Returns a string representation of this operation. */ - override def toString(): String = this match { - case ADD => "ADD"; - case SUB => "SUB"; - case MUL => "MUL"; - case DIV => "DIV"; - case REM => "REM"; - case NOT => "NOT"; - case _ => throw new RuntimeException("ArithmeticOp unknown case"); - } - } - - /** An arithmetic addition operation */ - case object ADD extends ArithmeticOp; - - /** An arithmetic subtraction operation */ - case object SUB extends ArithmeticOp; - - /** An arithmetic multiplication operation */ - case object MUL extends ArithmeticOp; - - /** An arithmetic division operation */ - case object DIV extends ArithmeticOp; - - /** An arithmetic remainder operation */ - case object REM extends ArithmeticOp; - - /** Bitwise negation. */ - case object NOT extends ArithmeticOp; - - /** This class represents a shift operation. */ - class ShiftOp { - - /** Returns a string representation of this operation. */ - override def toString(): String = this match { - case LSL => "LSL"; - case ASR => "ASR"; - case LSR => "LSR"; - case _ => throw new RuntimeException("ShitOp unknown case"); - } - } - - /** A logical shift to the left */ - case object LSL extends ShiftOp; - - /** An arithmetic shift to the right */ - case object ASR extends ShiftOp; - - /** A logical shift to the right */ - case object LSR extends ShiftOp; - - /** This class represents a logical operation. */ - class LogicalOp { - - /** Returns a string representation of this operation. */ - override def toString(): String = this match { - case AND => return "AND"; - case OR => return "OR"; - case XOR => return "XOR"; - case _ => throw new RuntimeException("LogicalOp unknown case"); - } - } - - /** A bitwise AND operation */ - case object AND extends LogicalOp; - - /** A bitwise OR operation */ - case object OR extends LogicalOp; - - /** A bitwise XOR operation */ - case object XOR extends LogicalOp; -} - diff --git a/sources/scala/tools/nsc/backend/icode/Printers.scala b/sources/scala/tools/nsc/backend/icode/Printers.scala deleted file mode 100644 index dbc7badb9a..0000000000 --- a/sources/scala/tools/nsc/backend/icode/Printers.scala +++ /dev/null @@ -1,128 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -import java.io.PrintWriter; - -import scala.tools.nsc.util.Position; -import scala.tools.nsc.symtab.Flags; - -abstract class Printers { - val global: Global; - import global._; - import global.icodes.opcodes._; - import global.icodes._; - - class TextPrinter(writer: PrintWriter) { - var margin = 0; - var out = writer; - val linearizer = new NormalLinearizer(); - - final val TAB = 2; - - def setWriter(w: PrintWriter) = (out = w); - - def indent = margin = margin + TAB; - def undent = margin = margin - TAB; - - def print(s: String) = out.print(s); - def print(o: Any): Unit = print(o.toString()); - - def println(s: String): Unit = { - print(s); - println - } - - def println = { - out.println(); - var i = 0; - while (i < margin) { - print(" "); - i = i + 1; - } - } - - def printList[a](l: List[a], sep: String): Unit = l match { - case Nil => (); - case x :: Nil => print(x); - case x :: xs => print(x); print(sep); printList(xs, sep); - } - - def printList[a](pr: a => Unit)(l: List[a], sep: String): Unit = l match { - case Nil => (); - case x :: Nil => pr(x); - case x :: xs => pr(x); print(sep); printList(pr)(xs, sep); - } - - - private var clazz : IClass = _; - def printClass(cls: IClass): Unit = { - this.clazz = cls; - print(cls.symbol.toString()); print(" extends "); - printList(cls.symbol.info.parents, ", "); - indent; println(" {"); - println("// fields:"); - cls.fields.foreach(printField); println; - println("// methods"); - cls.methods.foreach(printMethod); - undent; println; - println("}"); - } - - def printField(f: IField): Unit = { - print(f.symbol.keyString); print(" "); - print(f.symbol.nameString); print(": "); - println(f.symbol.info.toString()); - } - - def printMethod(m: IMethod): Unit = { - print("def "); print(m.symbol.name); - print("("); printList(printParam)(m.params.reverse, ", "); print(")"); - print(": "); print(m.symbol.info.resultType); - - if (!m.isDeferred) { - println(" {"); - println("locals: " + m.locals.mkString("", ", ", "")); - println; - linearizer.linearize(m) foreach printBlock; - println("}"); - - indent;println("Exception handlers: "); - m.exh foreach printExceptionHandler; - - undent;println; - } else - println; - } - - def printParam(p: Local): Unit = { - print(p.sym.name); print(": "); print(p.sym.info); - print(" ("); print(p.kind); print(")"); - } - - def printExceptionHandler(e: ExceptionHandler) = { - indent; - println("catch (" + e.cls.simpleName + ") in " + e.covered + " starting at: " + e.startBlock); - undent; - println("with finalizer: " + e.finalizer); -// linearizer.linearize(e.startBlock) foreach printBlock; - } - - def printBlock(bb: BasicBlock): Unit = { - print(bb.label); print(": "); indent; println; - bb traverse printInstruction; - undent; println; - } - - def printInstruction(i: Instruction): Unit = { - if (settings.debug.value) - print("/* " + Position.line(clazz.cunit.source, i.pos) + " */ "); - println(i.toString()); - } - } -} diff --git a/sources/scala/tools/nsc/backend/icode/TypeKinds.scala b/sources/scala/tools/nsc/backend/icode/TypeKinds.scala deleted file mode 100644 index c1f0c204c6..0000000000 --- a/sources/scala/tools/nsc/backend/icode/TypeKinds.scala +++ /dev/null @@ -1,352 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -/* A type case - - case UNIT => - case BOOL => - case BYTE => - case SHORT => - case CHAR => - case INT => - case LONG => - case FLOAT => - case DOUBLE => - case REFERENCE(cls) => - case ARRAY(elem) => - -*/ - -import scala.collection.mutable.{Map, HashMap}; - -[_trait_] abstract class TypeKinds: ICodes { - import global._; - - /** This class represents a type kind. Type kinds - * represent the types that the VM know (or the ICode - * view of what VMs know). - */ - abstract class TypeKind { - - /** Returns a string representation of this type kind. */ - override def toString(): String = this match { - case UNIT => "UNIT"; - case BOOL => "BOOL"; - case BYTE => "BYTE" - case SHORT => "SHORT"; - case CHAR => "CHAR"; - case INT => "INT"; - case LONG => "LONG"; - case FLOAT => "FLOAT"; - case DOUBLE => "DOUBLE"; - case REFERENCE(cls) => "REFERENCE(" + cls.fullNameString + ")" ; - case ARRAY(elem) => "ARRAY[" + elem + "]"; - case _ => abort("Unkown type kind."); - } - - def toType: Type = this match { - case UNIT => definitions.UnitClass.info; - case BOOL => definitions.BooleanClass.info; - case BYTE => definitions.ByteClass.info; - case SHORT => definitions.ShortClass.info; - case CHAR => definitions.CharClass.info; - case INT => definitions.IntClass.info; - case LONG => definitions.LongClass.info; - case FLOAT => definitions.FloatClass.info; - case DOUBLE => definitions.DoubleClass.info; - case REFERENCE(cls) => typeRef(cls.typeConstructor.prefix, cls, Nil); - case ARRAY(elem) => typeRef(definitions.ArrayClass.typeConstructor.prefix, - definitions.ArrayClass, - elem.toType :: Nil); - case _ => abort("Unknown type kind."); - } - - def isReferenceType: Boolean = false; - def isArrayType: Boolean = false; - def isValueType: Boolean = !isReferenceType && !isArrayType; - - - def isIntType: Boolean = this match { - case BYTE | SHORT | INT | LONG | CHAR => true; - case _ => false; - } - - def isRealType: Boolean = this match { - case FLOAT | DOUBLE => true; - case _ => false; - } - - def isNumericType: Boolean = isIntType | isRealType; - - def maxType(other: TypeKind): TypeKind; - - /** Simple subtyping check */ - def <:<(other: TypeKind): Boolean = (this == other); - - override def equals(other: Any): Boolean = - this eq other.asInstanceOf[AnyRef]; - } - - /** - * The least upper bound of two typekinds. They have to be either - * REFERENCE or ARRAY kinds. - * - * The lub is based on the lub of scala types. - */ - def lub(a: TypeKind, b: TypeKind): TypeKind = { - def lub0(t1: Type, t2: Type): Type = { - val lubTpe = global.lub(t1 :: t2 :: Nil); - assert(lubTpe.symbol.isClass, - "Least upper bound of " + t1 + " and " + t2 + " is not a class: " + lubTpe); - lubTpe; - } - - if ((a.isReferenceType || a.isArrayType) && - (b.isReferenceType || b.isArrayType)) - toTypeKind(lub0(a.toType, b.toType)) - else if (a == b) a - else if (a == REFERENCE(definitions.AllClass)) b - else if (b == REFERENCE(definitions.AllClass)) a - else throw new CheckerError("Incompatible types: " + a + " with " + b); - } - - /** The unit value */ - case object UNIT extends TypeKind { - def maxType(other: TypeKind): TypeKind = other match { - case UNIT => UNIT; - case _ => abort("Uncomparbale type kinds: UNIT with " + other); - } - } - - /** A boolean value */ - case object BOOL extends TypeKind { - override def maxType(other: TypeKind): TypeKind = other match { - case BOOL => BOOL; - case _ => abort("Uncomparbale type kinds: BOOL with " + other); - } - } - - /** A 1-byte signed integer */ - case object BYTE extends TypeKind { - override def maxType(other: TypeKind): TypeKind = - other match { - case INT => INT; - case BYTE | SHORT | INT | LONG | FLOAT | DOUBLE => other; - case _ => abort("Uncomparbale type kinds: BYTE with " + other); - } - } - - /** A 2-byte signed integer */ - case object SHORT extends TypeKind { - override def maxType(other: TypeKind): TypeKind = - other match { - case BYTE | SHORT | CHAR => SHORT; - case INT | LONG | FLOAT | DOUBLE => other; - case _ => abort("Uncomparbale type kinds: SHORT with " + other); - } - } - - /** A 2-byte signed integer */ - case object CHAR extends TypeKind { - override def maxType(other: TypeKind): TypeKind = - other match { - case BYTE | SHORT | CHAR => CHAR; - case INT | LONG | FLOAT | DOUBLE => other; - case _ => abort("Uncomparbale type kinds: CHAR with " + other); - } - } - - - /** A 4-byte signed integer */ - case object INT extends TypeKind { - override def maxType(other: TypeKind): TypeKind = - other match { - case BYTE | SHORT | CHAR | INT => INT; - case LONG | FLOAT | DOUBLE => other; - case _ => abort("Uncomparbale type kinds: INT with " + other); - } - } - - /** An 8-byte signed integer */ - case object LONG extends TypeKind { - override def maxType(other: TypeKind): TypeKind = - other match { - case BYTE | SHORT | CHAR | INT | LONG => LONG; - case FLOAT | DOUBLE => DOUBLE; - case _ => abort("Uncomparbale type kinds: LONG with " + other); - } - } - - /** A 4-byte floating point number */ - case object FLOAT extends TypeKind { - override def maxType(other: TypeKind): TypeKind = other match { - case BYTE | SHORT | CHAR | INT | FLOAT => FLOAT; - case DOUBLE => DOUBLE; - case _ => abort("Uncomparbale type kinds: FLOAT with " + other); - } - } - - /** An 8-byte floating point number */ - case object DOUBLE extends TypeKind { - override def maxType(other: TypeKind): TypeKind = - if (other.isNumericType) - DOUBLE; - else - abort("Uncomparbale type kinds: DOUBLE with " + other); - } - - /** A string reference */ - // case object STRING extends TypeKind { - // override def maxType(other: TypeKind): TypeKind = other match { - // case STRING => STRING; - // case _ => - // abort("Uncomparbale type kinds: STRING with " + other); - // } - // } - - /** A class type. */ - case class REFERENCE(cls: Symbol) extends TypeKind { - assert(cls != null, - "REFERENCE to null class symbol."); - assert(cls != definitions.ArrayClass, - "REFERENCE to Array is not allowed, should be ARRAY[..] instead"); - - override def toString(): String = - "REFERENCE(" + cls.fullNameString + ")"; - - /** - * Approximate `lub'. The common type of two references is - * always AnyRef. For 'real' least upper bound wrt to subclassing - * use method 'lub'. - */ - override def maxType(other: TypeKind): TypeKind = - other match { - case REFERENCE(_) => REFERENCE(definitions.AnyRefClass); - case _ => - abort("Uncomparbale type kinds: REFERENCE with " + other); - } - - /** Checks subtyping relationship. */ - override def <:<(other: TypeKind): Boolean = - if (cls == definitions.AllClass) - true - else other match { - case REFERENCE(cls2) => - cls.tpe <:< cls2.tpe; - case ARRAY(_) => - cls == definitions.AllRefClass; - case _ => false; - } - - override def isReferenceType: Boolean = true; - - override def equals(other: Any): Boolean = other match { - case REFERENCE(cls2) => cls == cls2; - case _ => false; - } - } - - - case class ARRAY(val elem: TypeKind) extends TypeKind { - override def toString(): String = - "ARRAY[" + elem + "]"; - - override def isArrayType = true; - - /** - * Approximate `lub'. The common type of two references is - * always AnyRef. For 'real' least upper bound wrt to subclassing - * use method 'lub'. - */ - override def maxType(other: TypeKind): TypeKind = - other match { - case REFERENCE(_) => REFERENCE(definitions.AnyRefClass); - case ARRAY(elem2) => ARRAY(elem maxType elem2); - case _ => - abort("Uncomparbale type kinds: ARRAY with " + other); - } - - /** Checks subtyping relationship. */ - override def <:<(other: TypeKind): Boolean = - other match { - case ARRAY(elem2) => - elem <:< elem2; - case REFERENCE(sym) => - (sym == definitions.AnyRefClass || - sym == definitions.ObjectClass) // TODO: platform dependent! - - case _ => false; - } - - override def equals(other: Any): Boolean = other match { - case ARRAY(elem2) => elem == elem2; - case _ => false; - } - - } - - ////////////////// Conversions ////////////////////////////// - - - /** Return the TypeKind of the given type */ - def toTypeKind(t: Type): TypeKind = t match { - case ThisType(sym) => REFERENCE(sym); - - case SingleType(pre, sym) => - primitiveTypeMap get sym match { - case Some(k) => k; - case None => REFERENCE(sym); - } - - case ConstantType(value) => - toTypeKind(value.tpe); - - case TypeRef(_, sym, args) => - primitiveTypeMap get sym match { - case Some(k) => k; - case None => - if (sym == definitions.ArrayClass) - ARRAY(toTypeKind(args.head)) - else - REFERENCE(sym); - } - - case ClassInfoType(_, _, sym) => - primitiveTypeMap get sym match { - case Some(k) => k; - case None => - if (sym == definitions.ArrayClass) - abort("ClassInfoType to ArrayClass!"); - else - REFERENCE(sym); - } - - case _ => abort("Unknown type: " + t); - } - - /** A map from scala primitive Types to ICode TypeKinds */ - private var primitiveTypeMap: Map[Symbol, TypeKind] = null; - - /** Initialize the map from scala primitive types to ICode types */ - def initPrimitiveTypeMap = { - log("Initializing primitive map"); - primitiveTypeMap = new HashMap(); - primitiveTypeMap += definitions.UnitClass -> UNIT; - primitiveTypeMap += definitions.BooleanClass -> BOOL; - primitiveTypeMap += definitions.ByteClass -> BYTE; - primitiveTypeMap += definitions.ShortClass -> SHORT; - primitiveTypeMap += definitions.CharClass -> CHAR; - primitiveTypeMap += definitions.IntClass -> INT; - primitiveTypeMap += definitions.LongClass -> LONG; - primitiveTypeMap += definitions.FloatClass -> FLOAT; - primitiveTypeMap += definitions.DoubleClass -> DOUBLE; -// primitiveTypeMap += definitions.StringClass -> STRING; - } - -} diff --git a/sources/scala/tools/nsc/backend/icode/TypeStacks.scala b/sources/scala/tools/nsc/backend/icode/TypeStacks.scala deleted file mode 100644 index 1f0f8b887c..0000000000 --- a/sources/scala/tools/nsc/backend/icode/TypeStacks.scala +++ /dev/null @@ -1,96 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.icode; - -import scala.tools.nsc.backend.icode.Primitives; - -trait TypeStacks: ICodes { - import opcodes._; - import global.{Symbol, Type, definitions}; - - /* This class simulates the type of the opperand - * stack of the ICode. - */ - type Rep = List[TypeKind]; - - class TypeStack { - var types: Rep = Nil; - - def this(stack: Rep) = { - this(); - this.types = stack; - } - - def this(that: TypeStack) = { - this(that.types); - } - - def length: Int = types.length; - - /** Push a type on the type stack. UNITs are ignored. */ - def push(t: TypeKind) = - if (t != UNIT) - types = t :: types; - - /** Removes the value on top of the stack, and returns it. It assumes - * the stack contains at least one element. - */ - def pop: TypeKind = { - val t = types.head; - types = types.tail; - t - } - - /** Return the topmost two values on the stack. It assumes the stack - * is large enough. Topmost element first. - */ - def pop2: Pair[TypeKind, TypeKind] = Pair(pop, pop); - - /** Return the topmost three values on the stack. It assumes the stack - * is large enough. Topmost element first. - */ - def pop3: Triple[TypeKind, TypeKind, TypeKind] = Triple(pop, pop, pop); - - /** - * A TypeStack aggress with another one if they have the same - * length and each type kind agrees position-wise. Two - * types agree if they are subtypes of one another. - */ - def agreesWith(other: TypeStack): Boolean = ( - (types.length == other.types.length) && - List.forall2(types, other.types) ((t1, t2) => t1 <:< t2 || t2 <:< t1) - ); - - def mergeWith(that: TypeStack): TypeStack = { - def merge(a: TypeStack, b: TypeStack): TypeStack = { - val lst = List.map2(a.types, b.types) ((k1, k2) => k1 match { - case REFERENCE(cls1) => - val REFERENCE(cls2) = k2; - lub(k1,k2); - case _ => k1; - }); - new TypeStack(lst) - } - - assert(this agreesWith that, - "Incompatible type stacks: " + this + ", " + that); - merge(this, that) - } - - /* This method returns a String representation of the stack */ - override def toString() = { - (types.foldLeft(new StringBuffer("")) ((buf, k) => buf.append(" ").append(k))).toString(); - } - - override def equals(other: Any): Boolean = ( - other.isInstanceOf[TypeStack] && - List.forall2(other.asInstanceOf[TypeStack].types, types)((a, b) => a == b) - ); - } - -} diff --git a/sources/scala/tools/nsc/backend/jvm/GenJVM.scala b/sources/scala/tools/nsc/backend/jvm/GenJVM.scala deleted file mode 100644 index 50a86fdf27..0000000000 --- a/sources/scala/tools/nsc/backend/jvm/GenJVM.scala +++ /dev/null @@ -1,1054 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.backend.jvm; - -import java.io.File; - -import scala.collection.mutable.{Map, HashMap}; -import scala.tools.nsc.symtab._; -import scala.tools.nsc.util.Position; - -import ch.epfl.lamp.fjbg._; - -/** - */ -abstract class GenJVM extends SubComponent { - import global._; - import icodes._; - import icodes.opcodes._; - - val phaseName = "jvm"; - - /** Create a new phase */ - override def newPhase(p: Phase) = new JvmPhase(p); - - /** JVM code generation phase - */ - class JvmPhase(prev: Phase) extends GlobalPhase(prev) { - def name = phaseName; - override def newFlags = phaseNewFlags; - - override def erasedTypes = true; - val codeGenerator = new BytecodeGenerator; - - override def run: Unit = - classes foreach codeGenerator.genClass; - - override def apply(unit: CompilationUnit): Unit = - abort("JVM works on icode classes, not on compilation units!"); - } - - /** - * Java bytecode generator. - * - */ - class BytecodeGenerator { - val MIN_SWITCH_DENSITY = 0.7; - val MODULE_INSTANCE_NAME = "MODULE$"; - val JAVA_LANG_STRINGBUFFER = "java.lang.StringBuffer"; - val JAVA_RMI_REMOTEEXCEPTION = "java.rmi.RemoteException"; - - val stringBufferType = new JObjectType(JAVA_LANG_STRINGBUFFER); - val toStringType = new JMethodType(JObjectType.JAVA_LANG_STRING, JType.EMPTY_ARRAY); - - // Scala attributes - val SerializableAttr = definitions.SerializableAttr; - val SerialVersionUID = definitions.getClass("scala.SerialVersionUID").tpe; - val CloneableAttr = definitions.getClass("scala.cloneable").tpe; - val TransientAtt = definitions.getClass("scala.transient").tpe; - val VolatileAttr = definitions.getClass("scala.volatile").tpe; - val RemoteAttr = definitions.getClass("scala.remote").tpe; - - val CloneableClass = definitions.getClass("java.lang.Cloneable"); - val RemoteInterface = definitions.getClass("java.rmi.Remote"); - - var clasz: IClass = _; - var method: IMethod = _; - var code: Code = _; - var jclass: JClass = _; - var jmethod: JMethod = _; - var jcode: JExtendedCode = _; - - val fjbgContext = new FJBGContext(); - - def emitClass(jclass: JClass, sym: Symbol): Unit = { - def addScalaAttr(sym: Symbol): Unit = currentRun.symData.get(sym) match { - case Some(pickle) => - val scalaAttr = fjbgContext.JOtherAttribute(jclass, - jclass, - nme.ScalaSignatureATTR.toString(), - pickle.bytes, - pickle.writeIndex); - jclass.addAttribute(scalaAttr); - currentRun.symData -= sym; - currentRun.symData -= sym.linkedSym; - //System.out.println("Generated ScalaSig Attr for " + sym);//debug - case _ => - log("Could not find pickle information for " + sym); - } - if (!jclass.getName().endsWith("$")) - addScalaAttr(if (isTopLevelModule(sym)) sym.sourceModule else sym); - val outfile = getFile(jclass, ".class"); - jclass.writeTo(outfile); - val file = scala.tools.util.AbstractFile.getFile(outfile); - informProgress("wrote " + outfile + " " + (if (file != null) "" + file.getFile() + " " + file.getFile().exists() else "no file")); - } - - var serialVUID: Option[Long] = None; - var remoteClass: Boolean = false; - - def genClass(c: IClass): Unit = { - if (settings.debug.value) - log("Generating class " + c.symbol + " flags: " + Flags.flagsToString(c.symbol.flags)); - clasz = c; - var parents = c.symbol.info.parents; - var ifaces = JClass.NO_INTERFACES; - val name = javaName(c.symbol); - serialVUID = None; - remoteClass = false; - - if (parents.isEmpty) - parents = definitions.ObjectClass.tpe :: parents; - - c.symbol.attributes foreach { a => a match { - case Pair(SerializableAttr, _) => - parents = parents ::: List(definitions.SerializableClass.tpe); - case Pair(CloneableAttr, _) => - parents = parents ::: List(CloneableClass.tpe); - case Pair(SerialVersionUID, value :: _) => - serialVUID = Some(value.longValue); - case Pair(RemoteAttr, _) => - parents = parents ::: List(RemoteInterface.tpe); - remoteClass = true; - case _ => (); - } - } - parents = parents.removeDuplicates; - - if (parents.length > 1 ) { - ifaces = new Array[String](parents.length - 1); - parents.drop(1).map((s) => javaName(s.symbol)).copyToArray(ifaces, 0); - () - } - - jclass = fjbgContext.JClass(javaFlags(c.symbol), - name, - javaName(parents(0).symbol), - ifaces, - c.cunit.source.toString()); - - if (isTopLevelModule(c.symbol) || serialVUID != None) { - if (isTopLevelModule(c.symbol)) - addModuleInstanceField; - addStaticInit(jclass); - - if (c.symbol.linkedClass != NoSymbol) - log("No mirror class for module with linked class: " + c.symbol.fullNameString); - else - dumpMirrorClass; - } - - clasz.fields foreach genField; - clasz.methods foreach genMethod; - - emitClass(jclass, c.symbol) - } - - def isTopLevelModule(sym: Symbol): Boolean = { - sym.isModuleClass && !sym.isImplClass && !sym.hasFlag(Flags.LIFTED) /* && !atPhase(currentRun.erasurePhase)(sym.isNestedClass) */ - } - - def genField(f: IField): Unit = { - if (settings.debug.value) - log("Adding field: " + f.symbol.fullNameString); - var attributes = 0; - - f.symbol.attributes foreach { a => a match { - case Pair(TransientAtt, _) => attributes = attributes | JAccessFlags.ACC_TRANSIENT; - case Pair(VolatileAttr, _) => attributes = attributes | JAccessFlags.ACC_VOLATILE; - case _ => (); - }} - jclass.addNewField(javaFlags(f.symbol) | attributes, - javaName(f.symbol), - javaType(toTypeKind(f.symbol.tpe))); - } - - def genMethod(m: IMethod): Unit = { - if (settings.debug.value) - log("Generating method " + m.symbol + " flags: " + Flags.flagsToString(m.symbol.flags) + - " owner: " + m.symbol.owner); - method = m; - endPC.clear; - computeLocalVarsIndex(m); - - var resTpe = javaType(toTypeKind(m.symbol.tpe.resultType)); - if (m.symbol.isClassConstructor) - resTpe = JType.VOID; - - var flags = javaFlags(m.symbol); - if (jclass.isInterface()) - flags = flags | JAccessFlags.ACC_ABSTRACT; - - jmethod = jclass.addNewMethod(flags, - javaName(m.symbol), - resTpe, - javaTypes(m.params map (.kind)), - javaNames(m.params map (.sym))); - - if (m.symbol.hasFlag(Flags.BRIDGE)) - jmethod.addAttribute(fjbgContext.JOtherAttribute(jclass, jmethod, "Bridge", - new Array[Byte](0))); - if (remoteClass || (m.symbol.attributes contains Pair(RemoteAttr, Nil))) - if (jmethod.isPublic()) { - // (see http://java.sun.com/docs/books/vmspec/html/ClassFile.doc.html#3129) - // Exceptions_attribute { - // .. - // u2 number_of_exceptions; - // u2 exception_index_table[number_of_exceptions]; - // } - val cp = jclass.getConstantPool(); - val reInx = cp.addClass(JAVA_RMI_REMOTEEXCEPTION); - val contents = java.nio.ByteBuffer.allocate(4); // u2 + u2[1] - contents.putShort(1.asInstanceOf[Short]); - contents.putShort(reInx.asInstanceOf[Short]); - if (settings.debug.value) - log("adding 'Exceptions_attribute' " + contents + " for remote method " + method); - jmethod.addAttribute( - fjbgContext.JOtherAttribute(jclass, jmethod, "Exceptions", contents.array())); - } - - if (!jmethod.isAbstract()) { - for (val local <- m.locals; (! m.params.contains(local))) { - if (settings.debug.value) - log("add local var: " + local); - jmethod.addNewLocalVariable(javaType(local.kind), javaName(local.sym)); - } - - jcode = jmethod.getCode().asInstanceOf[JExtendedCode]; - genCode(m); - genLocalVariableTable; - } - } - - def addModuleInstanceField: Unit = { - import JAccessFlags._; - jclass.addNewField(ACC_PUBLIC | ACC_FINAL | ACC_STATIC, - MODULE_INSTANCE_NAME, - jclass.getType()); - } - - def addStaticInit(cls: JClass): Unit = { - import JAccessFlags._; - val clinitMethod = cls.addNewMethod(ACC_PUBLIC | ACC_STATIC, - "", - JType.VOID, - JType.EMPTY_ARRAY, - new Array[String](0)); - val clinit = clinitMethod.getCode().asInstanceOf[JExtendedCode]; - if (isTopLevelModule(clasz.symbol)) { - clinit.emitNEW(cls.getName()); - clinit.emitDUP(); - clinit.emitINVOKESPECIAL(cls.getName(), - JMethod.INSTANCE_CONSTRUCTOR_NAME, - JMethodType.ARGLESS_VOID_FUNCTION); - } - - serialVUID match { - case Some(value) => - val fieldName = "serialVersionUID"; - jclass.addNewField(JAccessFlags.ACC_STATIC | JAccessFlags.ACC_PUBLIC, - fieldName, - JType.LONG); - clinit.emitPUSH(value); - clinit.emitPUTSTATIC(jclass.getName(), fieldName, JType.LONG); - case None => (); - } - - clinit.emitRETURN(); - } - - def dumpMirrorClass: Unit = { - import JAccessFlags._; - assert(clasz.symbol.isModuleClass); - if (settings.debug.value) - log("Dumping mirror class for object: " + clasz); - val moduleName = javaName(clasz.symbol); // + "$"; - val mirrorName = moduleName.substring(0, moduleName.length() - 1); - val mirrorClass = fjbgContext.JClass(ACC_SUPER | ACC_PUBLIC | ACC_FINAL, - mirrorName, - "java.lang.Object", - JClass.NO_INTERFACES, - clasz.cunit.source.toString()); - for (val m <- clasz.methods; !(m.symbol.hasFlag(Flags.PRIVATE)) && !m.symbol.isClassConstructor && !isStaticSymbol(m.symbol) ) { - val mirrorMethod = mirrorClass.addNewMethod(ACC_PUBLIC | ACC_FINAL | ACC_STATIC, - javaName(m.symbol), - javaType(toTypeKind(m.symbol.tpe.resultType)), - javaTypes(m.params map (.kind)), - javaNames(m.params map (.sym))); - val mirrorCode = mirrorMethod.getCode().asInstanceOf[JExtendedCode]; - mirrorCode.emitGETSTATIC(moduleName, - MODULE_INSTANCE_NAME, - new JObjectType(moduleName)); - var i = 0; - var index = 0; - var argTypes = mirrorMethod.getArgumentTypes(); - while (i < argTypes.length) { - mirrorCode.emitLOAD(index, argTypes(i)); - index = index + argTypes(i).getSize(); - i = i + 1; - } - - mirrorCode.emitINVOKEVIRTUAL(moduleName, mirrorMethod.getName(), mirrorMethod.getType().asInstanceOf[JMethodType]); - mirrorCode.emitRETURN(mirrorMethod.getReturnType()); - } - emitClass(mirrorClass, clasz.symbol); - } - - - val linearizer = new NormalLinearizer(); - var linearization: List[BasicBlock] = Nil; - - var isModuleInitialized = false; - def genCode(m: IMethod): Unit = { - labels.clear; - isModuleInitialized = false; - - code = m.code; - linearization = linearizer.linearize(m); - makeLabels(linearization); - genBlocks(linearization); - - if (this.method.exh != Nil) - genExceptionHandlers; - } - - var nextBlock: BasicBlock = _; - - def genBlocks(l: List[BasicBlock]): Unit = l match { - case Nil => (); - case x :: Nil => nextBlock = null; genBlock(x); - case x :: y :: ys => nextBlock = y; genBlock(x); genBlocks(y :: ys); - } - - - /** Generate exception handlers for the current method. */ - def genExceptionHandlers: Unit = { - - def ranges(e: ExceptionHandler): List[Pair[Int, Int]] = { - var covered = e.covered; - var ranges: List[Pair[Int, Int]] = Nil; - var start = -1; - var end = -1; - - linearization foreach ((b) => { - if (! (covered contains b) ) { - if (start >= 0) { // we're inside a handler range - end = labels(b).getAnchor(); - ranges = Pair(start, end) :: ranges; - start = -1; - } - } else { - if (start >= 0) { // we're inside a handler range - end = endPC(b); - } else { - start = labels(b).getAnchor(); - end = endPC(b); - } - covered = covered remove b.==; - } - }); - - if (start >= 0) { - ranges = Pair(start, end) :: ranges; - } - - if (covered != Nil) - if (settings.debug.value) - log("Some covered blocks were not found in method: " + method + - " covered: " + covered + " not in " + linearization); - ranges - } - - this.method.exh foreach ((e) => { - ranges(e).sort({ (p1, p2) => p1._1 < p2._1 }) - .foreach ((p) => { - if (settings.debug.value) - log("Adding exception handler " + e + "at block: " + e.startBlock + " for " + method + - " from: " + p._1 + " to: " + p._2 + " catching: " + e.cls); - jcode.addExceptionHandler(p._1, p._2, - labels(e.startBlock).getAnchor(), - if (e.cls == NoSymbol) - null - else javaName(e.cls)) - }) - }); - } - - def genBlock(b: BasicBlock): Unit = { - labels(b).anchorToNext(); - - if (settings.debug.value) - log("Generating code for block: " + b + " at pc: " + labels(b).getAnchor()); - var lastMappedPC = 0; - var lastLineNr =0; - var crtPC = 0; - - b traverse ( instr => { - if (b.lastInstruction == instr) - endPC(b) = jcode.getPC(); - - instr match { - case THIS(clasz) => - jcode.emitALOAD_0(); - - case CONSTANT(const) => - const.tag match { - case UnitTag => (); - case BooleanTag => jcode.emitPUSH(const.booleanValue); - case ByteTag => jcode.emitPUSH(const.byteValue); - case ShortTag => jcode.emitPUSH(const.shortValue); - case CharTag => jcode.emitPUSH(const.charValue); - case IntTag => jcode.emitPUSH(const.intValue); - case LongTag => jcode.emitPUSH(const.longValue); - case FloatTag => jcode.emitPUSH(const.floatValue); - case DoubleTag => jcode.emitPUSH(const.doubleValue); - case StringTag => jcode.emitPUSH(const.stringValue); - case NullTag => jcode.emitACONST_NULL(); - case _ => abort("Unknown constant value: " + const); - } - - case LOAD_ARRAY_ITEM(kind) => - jcode.emitALOAD(javaType(kind)); - - case LOAD_LOCAL(local, isArg) => - if (isArg) - jcode.emitLOAD(indexOf(local), javaType(local.kind)); - else - jcode.emitLOAD(indexOf(local), javaType(local.kind)); - - case LOAD_FIELD(field, isStatic) => - var owner = javaName(field.owner); -// if (field.owner.hasFlag(Flags.MODULE)) owner = owner + "$"; - if (settings.debug.value) - log("LOAD_FIELD with owner: " + owner + " flags: " + Flags.flagsToString(field.owner.flags)); - if (isStatic) - jcode.emitGETSTATIC(owner, - javaName(field), - javaType(field)); - else - jcode.emitGETFIELD(owner, - javaName(field), - javaType(field)); - - case LOAD_MODULE(module) => - assert(module.isModule || module.isModuleClass, "Expected module: " + module); - if (settings.debug.value) - log("genearting LOAD_MODULE for: " + module + " flags: " + - Flags.flagsToString(module.flags)); - jcode.emitGETSTATIC(javaName(module) /* + "$" */ , - MODULE_INSTANCE_NAME, - javaType(module)); - - case STORE_ARRAY_ITEM(kind) => - jcode.emitASTORE(javaType(kind)); - - case STORE_LOCAL(local, isArg) => - if (isArg) - jcode.emitSTORE(indexOf(local), javaType(local.kind)); - else - jcode.emitSTORE(indexOf(local), javaType(local.kind)); - - case STORE_FIELD(field, isStatic) => - val owner = javaName(field.owner); // + (if (field.owner.hasFlag(Flags.MODULE)) "$" else ""); - if (isStatic) - jcode.emitPUTSTATIC(owner, - javaName(field), - javaType(field)); - else - jcode.emitPUTFIELD(owner, - javaName(field), - javaType(field)); - - case CALL_PRIMITIVE(primitive) => - genPrimitive(primitive, instr.pos); - - // TODO: reference the type of the receiver instead of the - // method owner. - case CALL_METHOD(method, style) => - val owner = javaName(method.owner); // + (if (method.owner.isModuleClass) "$" else ""); - - style match { - case Dynamic => - if (method.owner.hasFlag(Flags.INTERFACE)) - jcode.emitINVOKEINTERFACE(owner, - javaName(method), - javaType(method).asInstanceOf[JMethodType]) - else - jcode.emitINVOKEVIRTUAL(owner, - javaName(method), - javaType(method).asInstanceOf[JMethodType]); - - case Static(instance) => - if (instance) { - jcode.emitINVOKESPECIAL(owner, - javaName(method), - javaType(method).asInstanceOf[JMethodType]); - } else - jcode.emitINVOKESTATIC(owner, - javaName(method), - javaType(method).asInstanceOf[JMethodType]); - - case SuperCall(_) => - jcode.emitINVOKESPECIAL(owner, - javaName(method), - javaType(method).asInstanceOf[JMethodType]); - // we initialize the MODULE$ field immediately after the super ctor - if (isTopLevelModule(clasz.symbol) && !isModuleInitialized && - jmethod.getName() == JMethod.INSTANCE_CONSTRUCTOR_NAME && - javaName(method) == JMethod.INSTANCE_CONSTRUCTOR_NAME) { - isModuleInitialized = true; - jcode.emitALOAD_0(); - jcode.emitPUTSTATIC(jclass.getName(), - MODULE_INSTANCE_NAME, - jclass.getType()); - } - - - } - - case NEW(REFERENCE(cls)) => - val className = javaName(cls); - jcode.emitNEW(className); - - case CREATE_ARRAY(elem) => elem match { - case REFERENCE(_) | ARRAY(_) => - jcode.emitANEWARRAY(javaType(elem).asInstanceOf[JReferenceType]); - case _ => - jcode.emitNEWARRAY(javaType(elem)); - } - - case IS_INSTANCE(tpe) => - tpe match { - case REFERENCE(cls) => jcode.emitINSTANCEOF(new JObjectType(javaName(cls))); - case ARRAY(elem) => jcode.emitINSTANCEOF(new JArrayType(javaType(elem))); - case _ => abort("Unknown reference type in IS_INSTANCE: " + tpe); - } - - case CHECK_CAST(tpe) => - tpe match { - case REFERENCE(cls) => jcode.emitCHECKCAST(new JObjectType(javaName(cls))); - case ARRAY(elem) => jcode.emitCHECKCAST(new JArrayType(javaType(elem))); - case _ => abort("Unknown reference type in IS_INSTANCE: " + tpe); - } - - case SWITCH(tags, branches) => - val tagArray = new Array[Array[Int]](tags.length); - var caze = tags; - var i = 0; - while (i < tagArray.length) { - tagArray(i) = new Array[Int](caze.head.length); - caze.head.copyToArray(tagArray(i), 0); - i = i + 1; - caze = caze.tail; - } - val branchArray = new Array[JCode$Label](tagArray.length); - if (settings.debug.value) - log("Emitting SWITHCH:\ntags: " + tags + "\nbranches: " + branches); - jcode.emitSWITCH(tagArray, - (branches map labels dropRight 1).copyToArray(branchArray, 0), - labels(branches.last), - MIN_SWITCH_DENSITY); - - case JUMP(where) => - if (nextBlock != where) - jcode.emitGOTO_maybe_W(labels(where), false); // default to short jumps - - case CJUMP(success, failure, cond, kind) => - kind match { - case BOOL | BYTE | CHAR | SHORT | INT => - if (nextBlock == success) { - jcode.emitIF_ICMP(conds(negate(cond)), labels(failure)); - // .. and fall through to success label - } else { - jcode.emitIF_ICMP(conds(cond), labels(success)); - if (nextBlock != failure) - jcode.emitGOTO_maybe_W(labels(failure), false); - } - - case REFERENCE(_) | ARRAY(_) => - if (nextBlock == success) { - jcode.emitIF_ACMP(conds(negate(cond)), labels(failure)); - // .. and fall through to success label - } else { - jcode.emitIF_ACMP(conds(cond), labels(success)); - if (nextBlock != failure) - jcode.emitGOTO_maybe_W(labels(failure), false); - } - - case _ => - kind match { - case LONG => jcode.emitLCMP(); - case FLOAT => jcode.emitFCMPG(); - case DOUBLE => jcode.emitDCMPG(); - } - if (nextBlock == success) { - jcode.emitIF(conds(negate(cond)), labels(failure)); - // .. and fall through to success label - } else { - jcode.emitIF(conds(cond), labels(success)); - if (nextBlock != failure) - jcode.emitGOTO_maybe_W(labels(failure), false); - } - } - - case CZJUMP(success, failure, cond, kind) => - kind match { - case BOOL | BYTE | CHAR | SHORT | INT => - if (nextBlock == success) { - jcode.emitIF(conds(negate(cond)), labels(failure)); - } else { - jcode.emitIF(conds(cond), labels(success)); - if (nextBlock != failure) - jcode.emitGOTO_maybe_W(labels(failure), false); - } - - case REFERENCE(_) | ARRAY(_) => - if (nextBlock == success) { - jcode.emitIFNONNULL(labels(failure)); - } else { - jcode.emitIFNULL(labels(success)); - if (nextBlock != failure) - jcode.emitGOTO_maybe_W(labels(failure), false); - } - - case _ => - kind match { - case LONG => jcode.emitLCONST_0(); jcode.emitLCMP(); - case FLOAT => jcode.emitFCONST_0(); jcode.emitFCMPL(); - case DOUBLE => jcode.emitDCONST_0(); jcode.emitDCMPL(); - } - if (nextBlock == success) { - jcode.emitIF(conds(negate(cond)), labels(failure)); - } else { - jcode.emitIF(conds(cond), labels(success)); - if (nextBlock != failure) - jcode.emitGOTO_maybe_W(labels(failure), false); - } - } - - case RETURN(kind) => - jcode.emitRETURN(javaType(kind)); - - case THROW() => - jcode.emitATHROW(); - - case DROP(kind) => - kind match { - case LONG | DOUBLE => jcode.emitPOP2(); - case _ => jcode.emitPOP(); - } - - case DUP(kind) => - kind match { - case LONG | DOUBLE => jcode.emitDUP2(); - case _ => jcode.emitDUP(); - } - - - case MONITOR_ENTER() => - jcode.emitMONITORENTER(); - - case MONITOR_EXIT() => - jcode.emitMONITOREXIT(); - } - - crtPC = jcode.getPC(); - val crtLine = try { clasz.cunit.position(instr.pos).line; } catch { - case _: Error => lastLineNr; - } - //System.err.println("CRTLINE: " + instr.pos + " " + - // /* (if (instr.pos < clasz.cunit.source.content.length) clasz.cunit.source.content(instr.pos) else '*') + */ " " + crtLine); - - if (crtPC > lastMappedPC) { - jcode.completeLineNumber(lastMappedPC, crtPC, crtLine); - lastMappedPC = crtPC; - lastLineNr = crtLine; - } - - }); - } - - - def genPrimitive(primitive: Primitive, pos: Int): Unit = { - primitive match { - case Negation(kind) => - kind match { - case BOOL | BYTE | CHAR | SHORT | INT => - jcode.emitINEG(); - - case LONG => jcode.emitLNEG(); - case FLOAT => jcode.emitFNEG(); - case DOUBLE => jcode.emitDNEG(); - case _ => abort("Impossible to negate a " + kind); - } - - case Arithmetic(op, kind) => - op match { - case ADD => jcode.emitADD(javaType(kind)); - case SUB => - kind match { - case BOOL | BYTE | CHAR | SHORT | INT => - jcode.emitISUB(); - case LONG => jcode.emitLSUB(); - case FLOAT => jcode.emitFSUB(); - case DOUBLE => jcode.emitDSUB(); - } - - case MUL => - kind match { - case BOOL | BYTE | CHAR | SHORT | INT => - jcode.emitIMUL(); - case LONG => jcode.emitLMUL(); - case FLOAT => jcode.emitFMUL(); - case DOUBLE => jcode.emitDMUL(); - } - - case DIV => - kind match { - case BOOL | BYTE | CHAR | SHORT | INT => - jcode.emitIDIV(); - case LONG => jcode.emitLDIV(); - case FLOAT => jcode.emitFDIV(); - case DOUBLE => jcode.emitDDIV(); - } - - case REM => - kind match { - case BOOL | BYTE | CHAR | SHORT | INT => - jcode.emitIREM(); - case LONG => jcode.emitLREM(); - case FLOAT => jcode.emitFREM(); - case DOUBLE => jcode.emitDREM(); - } - - case NOT => - kind match { - case BOOL | BYTE | CHAR | SHORT | INT => - jcode.emitPUSH(-1); - jcode.emitIXOR();; - case LONG => - jcode.emitPUSH(-1l); - jcode.emitLXOR();; - case _ => abort("Impossible to negate an " + kind); - } - - case _ => abort("Unknown arithmetic primitive " + primitive ); - } - - case Logical(op, kind) => Pair(op, kind) match { - case Pair(AND, LONG) => - jcode.emitLAND(); - case Pair(AND, INT) => - jcode.emitIAND(); - case Pair(AND, _) => - jcode.emitIAND(); - if (kind != BOOL) - jcode.emitT2T(javaType(INT), javaType(kind)); - - case Pair(OR, LONG) => - jcode.emitLOR(); - case Pair(OR, INT) => - jcode.emitIOR(); - case Pair(OR, _) => - jcode.emitIOR(); - if (kind != BOOL) - jcode.emitT2T(javaType(INT), javaType(kind)); - - case Pair(XOR, LONG) => - jcode.emitLXOR(); - case Pair(XOR, INT) => - jcode.emitIXOR(); - case Pair(XOR, _) => - jcode.emitIXOR(); - if (kind != BOOL) - jcode.emitT2T(javaType(INT), javaType(kind)); - } - - case Shift(op, kind) => Pair(op, kind) match { - case Pair(LSL, LONG) => - jcode.emitLSHL(); - case Pair(LSL, INT) => - jcode.emitISHL(); - case Pair(LSL, _) => - jcode.emitISHL(); - jcode.emitT2T(javaType(INT), javaType(kind)); - - case Pair(ASR, LONG) => - jcode.emitLSHR(); - case Pair(ASR, INT) => - jcode.emitISHR(); - case Pair(ASR, _) => - jcode.emitISHR(); - jcode.emitT2T(javaType(INT), javaType(kind)); - - case Pair(LSR, LONG) => - jcode.emitLUSHR(); - case Pair(LSR, INT) => - jcode.emitIUSHR(); - case Pair(LSR, _) => - jcode.emitIUSHR(); - jcode.emitT2T(javaType(INT), javaType(kind)); - } - - case Conversion(src, dst) => - if (settings.debug.value) - log("Converting from: " + src + " to: " + dst); - if (dst == BOOL) { - Console.println("Illegal conversion at: " + clasz + - " at: " + method.sourceFile + ":" + Position.line(clasz.cunit.source, pos)); - } else - jcode.emitT2T(javaType(src), javaType(dst)); - - case ArrayLength(_) => - jcode.emitARRAYLENGTH(); - - case StartConcat => - jcode.emitNEW(JAVA_LANG_STRINGBUFFER); - jcode.emitDUP(); - jcode.emitINVOKESPECIAL(JAVA_LANG_STRINGBUFFER, - JMethod.INSTANCE_CONSTRUCTOR_NAME, - JMethodType.ARGLESS_VOID_FUNCTION); - - case StringConcat(el) => - val jtype = el match { - case REFERENCE(_) | ARRAY(_)=> JObjectType.JAVA_LANG_OBJECT; - case _ => javaType(el); - } - jcode.emitINVOKEVIRTUAL(JAVA_LANG_STRINGBUFFER, - "append", - new JMethodType(stringBufferType, - Predef.Array(jtype))); - case EndConcat => - jcode.emitINVOKEVIRTUAL(JAVA_LANG_STRINGBUFFER, - "toString", - toStringType); - - case _ => abort("Unimplemented primitive " + primitive); - } - } - - val endPC: HashMap[BasicBlock, Int] = new HashMap(); - val labels: HashMap[BasicBlock, JCode$Label] = new HashMap(); - val conds: HashMap[TestOp, Int] = new HashMap(); - - conds += EQ -> JExtendedCode.COND_EQ; - conds += NE -> JExtendedCode.COND_NE; - conds += LT -> JExtendedCode.COND_LT; - conds += GT -> JExtendedCode.COND_GT; - conds += LE -> JExtendedCode.COND_LE; - conds += GE -> JExtendedCode.COND_GE; - - val negate: HashMap[TestOp, TestOp] = new HashMap(); - - negate += EQ -> NE; - negate += NE -> EQ; - negate += LT -> GE; - negate += GT -> LE; - negate += LE -> GT; - negate += GE -> LT; - - def makeLabels(bs: List[BasicBlock]) = { - //labels.clear; - if (settings.debug.value) - log("Making labels for: " + method); - bs foreach (bb => labels += bb -> jcode.newLabel() ); - } - - - ////////////////////// local vars /////////////////////// - - def sizeOf(sym: Symbol): Int = sizeOf(toTypeKind(sym.tpe)); - - - def sizeOf(k: TypeKind): Int = k match { - case DOUBLE | LONG => 2; - case _ => 1; - } - - def indexOf(m: IMethod, sym: Symbol): Int = { - val Some(local) = m.lookupLocal(sym); - assert (local.index >= 0, - "Invalid index for: " + local); - local.index - } - - def indexOf(local: Local): Int = { - assert (local.index >= 0, - "Invalid index for: " + local); - local.index - } - - /** - * Compute the indexes of each local variable of the given - * method. - */ - def computeLocalVarsIndex(m: IMethod): Unit = { - var idx = 1; - if (isStaticSymbol(m.symbol)) - idx = 0; - - for (val l <- m.locals) { - if (settings.debug.value) - log("Index value for " + l + ": " + idx); - l.index = idx; - idx = idx + sizeOf(l.kind); - } - } - - ////////////////////// Utilities //////////////////////// - - /** Return the a name of this symbol that can be used on the Java - * platform. It removes spaces from names. - * - * Special handling: scala.All and scala.AllRef are 'erased' to - * scala.All$ and scala.AllRef$. This is needed because they are - * not real classes, and they mean 'abrupt termination upon evaluation - * of that expression' or 'null' respectively. This handling is - * done already in GenICode, but here we need to remove references - * from method signatures to these types, because such classes can - * not exist in the classpath: the type checker will be very confused. - */ - def javaName(sym: Symbol): String = { - val suffix = if (sym.hasFlag(Flags.MODULE) && !sym.isMethod && - !sym.isImplClass && - !sym.hasFlag(Flags.JAVA)) "$" else ""; - - if (sym == definitions.AllClass) - return "scala.All$" - else if (sym == definitions.AllRefClass) - return "scala.AllRef$"; - - (if (sym.isClass || (sym.isModule && !sym.isMethod)) - sym.fullNameString('/') - else - sym.simpleName.toString().trim()) + suffix; - } - - def javaNames(syms: List[Symbol]): Array[String] = { - val res = new Array[String](syms.length); - var i = 0; - syms foreach ( s => { res(i) = javaName(s); i = i + 1; } ); - res - } - - /** - * Return the Java modifiers for the given symbol. - * Java modifiers for classes: - * - public, abstract, final, strictfp (not used) - * for interfaces: - * - the same as for classes, without 'final' - * for fields: - * - public, protected, private - * - static, final - * for methods: - * - the same as for fields, plus: - * - abstract, synchronized (not used), strictfp (not used), native (not used) - */ - def javaFlags(sym: Symbol): Int = { - import JAccessFlags._; - - var jf: Int = 0; - val f = sym.flags; - jf = jf | (if (sym hasFlag Flags.PRIVATE) ACC_PRIVATE else ACC_PUBLIC); - jf = jf | (if ((sym hasFlag Flags.ABSTRACT) || - (sym hasFlag Flags.DEFERRED)) ACC_ABSTRACT else 0); - jf = jf | (if (sym hasFlag Flags.INTERFACE) ACC_INTERFACE else 0); - jf = jf | (if ((sym hasFlag Flags.FINAL) && !sym.enclClass.hasFlag(Flags.INTERFACE)) ACC_FINAL else 0); - jf = jf | (if (isStaticSymbol(sym)) ACC_STATIC else 0); - jf - } - - def isStaticSymbol(s: Symbol): Boolean = - s.hasFlag(Flags.STATIC) || s.hasFlag(Flags.STATICMEMBER) || s.owner.isImplClass; - - def javaType(t: TypeKind): JType = t match { - case UNIT => JType.VOID; - - case BOOL => JType.BOOLEAN; - case BYTE => JType.BYTE; - case SHORT => JType.SHORT; - case CHAR => JType.CHAR; - case INT => JType.INT; - case LONG => JType.LONG; - case FLOAT => JType.FLOAT; - case DOUBLE => JType.DOUBLE; - case REFERENCE(cls) => new JObjectType(javaName(cls)); - case ARRAY(elem) => new JArrayType(javaType(elem)); - } - - def javaType(s: Symbol): JType = - if (s.isMethod) - new JMethodType( - if (s.isClassConstructor) - JType.VOID else javaType(toTypeKind(s.tpe.resultType)), - javaTypes(s.tpe.paramTypes map toTypeKind)) - else - javaType(toTypeKind(s.tpe)); - - def javaTypes(ts: List[TypeKind]): Array[JType] = { - val res = new Array[JType](ts.length); - var i = 0; - ts foreach ( t => { res(i) = javaType(t); i = i + 1; } ); - res - } - -// def javaTypes(syms: List[Symbol]): Array[JType] = { -// val res = new Array[JType](syms.length); -// var i = 0; -// syms foreach ( s => { res(i) = javaType(toTypeKind(s.tpe)); i = i + 1; } ); -// res -// } - - def getFile(cls: JClass, suffix: String): String = { - val path = cls.getName().replace('.', File.separatorChar); - settings.outdir.value + File.separatorChar + path + suffix - } - - private def genLocalVariableTable: Unit = { - val vars: Array[JLocalVariable] = jmethod.getLocalVariables(); - - if (!settings.debuginfo.value || vars.length == 0) - return; - - val pool = jclass.getConstantPool(); - val pc = jcode.getPC(); - var anonCounter = 0; - - val lvTab = java.nio.ByteBuffer.allocate(2 + 10 * vars.length); - lvTab.putShort(vars.length.asInstanceOf[Short]); - for (val lv <- vars) { - val name = if (lv.getName() == null) { - anonCounter = anonCounter + 1; - "" - } else lv.getName(); - - lvTab.putShort(0.asInstanceOf[Short]); - lvTab.putShort(pc.asInstanceOf[Short]); - lvTab.putShort(pool.addUtf8(name).asInstanceOf[Short]); - lvTab.putShort(pool.addUtf8(lv.getType().getSignature()).asInstanceOf[Short]); - lvTab.putShort(lv.getIndex().asInstanceOf[Short]); - } - val attr = - fjbgContext.JOtherAttribute(jclass, - jmethod, - "LocalVariableTable", - lvTab.array()); - jcode.addAttribute(attr); - } - } -} diff --git a/sources/scala/tools/nsc/matching/AlgebraicMatchers.scala b/sources/scala/tools/nsc/matching/AlgebraicMatchers.scala deleted file mode 100644 index 4137b128eb..0000000000 --- a/sources/scala/tools/nsc/matching/AlgebraicMatchers.scala +++ /dev/null @@ -1,172 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ - -package scala.tools.nsc.matching; - -/** the pattern matcher, tweaked to work with regular patterns - * @author Burak Emir - */ -trait AlgebraicMatchers : TransMatcher { - - import global._; - - class AlgebraicMatcher extends PatternMatcher { - - import java.util.Vector ; - import java.util.Iterator ; - - var _m: PartialMatcher = _; - - override protected var delegateSequenceMatching = true; - override protected var optimize = false; - - /** constructs an algebraic pattern matcher from cases */ - def construct(m: PartialMatcher, cases: List[CaseDef]): Unit = - construct(m, cases, true); - - /** constructs an algebraic pattern matcher from cases */ - def construct(m: PartialMatcher, cases: List[CaseDef], doBinding: Boolean): Unit = { - this._m = m; - super.initialize( _m.selector, _m.owner, doBinding ); - - val it = cases.elements; - while (it.hasNext) { - val cdef = it.next; - /* - if(cdef != null) - Console.println("algebraic matcher: "+cdef.toString()); // DEBUG - else - scala.Predef.error("got CaseDef null in alg matcher!"); - */ - enter(cdef); - } - - //if (unit.global.log()) { - // unit.global.log("internal pattern matching structure"); - // print(); - // } - _m.tree = toTree(); - } - - - /** initializes this AlgebraicMatcher, see Matcher.initialize - void initialize() {} - */ - /* - def isStarApply(tree: Tree.Apply): Boolean = { - val params:Array[Symbol] = tree.fun.getType().valueParams(); - //System.err.println( tree.fun.type.resultType().symbol() ); - (tree.args.length == 1) - && (tree.getType().symbol().flags & Modifiers.CASE) != 0 - && params.length > 0 - && (params(params.length-1).flags & Modifiers.REPEATED) != 0; - } - */ - //////////// generator methods - - override def toTree(): Tree = { - - this.exit = currentOwner.newLabel(root.pos, "exitA") - .setInfo(new MethodType(List(resultType), resultType)); - - val result = exit.newValueParameter(root.pos, "resultA").setInfo( resultType ); - - Block( - List ( - ValDef(root.symbol, _m.selector) - ), - If( super.toTree(root.and), - LabelDef(exit, List(result), Ident(result)), - ThrowMatchError( _m.pos, resultType )) - ); - } - - protected override def toTree(node: PatternNode, selector: Tree): Tree = { - //System.err.println("AM.toTree called"+node); - if (node == null) - Literal(false); - else node match { - case SeqContainerPat( _, _ ) => - callSequenceMatcher( node, - selector ); - case _ => - super.toTree( node, selector ); - } - } - - /** collects all sequence patterns and returns the default - */ - def collectSeqPats(node1: PatternNode, seqPatNodes: Vector, bodies: Vector): PatternNode = { - var node = node1; - var defaultNode: PatternNode = null; - var exit = false; - do { - if( node == null ) - exit=true; //defaultNode = node; // break - else - node match { - case SeqContainerPat( _, _ ) => - seqPatNodes.add( node ); - bodies.add( super.toTree( node.and ) ); - node = node.or; - exit//defaultNode = node; // break; - - case _ => - defaultNode = node; - } - } while (!exit && (null == defaultNode)) ; - - defaultNode; - } - - def callSequenceMatcher(node: PatternNode, selector1: Tree): Tree = { - - //Console.println("calling sequent matcher for"+node); - /* ???????????????????????? necessary to test whether is a Seq? - gen.If(selector.pos, maybe And( Is(selector, seqpat.type()) )???) - */ - - // translate the _.and subtree of this SeqContainerPat - - val seqPatNodes = new Vector(); - val bodies = new Vector(); - - var defaultNode = collectSeqPats(node, seqPatNodes, bodies); - - val defaultCase = toTree(defaultNode, selector1); - - val wordRec = new SequenceMatcher(); - - val m = new PartialMatcher { - val owner = _m.owner; - val selector = selector1; - } - - var pats: scala.List[Tree] = Nil; - var body: scala.List[Tree] = Nil; - - val tmp = bodies.toArray(); - var j = 0; - val it = seqPatNodes.iterator(); - while (it.hasNext()) { - //pats(j) = it.next().asInstanceOf[SeqContainerPat].seqpat; - pats = it.next().asInstanceOf[SeqContainerPat].seqpat :: pats; - //body(j) = tmp(j).asInstanceOf[Tree]; - body = tmp(j).asInstanceOf[Tree] :: body; - j = j + 1; - } - //Tree defaultTree = toTree(node.or, selector); // cdef.body ; - - wordRec.construct(m, pats.reverse, body.reverse, defaultCase, doBinding); - - //_m.defs.addAll(m.defs); - - m.tree; - } - -} // class AlgebraicMatcher - -} diff --git a/sources/scala/tools/nsc/matching/Autom2.scala b/sources/scala/tools/nsc/matching/Autom2.scala deleted file mode 100644 index b99db700b4..0000000000 --- a/sources/scala/tools/nsc/matching/Autom2.scala +++ /dev/null @@ -1,196 +0,0 @@ -package scala.tools.nsc.matching ; - -//import java.util._ ; - -import scala.tools.nsc.util.Position; - -trait Autom2: TransMatcher { - - import global._; - - /** @param owner owner of the pattern matching expression - */ - abstract class Autom2Scala { - - val dfa: DetWordAutom; - val owner: Symbol; - - protected var optimize = true; - - final val FAIL = -1; - - /** symbol of the matcher DefDef or Label */ - var funSym:Symbol = _; - - /** symbol of the iterator ( scala.SequenceIterator ) */ - var iterSym: Symbol = _; - - /** symbol of the switching result ( scala.Int ) */ - var resultSym: Symbol = _; - - /** symbol of the state variable ( scala.Int ) */ - var stateSym: Symbol = _; - - /** symbol of variable holding current label */ - var curSym: Symbol = _; - - /** symbol of boolean variable that indicates we have not reached end of sequence */ - var hasnSym: Symbol = _; - - val am = new AlgebraicMatcher(); - - var pos: Int = Position.FIRSTPOS; - - val elementType: Type; - - def funRetType(): Type = { - funSym.tpe match { - case MethodType( _, retType )=> retType; - case _ => scala.Predef.error("quoi?"); - } - } - - def callFun(args: List[Tree]): Tree = Apply(Ident(funSym),args); - - // overridden in RightTracerInScala - def loadCurrentElem(body: Tree): Tree = { - Block( - List( - ValDef(this.hasnSym, _hasNext( _iter() ) ), - ValDef(this.curSym, If(Ident( hasnSym ), - _next( _iter() ), - EmptyTree)) - ), - body - ); - } - - /** bug ?? */ - def currentElem() = { Ident( curSym ) } - - def currentMatches(label: Label): Tree = { - label match { - case TreeLabel( pat ) => - _cur_match( pat ); - case SimpleLabel(lit: Literal) => - Equals( currentElem(), lit ); - case _ => // cannot happen - scala.Predef.error("expected either algebraic or simple label:"+label); - } - } - - // - // translation of automata to scala code - // - - - /** `[switchResult]' */ - def _swres(): Tree = { Ident( resultSym );} - - /** `' param */ - def _state(): Tree = { Ident( stateSym ); } - - /** `' param */ - def _iter(): Tree = { Ident( iterSym ); } - - /** simple optimization: if we are in a sink state, stop traversing sequence - */ - def stateWrap(i: Int): Tree = { - if( dfa.isSink( i )) - run_finished( i ); // state won't change! optimization - else - If( Negate( Ident( hasnSym )), - run_finished( i ), - code_state_NEW( i )); - } - - /** body of the matcherDefFun - */ - def code_body_NEW(): Tree = { - var cases: List[CaseDef] = Nil; - - //val tags = new Array[Int](dfa.nstates()); - //val bodies = new Array[Tree](dfa.nstates()); - var i = 0; while (i < dfa.nstates()) { - cases = CaseDef( Literal(i), stateWrap(i)) :: cases; - i = i + 1; - } - //if( optimize ) - loadCurrentElem( Match( _state(), cases )); - - /* - Tree res = code_error(); - for( int i = dfa.nstates-2; i>= 0; i-- ) - res = gen.If( Equals( _state(), gen.mkIntLit( pos, i )), - bodies[ i ] , - res ); - - return loadCurrentElem( res ); - */ - } - - /* calling the (AlgebraicMatcher)PatternMatcher here */ - def _cur_match(pat: Tree): Tree = { - val m: PartialMatcher = new PartialMatcher { - val owner = Autom2Scala.this.funSym; /* owner*/ - val selector = currentElem(); /* root */ - /* defs.boolean_TYPE() restype */ - }; - - am.construct( m, List ( - CaseDef( pat, Literal(true)), - CaseDef( Ident(nme.WILDCARD), Literal(false)) - ), - false); - am.toTree(); - } - - // @todo should be abstract - def code_delta( i:Int, label: Label): Tree = { - scala.Predef.error("should not happen"); - } - - /** some error happened which is due to bug in translation/automaton - */ - final def code_error(): Tree = { - ThrowMatchError( pos , funRetType() ); - } - - def code_fail(): Tree = { - Literal( FAIL ); //gen.mkIntLit(Position.FIRSTPOS, FAIL ); - } - - /** code for the return value of the automaton translation - */ - def run_finished(state: Int): Tree = { - if( dfa.isFinal( state )) - Literal( - dfa.finals.get( new Integer( state ) ).asInstanceOf[Integer] - .intValue() - ) - else - Literal( FAIL ); - } - - def code_state_NEW(i: Int): Tree = { - var stateBody = code_delta( i, DefaultLabel() ); - if( stateBody == null ) - stateBody = code_fail(); - val trans = dfa.deltaq( i ); - - val labs = dfa.labels().iterator(); - while(labs.hasNext()) { - val label = labs.next(); - val next = trans.get( label ).asInstanceOf[Integer]; - val action = code_delta( i, label.asInstanceOf[Label] ); - if( action != null ) { - /*assert*/ //stateBody != null : "stateBody is null"; - stateBody = If( currentMatches(label.asInstanceOf[Label] ), - action, - stateBody); - } - } - stateBody; - } - } -} diff --git a/sources/scala/tools/nsc/matching/BerrySethis.scala b/sources/scala/tools/nsc/matching/BerrySethis.scala deleted file mode 100644 index 85638903b0..0000000000 --- a/sources/scala/tools/nsc/matching/BerrySethis.scala +++ /dev/null @@ -1,800 +0,0 @@ -package scala.tools.nsc.matching ; - -import java.util.{ HashSet, HashMap, TreeSet, TreeMap, Vector }; - -//import scala.compiler.printer.XMLAutomPrinter; - -trait BerrySethis: TransMatcher { - -import global._; -/** a Berry-Sethi style construction for nfas. - * this class plays is the "Builder" for the "Director" class WordRecognizer. - */ - -class BerrySethi { - - /* - def isStar(n: Name): boolean = { - TreeInfo.isNameOfStarPattern(n); - } - */ - /* - - String s = n.toString(); - return (s.indexOf("$") != -1) - &&(!s.startsWith("nest")); - } - */ - - var labels: HashSet = _; - - var pos: int = _; - // maps a literal pattern to an Integer ( the position ) - // is not *really* needed (postfix order determines position!) - var posMap: HashMap = _; // pos: Patterns -> Positions - // don't let this fool you, only labelAt is a real, surjective mapping - var labelAt: HashMap= _; // chi: Positions -> Obj - - var globalFirst: TreeSet= _; - - // results which hold all info for the NondetWordAutomaton - - var follow: HashMap= _; // follow: Positions -> Set[Positions] - - - // Unit test ? - def nullable(pat: Tree): Boolean = - //System.out.print(""); - //DEBUG.print( pat ); - //System.out.println(""); - pat match { - case Apply(_, _) => false; - case Sequence( trees ) => trees.isEmpty || (trees forall {nullable}); - case Star(t) => true; // ? new - case Bind(n, t) => nullable( t ); - case Alternative(choices) => choices exists {nullable} - case _ => false; - } - - - - /** returns true if a Sequence pattern matches the empty sequence - * @param pat the sequence pattern. - def nullableSequence(pat: Tree): Boolean = - pat match { - case Sequence(pats) => pats forall {nullable}; - } - } - */ - - /** returns true if a sequence of patterns (usually children of a - * sequence or subsequence node) is nullable. - * @param pats the sequence of patterns - def nullable(pats: Array[Tree]): Boolean = { - var result = true; - var i = 0; - while(i < pats.length && result){ - result = result && nullable( pats( i ) ); - i = i + 1 - } - return result; - } - */ - - /** computes first( alpha ) where alpha is a word regexp - */ - - def compFirst( pat:Tree ): TreeSet = { - //System.out.print(""); - //DEBUG.print( pat ); - //System.out.println(""); - pat match { - case Sequence( trees ) => - return compFirst( trees ); - case Typed(_,_) | Select(_,_) | Apply(_, _) => - val tmp = new TreeSet(); - tmp.add( posMap.get( pat ).asInstanceOf[Integer]); // singleton set - return tmp; - - case Literal( _ ) => - val tmp = new TreeSet(); - tmp.add( posMap.get( pat ).asInstanceOf[Integer]); // singleton set - return tmp; - //case Subsequence( Tree[] trees ) => - //return compFirst( trees ); - case Alternative( trees ) => - val tmp = new TreeSet(); - var i = 0; - while(i < trees.length) { - tmp.addAll( compFirst( trees( i ) )); - i = i + 1 - } - return tmp; - - case Bind(_, tree) => - return compFirst(tree); - - case Ident( name ) => - //if (name != Name.fromString("_")) - // error("unexpected pattern"); - val tmp = new TreeSet(); - tmp.add( posMap.get( pat ).asInstanceOf[Integer]); // singleton set - return tmp; - - case _ => - scala.Predef.error("unexpected pattern"); - } - } - - - - /** computes last( alpha ) where alpha is a word regexp - */ - def compLast(pat: Tree): TreeSet = { - //System.out.print(""); - //DEBUG.print( pat ); - //System.out.println(""); - pat match { - case Sequence( _ ) | Apply(_, _) => - val tmp = new TreeSet(); - tmp.add(posMap.get( pat ).asInstanceOf[Integer]); // singleton set - return tmp; - - case Literal( _ ) => - val tmp = new TreeSet(); - tmp.add( posMap.get( pat ).asInstanceOf[Integer]); // singleton set - return tmp; - - case Alternative( trees ) => - val tmp = new TreeSet(); - var i = 0; - while(i < trees.length) { - tmp.addAll( compLast( trees )); - i = i + 1 - } - return tmp; - - case Bind( _, tree ) => - return compLast( tree ); - - case _ => - scala.Predef.error("unexpected pattern"); - } - } - - - /** computes first(w) where w=alpha_1...alpha_n are successors of a - * sequence node - * @todo make tail recursive - */ - def compFirst( pats:scala.List[Tree] ): TreeSet = pats match { - case List() => new TreeSet(); - case x::xs => - val res = compFirst(x); - if(nullable(x)) - res.addAll(compFirst(xs)); - res - } - - // Unit test ? - - /** computes last(w) where w are successors of a sequence node - */ - def compLast(pats: scala.List[Tree]): TreeSet = pats match { - case List() => new TreeSet(); - - case _ => - /* - System.out.print(""); - for( int k = 0; k= 0 )) { - tmp = pats( i ); - result.addAll( compLast( tmp )); - i = i + 1; - } - return result; - } - - // starts from the right-to-left - // precondition: pos is final - // pats are successor patterns of a Sequence node - // returns first-set (== follow set of initial state) - def compFollow(pats: scala.List[Tree]): TreeSet = { - var first:TreeSet = null; - this.recVars = new HashMap(); - var fol = new TreeSet(); - if( pats.length > 0 ) {//non-empty expr - var i = pats.length; - fol.add( new Integer( pos )); // don't modify pos ! - do { - i = i - 1; - first = compFollow1( fol, pats( i ) ); - if( nullable( pats( i ) )) - fol.addAll( first ); - else - fol = first; - //System.out.println("in compFollow: first"+first); - //System.out.println("in compFollow: fol"+fol); - - } while( i > 0 ); - } - this.follow.put(new Integer( 0 ), fol); - return fol; - } - - var recVars: HashMap = _; - - /** returns the first set of an expression, setting the follow set along - * the way - */ - def compFollow1( fol1:TreeSet , pat:Tree ): TreeSet = { - var fol = fol1; - //System.out.println("compFollow1("+fol+","+pat+")"); - pat match { - case Sequence( trees ) => - var first: TreeSet = null; - var i = trees.length; - if( i > 0 ) { // is nonempty - do { - i = i - 1; - first = compFollow1(fol, trees( i )); - if( nullable( trees( i ) )) - fol.addAll( first ); - else - fol = first; - } while( i > 0 ) ; - } - if( null == first ) first = new TreeSet(); - return first; - - case Alternative( choices ) => - val first = new TreeSet(); - var i = choices.length - 1; - while(i >= 0) { - first.addAll( compFollow1( fol, choices( i ) )); - i = i - 1; - } - return first; - - case Star(t) => - - val first = compFirst( t ); - fol.addAll(first); - compFollow1(fol,t); - - case Bind( n, t ) => // == can also be star - - val first = compFirst( t ); - //System.out.print("BIND" + first); - //recVars.put( pat.symbol, first ); - - // if( appearsRightmost( n, t )) - // follow = oldfollw + ownfirst - - //if( isStar( n ) ) - // fol.addAll( first ); // an iterated pattern - - // continue to compute follow sets with adjusted fol - return compFollow1( fol, t ); - - case Ident( n ) => - if ((pat.symbol != null ) - && pat.symbol.isPrimaryConstructor) { - // same as Apply - val pos = this.posMap.get( pat ).asInstanceOf[Integer]; - val tset = fol.clone().asInstanceOf[TreeSet]; - this.follow.put( pos, tset ); - val first = new TreeSet(); - first.add( pos ); - return first; - } - /* - if ( recVars.keySet().contains( pat.symbol )) { // grammar - val first = recVars.get( pat.symbol ).asInstanceOf[TreeSet]; - val follow = fol.clone().asInstanceOf[TreeSet]; - first.addAll( follow ); - //recVars.put//this.follow.put( pat.symbol, follow ); - return first; - } - */ - // --- --- only happens when called from BindingBerrySethi - // [... x ...] changed to [... x@_ ...] - - // non-generated, non-recursive variable should not appear, - // so this is a wildcard pattern _ - - val pos = this.posMap.get( pat ).asInstanceOf[Integer]; - val tset = fol.clone().asInstanceOf[TreeSet]; - this.follow.put( pos, tset ); - val first = new TreeSet(); - first.add( pos ); - //System.out.println("Ident("+n+",...) first:"+first); - //System.out.println("Ident("+n+",...) follow:"+tset); - return first; - - case Apply(_, _) | Literal( _ ) | Typed(_,_) | Select(_,_) => - val pos = this.posMap.get( pat ).asInstanceOf[Integer]; - val tset = fol.clone().asInstanceOf[TreeSet]; - this.follow.put( pos, tset ); - val first = new TreeSet(); - first.add( pos ); - return first; - - case _ => - scala.Predef.error("unexpected pattern: "+pat.getClass()); - } - } - - /** called at the leaves of the regexp - */ - def seenLabel( pat:Tree , i:Integer , label:Label ): Unit = { - this.posMap.put( pat, i ); - this.labelAt.put( i, label ); - if( label != DefaultLabel() ) { - /* - if( this.labels.contains( label ) ) { - switch(label) { - case TreeLabel(Apply(_, Tree[] args)) => - if( args.length > 0 ) { - unit.warning(pat.pos, "if this pattern in nondeterminism, it will not compile correctly"); - } - } - } - */ - this.labels.add( label ); - } - - } - - /** overriden in BindingBerrySethi - */ - def seenLabel( pat:Tree , label:Label ): Unit = { - seenLabel( pat, new Integer( {pos = pos + 1; pos} ), label ); - } - - /** returns "Sethi-length" of a pattern, creating the set of position - * along the way - */ - - var activeBinders:Vector = _; - - // todo: replace global variable pos with acc - def traverse( pat:Tree ): Unit = { - pat match { - - // (is tree automaton stuff, more than Berry-Sethi) - case Apply( _, _ ) | Typed( _, _ )| Select( _, _ ) => - val label = new TreeLabel( pat ); - seenLabel( pat, label ) ; - return ; - - case p @ Literal( _ ) => - val label = new SimpleLabel( p ); - seenLabel( pat, label ) ; - - return ; - - case Sequence( trees ) => - var i = 0; - while(i < trees.length) { - traverse( trees( i ) ); - i = i + 1 - } - return ; - - case Alternative( trees ) => - var i = 0; - while(i < trees.length) { - traverse( trees( i ) ); - i = i + 1 - } - return ; - - case Bind( name, body) => - //recVars.put( pat.symbol, java.lang.Boolean.TRUE ); - //if( !isStar( name ) ) { - activeBinders.add( pat.symbol ); - traverse( body ); - activeBinders.remove( pat.symbol ); - //} - //else - // - case Star(body) => traverse( body ); - - case Ident(name) => - if ((pat.symbol != null ) - && pat.symbol.isPrimaryConstructor) { - // same as Apply - val label = new TreeLabel( pat ); - seenLabel( pat, label ) ; - - return ; - } - - scala.Predef.error("should not get here"); // removed idents? - //if( null != recVars.get( pat.symbol ) ) { - // return ; - //} - // _ and variable x ( == x @ _ ) - val label = DefaultLabel(); - seenLabel( pat, label ); - - return ; - - } - } - - - var finals: TreeMap = _; // final states - - //TreeSet initialsRev; // final states - - var deltaq:Array[HashMap] = _; // delta - - - - var defaultq: Array[Vector] = _; // default transitions - - - //HashMap deltaqRev[]; // delta of Rev - //Vector defaultqRev[]; // default transitions of Rev - - - def makeTransition(srcI:Integer, destI:Integer, label: Label): Unit = { - var src = srcI.intValue() ; - var dest = destI.intValue() ; - var arrows: Vector = null; //, revArrows; - //Label revLabel = new Pair( srcI, label ); - label match { - case DefaultLabel() => - arrows = defaultq( src ); - //revArrows = defaultqRev[ dest ]; - case _ => - arrows = deltaq( src ).get( label ).asInstanceOf[Vector]; - if( arrows == null ) - deltaq( src ).put( label, - {arrows = new Vector(); arrows} ); - /* - revArrows = (Vector) deltaqRev[ dest ].get( revLabel ); - if( revArrows == null ) - deltaqRev[ dest ].put( revLabel, - revArrows = new Vector() ); - */ - } - arrows.add( destI ); - //revArrows.add( srcI ); - } - - - var initials: TreeSet = _; - //NondetWordAutom revNfa ; - - def initialize( subexpr:List[Tree] ): Unit = { - this.posMap = new HashMap(); - this.labelAt = new HashMap(); - - - this.follow = new HashMap(); - this.labels = new HashSet(); - this.recVars = new HashMap(); - this.pos = 0; - // determine "Sethi-length" of the regexp - activeBinders = new Vector(); - val it = subexpr.elements; - while(it.hasNext ) - traverse( it.next ); - - - this.initials = new TreeSet(); - initials.add( new Integer( 0 )); - - } - - def initializeAutom(): Unit = { - - finals = new TreeMap(); // final states - deltaq = new Array[HashMap]( pos ); // delta - defaultq = new Array[Vector]( pos ); // default transitions - - var j = 0; - while(j < pos) { - deltaq( j ) = new HashMap(); - defaultq( j ) = new Vector(); - j = j + 1; - } - } - - def collectTransitions(): Unit = { // make transitions - var j = 0; - while(j < pos) { - val q = new Integer( j ); - - //System.out.print( "--q="+q ); - //System.out.println(" labelAt:"+labelAt.get( q )); - - val fol = this.follow.get( q ).asInstanceOf[TreeSet]; - //assert fol != null; - val it = fol.iterator(); - while(it.hasNext()) { - val p = it.next().asInstanceOf[Integer]; - //System.out.println( "-- -- p="+p ); - if( p.intValue() == pos ) { - finals.put( q, finalTag ); - } else { - makeTransition( new Integer(j), p, - labelAt.get( p ).asInstanceOf[Label]); - } - } - j = j + 1 - } - } - - var finalTag: Integer = _; - - def automatonFrom(pat: Tree , finalTag: Integer): NondetWordAutom = { - - this.finalTag = finalTag; - - //System.out.println( "enter automatonFrom("+pat+","+finalTag+")"); // UNIT TEST - //System.out.println( pat ); - //System.out.println( nullableSequence( pat )); // UNIT TEST - pat match { - case Sequence( subexpr ) => - initialize( subexpr ); - - - // (1) compute first - - //globalFirst = compFirst( subexpr ); - //System.out.println(globalFirst); - - // (2) compute follow; - pos = pos + 1; - //Set ignore = compFollow( subexpr ); - //System.out.println(ignore); - //System.exit(0); - //assert (ignore.equals( globalFirst )); - - globalFirst = compFollow( subexpr ); - - //System.out.print("someFirst:");debugPrint(someFirst); - - // construct the automaton's explicit representation - - initializeAutom(); - - - // defaultqRev = new Vector[pos]; // default transitions - - collectTransitions(); - - if (subexpr forall {nullable}) // initial state is final - finals.put(new Integer(0), finalTag); - - //TreeSet initials = new TreeSet(); - //initials.add(new Integer(0)); - - val result = - new NondetWordAutom(pos, // = nstates - labels, - initials, - finals, - deltaq, - defaultq, - null/*(Object) qbinders*/); - - /* - System.out.println("inBerrySethi"); - XMLAutomPrinter pr = new XMLAutomPrinter( System.out ); - pr.begin(); - pr.print(result); - pr.print(revNfa); - pr.end(); - System.out.println("initialsRev = "+initialsRev); - System.out.println("outBerrySethi"); - */ - //System.exit(0); - //result.print(); - return result; - } - - scala.Predef.error("expected a sequence pattern"); - } - - def print1(): Unit = { - Console.println("after sethi-style processing"); - Console.println("#positions:" + pos); - Console.println("posMap:"); - - var it = this.posMap.keySet().iterator(); - while(it.hasNext()) { - val t = it.next().asInstanceOf[Tree]; - t match { - case Literal( _ ) => - Console.print( "(" + t.toString() + " -> "); - val s2 = (posMap.get(t).asInstanceOf[Integer]).toString(); - Console.print( s2 +") "); - } - } - Console.println("\nfollow: "); - var j = 1; - while(j < pos ) { - val fol = this.follow.get(new Integer(j)).asInstanceOf[TreeSet]; - Console.print("("+j+" -> "+fol.toString()+") "); - //debugPrint( fol ); - Console.println; - j = j + 1; - } - - } -} // class BerrySethi - -//import scala.compiler.printer.XMLTreePrinter ; -//import scala.compiler.printer.XMLAutomPrinter ; - -/** a Berry-Sethi style construction for nfas. - * this class plays is the "Builder" for the "Director" class - * WordRecognizer. - */ - -class BindingBerrySethi extends BerrySethi { - - // variables - - var deltaqRev : Array[HashMap] = _; // delta of Rev - var defaultqRev: Array[Vector] = _; // default transitions of Rev - var qbinders : Array[Vector] = _; // transitions <-> variables - var revnfa : NondetWordAutom = _ ; - var varAt : HashMap = _; // chi: Positions -> Vars (Symbol) - - override def makeTransition(srcI: Integer, destI: Integer, label: Label): Unit = { - val src = srcI.intValue() ; - val dest = destI.intValue() ; - var arrows: Vector = null; - var revArrows: Vector = null; - val revLabel = new LPair(srcI, label); - label match { - case DefaultLabel() => - arrows = defaultq(src); - revArrows = defaultqRev(dest); - - case _ => - arrows = deltaq(src).get(label).asInstanceOf[Vector]; - if (arrows == null) - deltaq(src).put(label, - {arrows = new Vector(); arrows} ); - revArrows = deltaqRev(dest).get(revLabel).asInstanceOf[Vector]; - if (revArrows == null) - deltaqRev(dest).put(revLabel, {revArrows = new Vector(); revArrows} ); - } - arrows.add(destI); - revArrows.add(srcI); - } - - override def seenLabel(pat: Tree, label: Label): Unit = { - var i = new Integer({pos = pos + 1; pos} ); - seenLabel( pat, i, label ); - pat match { - case Apply(_, _) | Literal( _ ) | Select(_, _) | Typed(_,_) => - this.varAt.put( i, activeBinders.clone() ); // below @ ? - - case Ident( name ) => - //assert ( pat.symbol() == Global.instance.definitions.PATTERN_WILDCARD )||( name.toString().indexOf("$") > -1 ) : "found variable label "+name; - - val binders = activeBinders.clone().asInstanceOf[Vector]; - /* - if( pat.symbol() != Global.instance.definitions.PATTERN_WILDCARD) { - binders.add( pat.symbol() ); - } - */ - this.varAt.put( i, binders ); - } - } - - override def initialize( pats:List[Tree] ): Unit = { - this.varAt = new HashMap(); // Xperiment - super.initialize( pats ); - } - - override def initializeAutom(): Unit = { - super.initializeAutom(); - deltaqRev = new Array[HashMap](pos); // deltaRev - defaultqRev = new Array[Vector](pos); // default transitions - qbinders = new Array[Vector](pos); // transitions <-> variables - - var j = 0; - while (j < pos) { - deltaqRev(j) = new HashMap(); - defaultqRev(j) = new Vector(); - qbinders(j) = varAt.get(new Integer(j)).asInstanceOf[Vector]; - j = j + 1; - } - varAt.clear(); // clean up - } - - - override def automatonFrom(pat: Tree, finalTag: Integer): NondetWordAutom = { - this.finalTag = finalTag ; - //System.out.println("enter automatonFrom("+ pat +")"); - pat match { - case Sequence(subexpr) => - - initialize(subexpr); - - // (1) compute first + follow; - pos = pos + 1; - - globalFirst = compFollow( subexpr ); - - - - initializeAutom(); // explicit representation - - collectTransitions(); - - val result = - new NondetWordAutom(pos, // = nstates - labels, - initials, - finals, - deltaq, - defaultq, - qbinders); - - result.leftTrans = true; - - val revInitials = new TreeSet(finals.keySet()); - /* - pos++; // adding a state - HashSet deltaqRev2[] = new HashSet[ deltaqRev.length + 1]; - HashSet defaultqRev2[] = new HashSet[ deltaqRev.length + 1]; - HashSet qbinders[] = new HashSet[ deltaqRev.length + 1]; - for (Iterator it = finals.keySet().iterator(); it.hasNext(); ) { - - } - */ - val revFinals = new TreeMap(); - var it = initials.iterator(); - while(it.hasNext()) { - revFinals.put(it.next(), finalTag); - } - revnfa = new NondetWordAutom(pos, - labels, - revInitials, - revFinals, - deltaqRev, - defaultqRev, - qbinders); - - revnfa.rightTrans = true; - - /* - System.out.println("inBerrySethi"); - XMLAutomPrinter pr = new XMLAutomPrinter(System.out); - pr.begin(); - pr.print(result); - pr.print(revnfa); - pr.end(); - System.out.println("initialsRev = " + initialsRev); - System.out.println("outBerrySethi"); - */ - //System.exit(0); - return result; //print(); - } - } - -} // class BindingBerrySethi - - - -} diff --git a/sources/scala/tools/nsc/matching/CodeFactory.scala b/sources/scala/tools/nsc/matching/CodeFactory.scala deleted file mode 100644 index 1d6882a0fa..0000000000 --- a/sources/scala/tools/nsc/matching/CodeFactory.scala +++ /dev/null @@ -1,260 +0,0 @@ -/* -** $Id$ -*/ -package scala.tools.nsc.matching ; - -import scala.tools.nsc.util.Position; - -[_trait_] abstract class CodeFactory: TransMatcher { - - import global._ ; - - import definitions._; // standard classes and methods - import typer.typed; // methods to type trees - import posAssigner.atPos; // for filling in tree positions - - - /** returns `List[ Tuple2[ scala.Int, ] ]' */ - def SeqTraceType( elemType: Type ): Type = { - appliedType(definitions.ListClass.typeConstructor, - List(pairType(definitions.IntClass.info, - elemType))) - } - - - - def pairType(left: Type, right: Type) = { - appliedType( definitions.TupleClass(2).typeConstructor, - List(left,right)) - } - - /** returns `Iterator[ elemType ]' */ - def _seqIterType( elemType: Type ): Type = { - appliedType( definitions.IteratorClass.typeConstructor, - List(elemType)) - } - - /** returns A for T <: Sequence[ A ] - */ - def getElemType_Sequence(tpe: Type): Type = { - //System.err.println("getElemType_Sequence("+tpe.widen()+")"); - val tpe1 = tpe.widen.baseType( definitions.SeqClass ); - - if( tpe1 == NoType ) - Predef.error("arg "+tpe+" not subtype of Seq[ A ]"); - - return tpe1.typeArgs( 0 ); - } - - - // --------- these are new - - /** a faked switch statement - */ - def Switch(condition: Array[Tree], body: Array[Tree], defaultBody: Tree): Tree = { - //assert condition != null:"cond is null"; - //assert body != null:"body is null"; - //assert defaultBody != null:"defaultBody is null"; - var result = defaultBody; - - var i = condition.length-1; - while (i >= 0) { - result = If(condition(i), body(i), result); - i = i - 1 - } - - return result ; - } - - /** returns code `.elements' */ - def newIterator( seqObj:Tree ): Tree = - Apply(Select(seqObj, newTermName("elements")), List()); - - - /** `it.next()' */ - def _next(iter: Tree) = - Apply(Select(iter, definitions.Iterator_next), List()); - - - /** `it.hasNext()' */ - def _hasNext(iter: Tree) = - Apply(Select(iter, definitions.Iterator_hasNext), List()); - - - /** `!it.hasCur()' */ - def _not_hasNext( iter:Tree ) = - Apply(Select(_hasNext(iter), definitions.Boolean_not), List()); - - - /** `trace.isEmpty' */ - def isEmpty( iter: Tree ): Tree = - Apply(Select(iter, definitions.List_isEmpty), List()); - - - /** `arg.head' */ - def SeqList_head( arg: Tree ) = - Apply(Select(arg, definitions.List_head), List()); - - - def Negate(tree: Tree) = tree match { - case Literal(Constant(value:Boolean))=> - Literal(Constant(!value)) - case _ => - Apply(Select(tree, definitions.Boolean_not), List()); - } - - /*protected*/ def And(left: Tree, right: Tree): Tree = left match { - case Literal(Constant(value:Boolean)) => - if(value) right else left; - case _ => - right match { - case Literal(Constant(true)) => - left; - case _ => - Apply(Select(left, definitions.Boolean_and), List(right)); - } - } - - /*protected*/ def Or(left: Tree, right: Tree): Tree = { - left match { -/* - case If(cond: Tree, thenp: Tree, Literal(Constant(false))) => // little opt, frequent special case - If(cond, thenp, right) -*/ - case Literal(Constant(value: Boolean))=> - if(value) left else right; - case _ => - right match { - case Literal(Constant(false)) => - left; - case _ => - Apply(Select(left, definitions.Boolean_or), List(right)); - } - } - } - - // used by Equals - private def getCoerceToInt(left: Type): Symbol = { - val sym = left.nonPrivateMember( nme.coerce ); - //assert sym != Symbol.NONE : Debug.show(left); - - sym.alternatives.find { - x => x.info match { - case MethodType(vparams, restpe) => - vparams.length == 0 && isSameType(restpe,definitions.IntClass.info) - } - }.get - } - - // used by Equals -/* - private def getEqEq(left: Type, right: Type): Symbol = { - //Console.println("getEqeq of left == "+left); - val sym = left.nonPrivateMember( nme.EQEQ ); - - - //if (sym == NoSymbol) - // error("no eqeq for "+left); - // : Debug.show(left) + "::" + Debug.show(left.members()); - - var fun: Symbol = null; - var ftype:Type = null; // faster than `definitions.AnyClass.tpe' - sym.alternatives.foreach { - x => - //Console.println("getEqEq: "+x); - val vparams = x.info.paramTypes; - //Console.println("vparams.length == "+vparams.length); - - if (vparams.length == 1) { - val vptype = vparams(0); - //Console.println("vptype == "+vptype); - //Console.println(" ftype == "+ftype); - //Console.println(" cond1 == "+isSubType(right, vptype)); - //Console.println(" cond2("+vptype+","+ftype+") == "+(ftype == null || isSubType(vptype, ftype))); - //Console.println("vptype.getClass "+vptype.getClass()); - if (isSubType(right, vptype) && (ftype == null || isSubType(vptype, ftype)) ) { - fun = x; - ftype = vptype; - //Console.println("fun now: "+fun+" ftype now "+ftype); - } - } - } - //if (fun == null) scala.Predef.error("couldn't find eqeq for left"+left); - fun; - } -*/ - def Equals(left: Tree , right: Tree ): Tree = Apply(Select(left, nme.EQEQ), List(right)); -/* { var left = left1; - var right = right1; -*/ -/* - //Console.println("CodeFactory:: left.tpe =" + left.tpe + " right.tpe "+right.tpe+")"); - val ltype = left.tpe.widen; - var rtype = right.tpe.widen; - if (isSameType(ltype, rtype) - && (isSameType(ltype, definitions.CharClass.info) - || isSameType(ltype,definitions.ByteClass.info) - || isSameType(ltype,definitions.ShortClass.info))) - { - //Console.println("getcoerce"+getCoerceToInt(rtype)); - //Console.println("getcoerce.tpe"+getCoerceToInt(rtype).tpe); - right = Apply(Select(right, getCoerceToInt(rtype)), List()); - rtype = definitions.IntClass.info; - } - val eqsym = getEqEq(ltype, rtype); -*/ - //Console.println("eqsym "+eqsym); - //Console.println("eqsym.tpe "+eqsym.tpe); -// Apply(Select(left1, nme.EQEQ/*eqsym*/), List(right1)); -// } - - def ThrowMatchError(pos: Int, tpe: Type ) = - atPos(pos) { - Throw( - New( - TypeTree(definitions.MatchErrorClass.tpe), - List(List( - Literal(cunit.toString()), - Literal(Position.line(cunit.source, pos)))))) - } - -/* - Apply( - TypeApply( - gen.mkRef(definitions.MatchError_fail), - List(TypeTree(tpe)) - ), - List( - Literal(cunit.toString()), - Literal(Position.line(cunit.source, pos)) - ) - ); -*/ - - /* // ?! - def ThrowMatchError(pos:int , tree:Tree ) = - Apply( - gen.mkRef(definitions.MatchError_report), - List( - Literal(cunit.toString()), - Literal(Position.line(cunit.source, pos)), - tree - ) - ); - */ - -// def Error(pos: Int) = -// ThrowMatchError(pos); - - - /* - def newPair(left: Tree, right: Tree) = - New( - Apply( - gen.mkRef(definitions.TupleClass(2)), - List(left,right) - ) - ); - */ -} - diff --git a/sources/scala/tools/nsc/matching/DetWordAutoms.scala b/sources/scala/tools/nsc/matching/DetWordAutoms.scala deleted file mode 100644 index 8e4d2943be..0000000000 --- a/sources/scala/tools/nsc/matching/DetWordAutoms.scala +++ /dev/null @@ -1,884 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ -package scala.tools.nsc.matching ; - -import java.util._ ; - -trait DetWordAutoms: TransMatcher { - -import global._; -class DetWordAutom { - - /** determinization -- standard algorithm considering only - * reachable states - */ - def this(nfa: NondetWordAutom) = { - this(); - //Console.println("DWA:this(.)"); - //Console.println(nfa.nstates); - //nfa.print(); - determinize( nfa ); - //Console.println(_nstates); - } - - //final static Integer FINTAG = new Integer(0); - - /** number of states */ - var _nstates:int =0; - - /** the 'alphabet' */ - var _labels:HashSet = _; - - /** the set of final states, here as a TreeMap */ - /*protected*/ var finals:TreeMap = _; - - /** dfa: HashMap trans: Object -> Integer - * nfa: HashMap trans: Object -> Vector [ Integer ] - * - * nfa: Integer ->(Object -> Vector [ Int ]) - * [q] |->( a |-> { q' | (q,a,q') in \deltaright } ) - * - * dfa: Integer ->(Object -> Int) - * [q] |->( a |-> q' | \deltaright(q,a) = q' } ) - */ - - var _deltaq: Array[HashMap] = _; - - var _defaultq: Array[Integer] = _; // this gives the default transitions - - //protected HashMap deltaq[]; - - // --- accessor methods - - /** returns number of states - */ - def nstates(): Int = _nstates; - - /** returns the labels - */ - def labels(): HashSet = _labels; - - /** returns the transitions - */ - def deltaq( state:int ): HashMap = _deltaq( state ); - - /** returns the transitions - */ - def deltaq( state:Integer ): HashMap = _deltaq( state.intValue() ); - - /** for a set of nfa states (that must exist), returns its transitions - */ - def deltaq(nset: TreeSet): HashMap = - deltaq( indexMap.get( nset ).asInstanceOf[Integer] ); - - /** for a set of nfa states (that must exist), returns its transitions - */ - def defaultq( nset:TreeSet ): Integer = - defaultq( indexMap.get( nset ).asInstanceOf[Integer] ); - - /** returns the transitions - */ - def defaultq( state: int ): Integer = - _defaultq( state ); - - /** returns the transitions - */ - def defaultq( state: Integer ): Integer = - _defaultq( state.intValue() ); - - /** returns true if the state is final - */ - def isFinal(state: int): boolean = - ((finals != null) - && (finals.get( new Integer( state )) != null)); - - /** returns true if the state is final - */ - def isFinal(state: Integer): boolean = { - return ((finals != null) && finals.containsKey( state )); - } - - /** returns true if the state is final - */ - def finalTag( state:Integer ): Integer = { - return finals.get( state ).asInstanceOf[Integer]; - } - - - def finalTag( state: int ): Integer = { - return finals.get( new Integer (state )).asInstanceOf[Integer]; - } - - /** returns true if the set of states contains at least one final state - */ - def containsFinal( Q: TreeSet ): boolean = { - val it = Q.iterator(); - while(it.hasNext()) { - if( isFinal(it.next().asInstanceOf[Integer])) - return true; - } - return false; - } - - - /** returns true if there are no finite states - */ - def isEmpty(): boolean = { - return finals.isEmpty(); - } - - // END stuff from FiniteAutom - - final val FIRST: int = 0; - final val LAST: int = FIRST + 1; - - //static final int WHICH_LONGEST_MATCH = FIRST ; - final val WHICH_LONGEST_MATCH:int = LAST ; - - // inherited from FiniteAutom: - - // int nstates; // number of states - // HashSet labels;// the alphabet - // TreeMap finals; - - // HashMap deltaq[]; - //Integer defaultq[]; - - - // TEMPORARY VAR used only during determinization and debug printing - // Q -> (Label -> Q ) - var delta/*Map*/ : HashMap = _; - // Q -> Integer; - var indexMap: HashMap = _; - - // Integer -> Q - var invIndexMap: HashMap = _; - - // only not null if this is a right-transducer - var qbinders: Array[Vector] = _; - - final val NODEFAULT: Integer = new Integer( -1 ); - - def isSink( i:int ): boolean = { - return ( _deltaq( i ).keySet().isEmpty() - && (_defaultq != null ) - && (_defaultq( i ).intValue() == i) ); - } - - def hasDefault( i:int ): boolean = { - return _defaultq( i ) != NODEFAULT; - } - - def determinize( nfa: NondetWordAutom ): Unit = { - //Console.println("DetWordAutom:determinize"); - //System.out.println("nfa:");nfa.print(); - var states:TreeSet = null; // temp: Set[Set[Integer]] - var deftrans:HashMap = null; // Set[Integer] -> Int - - var trans: HashMap = null; // always points to a mapping ( Label -> Q ) - var ix = 0; // state index - - this._labels = nfa.labels; - ////System.out.println("Labels: "+labels); - this.delta/*Map*/ = new HashMap(); - //this.dead = -1; - - states = new TreeSet( new StateSetComparator() ); - deftrans = new HashMap(); - // temporarily: Map[Set[Integer]] later: Map[Integer] - this.finals = new TreeMap( new StateSetComparator() ); - this.invIndexMap = new HashMap(); - this.indexMap = new HashMap(); - - // new initial state (singleton set { q0 } by construction) - val q0 = new TreeSet(); - q0.addAll( nfa.initials ); /*new Integer( 0 )); */ - states.add( q0 ); - - val empty = new TreeSet(); - deftrans.put( q0, empty ); - states.add( empty ); - deftrans.put( empty, empty ); - - val rest = new Stack(); - if( nfa.isFinal( 0 ) ) - this.finals.put( q0, nfa.finalTag( 0 ) ); - - //Console.println("...beginning"); - - rest.push( empty ); - rest.push( q0 ); - //Console.println("...beginning 2" ); - while( !rest.empty() ) { - //Console.println("...beginning 3" ); - val P1 = rest.pop().asInstanceOf[TreeSet]; - - //System.out.println("states:"+ states); - //System.out.println("P1:"+ P1); - - invIndexMap.put( new Integer( ix ), P1 ); - indexMap.put( P1, new Integer( ix )); - ix = ix + 1; - delta/*Map*/.put( P1, {trans = new HashMap(); trans}); - - //Console.println("...beginning 4" ); - // labelled transitions - val it = _labels.iterator(); - //Console.println("it = "+it ); - //Console.println(it.hasNext()); - - while( it.hasNext() ) { - //Console.println("...beginning 5" ); - //Console.flush; - val label = it.next(); - //Console.print( "Label: " + label +" "); - // Qdest will contain all states reachable via `label' - // from some nfa state in P1; - val Qdest = nfa.getSide( P1, label ); - //Console.println("Qdest:"+Qdest); - if( !states.contains( Qdest ) ) { - states.add( Qdest ); - ////System.out.print(" (added)" ); - rest.push( Qdest ); - ////System.out.print(" (pushed)"); - - //Console.println("nfa.containsFinal("+Qdest+") =="+nfa.containsFinal( Qdest )); - - if( nfa.containsFinal( Qdest ) ) - this.finals.put( Qdest, nfa.finalTag( Qdest )); - ////System.out.print(" (added final)"); - - } - ////System.out.println(".Qdest"); - - trans.put( label, Qdest ); - // //System.out.println( "Qdest: " + Qdest); - //Console.println("Y marks"); - } - - // default transitions - - val defTarget: TreeSet = nfa.defaultq( P1 ).asInstanceOf[TreeSet]; - //System.out.println("defTarget:"+defTarget); - deftrans.put( P1, defTarget ); - - //Console.println("X marks 0"); - - if( !states.contains( defTarget ) ) { - //Console.println("X marks 1"); - - states.add( defTarget ); - rest.push( defTarget ); - //Console.println("nfa.containsFinal("+defTarget+")"+nfa.containsFinal( defTarget )); - if( nfa.containsFinal( defTarget ) ) - this.finals.put( defTarget, nfa.finalTag( defTarget )); - } - - //Console.println("X marks"); - } - - //Console.println("...continuing"); - - // - //printBefore( states, deftrans ); - - // do not call printBefore after this point - // //System.out.println("indexMap: "+indexMap); - - this._nstates = states.size(); - _deltaq = new Array[HashMap]( _nstates ); - _defaultq = new Array[Integer]( _nstates ); - - // we replace Set[Set[Integer]] by its index and clean up - - val jt = states.iterator(); - while(jt.hasNext()) { - val state = jt.next().asInstanceOf[TreeSet]; - val state_x = indexMap.get( state ).asInstanceOf[Integer]; - - val defTarget = deftrans.get( state ).asInstanceOf[TreeSet]; - var defTarget_x: Integer = null; - if( null != defTarget) { - defTarget_x = indexMap.get( defTarget ).asInstanceOf[Integer]; - ////System.out.println("deftarget" + defTarget); - } else - defTarget_x = NODEFAULT; - - ////System.out.print(state.toString() + " --> " + state_x); - //System.out.println(" deftarget " + defTarget + " --> "+defTarget_x); - - trans = delta/*Map*/.get( state ).asInstanceOf[HashMap]; - val newTrans = new HashMap(); - val labs = _labels.iterator(); - while(labs.hasNext()) { - val label = labs.next(); - val target = trans.get( label ).asInstanceOf[TreeSet]; - var target_x: Integer = null; - if( null != target ) { - // //System.out.println("target :"+target); - target_x = indexMap.get( target ).asInstanceOf[Integer]; - - if( target_x.intValue() != defTarget_x.intValue() ) { - // replace target by target_x - // (use type-unawareness) - newTrans.put( label, target_x ); - } - trans.remove( label ); - } - - } - _deltaq( state_x.intValue() ) = newTrans; - _defaultq( state_x.intValue() ) = defTarget_x; - - delta/*Map*/.remove( state ); - deftrans.remove( state ); - - } - //Console.println("determinize::: finals"+finals); - val oldfin: TreeMap = finals; - this.finals = new TreeMap(); - var kt = oldfin.keySet().iterator(); - while(kt.hasNext()) { - val state = kt.next().asInstanceOf[TreeSet]; - val state_x = indexMap.get( state ).asInstanceOf[Integer];; - this.finals.put( state_x, oldfin.get( state ) ); // conserve tags - } - - // clean up, delete temporary stuff - /* - // we cannot clean up, indexmap is needed later - for( Iterator it = states.iterator(); it.hasNext(); ) { - ((TreeSet) it.next()).clear(); - } - */ - states.clear(); - - //Console.println("...done"); - //minimize(); - } - - - - def isDead(state: Int): Boolean = { - return state == _nstates - 1; // by construction - } - - def isDead(state: Integer): Boolean = { - return state.intValue() == _nstates - 1; // by construction - } - - - /** returns target of the transition from state i with label label. - * null if no such transition exists. - */ - def delta(i: Int, label: Label): Integer = { - var target:Integer = null; - label match { - case DefaultLabel() => - if (! hasDefault(i)) - return null; - return _defaultq( i ).asInstanceOf[Integer] ; - case SimpleLabel( _ ) | TreeLabel( _ ) => - return _deltaq( i ).get( label ).asInstanceOf[Integer] ; - /*case LPair( Integer state, Label lab ): - return state; - */ - case _ => - scala.Predef.error("whut's this: label="+label+", class "+label.getClass()); - } - } - - def delta(i: Integer, label: Label): Integer = - delta(i.intValue(), label); - - /** should maybe in nfa, not here - */ - /*static */ - protected def smallestFinal( nfa: NondetWordAutom, states:TreeSet ): Integer = { - - var min = Integer.MAX_VALUE ; - val it = states.iterator(); - while (it.hasNext()) { - val state = it.next().asInstanceOf[Integer]; - if( nfa.isFinal( state ) && (state.intValue() < min )) - min = state.intValue(); - } - if (min == Integer.MAX_VALUE) - scala.Predef.error("I expected a final set of states"); - return new Integer( min ); - } - - protected def allSetsThatContain( ndstate: Integer ): Vector = { - val v = new Vector(); - val it = indexMap.keySet().iterator(); - while(it.hasNext()) { - val ndstateSet = it.next().asInstanceOf[TreeSet]; - if( ndstateSet.contains( ndstate )) - v.add( ndstateSet ); - } - return v; - } - - - protected def filterItOutQuoi( dLeft: DetWordAutom, npTarget: Npair,lab:LPair , nsrc:TreeMap ):Unit = { - val theLabel = lab.lab; - val ntarget = lab.state; - - // e.g.[2,(3),4] --> 7 - val dstate = dLeft.indexMap.get( npTarget.nset ).asInstanceOf[Integer]; - - // eg. 3 -> [3] [2,3] - val targets:Vector = dLeft.allSetsThatContain( ntarget ); - - ////System.out.println( targets+", of these " ) ; - - // filter out those source states which arrive here... - val su = targets.iterator(); - while(su.hasNext()) { - val nset = su.next().asInstanceOf[TreeSet]; - val ddelta = dLeft.deltaq( nset ).asInstanceOf[HashMap]; - - // ... at THIS dstate - if(ddelta.get( theLabel ).asInstanceOf[Integer] == dstate ) { - - val np1 = new Npair( ntarget, nset ); - - ////System.out.print( np1.toString( dLeft.indexMap )); - - if( WHICH_LONGEST_MATCH == FIRST ) - addTransitionFLM( nsrc, np1 ); - else - addTransitionLLM( nsrc, np1 ); - } - - } - } - - /** all default transitions from sets that contain nq to npTarget - */ - protected def filterItOutQuoiDefault( dLeft: DetWordAutom ,npTarget:Npair , nq:Integer , nsrc:TreeMap ): Unit = { - - - ////System.out.println( "npTarget = " + npTarget ) ; - - val allSources = dLeft.allSetsThatContain( npTarget.nstate ); - val it = allSources.iterator(); - while(it.hasNext()) { - - // e.g.[2,(3),4] --> 7 - //Integer dstate = (Integer) dLeft.indexMap.get( npTarget.nset ); - - val dstate = dLeft.indexMap.get( it.next() ).asInstanceOf[Integer]; - - //System.out.println( "dstate = " + dstate ) ; - - //assert dstate != null; - - // eg. 3 -> [3] [2,3] - val targets = dLeft.allSetsThatContain( nq ); - - //System.out.println( "targets: " + targets ) ; - - // filter out those source states which arrive here... - val su = targets.iterator(); - while(su.hasNext()) { - val nset = su.next().asInstanceOf[TreeSet]; - val ddef = dLeft.defaultq( nset ); - - //System.out.println( "ddef ="+ddef ); - - // ... at THIS dstate - if( ddef == dstate ) { - - val np1 = new Npair( nq, nset ); - - // print target - //System.out.print( np1.toString( dLeft.indexMap )); - - if( WHICH_LONGEST_MATCH == FIRST ) - addTransitionFLM( nsrc, np1 ); - else - addTransitionLLM( nsrc, np1 ); - - } - - } - } - } - - /** this implements the first longest match policy - */ - protected def addTransitionFLM( nsrc:TreeMap , np:Npair ): Unit= { - val np2 = nsrc.get( np.nset ).asInstanceOf[Npair ]; - - // (policy) first longest match - if(( np2 == null ) - ||( np2.nstate.intValue() > np.nstate.intValue())) { - nsrc.put( np.nset, np ); - } - - } - - /** this implements the last longest match policy (!) - */ - protected def addTransitionLLM(nsrc: TreeMap, np: Npair ): Unit = { - val np2 = nsrc.get( np.nset ).asInstanceOf[Npair]; - - // (policy) first longest match - if(( np2 == null ) - ||( np2.nstate.intValue() < np.nstate.intValue())) { - nsrc.put( np.nset, np ); - } - - } - - - /** build a deterministic right to left transducer from the args - */ - def this(right: NondetWordAutom, left:NondetWordAutom, dLeft: DetWordAutom ) = { - this(); - - /* System.out.println("DetWordAutom.(nfa,nfa,dfa)"); - System.out.println("nfa-left:");left.print(); - System.out.println("nfa-right:");right.print(); - System.out.println("dLeft:"+dLeft.print()); - System.out.println("dLeft.finals"+dLeft.finals); - */ - this.indexMap = dLeft.indexMap; - this.invIndexMap = dLeft.invIndexMap; - // fix indexMap - /* // unnecessary - TreeSet q0 = new TreeSet(); - q0.add( new Integer( 0 )); - indexMap.put( q0, new Integer( 0 )); - //System.out.println("check out the indexMap!" + indexMap); - */ - - val visited_n = new TreeSet( new NpairComparator() ); - val rest = new Stack(); - - // right is "nearly deterministic" - // we can follow reverse traces paths by using dLeft.indexMap - - // start with right.initials, left.final, dLeft.final - val it = dLeft.finals.keySet().iterator(); - while(it.hasNext()) { - val fstate = it.next().asInstanceOf[Integer]; - val nfstate = invIndexMap.get( fstate ).asInstanceOf[TreeSet]; - //System.out.print( "final state:"+fstate); - //System.out.print( " correspond to set of states:"+ nfstate ); - - val min_ndstate: Integer = smallestFinal( left, nfstate ); - - val npair:Npair = new Npair( min_ndstate, nfstate ); - - //System.out.println( " smallest final of these: "+ min_ndstate ); - - - //System.out.println( "push final nfa state "+npair.toString( dLeft.indexMap )); - - if( !visited_n.contains( npair )) { - visited_n.add( npair ); - rest.push( npair ); - } - } - - val ratLab = new HashMap(); // maps nset to label,HashMap - val ratDelta = new HashMap(); // maps nset to Vector[ NP ]targets - - val ratDefault = new HashMap(); // maps nset to NP (one target) - - var ix = 1; - val ix_initial = rest.clone().asInstanceOf[Stack]; - var ix_final = new TreeSet( new NpairComparator() );; - - val newIndexMap = new TreeMap( new NpairComparator() ); - - while( !rest.isEmpty() ) { - - val npair = rest.pop().asInstanceOf[Npair]; - newIndexMap.put( npair, new Integer(ix)); - - ratDelta.put( npair, new Vector() ); - - if( npair.nset.contains( new Integer( 0 )) ) { - ix_final.add( npair ); - } - ix = ix + 1; - - //System.out.println(" popped "+npair.toString( dLeft.indexMap )); - - ////System.out.print(" binders: "); - ////System.out.print( right.qbinders[ npair.nstate.intValue() ] ); - - val delta = right.deltaq( npair.nstate ); - - ////System.out.print(" we could have arrived : "); - //search the delta for target invIndexMap - - val labelToNset = new HashMap(); - val labelToFrom = new HashMap(); - - // maps nsets to the active nstates - var nsrc = new TreeMap( new StateSetComparator() ); - - // berry-sethi construction assures that - // there is only one label for outgoing transitions - var theLabel:Label = null; - - // collect all transition possible in the DFA - val jt = delta.keySet().iterator(); - while(jt.hasNext()) { - val lab = jt.next().asInstanceOf[LPair]; - - // lab.state is the target in the NFA - - if( null == theLabel ) { - ratLab.put( npair, lab.lab ); - ////System.out.print(" with \""+lab.lab+"\" "); - } - theLabel = lab.lab ; - - ////System.out.print("\nfrom n" + lab.state +" ... "); - - // these are too many, filter out those that exist in DFA - - filterItOutQuoi( dLeft, npair, lab, nsrc ); - - } - - - ////System.out.println( "---" ); - - ////System.out.println("all sources: "); - - // !! first longest match - val ut = nsrc.keySet().iterator(); - while(ut.hasNext()) { - val nset = ut.next().asInstanceOf[TreeSet]; - val np2: Npair = nsrc.get( nset ).asInstanceOf[Npair] ; - - //assert( np2 != null ); - ////System.out.println("target: n"+npair.nstate+" via: "+theLabel+" from "+ np2.toString( dLeft.indexMap ));// nset:"+nset+ " namely state n"+ dest); - - val v = ratDelta.get( npair ).asInstanceOf[Vector]; - - v.add( np2 ); - - if( !visited_n.contains( np2 ) ) { - - visited_n.add( np2 ); - rest.push( np2 ); - } - - } - - //System.out.println("default sources: "); - - // maps nsets to the active nstates - nsrc = new TreeMap( new StateSetComparator() ); - - // now for all default transitions that arrive at this nfa state - val defqs = right.defaultq( npair.nstate ); - val kt = defqs.iterator(); - while( kt.hasNext() ) { - val nq = kt.next().asInstanceOf[Integer]; - //System.out.println("checking nq="+nq); - filterItOutQuoiDefault( dLeft, npair, nq, nsrc ); - //System.out.println( "nsrc after "+nq+" is "+nsrc ); - } - - //System.out.println( "defqs :"+defqs ); - //System.out.println( "nsrc :"+nsrc ); - var nut = nsrc.keySet().iterator(); - while(nut.hasNext()) { - - val np2 = nsrc.get( nut.next() ).asInstanceOf[Npair]; - - var v = ratDefault.get( npair ).asInstanceOf[Vector] ; - if( v == null ) - ratDefault.put( npair, {v = new Vector(); v} ); - v.add( np2 ); - - if( !visited_n.contains( np2 ) ) { - - visited_n.add( np2 ); - rest.push( np2 ); - } - - } - - ////System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"); - - } - - // Renumbering - - ////System.out.println( "output: a dfa with "+ix+"states"); - - // FIX: empty regular expression (as in "List()") is valid - //assert ( !ix_final.isEmpty() ) : "no final states found"; - - ////System.out.println( "final state:"+ix_final); - - //System.out.println( "indexMap: " +indexMap); - //System.out.println( "newIndexMap: " +newIndexMap); - this.finals = new TreeMap(); - this._nstates = ix; - val dratDelta = new Array[HashMap]( ix ); - qbinders = new Array[Vector]( ix ); - _labels = new HashSet(); - val kit = ratDelta.keySet().iterator(); - while(kit.hasNext()) { - val np = kit.next().asInstanceOf[Npair]; - - //System.out.print( "\nstate: "+np); - val ndset = np.nset; - val dstate = newIndexMap.get( np ).asInstanceOf[Integer]; - //assert dstate != null : "no dstate for "+np.toString(dLeft.indexMap); - - //System.out.print(" binders:"); - - qbinders( dstate.intValue() ) = left.qbinders( np.nstate.intValue() ); - - //System.out.print( qbinders[dstate.intValue() ]); - - //System.out.println(" transitions:"); - if( ix_final.contains( np ) ) { - val fin_ix = newIndexMap.get( np ).asInstanceOf[Integer]; - finals.put( fin_ix, new Integer( 0 )); - } - - val lab = ratLab.get( np ).asInstanceOf[Label]; - val v = ratDelta.get( np ).asInstanceOf[Vector]; - - val ddelta = new HashMap(); - - // v might be null if there are only default transitions - if( v != null ) { - val it2 = v.iterator(); - while(it2.hasNext()) { - - val np2= it2.next().asInstanceOf[Npair]; - //System.out.print( "("+lab+","+np2+") " ); - val ddestR = newIndexMap.get( np2 ).asInstanceOf[Integer]; - val ddest = indexMap.get( np2.nset ).asInstanceOf[Integer]; - //assert ddest != null : - //"no ddest for " - //+np2.toString(dLeft.indexMap); - - val newLab = new LPair(ddest, lab); - ddelta.put( newLab, ddestR ); - _labels.add( newLab ); - - } - dratDelta( dstate.intValue() ) = ddelta; - - } - } - var itt = ratDefault.keySet().iterator(); - while(itt.hasNext()) { - val np = itt.next().asInstanceOf[Npair]; - val dstate = newIndexMap.get( np ).asInstanceOf[Integer]; - - //System.out.print("\nstate: "+np+" default trans: "); - - val v = ratDefault.get( np ).asInstanceOf[Vector]; - val ut = v.iterator(); - while(ut.hasNext()) { - val np2 = ut.next().asInstanceOf[Npair]; - val targetL = indexMap.get( np2.nset ).asInstanceOf[Integer];; - val targetR = newIndexMap.get( np2 ).asInstanceOf[Integer];; - - val defLab = new LPair( targetL, DefaultLabel() ); - - _labels.add( defLab ); - //System.out.print( "("+defLab+","+np2+") " ); - - var d = dratDelta( dstate.intValue() ); - if( d == null ) - dratDelta( dstate.intValue() ) = {d = new HashMap(); d}; - - d.put( defLab, targetR ); - } - } - - _deltaq = dratDelta; - - val hmap = new HashMap(); - - // final states of left are initial states of right - // problem: still need to choose the one - - while( !ix_initial.isEmpty() ) { - val np = ix_initial.pop().asInstanceOf[Npair]; - - val i = newIndexMap.get( np ).asInstanceOf[Integer]; //R-state - val dtarget = indexMap.get( np.nset ).asInstanceOf[Integer];// left-d-state - - hmap.put( dtarget, i ); - } - _deltaq( 0 ) = hmap; // careful, this maps Int to Int - - qbinders( 0 ) = new Vector(); - //((Vector[])defaultq)[ 0 ] = new Vector(); is null - //printBeforeRAT( dratDelta ); - - } - - def printBeforeRAT1(str: String): Unit = { - val tmp = new StringBuffer( str ); - var j = tmp.length(); - while(j < 20) { - tmp.append(" "); - j = j + 1; - } - Console.println( tmp.toString() ); - } - - def printBeforeRAT( dratDelta: Array[HashMap] ): Unit = { - //System.out.println(); - printBeforeRAT1( "dratDelta" ); - printBeforeRAT1( "[index]" ); - //System.out.println(); - var i = 0; - while(i < dratDelta.length) { - if( isFinal( i )) - printBeforeRAT1( "*"+i ); - else - printBeforeRAT1( " "+i ); - - //System.out.println( dratDelta[ i ] ); - i = i + 1 - } - } - - /** you may only call this before the set[set[...]] representation - * gets flattened. - */ - def printBefore(states: TreeSet, deftrans: HashMap): Unit = { - var trans: HashMap = null; - Console.println(states); - val it = states.iterator(); - while (it.hasNext()) { - val state = it.next().asInstanceOf[TreeSet]; - Console.print("state:" + state.toString() + " transitions "); - trans = delta/*Map*/.get( state ).asInstanceOf[HashMap]; - val labs = _labels.iterator(); - while(labs.hasNext()) { - val label = labs.next(); - val target = trans.get( label ).asInstanceOf[TreeSet]; - Console.print( " (" + label.toString() - + "," + target.toString()+")"); - } - Console.print("default trans"+deftrans.get(state)); - Console.println; - } - Console.println("final states:" + finals); - } -} - -} diff --git a/sources/scala/tools/nsc/matching/LeftTracers.scala b/sources/scala/tools/nsc/matching/LeftTracers.scala deleted file mode 100644 index b58e11b4cb..0000000000 --- a/sources/scala/tools/nsc/matching/LeftTracers.scala +++ /dev/null @@ -1,232 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ - -package scala.tools.nsc.matching; - -import java.util._ ; - -import scala.tools.nsc.util.Position; - -trait LeftTracers: TransMatcher { - -import global._; - -abstract class LeftTracerInScala extends Autom2Scala { - - val selector: Tree; - val elementType: Type; - - /** symbol of the accumulator ( scala.SequenceList ) - */ - var accumSym: Symbol = _; - var accumType: Type = _; - var accumTypeArg: Type =_ ; - - def _accumType(elemType: Type): Type = { - SeqTraceType( elemType ); - } - - protected def initializeSyms(): Unit = { - this.funSym = owner.newLabel( pos, fresh.newName( "left" )); - - this.iterSym = owner.newVariable( pos, fresh.newName( "iter" )) - .setInfo( _seqIterType( elementType ) ) ; - - this.stateSym = owner.newVariable( pos, fresh.newName( "q" )) - .setInfo( definitions.IntClass.info ) ; - - this.accumType = _accumType( elementType ); - this.accumTypeArg = accumType.typeArgs( 0 ); - this.accumSym = owner.newVariable( pos, // accumulator - fresh.newName( "acc" )) - .setInfo( accumType ); - - //this.funSym - // .setInfo( new MethodType( new Symbol[] { - // accumSym, iterSym, stateSym}, - // accumType)); - - this.funSym.setInfo( - MethodType( - scala.List ( // dummy symbol MethodType - definitions.IntClass.info, - accumType - ), - accumType) - ); - - //funSym.newValueParameter( pos, fresh.newName( "q" )) - //.setInfo(definitions.IntClass.info), - //funSym.newValueParameter( pos, fresh.newName( "acc" )) - //.setInfo( accumType ) ), - // accumType)); // result type = List[T] - - this.resultSym = owner.newVariable(pos, fresh.newName("trace")) - .setInfo( accumType ) ; - - this.curSym = owner.newVariable( pos, "cur" ) - .setInfo( elementType ); - - this.hasnSym = owner.newVariable( pos, nme.hasNext ) - .setInfo( definitions.BooleanClass.info ); - - } - - /* should throw an exception here really, e.g. MatchError - */ - override def code_fail() = Ident( accumSym ); - - /** returns translation of transition with label from i. - * returns null if there is no such transition(no translation needed) - */ - override def code_delta(i: Int, label: Label): Tree = { - val target = dfa.delta( i, label ); - - /* - System.out.println("LeftTracer:calling dfa.delta("+i+","+label+")"); - System.out.println("result: "+target); - */ - if( target == null ) - null; - else { - // (optimization) that one is a dead state (does not make sense for tracer) - /* - if( target == dfa.nstates - 1 ) - return code_fail(); - */ - - /* - Tree newAcc = newSeqTraceCons(new Integer(i), - currentElem(), - _ref( accumSym )); - */ - val hd = gen.mkNewPair( Literal(i), currentElem() ); - - val newAcc = gen.mkNewCons(hd, Ident(accumSym )); - - //return callFun( new Tree[] { newAcc , _iter(), mkIntLit( pos, target )} ); - callFun( scala.List( Literal(target.intValue() ), newAcc ) ); - } - } - - - def code_body(): Tree = { - - var body = code_error(); // never reached at runtime. - - // state [ nstates-1 ] is the dead state, so we skip it - - //`if( state == q ) else {...}' - var i = dfa.nstates() - 2; - while (i >= 0) { - body = code_state(i, body); - i = i - 1; - } - loadCurrentElem(body); - } - - /** return code for state i of the dfa SAME AS IN SUPER, ONLY SINK IS GONE - */ - def code_state(i: Int, elseBody: Tree): Tree = { - - var runFinished: Tree = null; // holds result of the run - var finalSwRes: Int = 0; - - runFinished = run_finished(i); - - var stateBody: Tree = null ; // action(delta) for one particular label/test - - // default action (fail if there is none) - - stateBody = code_delta( i, DefaultLabel()); - - if( stateBody == null ) - stateBody = code_fail(); - // transitions of state i - - val trans = dfa.deltaq( i ); - val labs = dfa.deltaq( i ).keySet().iterator(); - while(labs.hasNext()) { - val label = labs.next(); - val next = trans.get( label ).asInstanceOf[Integer]; - - val action = code_delta( i, label.asInstanceOf[Label] ); - - if( action != null ) { - stateBody = If( currentMatches(label.asInstanceOf[Label]), - action, - stateBody); - } - } - stateBody = If(Negate(Ident(hasnSym)), - runFinished, - stateBody ); - If( Equals( _state(), Literal( i )), - stateBody , - elseBody ); - } - - def getTrace(): Tree = { - - initializeSyms(); - - Block(scala.List( - ValDef( iterSym, newIterator( selector )), - ValDef( stateSym, Literal( 0 ) ), - ValDef( accumSym, gen.mkNil /*mkNil( pos )*/), - ValDef( resultSym, - LabelDef( this.funSym, - scala.List ( - stateSym, - accumSym - ), code_body() /* code_body_new ? */ )) - ), - Ident( resultSym )); - } - - // calling the AlgebraicMatcher here - override def _cur_match(pat: Tree): Tree = { - //return mkBooleanLit(pos, true); - - //System.out.println("calling algebraic matcher on type:" + pat.type); - - val m = new PartialMatcher { - val owner = LeftTracerInScala.this.owner; - val selector = currentElem(); - - // result type definitions.BooleanClass.info ); - } - - pat match { - case Sequence(pats) if containsBinding(pat) => - //scala.Predef.error("should not happen?!"); - null; // Literal(true); ?! - case _ => - am.construct(m, scala.List ( - CaseDef( pat, Literal( true )), - CaseDef( Ident( nme.WILDCARD ), Literal(false)) ), - false); - am.toTree(); - } - } - - - /** return the accumulator + last state - */ - override def run_finished(state: Int): Tree = { - val hd = gen.mkNewPair( Literal(state), EmptyTree); - //System.err.println(hd.type); - gen.mkNewCons(hd, Ident( accumSym )); -/* - mkNewCons(pos, - accumTypeArg, - hd, - Ident( accumSym )); -*/ - } - -} // TracerInScala -} // LeftTracers diff --git a/sources/scala/tools/nsc/matching/MatcherLabels.scala b/sources/scala/tools/nsc/matching/MatcherLabels.scala deleted file mode 100644 index 06c8cd2baa..0000000000 --- a/sources/scala/tools/nsc/matching/MatcherLabels.scala +++ /dev/null @@ -1,126 +0,0 @@ -package scala.tools.nsc.matching ; - -[_trait_] abstract class MatcherLabels: TransMatcher { - - import global._ ; - - /** - * This class represents the label that a transition in an automaton - * may carry. These get translated to specific (boolean) tests - */ - - class Label { - - //case class RLabel(Object rstate, Label lab, Symbol vars[]); - - override def hashCode(): Int = this match { - case DefaultLabel() => - return 0; - case SimpleLabel(lit) => - return lit.value.hashCode(); - case TreeLabel(pat) => - // if pat is an Apply, than this case can only be correctly - // handled there are no other similar Applys (nondeterminism) - return pat.tpe.hashCode(); - case TypeLabel(tpe) => - return tpe.hashCode(); - case _ => - return super.hashCode(); - } - - override def equals( o: Any ): Boolean = { - if( !(o.isInstanceOf[Label] )) - return false; - val oL = o.asInstanceOf[Label]; - //System.out.print(this + " equals " + oL); - this match { - case DefaultLabel()=> - oL match { - case DefaultLabel() => - return true; - case _ => false; - } // - case SimpleLabel( lit ) => - oL match { - case SimpleLabel( lit2 ) => - return (/*(lit.kind == lit2.kind) - && */lit.value.equals( lit2.value )); - case _ => false; - } - - case TreeLabel( pat ) => - oL match { - case TreeLabel( pat2 ) => - pat match { - case Apply( _, _ ) => - pat2 match { - case Apply( _, _ ) => - return (treeInfo.methPart/*methSymbol?*/( pat ) - == treeInfo.methPart/*methSymbol*/( pat2 )); - } - case _ => false; - } - case _ => false - } - - case TypeLabel(tpe) => - oL match { - case TypeLabel( tpe2) => - return tpe.equals(tpe2); - case _ => false; - } - case LPair(state, lab) => - oL match { - case LPair(state2, lab2) => - return state.equals(state2) && lab.equals(lab2); - case _ => false; - } - case _ => return false; - } - } - - - def toString2(): String = { - val ext = System.getProperty("extendedMatching"); - if ((ext != null) && ext.equals("true")) { - this match { - case DefaultLabel() => - return "<>:p"+p; - case SimpleLabel( lit ) => - return lit.toString()+":p"+p; - case TreeLabel( pat ) => - return pat.tpe.toString()+":p"+p; - - case _ => scala.Predef.error("this never happens"); - } - } - scala.Predef.error("this never happens"); - } - - override def toString(): String = this match { - case DefaultLabel() => - "<>"; - case SimpleLabel( lit) => - lit.toString(); - case TreeLabel(pat) => - pat.toString(); - case TypeLabel(tpe) => - tpe.toString(); - case LPair(state, lab) => - "(" + state.toString() + "," + lab.toString() + ")"; - case _ => - scala.Predef.error("this never happens"); - } - - val p = -1; // tree state - only needed for extended matching - -} - - case class DefaultLabel() extends Label; - case class SimpleLabel(lit: Literal) extends Label; - case class TreeLabel(pat: Tree) extends Label; // Apply, Sequence - case class TypeLabel(tpe: Type) extends Label; // Apply, Sequence - case class LPair(state: Integer, lab: Label) extends Label; - -} - diff --git a/sources/scala/tools/nsc/matching/NondetWordAutoms.scala b/sources/scala/tools/nsc/matching/NondetWordAutoms.scala deleted file mode 100644 index cd1d8b576e..0000000000 --- a/sources/scala/tools/nsc/matching/NondetWordAutoms.scala +++ /dev/null @@ -1,522 +0,0 @@ -package scala.tools.nsc.matching ; -import java.util._ ; - -trait NondetWordAutoms { -/** a nondeterministic word automaton. - * states are represented (implicitly) as Integer objects. - */ -class NondetWordAutom { - // BEGIN stuff from FiniteAutom - - //final static Integer FINTAG = new Integer(0); - - /** number of states */ - var nstates: int =_; - - /** the 'alphabet' */ - var labels: HashSet = _; - - /** the set of final states, here as a TreeMap */ - var finals: TreeMap = _; - - /** dfa: HashMap trans: Object -> Integer - * nfa: HashMap trans: Object -> Vector [ Integer ] - * - * nfa: Integer ->(Object -> Vector [ Int ]) - * [q] |->( a |-> { q' | (q,a,q') in \deltaright } ) - * - * dfa: Integer ->(Object -> Int) - * [q] |->( a |-> q' | \deltaright(q,a) = q' } ) - */ - - var _deltaq:Array[HashMap] = _; - - var _defaultq:Array[Vector] = _; // this gives the default transitions - - //public HashMap deltaq[]; - - // --- accessor methods - - /** returns number of states - def nstates(): int = { - return nstates; - } - */ - - /** returns the labels - def labels(): HashSet = { - return _labels; - } - */ - - /** returns the transitions - */ - def deltaq( state: int ):HashMap = { - return _deltaq( state ); - } - - /** returns the transitions - */ - def deltaq( state: Integer ): HashMap = { - return _deltaq( state.intValue() ); - } - - /** returns the transitions - */ - def defaultq( state: int ): Vector = { - return _defaultq( state ); - } - - /** returns the transitions - */ - def defaultq( state:Integer ): Vector = { - return _defaultq( state.intValue() ); - } - - - /** returns true if the state is final - */ - def isFinal( state:int ): boolean = { - return ((finals != null) - && (finals.get( new Integer( state )) != null)); - } - - /** returns true if the state is final - */ - def isFinal( state:Integer ): boolean = { - return ((finals != null) && finals.containsKey( state )); - } - - /** returns true if the state is final - */ - def finalTag( state: Integer ): Integer = { - return finals.get( state ).asInstanceOf[Integer]; - } - - - def finalTag( state:int ): Integer = { - return finals.get( new Integer (state )).asInstanceOf[Integer]; - } - - /** returns true if the set of states contains at least one final state - */ - def containsFinal( Q:TreeSet ): boolean = { - var it = Q.iterator(); - while(it.hasNext()) { - if( isFinal( it.next().asInstanceOf[Integer])) - return true; - } - return false; - } - - - /** returns true if there are no finite states - */ - def isEmpty(): boolean = finals.isEmpty(); - - // END stuff from FiniteAutom - - - // inherited from FiniteAutom - - // set of *distinct* objects that may label transitions - // see Object.hashCode() to see why this works - - //HashSet labels; - //TreeMap finals; - - var initials: TreeSet = _; // ? need this ? - // --- - - // Object deltaq --> - // HashMap deltaq[]; // this gives the transitions of q; - - var leftTrans: boolean = _; - var rightTrans: boolean = _; - - /** if true, this automaton behaves as a special left transducer. - * if a run succeeds, the result is not "true" but the entire - * run of the automaton as a sequence of (label,state) - pairs. - * used for binding variables. - */ - def producesRun(): boolean = { - return leftTrans; - } - - def consumesRun(): boolean = { - return rightTrans; - } - - def initial( i: Integer ): boolean = { - return initials.contains( i ); - } - var qbinders: Array[Vector] = _; - - /** returns all states accessible from Qsrc via label. - * used by class DetWordAutomaton. - */ - def getSide ( Qsrc:TreeSet , label:Object ): TreeSet = { - //Console.println("NWA::getSide(Qsrc="+Qsrc); - val Qdest = new TreeSet(); - var it = Qsrc.iterator(); - while(it.hasNext()) {// state - val q = it.next().asInstanceOf[Integer].intValue(); - val ps = deltaq( q ).get( label ).asInstanceOf[Vector]; - //Console.println("deltaq(q) = "+deltaq(q)); - //Console.println("_deltaq(q) = "+_deltaq(q)); - //Console.println("ps = "+ps); - if( null != ps ) { - Qdest.addAll( ps ); - } - //Console.println("defq = "+_defaultq( q )); - Qdest.addAll( _defaultq( q ) ); - } - //Console.println("DONE-NWA::getSide"); - return Qdest; - } - - /** returns the transitions - */ - def defaultq( P1: Set ): Object = { - val defTarget = new TreeSet(); - var p1 = P1.iterator(); - while(p1.hasNext()) { - val q1 = p1.next().asInstanceOf[Integer].intValue(); - //System.out.println(" q1:"+q1+ " defa: "+defaultq( q1 )); - defTarget.addAll( _defaultq( q1 ) ); - } - return defTarget; - } - - - /** first match policy: among several final states, the smallest one is - * chosen. used by class DetWordAutomaton - */ - def finalTag( Q:Set ): Integer = { - - var min = Integer.MAX_VALUE ; - var it = Q.iterator(); - while(it.hasNext()) { - val state = it.next().asInstanceOf[Integer]; - val tag = finals.get( state ).asInstanceOf[Integer]; - if( tag != null ) { - if( tag.intValue() < min ) - min = tag.intValue(); - } - } - - if ( min == Integer.MAX_VALUE ) - scala.Predef.error( "there should be a final state "); - - return new Integer( min ); - } - - /* - void tmap(int offs, TreeMap t) = { - TreeMap nt = new TreeMap(); - for(Iterator it = t.keySet().iterator(); it.hasNext(); ) = { - Integer key = (Integer) it.next(); - Integer newkey = new Integer( key.intValue() + offs ); - Integer val = (Integer) t.get( key ); - Integer newval = new Integer( val.intValue() + offs ); - - nt.put( newkey, newval ); - } - return nt; - } - */ - // hashmaps, treemaps - def mapmap(src:Map, offset:int , dest:Map , mapkeys:boolean , mapvals:boolean ): Map = { - var it = src.keySet().iterator(); - while(it.hasNext()) { - var key = it.next(); - var value = src.get( key ); - if( mapkeys ) key = new Integer( key.asInstanceOf[Integer].intValue() - + offset ); - if( mapvals ) value = vmap( offset, value.asInstanceOf[Vector] ) ; - /* new Integer( ((Integer)val).intValue() - + offset ); - */ - dest.put( key, value ); - } - return dest; - } - - def vmap(offs:int , v:Vector ): Vector = { - if( v == null ) - return null; - var res = new Vector( v.size() ); - var it = v.iterator(); - while(it.hasNext()) { - val item = it.next().asInstanceOf[Integer]; - res.add( new Integer( item.intValue() + offs )); - } - return res; - - } - - /* - void relocate_defaultq( int offs, Vector _defaultq[] ) = { - for( int i = 0; i < this.nstates; i++ ) = { - _defaultq[ i + offset ] = vmap( offset, ((Vector[])defaultq)[ i ]); - } - } - */ - - /** copies the values in the fields of this object into the - * arguments, possibly adding an offset. - */ - def relocate( offset:int, _finals:TreeMap, _deltaq1:Array[HashMap], _defaultq1:Array[Vector], _qbinders1:Array[Vector] ): Unit = { - - mapmap( finals, offset, _finals, true, false); - var i = 0; - while(i < this.nstates) { - - _deltaq1 ( i + offset ) = - mapmap( deltaq( i ), offset, new HashMap(), false, true).asInstanceOf[HashMap]; - - _defaultq1( i + offset ) = vmap( offset, this.defaultq( i ) ); - i = i + 1; - } - if ((_qbinders1 != null) &&( qbinders != null )) { - i = 0; - while(i < this.nstates ) { - //System.out.println("hallo"+qbinders); - //System.out.println("qbinders[ i ] :"+qbinders[ i ]); - //assert _qbinders != null; - //System.out.println("_qbinders :"+_qbinders); - - _qbinders1( i + offset ) = qbinders( i ); - i = i + 1 - } - } - } - - - /** if there is more than one initial state, a new initial state - * is created, with index 0 - */ - def normalize( initials:TreeSet , reloc:boolean ): Unit = { - //if( initials.size() == 1 ) - // return; - - var idelta = new HashMap(); - var idefault = new TreeSet(); - - var q0 = new Integer( 0 ); - - var it = initials.iterator(); - while(it.hasNext()) { - - val ostate = it.next().asInstanceOf[Integer]; - - val finTag = finals.get( ostate ).asInstanceOf[Integer] ; - if(( finTag != null ) && ( finals.get( q0 ) == null)) - finals.put( q0, finTag ); - - - var tmp = deltaq( ostate ); - - if( reloc ) - tmp = mapmap( tmp, 1, new HashMap(), false, true ).asInstanceOf[HashMap]; - - val labs = tmp.keySet().iterator(); - while(labs.hasNext()) { - val lab = labs.next(); - var itarget = idelta.get( lab ).asInstanceOf[Vector]; - if( null == itarget ) - idelta.put( lab, {itarget = new Vector(); itarget}); - val otarget = tmp.get( lab ).asInstanceOf[Vector]; - itarget.addAll( otarget ); - } - //System.out.println( "normalize:defaultq[ "+ostate+" ] "+((Vector[]) defaultq) [ ostate.intValue() ]); - if( defaultq( ostate ) != null ) - idefault.addAll( defaultq( ostate ) ); - } - - if( reloc ) { - val m = 1 + this.nstates; - val _finals = new TreeMap(); - val _deltaq = new Array[HashMap]( m ); - val _defaultq = new Array[Vector]( m ); - var _qbinders: Array[Vector] = null; - - if( qbinders != null ) - _qbinders = new Array[Vector]( m ); - - relocate( 1, _finals, _deltaq, _defaultq, _qbinders ); - - this.nstates = m; - this.finals = _finals; - this._deltaq = _deltaq; - this._defaultq = _defaultq; - this.qbinders = _qbinders; - } - - this._deltaq ( 0 ) = idelta; - //System.out.println("normalize:deltaq[ 0 ]"+ idelta ); - this._defaultq( 0 ) = new Vector( idefault ); - - //System.out.println("normalize:defaultq[ 0 ]"+ idefault ); - - this.initials = new TreeSet(); - this.initials.add( q0 ); - } - - - /** called from Berry-Sethi construction. - */ - - def this(nstates:int, _labels:HashSet, initials: TreeSet, finals:TreeMap, deltaq:Array[HashMap], defaultq:Array[Vector], qbinders:Object ) = { - this(); - //Console.println("NWA::this(. . . . )"); - this.nstates = nstates; - this.labels = _labels; - this.initials = initials; - this.finals = finals; - this._deltaq = deltaq; - this._defaultq = defaultq; - this.qbinders = qbinders.asInstanceOf[Array[Vector]]; - //print(); - //System.exit(0); - } - - - - var offset:Array[int] = _; // only used if constructed from multiple - - def collectLabels( nfa:Array[NondetWordAutom ] ): Unit = { - this.labels = new HashSet(); - var i = 0; - while(i < nfa.length) { - this.labels.addAll( nfa( i ).labels ); - i = i + 1 - } - } - - def collectOffsets( nfa:Array[NondetWordAutom] ): Unit = { - this.offset = new Array[int]( nfa.length + 1 ); - offset( 0 ) = 1; // we have a new initial state - var i = 0; - while(i < nfa.length ) { - offset( i + 1 ) = nfa( i ).nstates + offset( i ); - i = i + 1 - } - } - - /** collapses several normalized NondetWordAutom objects into one. - */ - - def this( nfa: Array[NondetWordAutom] ) = { - this(); - //Console.println("NWA::this(.)"); - - //this.m - val m = nfa.length; - //System.out.println("enter NondetWordSwitch, " - // +"combining " + m + " automata"); - - collectLabels( nfa ); - collectOffsets( nfa ); - - //Console.println(" X 1"); - - - this.nstates = offset( nfa.length ); //m - 1 ] + nfa[ m - 1 ].nstates; - - - this.finals = new TreeMap(); - - this.qbinders = new Array[Vector]( nstates ); - - // new initial state gets all transitions from all initial states - - this._deltaq = new Array[HashMap]( nstates ); - this._defaultq = new Array[Vector]( nstates ); - //Console.println(" X 2"); - - //TreeSet defaultqSet = new TreeSet(); - _deltaq( 0 ) = new HashMap(); // 0 = our new initial state - - val initials = new TreeSet(); - - var i = 0; - while(i < m) { - //System.out.println("i (current NFA):"+i); - - val n = nfa( i ); - - val offs = offset( i ); - - initials.add( new Integer( offs )); - - n.relocate( offs, - this.finals, - this._deltaq, - this._defaultq, - this.qbinders ); - i = i + 1; - } - - normalize( initials, false ); - //Console.println("Leave-NWA::this(.)"); - } - - - - - def print(): Unit = { - - Console.print("NFA on labels "+ this.labels); - - if( offset != null ) { - Console.print("offset"); - var k = 0; - while(k < offset.length) { - if( k > 0) - Console.print(", "); - Console.print(offset(k)); - k = k + 1; - } - } - Console.println; - - Console.print("max state number :" + (nstates - 1) ); - - Console.println("initials" + initials); - - Console.println("finals" + finals); - - var i = 0; - while(i < nstates) { - Console.print("state: " + i); - if( finals.containsKey( new Integer( i )) ){ - Console.print("*"); //final - } - Console.print(" transitions: {"); - var arrows:HashMap = deltaq( i ); - - var it = arrows.keySet().iterator(); - while(it.hasNext()) { - val label = it.next(); - val targets = arrows.get( label ).asInstanceOf[Vector]; - val jt = targets.iterator(); - while(jt.hasNext()) { - val p = jt.next().asInstanceOf[Integer]; - Console.print("("+label+","+p+")"); - } - } - - Console.print("} "); - Console.print(" default transitions: "+_defaultq( i )); - if( null != qbinders ) - Console.println(" binders "+qbinders( i )); - Console.println; - i = i + 1; - } - } - - -} - -} diff --git a/sources/scala/tools/nsc/matching/Npair.scala b/sources/scala/tools/nsc/matching/Npair.scala deleted file mode 100644 index 8cb050de2e..0000000000 --- a/sources/scala/tools/nsc/matching/Npair.scala +++ /dev/null @@ -1,64 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ -package scala.tools.nsc.matching ; - -import java.util.{ HashMap, TreeSet }; -/** cartesian - */ - -/** Int x TreeSet[ Int ] - */ -case class Npair(nstate: Integer, nset: TreeSet) { - - override def equals(that: Any): Boolean = { - this match { - case Npair(nstate, nset) => - that match { - case Npair(_nstate, _nset) => - return ((nstate == _nstate) - && (nset == _nset)); - case _ => return false - } - case _ => return false - } - } - - override def toString(): String = this match { - case Npair(nstate, nset) => - //Integer dstate = (Integer) indexMap.get(nset); - ""; - case _ => null - } - - def toString(indexMap: HashMap): String = { - //assert indexMap != null; - this match { - case Npair(nstate, nset) => - //assert nstate != null; - val dstate = indexMap.get( nset ).asInstanceOf[Integer]; - return ""; - case _ => - return null; - } - } - - -} - -class NpairComparator extends StateSetComparator { - override def compare(o1: Any, o2: Any): Int = { - o1 match { - case Npair(nstate, nset) => o2 match { - case Npair(_nstate, _nset) => - val res = nstate.compareTo(_nstate); - if (res != 0) - return res; - else - return super.compare(nset, _nset); - } - } - } -} diff --git a/sources/scala/tools/nsc/matching/PatternMatchers.scala b/sources/scala/tools/nsc/matching/PatternMatchers.scala deleted file mode 100644 index 7d4292e3ff..0000000000 --- a/sources/scala/tools/nsc/matching/PatternMatchers.scala +++ /dev/null @@ -1,992 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ - -package scala.tools.nsc.matching ; - -import scala.tools.nsc.util.Position; - -trait PatternMatchers: (TransMatcher with PatternNodes) extends AnyRef with PatternNodeCreator { - - - import global._; - import typer.typed ; - import symtab.Flags; - - class PatternMatcher { - - - - protected var optimize = true; - protected var delegateSequenceMatching = false; - protected var doBinding = true; - - /** the owner of the pattern matching expression - */ - var owner:Symbol = _ ; - - /** the selector expression - */ - protected var selector: Tree = _; - - /** the root of the pattern node structure - */ - protected var root: PatternNode = _; - - /** the symbol of the result variable - */ -// protected var resultVar: Symbol = _; - - def defs = definitions; - /** init method, also needed in subclass AlgebraicMatcher - */ - def initialize(selector: Tree, owner: Symbol, doBinding: Boolean): Unit = { - - //Console.println("pm.initialize selector.tpe = "+selector.tpe); - - /* - this.mk = new PatternNodeCreator { - val global = PatternMatcher.this.global; - val unit = PatternMatcher.this.unit; - val owner = PatternMatcher.this.owner; - } - */ - /* - this.cf = new CodeFactory { - val global = PatternMatcher.this.global; - val unit = PatternMatcher.this.unit; - val owner = PatternMatcher.this.owner; - } - */ - this.root = pConstrPat(selector.pos, selector.tpe.widen); - //Console.println("selector.tpe "+selector.tpe); - //Console.println("selector.tpe.widen "+selector.tpe.widen); - //Console.println("root.symbol "+root.symbol); - //Console.println("root.symbol.tpe "+root.symbol.tpe); - this.root.and = pHeader(selector.pos, - selector.tpe.widen, - Ident(root.symbol).setType(root.tpe)); - //Console.println("resultType = "+resultType); - this.owner = owner; - this.selector = selector; - - this.optimize = this.optimize && (settings.target.value == "jvm"); - this.doBinding = doBinding; - } - - /** pretty printer - */ - def print(): Unit = { Console.println ( - root.and.print("", new StringBuffer()).toString() - )} - - /** enters a sequence of cases into the pattern matcher - */ - def construct(cases: List[Tree]): Unit = { - cases foreach enter; - } - - /** enter a single case into the pattern matcher - */ - protected def enter(caseDef: Tree): Unit = { - caseDef match { - case CaseDef(pat, guard, body) => - val env = new CaseEnv; - // PatternNode matched = match(pat, root); - val target = enter1(pat, -1, root, root.symbol, env); - // if (target.and != null) - // unit.error(pat.pos, "duplicate case"); - if (null == target.and) - target.and = pBody(caseDef.pos, env.getBoundVars(), guard, body); - else if (target.and.isInstanceOf[Body]) - updateBody(target.and.asInstanceOf[Body], env.getBoundVars(), guard, body); - else - cunit.error(pat.pos, "duplicate case"); - } - } - - protected def updateBody(tree: Body, bound: Array[ValDef], guard: Tree , body: Tree): Unit = { - if (tree.guard(tree.guard.length - 1) == EmptyTree) { - //unit.error(body.pos, "unreachable code"); - } else { - val bd = new Array[Array[ValDef]](tree.bound.length + 1); - val ng = new Array[Tree](tree.guard.length + 1); - val nb = new Array[Tree](tree.body.length + 1); - System.arraycopy(tree.bound, 0, bd, 0, tree.bound.length); - System.arraycopy(tree.guard, 0, ng, 0, tree.guard.length); - System.arraycopy(tree.body, 0, nb, 0, tree.body.length); - bd(bd.length - 1) = bound; - ng(ng.length - 1) = guard; - nb(nb.length - 1) = body; - tree.bound = bd ; - tree.guard = ng ; - tree.body = nb ; - } - } - - protected def patternArgs(tree: Tree):List[Tree] = { - tree match { - case Bind(_, pat) => - patternArgs(pat); - case Apply(_, args) => - if ( isSeqApply(tree.asInstanceOf[Apply]) && !delegateSequenceMatching) - args(0) match { - case ArrayValue(_, ts) => // test array values - ts; - //case Sequence(ts) => - // ts; - case _ => - args; - } - else args - case Sequence(ts) if (!delegateSequenceMatching) => - ts; - case ArrayValue(_, ts) => // test array values - ts; - case _ => - List(); - } - } - - /** returns true if apply is a "sequence apply". analyzer inserts Sequence nodes if something is a - * - * - last update: discussion with Martin 2005-02-18 - * - * - if true, tree.fn must be ignored. The analyzer ensures that the selector will be a subtype - * of fn; it thus assigns the expected type from the context (which is surely a subtype, - * but may have different flags etc. - * - * - so should be - * (( tree.args.length == 1 ) && tree.args(0).isInstanceOf[Sequence]) - * but fails - */ - protected def isSeqApply( tree: Apply ): Boolean = { - // Console.print("isSeqApply? "+tree.toString()); - // val res = - tree match { - case Apply(_, List(ArrayValue(_,_))) => (tree.tpe.symbol.flags & Flags.CASE) == 0 - case _ => false; - } - //Console.println(res); - //res; - } - - protected def patternNode(tree:Tree , header:Header , env: CaseEnv ): PatternNode = { - //if(tree!=null) Console.println("patternNode("+tree+","+header+")"); - //else scala.Predef.error("got null tree in patternNode"); - //Console.println("tree.tpe "+tree.tpe); - //Console.println("tree.getClass() "+tree.getClass()); - tree match { - case Bind(name, Typed(Ident( nme.WILDCARD ), tpe)) => // x@_:Type - if (isSubType(header.getTpe(),tpe.tpe)) { - //Console.println("U"); - val node = pDefaultPat(tree.pos, tpe.tpe); - env.newBoundVar( tree.symbol, tree.tpe, header.selector ); - node; - } else { - //Console.println("X"); - val node = pConstrPat(tree.pos, tpe.tpe); - env.newBoundVar( tree.symbol, - tpe.tpe /*scalac: tree.tpe */, - typed(Ident( node.casted ))); - node; - } - - case Bind(name, Ident(nme.WILDCARD)) => // x @ _ - val node = pDefaultPat(tree.pos, header.getTpe()); - if ((env != null) && (tree.symbol != defs.PatternWildcard)) - env.newBoundVar( tree.symbol, tree.tpe, header.selector); - node; - - case Bind(name, pat) => - val node = patternNode(pat, header, env); - if ((env != null) && (tree.symbol != defs.PatternWildcard)) { - val casted = node.symbol; - val theValue = if (casted == NoSymbol) header.selector else Ident( casted).setType(casted.tpe); - env.newBoundVar(tree.symbol, tree.tpe, theValue); - } - node; - - case t @ Apply(fn, args) => // pattern with args - //Console.println("Apply!"); - //Console.println("isSeqApply "+isSeqApply(t)); - //Console.println("delegateSequenceMatching "+delegateSequenceMatching); - if (isSeqApply(t)) { - if (!delegateSequenceMatching) { - args(0) match { - // case Sequence(ts)=> - case ArrayValue(_, ts)=> - //Console.println("doing pSeqpat "); - val res = pSequencePat(tree.pos, tree.tpe, ts.length); - //Console.println("pSeqpat.casted = "+res.casted); - //Console.println("pSeqpat.casted.pos = "+res.casted.pos); - res - } - } else { - //Console.println("delegating ... "); - val res = pConstrPat(tree.pos, tree.tpe); - res.and = pHeader(tree.pos, header.getTpe(), header.selector); - //res.and.and = pSeqContainerPat(tree.pos, tree.tpe, args(0)); - res.and.and = pSeqContainerPat(tree.pos, tree.tpe, Sequence(args(0).asInstanceOf[ArrayValue].elems)); - res; - } - } else if ((fn.symbol != null) && - fn.symbol.isStable && - !(fn.symbol.isModule && - ((fn.symbol.flags & Flags.CASE) != 0))) { - pVariablePat(tree.pos, tree); - } - else { - /* - Console.println("apply but not seqApply"); - Console.println("tree.tpe="+tree.tpe); - Console.println("tree.symbol="+tree.symbol); - */ - pConstrPat(tree.pos, tree.tpe); - } - case Typed(Ident( nme.WILDCARD ), tpe) => // x@_:Type - val doTest = isSubType(header.getTpe(),tpe.tpe); - if(doTest) - pDefaultPat(tree.pos, tpe.tpe) - else - pConstrPat(tree.pos, tpe.tpe); - - case t @ Typed(ident, tpe) => // variable pattern - //Console.println("Z"); - val doTest = isSubType(header.getTpe(),tpe.tpe); - val node = { - if(doTest) - pDefaultPat(tree.pos, tpe.tpe) - else - pConstrPat(tree.pos, tpe.tpe); - } - //if(t.expr.symbol == NoSymbol) { - // Console.println(t.toString()); - // scala.Predef.error("go typed pattern with no symbol in "+cunit.toString()); - // } - if ((null != env) /* && (ident.symbol != defs.PatternWildcard) */) - node match { - case ConstrPat(casted) => - env.newBoundVar(t.expr.symbol, - tpe.tpe, - Ident( casted ).setType(casted.tpe)); - case _ => - env.newBoundVar(t.expr.symbol, - tpe.tpe, - {if(doTest) - header.selector - else - typed(Ident(node - .asInstanceOf[ConstrPat] - .casted))}); - } - node; - - case Ident(nme.WILDCARD) => - pDefaultPat(tree.pos, header.getTpe()); - - case Ident(name) => // pattern without args or variable - - // nsc: wildcard's don't have symbols anymore! - //if (tree.symbol == defs.PatternWildcard) - // pDefaultPat(tree.pos, header.getTpe()); - //else - - if (tree.symbol.isPrimaryConstructor) { - scala.Predef.error("error may not happen: ident is primary constructor"+tree.symbol); // Burak - - } else if (treeInfo.isVariableName(name)) {// Burak - //old scalac - scala.Predef.error("this may not happen"); // Burak - - //nsc: desugarize (in case nsc does not do it) - /* - Console.println("Ident("+name+") in unit"+cunit); - Console.println("tree.symbol = "+tree.symbol); - // = treat the same as Bind(name, _) - val node = pDefaultPat(tree.pos, header.getTpe()); - if ((env != null) && (tree.symbol != defs.PatternWildcard)) - env.newBoundVar( tree.symbol, tree.tpe, header.selector); - node; - */ - } else - pVariablePat(tree.pos, tree); // a named constant Foo - - case Select(_, name) => // variable - if (tree.symbol.isPrimaryConstructor) - pConstrPat(tree.pos, tree.tpe); - else - pVariablePat(tree.pos, tree); - - case Literal(Constant(value)) => - pConstantPat(tree.pos, tree.tpe, value); - - //case Sequence(ts) => - case ArrayValue(_, ts) => - if ( !delegateSequenceMatching ) { - pSequencePat(tree.pos, tree.tpe, ts.length); - } else { - pSeqContainerPat(tree.pos, tree.tpe, tree); - } - case Alternative(ts) => - if(ts.length < 2) - scala.Predef.error("ill-formed Alternative"); - val subroot = pConstrPat(header.pos, header.getTpe()); - subroot.and = pHeader(header.pos, header.getTpe(), header.selector.duplicate); - val subenv = new CaseEnv; - var i = 0; while(i < ts.length) { - val target = enter1(ts(i), -1, subroot, subroot.symbol, subenv); - target.and = pBody(tree.pos); - i = i + 1 - } - pAltPat(tree.pos, subroot.and.asInstanceOf[Header]); - - case _ => - if(tree == null) - scala.Predef.error("unit = " + cunit + "; tree = null"); - else - scala.Predef.error("unit = " + cunit + "; tree = "+tree); - } - } - - protected def enter(pat: Tree, index: Int, target: PatternNode, casted: Symbol, env: CaseEnv ): PatternNode = { - target match { - case ConstrPat(newCasted) => - enter1(pat, index, target, newCasted, env); - case SequencePat(newCasted, len) => - enter1(pat, index, target, newCasted, env); - case _ => - enter1(pat, index, target, casted, env); - } - } - - private def newHeader(pos: Int, casted: Symbol, index: Int): Header = { - //Console.println("newHeader(pos,"+casted+","+index+")"); - //Console.println(" casted.tpe"+casted.tpe); - //Console.println(" casted.pos "+casted.pos+" equals firstpos?"+(casted.pos == Position.FIRSTPOS)); - val ident = typed(Ident(casted)); - if (casted.pos == Position.FIRSTPOS) { - //Console.println("FIRSTPOS"); - - //Console.println("DEBUG"); - //Console.println(); - - val t = typed( - Apply(Select( ident, ident.tpe.member(nme.apply)/* scalac: defs.functionApply( 1 )*/), - List( Literal( Constant(index) ) ))); - val seqType = t.tpe; - pHeader( pos, seqType, t ); - } else { - //Console.println("NOT FIRSTPOS"); - // Console.println("newHeader :: casted="+casted); - // Console.println("newHeader :: casted.tpe="+casted.tpe); - //Console.println("newHeader :: "); - val caseAccs = casted.tpe.symbol.caseFieldAccessors; - if (caseAccs.length <= index) System.out.println("selecting " + index + " in case fields of " + casted.tpe.symbol + "=" + casted.tpe.symbol.caseFieldAccessors);//debug - val ts = caseAccs(index); - //Console.println("newHeader :: ts="+ts); - //val accType = casted.tpe.memberType(ts); // old scalac - //val accTree = global.typer.typed(Select(ident, ts)); // ! - - val accTree = typed(Apply(Select(ident, ts), List())); // nsc ! - val accType = accTree.tpe; - //Console.println("newHeader :: accType="+accType); - //Console.println("newHeader :: accType.resultType ="+accType.resultType); - //Console.println("accTree.tpe =="+accTree.tpe); - - accType match { - // scala case accessor - case MethodType(_, _) => - //Console.println("Hello?!"); - pHeader(pos, accType.resultType, Apply(accTree, List())); - // jaco case accessor - case _ => - //Console.println("Hola?!"); - pHeader(pos, accType, accTree); - } - } - } - - /** main enter function - * - * invariant: ( curHeader == (Header)target.and ) holds - */ - protected def enter1(pat: Tree, index: Int, target: PatternNode, casted: Symbol, env: CaseEnv): PatternNode = { - //System.err.println("enter(" + pat + ", " + index + ", " + target + ", " + casted + ")"); - val patArgs = patternArgs(pat); // get pattern arguments - var curHeader = target.and.asInstanceOf[Header]; // advance one step in intermediate representation - if (curHeader == null) { // check if we have to add a new header - //assert index >= 0 : casted; - if (index < 0) { scala.Predef.error("error entering:" + casted); return null } - target.and = {curHeader = newHeader(pat.pos, casted, index); curHeader}; - curHeader.or = patternNode(pat, curHeader, env); - enter(patArgs, curHeader.or, casted, env); - } - else { - // find most recent header - while (curHeader.next != null) - curHeader = curHeader.next; - // create node - var patNode = patternNode(pat, curHeader, env); - var next: PatternNode = curHeader; - // add branch to curHeader, but reuse tests if possible - while (true) { - if (next.isSameAs(patNode)) { // test for patNode already present --> reuse - // substitute... !!! - patNode match { - case ConstrPat(ocasted) => - env.substitute(ocasted, typed(Ident(next.asInstanceOf[ConstrPat].casted))); - case _ => - } - return enter(patArgs, next, casted, env); - } else if (next.isDefaultPat() || // default case reached, or - ((next.or == null) && // no more alternatives and - (patNode.isDefaultPat() || next.subsumes(patNode)))) { - // new node is default or subsumed - var header = pHeader(patNode.pos, - curHeader.getTpe(), - curHeader.selector); - {curHeader.next = header; header}; - header.or = patNode; - return enter(patArgs, - patNode, - casted, - env); - } - else if (next.or == null) { - return enter(patArgs, {next.or = patNode; patNode}, casted, env); // add new branch - } else - next = next.or; - } - error("must not happen"); - null - } - } - - /** calls enter for an array of patterns, see enter - */ - protected def enter(pats:List[Tree], target1: PatternNode , casted1: Symbol , env: CaseEnv): PatternNode = { - var target = target1; - var casted = casted1; - target match { - case ConstrPat(newCasted) => - casted = newCasted; - case SequencePat(newCasted, len) => - casted = newCasted; - case _ => - } - var i = 0; while(i < pats.length) { - target = enter1(pats(i), i, target, casted, env); - i = i + 1 - } - target; - } - - protected def nCaseComponents(tree: Tree): int = { - tree match { - case Apply(fn, _) => - val tpe = tree.tpe.symbol.primaryConstructor.tpe; - //Console.println("~~~ " + tree.type() + ", " + tree.type().symbol.primaryConstructor()); - tpe match { - // I'm not sure if this is a good idea, but obviously, currently all case classes - // without constructor arguments have type NoType - case NoType => - error("this cannot happen"); - 0 - case MethodType(args, _) => - args.length; - case PolyType(tvars, MethodType(args, _)) => - args.length; - case PolyType(tvars, _) => - 0; - case _ => - error("not yet implemented;" + - "pattern matching for " + tree + ": " + tpe); - } - } - return 0; - } - - - //////////// generator methods - - def toTree(): Tree = { - if (optimize && isSimpleIntSwitch()) - intSwitchToTree(); - - else /* if (false && optimize && isSimpleSwitch()) - switchToTree(); - else */ { - //print(); - generalSwitchToTree(); - } - } - - case class Break(res:Boolean) extends java.lang.Throwable; - case class Break2() extends java.lang.Throwable; - - // TODO disentangle this - protected def isSimpleSwitch(): Boolean = { - print(); - var patNode = root.and; - while (patNode != null) { - var node = patNode; - while (({node = node.or; node}) != null) { - node match { - case VariablePat(tree) => - Console.println(((tree.symbol.flags & Flags.CASE) != 0)); - case ConstrPat(_) => - Console.println(node.getTpe().toString() + " / " + ((node.getTpe().symbol.flags & Flags.CASE) != 0)); - var inner = node.and; - def funct(inner: PatternNode): Boolean = { - //outer: while (true) { - inner match { - case _h:Header => - if (_h.next != null) - throw Break(false); - funct(inner.or) - - case DefaultPat() => - funct(inner.and); - - case b:Body => - if ((b.guard.length > 1) || - (b.guard(0) != EmptyTree)) - throw Break(false); - - throw Break2() // break outer - case _ => - Console.println(inner); - throw Break(false); - } - } - var res = false; - var set = false; - try { - funct(inner) - } catch { - case ex: Break => - res = ex.res; - set = true; - case ex: Break2 => - } - if(set) return res; - case _ => - return false; - } - } - patNode = patNode.nextH(); - } - return true; - } - - protected def isSimpleIntSwitch(): Boolean = { - if (isSameType(selector.tpe.widen, defs.IntClass.tpe)) { - var patNode = root.and; - while (patNode != null) { - var node = patNode; - while (({node = node.or; node}) != null) { - node match { - case ConstantPat(_) => ; - case _ => - return false; - } - node.and match { - case _b:Body => - if ((_b.guard.length > 1) || - (_b.guard(0) != EmptyTree) || - (_b.bound(0).length > 0)) - return false; - case _ => - return false; - } - } - patNode = patNode.nextH(); - } - return true; - } else - return false; - } - - class TagBodyPair(tag1: Int, body1: Tree, next1:TagBodyPair ) { - - var tag: int = tag1; - var body: Tree = body1; - var next: TagBodyPair = next1; - - def length(): Int = { - if (null == next) 1 else (next.length() + 1); - } - } - - protected def numCases(patNode1: PatternNode): Int = { - var patNode = patNode1; - var n = 0; - while (({patNode = patNode.or; patNode}) != null) - patNode match { - case DefaultPat() => ; - case _ => - n = n + 1; - } - n; - } - - protected def defaultBody(patNode1: PatternNode, otherwise: Tree ): Tree = { - var patNode = patNode1; - while (patNode != null) { - var node = patNode; - while (({node = node.or; node}) != null) - node match { - case DefaultPat() => - return node.and.bodyToTree(); - case _ => - } - patNode = patNode.nextH(); - } - otherwise; - } - - /** This method translates pattern matching expressions that match - * on integers on the top level. - */ - def intSwitchToTree(): Tree = { - def insert1(tag: Int, body: Tree, current: TagBodyPair): TagBodyPair = { - if (current == null) - return new TagBodyPair(tag, body, null); - else if (tag > current.tag) - return new TagBodyPair(current.tag, current.body, insert1(tag, body, current.next)); - else - return new TagBodyPair(tag, body, current); - } - - //print(); - val ncases = numCases(root.and); - val matchError = ThrowMatchError(selector.pos, resultType); - // without a case, we return a match error if there is no default case - if (ncases == 0) - return defaultBody(root.and, matchError); - // for one case we use a normal if-then-else instruction - else if (ncases == 1) { - root.and.or match { - case ConstantPat(value) => - return If(Equals(selector, Literal(value)), - (root.and.or.and).bodyToTree(), - defaultBody(root.and, matchError)); - case _ => - return generalSwitchToTree(); - } - } - // - // if we have more than 2 cases than use a switch statement - val _h:Header = root.and.asInstanceOf[Header]; - - val next = _h.next; - var mappings: TagBodyPair = null; - var defaultBody1: Tree = matchError; - var patNode = root.and; - while (patNode != null) { - var node = patNode.or; - while (node != null) { - node match { - case DefaultPat() => - if (defaultBody1 != null) - scala.Predef.error("not your day today"); - defaultBody1 = node.and.bodyToTree(); - node = node.or; - - case ConstantPat( value: Int )=> - mappings = insert1( - value, - node.and.bodyToTree(), - mappings); - node = node.or; - } - } - patNode = patNode.nextH(); - } - - var n = mappings.length(); - var nCases: List[CaseDef] = Nil; - while (mappings != null) { - nCases = CaseDef(Literal(mappings.tag), - mappings.body) :: nCases; - mappings = mappings.next; - } - /* - val tags = new Array[Int](n); - val bodies = new Array[Tree](n); - n = 0; - while (mappings != null) { - tags(n) = mappings.tag; - bodies(n) = mappings.body; - n = n + 1; - mappings = mappings.next; - } - return Switch(selector, tags, bodies, defaultBody1, resultType); - */ - nCases = CaseDef(Ident(nme.WILDCARD), defaultBody1) :: nCases; - return Match(selector, nCases) - } - - - var exit:Symbol = null; - /** simple optimization: if the last pattern is `case _' (no guards), we won't generate the ThrowMatchError - */ - def generalSwitchToTree(): Tree = { - this.exit = currentOwner.newLabel(root.pos, "exit") - .setInfo(new MethodType(List(resultType), resultType)); - //Console.println("resultType:"+resultType.toString()); - val result = exit.newValueParameter(root.pos, "result").setInfo( resultType ); - - //Console.println("generalSwitchToTree: "+root.or); - /* - val ts = List(ValDef(root.symbol, selector)); - val res = If(toTree(root.and), - LabelDef(exit, List(result), Ident(result)), - ThrowMatchError(selector.pos, resultType // , Ident(root.symbol) - )); - return Block(ts, res); - */ - return Block( - List( - ValDef(root.symbol, selector), - toTree(root.and), - ThrowMatchError(selector.pos, resultType)), - LabelDef(exit, List(result), Ident(result))) - } - - /*protected*/ def toTree(node1: PatternNode): Tree = { - def optimize1(selType:Type, alternatives1: PatternNode ): Boolean = { - var alts = alternatives1; - if (!optimize || !isSubType(selType, defs.ScalaObjectClass.tpe)) - return false; - var cases = 0; - while (alts != null) { - alts match { - case ConstrPat(_) => - if (alts.getTpe().symbol.hasFlag(Flags.CASE)) - cases = cases +1; - else - return false; - - case DefaultPat() => - ; - case _ => - return false; - } - alts = alts.or; - } - return cases > 2; - } // def optimize - - var node = node1; - - var res: Tree = typed(Literal(Constant(false))); //.setInfo(defs.BooleanClass); - //Console.println("pm.toTree res.tpe "+res.tpe); - while (node != null) - node match { - case _h:Header => - val selector = _h.selector; - val next = _h.next; - //res = And(mkNegate(res), toTree(node.or, selector)); - //Console.println("HEADER TYPE = " + selector.type); - if (optimize1(node.getTpe(), node.or)) - res = Or(res, toOptTree(node.or, selector)); - else - res = Or(res, toTree(node.or, selector)); - node = next; - - case _b:Body => - var bound = _b.bound; - val guard = _b.guard; - val body = _b.body; - if ((bound.length == 0) && - (guard.length == 0) && - (body.length == 0)) { - return Literal(Constant(true)); - } else if (!doBinding) - bound = Predef.Array[Array[ValDef]]( Predef.Array[ValDef]() ); - var i = guard.length - 1; while(i >= 0) { - val ts:Seq[Tree] = bound(i).asInstanceOf[Array[Tree]]; - val temp = currentOwner.newValue(body(i).pos, cunit.fresh.newName("r$")) - .setFlag(Flags.SYNTHETIC).setInfo(resultType); - var res0: Tree = - //Block( - // List(Assign(Ident(resultVar), body(i))), - // Literal(Constant(true))); - Block( - List( - ValDef(temp, body(i)), - Apply(Ident(exit), List(Ident(temp)))), - Literal(Constant(true)) - ); // forward jump - if (guard(i) != EmptyTree) - res0 = And(guard(i), res0); - res = Or(Block(ts.toList, res0), res); - i = i - 1 - } - return res; - case _ => - scala.Predef.error("I am tired"); - } - return res; - } - - - class TagNodePair(tag1: int, node1: PatternNode, next1: TagNodePair) { - var tag: int = tag1; - var node: PatternNode = node1; - var next: TagNodePair = next1; - - def length(): Int = { - return if (null == next) 1 else (next.length() + 1); - } - } - - protected def toOptTree(node1: PatternNode, selector: Tree): Tree = { - def insert2(tag: Int, node: PatternNode, current: TagNodePair): TagNodePair = { - if (current == null) - return new TagNodePair(tag, node, null); - else if (tag > current.tag) - return new TagNodePair(current.tag, current.node, insert2(tag, node, current.next)); - else if (tag == current.tag) { - val old = current.node; - ({current.node = node; node}).or = old; - return current; - } else - return new TagNodePair(tag, node, current); - } - - def insertNode(tag:int , node:PatternNode , current:TagNodePair ): TagNodePair = { - val newnode = node.dup(); - newnode.or = null; - return insert2(tag, newnode, current); - } - var node = node1; - //System.err.println("pm.toOptTree called"+node); - var cases: TagNodePair = null; - var defaultCase: PatternNode = null; - while (node != null) - node match { - case ConstrPat(casted) => - cases = insertNode(node.getTpe().symbol.tag, node, cases); - node = node.or; - - case DefaultPat() => - defaultCase = node; - node = node.or; - - case _ => - scala.Predef.error("errare humanum est"); - } - var n = cases.length(); - /* - val tags = new Array[int](n); - val bodies = new Array[Tree](n); - n = 0; - while (null != cases) { - tags(n) = cases.tag; - bodies(n) = toTree(cases.node, selector); - n = n + 1; - cases = cases.next; - } - */ - - - /* - return - Switch( - Apply( - Select(selector.duplicate, defs.ScalaObjectClass_tag), - List()), - tags, - bodies, - { if (defaultCase == null) Literal(false) else toTree(defaultCase.and) }, - defs.boolean_TYPE()); - */ - var nCases: List[CaseDef] = Nil; - while (cases != null) { - nCases = CaseDef(Literal(Constant(cases.tag)), - toTree(cases.node, selector)) :: nCases; - cases = cases.next; - } - - val defBody = if (defaultCase == null) - Literal(Constant(false)) - else - toTree(defaultCase.and); - - nCases = CaseDef(Ident(nme.WILDCARD), defBody) :: nCases; - return Match(Apply(Select(selector.duplicate, defs.ScalaObjectClass_tag), - List()), - nCases); - } - - protected def toTree(node:PatternNode , selector:Tree ): Tree = { - //Console.println("pm.toTree("+node+","+selector+")"); - //Console.println("pm.toTree selector.tpe = "+selector.tpe+")"); - if(selector.tpe == null) - scala.Predef.error("cannot go on"); - if (node == null) - return Literal(Constant(false)); - else - node match { - case DefaultPat() => - return toTree(node.and); - - case ConstrPat(casted) => - return If(gen.mkIsInstanceOf(selector.duplicate, node.getTpe()), - Block( - List(ValDef(casted, - gen.mkAsInstanceOf(selector.duplicate, node.getTpe(), true))), - toTree(node.and)), - toTree(node.or, selector.duplicate)); - case SequencePat(casted, len) => - return ( - Or( - And( - And(gen.mkIsInstanceOf(selector.duplicate, node.getTpe()), - Equals( - typed( - Apply( - Select( - gen.mkAsInstanceOf(selector.duplicate, - node.getTpe(), - true), - node.getTpe().member(nme.length) /*defs.Seq_length*/), - List()) - ), - typed( - Literal(Constant(len)) - ))), - Block( - List( - ValDef(casted, - gen.mkAsInstanceOf(selector.duplicate, node.getTpe(), true))), - toTree(node.and))), - toTree(node.or, selector.duplicate))); - case ConstantPat(value) => - //Console.println("selector = "+selector); - //Console.println("selector.tpe = "+selector.tpe); - return If(Equals(selector.duplicate, - typed(Literal(Constant(value))).setType(node.tpe)), - toTree(node.and), - toTree(node.or, selector.duplicate)); - case VariablePat(tree) => - return If(Equals(selector.duplicate, tree), - toTree(node.and), - toTree(node.or, selector.duplicate)); - case AltPat(header) => - return If(toTree(header), - toTree(node.and), - toTree(node.or, selector.duplicate)); - case _ => - scala.Predef.error("can't plant this tree"); - } - } -} - - -} diff --git a/sources/scala/tools/nsc/matching/PatternNodeCreator.scala b/sources/scala/tools/nsc/matching/PatternNodeCreator.scala deleted file mode 100644 index 79ba780469..0000000000 --- a/sources/scala/tools/nsc/matching/PatternNodeCreator.scala +++ /dev/null @@ -1,108 +0,0 @@ -package scala.tools.nsc.matching; - -import scala.tools.nsc.util.Position; - -/** PatternNode factory. - * we inherit the globals from PatternTool. - */ - -trait PatternNodeCreator: (TransMatcher with PatternNodes) { - - import global._; - - def pSequencePat(pos: Int , tpe:Type , len:int) = { - //assert (tpe != null); - val sym = newVar(Position.FIRSTPOS, tpe); - //Console.println("pncrea::sequencePat sym.pos = "+sym.pos); - val node = new SequencePat(sym, len); - node.pos = pos; - node.tpe = tpe; - //Console.println("pncrea::sequencePat sym.pos = "+sym.pos); - node; - } - - def pSeqContainerPat(pos: int, tpe: Type, seqpat:Tree ) = { - //assert (tpe != null); - val sym = newVar(Position.NOPOS, tpe); - val node = new SeqContainerPat(sym, seqpat); - node.pos = pos; - node.setType(tpe); - node; - } - - def pDefaultPat(pos: int, tpe: Type) = { - //assert (tpe != null); - val node = new DefaultPat(); - node.pos = pos; - node.setType(tpe); - node; - } - - def pConstrPat(pos: int, tpe: Type) = { - //assert (tpe != null); - val node = new ConstrPat(newVar(pos, tpe)); - node.pos = pos; - node.setType(tpe); - node; - } - - def pConstantPat(pos: int, tpe: Type, value: Any /*AConstant*/ ) = { - //assert (tpe != null); - val node = new ConstantPat( value ); - node.pos = pos; - node.setType(tpe); - node; - } - - def pVariablePat(pos: int, tree:Tree) = { - //assert (tree.tpe != null); - val node = new VariablePat( tree ); - node.pos = pos; - node.setType(tree.tpe); - node; - } - - def pAltPat(pos: int, header:Header ) = { - val node = new AltPat(header); - node.pos = pos; - node.setType(header.getTpe()); - node; - } - - // factories - - def pHeader(pos: int, tpe: Type, selector:Tree) = { - //assert (tpe != null); - val node = new Header(selector, null); - node.pos = pos; - node.setType(tpe); - node; - } - - def pBody(pos: int) = { - val node = new Body(new Array[Array[ValDef]](0), new Array[Tree](0), new Array[Tree](0)); - node.pos = pos; - node; - } - - def pBody(pos: int, bound:Array[ValDef] , guard:Tree, body:Tree) = { - val node = new Body(Predef.Array[Array[ValDef]](bound), Predef.Array[Tree](guard), Predef.Array[Tree](body)); - node.pos = pos; - node; - } - - def newVar(pos: int, name: Name, tpe: Type): Symbol= { - /** hack: pos has special meaning*/ - val sym = currentOwner.newVariable(pos, name); - //Console.println("patnodcre::newVar sym = "+sym+ "tpe = "+tpe); - sym.setInfo(tpe); - //System.out.println("PatternNodeCreator::newVar creates symbol "+sym); - //System.out.println("owner: "+sym.owner()); - sym; - } - - def newVar(pos: int, tpe: Type): Symbol = { - newVar(pos, cunit.fresh.newName("temp"), tpe); - } -} - diff --git a/sources/scala/tools/nsc/matching/PatternNodes.scala b/sources/scala/tools/nsc/matching/PatternNodes.scala deleted file mode 100644 index 551d964c39..0000000000 --- a/sources/scala/tools/nsc/matching/PatternNodes.scala +++ /dev/null @@ -1,371 +0,0 @@ -/* ____ ____ ____ ____ ______ *\ -** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala ** -** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL ** -** /_____/\____/\___/\____/____/ ** -** ** -** $Id$ -\* */ - -package scala.tools.nsc.matching ; - -import scala.tools.nsc.util.Position; - -trait PatternNodes: TransMatcher { - - import global._; - - /** Intermediate data structure for algebraic + pattern matcher - */ - class PatternNode { - var pos = Position.FIRSTPOS; - var tpe: Type = _; - var or: PatternNode = _; - var and: PatternNode = _; - - def bodyToTree(): Tree = this match { - case _b:Body => - return _b.body(0); - } - - def getTpe(): Type = { - tpe; - } - def setType(tpe: Type): Unit = { - this.tpe = tpe; - } - - def dup(): PatternNode = { - var res: PatternNode = null; - this match { - case h:Header => - res = new Header(h.selector, h.next); - - case b:Body=> - res = new Body(b.bound, b.guard, b.body); - - case DefaultPat() => - res = DefaultPat(); - - case ConstrPat(casted) => - res = ConstrPat(casted); - - case SequencePat(casted, len) => - res = SequencePat(casted, len); - - case SeqContainerPat(casted, seqpat) => - res = SeqContainerPat(casted, seqpat); - - case ConstantPat(value) => - res = ConstantPat(value); - - case VariablePat(tree) => - res = VariablePat(tree); - - case AltPat(subheader) => - res = AltPat(subheader); - - case _ => - error("") - } - res.pos = pos; - res.tpe = tpe; - res.or = or; - res.and = and; - res; - } - - def symbol: Symbol = { - this match { - case ConstrPat(casted) => - return casted; - case SequencePat(casted, _) => - return casted; - case SeqContainerPat(casted, _) => - return casted; - case _ => - return NoSymbol; //.NONE; - } - } - - def nextH(): PatternNode = { - this match { - case _h:Header => - return _h.next; - case _ => - return null; - } - } - - def isDefaultPat(): boolean = { - this match { - case DefaultPat() => - return true; - case _ => - return false; - } - } - - /** returns true if - * p and q are equal (constructor | sequence) type tests, or - * "q matches" => "p matches" - */ - def isSameAs(q: PatternNode): boolean = { - this match { - case ConstrPat(_) => - q match { - case ConstrPat(_) => - isSameType(q.getTpe(), this.getTpe()); - case _ => - false - } - case SequencePat(_, plen) => - q match { - case SequencePat(_, qlen) => - return (plen == qlen) && isSameType(q.getTpe(), this.getTpe()); - case _ => - false - } - case _ => - subsumes(q); - } - } - - /** returns true if "q matches" => "p matches" - */ - def subsumes(q:PatternNode): Boolean = { - this match { - case DefaultPat() => - q match { - case DefaultPat() => - true; - case _ => - false; - } - case ConstrPat(_) => - q match { - case ConstrPat(_) => - isSubType(q.getTpe(), this.getTpe()); - case _ => - false; - } - case SequencePat(_, plen) => - q match { - case SequencePat(_, qlen) => - (plen == qlen) && isSubType(q.getTpe(), this.getTpe()); - case _ => - false; - } - case ConstantPat(pval) => - q match { - case ConstantPat(qval) => - pval == qval; - case _ => - false; - } - case VariablePat(tree) => - q match { - case VariablePat(other) => - ((tree.symbol != null) && - (tree.symbol != NoSymbol) && - (!tree.symbol.isError) && - (tree.symbol == other.symbol)) - case _ => - false; - } - case _ => - false; - } - } - - override def toString(): String = { - this match { - case _h:Header => - return "Header(" + _h.selector + ")"; - case _b:Body => - return "Body"; - case DefaultPat() => - return "DefaultPat"; - case ConstrPat(casted) => - return "ConstrPat(" + casted + ")"; - case SequencePat(casted, len) => - return "SequencePat(" + casted + ", " + len + "...)"; - case SeqContainerPat(casted, seqpat) => - return "SeqContainerPat(" + casted + ", " + seqpat + ")"; - case ConstantPat(value) => - return "ConstantPat(" + value + ")"; - case VariablePat(tree) => - return "VariablePat"; - case _ => - return ""; - } - } - - def print(indent: String, sb: StringBuffer): StringBuffer = { - - val patNode = this; - - def cont = if (patNode.or != null) patNode.or.print(indent, sb); else sb; - - def newIndent(s: String) = { - val removeBar: Boolean = (null == patNode.or); - val sb = new StringBuffer(); - sb.append(indent); - if (removeBar) - sb.setCharAt(indent.length() - 1, ' '); - var i = 0; while (i < s.length()) { - sb.append(' '); - i = i + 1 - } - sb.toString() - } - - if (patNode == null) - sb.append(indent).append("NULL"); - else - patNode match { - - case _h: Header => - val selector = _h.selector; - val next = _h.next; - sb.append(indent + "HEADER(" + patNode.getTpe() + - ", " + selector + ")").append('\n'); - patNode.or.print(indent + "|", sb); - if (next != null) - next.print(indent, sb); - else - sb - case ConstrPat(casted) => - val s = ("-- " + patNode.getTpe().symbol.name + - "(" + patNode.getTpe() + ", " + casted + ") -> "); - val nindent = newIndent(s); - sb.append(nindent + s).append('\n'); - patNode.and.print(nindent, sb); - cont; - - case SequencePat( casted, plen ) => - val s = ("-- " + patNode.getTpe().symbol.name + "(" + - patNode.getTpe() + - ", " + casted + ", " + plen + ") -> "); - val nindent = newIndent(s); - sb.append(indent + s).append('\n'); - patNode.and.print(nindent, sb); - cont; - - case DefaultPat() => - sb.append(indent + "-- _ -> ").append('\n'); - patNode.and.print(indent.substring(0, indent.length() - 1) + - " ", sb); - cont; - - case ConstantPat(value) => - val s = "-- CONST(" + value + ") -> "; - val nindent = newIndent(s); - sb.append(indent + s).append('\n'); - patNode.and.print( nindent, sb); - cont; - - case VariablePat(tree) => - val s = "-- STABLEID(" + tree + ": " + patNode.getTpe() + ") -> "; - val nindent = newIndent(s); - sb.append(indent + s).append('\n'); - patNode.and.print(nindent, sb); - cont; - - case AltPat(header) => - sb.append(indent + "-- ALTERNATIVES:").append('\n'); - header.print(indent + " * ", sb); - patNode.and.print(indent + " * -> ", sb); - cont; - - case _b:Body => - if ((_b.guard.length == 0) && (_b.body.length == 0)) - sb.append(indent + "true").append('\n') ; - else - sb.append(indent + "BODY(" + _b.body.length + ")").append('\n'); - - } - } // def print - - } - - class Header(sel1: Tree, next1: Header ) extends PatternNode { - var selector: Tree = sel1; - var next: Header = next1; - } - - class Body(bound1: Array[Array[ValDef]] , guard1:Array[Tree] , body1:Array[Tree] ) extends PatternNode { - var bound = bound1; - var guard = guard1; - var body = body1; - } - - case class DefaultPat()extends PatternNode; - case class ConstrPat(casted:Symbol ) extends PatternNode; - case class ConstantPat(value: Any /*AConstant*/ ) extends PatternNode; - case class VariablePat(tree: Tree ) extends PatternNode; - case class AltPat(subheader: Header ) extends PatternNode; - case class SequencePat( casted: Symbol, len:int) extends PatternNode; // only used in PatternMatcher - case class SeqContainerPat(casted: Symbol , seqpat: Tree ) extends PatternNode; // in AlgebraicMatcher - - /** the environment for a body of a case - * @param owner the owner of the variables created here - */ - class CaseEnv { -// (val owner:Symbol, unit:CompilationUnit) - private var boundVars:scala.Array[ValDef] = new Array[ValDef](4); - private var numVars = 0; - - /** substitutes a symbol on the right hand side of a ValDef - */ - def substitute(oldSym: Symbol, newInit: Tree): Unit = { - var i = 0; while( i < numVars) { - if( boundVars(i).rhs.symbol == oldSym ) { - boundVars(i) = ValDef(boundVars(i).symbol, newInit); - return; - } - i = i + 1; - } - } - - def newBoundVar(sym:Symbol, tpe: Type, init:Tree ): Unit = { - //if(sym == Symbol.NoSymbol ) { -// scala.Predef.Error("can't add variable with NoSymbol"); -// } - // sym.setOwner( owner ); // FIXME should be corrected earlier - // @maybe is corrected now? bq - if (numVars == boundVars.length) { - val newVars = new Array[ValDef](numVars * 2); - System.arraycopy(boundVars, 0, newVars, 0, numVars); - this.boundVars = newVars; - } - sym.setInfo(tpe); - this.boundVars(numVars) = ValDef(sym, init.duplicate); - numVars = numVars + 1; - } - - def getBoundVars(): Array[ValDef] = { - val newVars = new Array[ValDef](numVars); - System.arraycopy(boundVars, 0, newVars, 0, numVars); - return newVars; - } - - override def equals(obj: Any): Boolean = { - if (!(obj.isInstanceOf[CaseEnv])) - return false; - val env = obj.asInstanceOf[CaseEnv]; - if (env.numVars != numVars) - return false; - var i = 0; while(i < numVars) { - if ((boundVars(i).name != env.boundVars(i).name) || - !isSameType(boundVars(i).tpe, env.boundVars(i).tpe) || - (boundVars(i).rhs != env.boundVars(i).rhs)) - return false; - i = i + 1; - } - return true; - } - - } // class CaseEnv - - -} diff --git a/sources/scala/tools/nsc/matching/RightTracers.scala b/sources/scala/tools/nsc/matching/RightTracers.scala deleted file mode 100644 index f0daf20fed..0000000000 --- a/sources/scala/tools/nsc/matching/RightTracers.scala +++ /dev/null @@ -1,537 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ - -package scala.tools.nsc.matching; - -import java.util._ ; - -import scala.tools.nsc.util.Position; -import scala.tools.nsc.symtab.Flags; - -trait RightTracers: TransMatcher { - - import global._ ; - import java.util._ ; - -//import Scope.SymbolIterator; - -//import scalac.util.Name ; -//import scalac.util.Names ; - -//import scala.tools.util.Position; - - /** translate right tracer to code - * @param dfa determinized left tracer - * @param left nondeterm. left tracer (only needed for variables!) - * @param pat ? - * @param elementType ... - */ -abstract class RightTracerInScala extends Autom2Scala { - - val seqVars: Set; - val pat:Tree; - val elementType: Type; - - - def SeqTrace_headElem( arg: Tree ) = { // REMOVE SeqTrace - val t = Apply(Select(arg, definitions.List_head), Nil); - Apply(Select(t, definitions.tupleField(2,2)),Nil) - } - - def SeqTrace_headState( arg: Tree ) = { // REMOVE SeqTrace - val t = Apply(Select(arg, definitions.List_head), Nil); - Apply(Select(t, definitions.tupleField(2,1)), Nil) - } - - def SeqTrace_tail( arg: Tree ): Tree = // REMOVE SeqTrace - Apply(Select(arg, definitions.List_tail), Nil); - - final def collectVars(pat: Tree): HashSet = { - var vars = new HashSet(); - - def handleVariableSymbol(sym: Symbol): Unit = { - vars.add( sym ); - } - def isVariableName(name: Name): Boolean = - ( name != nme.WILDCARD ) && ( treeInfo.isVariableName( name ) ) ; - - def isVariableSymbol(sym: Symbol): Boolean = { - ( sym != null )&&( !sym.isPrimaryConstructor ); - } - - def traverse(tree: Tree): Unit = { - tree match { - case x @ Ident(name)=> - if(x.symbol != definitions.PatternWildcard) - scala.Predef.error("shouldn't happen?!"); - - case Star(t) => - traverse(t); - case Bind(name, subtree) => - var sym: Symbol = null; - if( isVariableName( name ) - && isVariableSymbol( {sym = tree.symbol; tree.symbol} )) - handleVariableSymbol( sym ); - - traverse( subtree ); - - // congruence cases - case Apply(fun, args) => args foreach {traverse}; - case Sequence(trees) => trees foreach {traverse}; - case Typed(expr, tpe) => traverse(expr); // needed?? - case _ : Alternative | _ : Select | _ : Literal => ; // no variables - case _ => Predef.error("unknown node:"+tree+" = "+tree.getClass()); - } - } - traverse( pat ); - return vars; - } - - //final def defs = cf.defs; - - val allVars: Set = collectVars( pat ); - - var varsToExport: Set = new HashSet(); // @todo HANDLE seqVars THESE GLOBALLY INSTEAD OF LOCALLY - - varsToExport.addAll( allVars ); - varsToExport.removeAll( seqVars ); - - var targetSym:Symbol = _; - - var helpMap = new HashMap(); - var helpMap2 = new HashMap(); - var helpVarDefs:scala.List[Tree] = Nil; - - val it = seqVars.iterator(); - while(it.hasNext()) { - makeHelpVar( it.next().asInstanceOf[Symbol] ); - } - - val jt = allVars.iterator(); - while(jt.hasNext()) { - val varSym = jt.next().asInstanceOf[Symbol]; - if(( varSym.name.toString().indexOf("$") == -1 ) - && ( !seqVars.contains( varSym ))) { - makeHelpVar( varSym, true ); - } - } - - //System.out.println("allVars: "+allVars); - //System.out.println("seqVars: "+seqVars); - //System.out.println("helpVarDefs now: "+helpVarDefs); - - initializeSyms(); - - def makeHelpVar(realVar: Symbol): Unit = { - makeHelpVar( realVar, false ); - } - - /** makes a helpvar and puts mapping into helpMap, ValDef into helpVarDefs - */ - - def makeHelpVar(realVar: Symbol, keepType: Boolean): Unit = { - val helpVar = owner.newVariable( pos, - fresh.newName( realVar.name - .toString()+"RTIS" )); - var rhs: Tree = null; - - //System.out.println("RTiS making helpvar : "+realVar+" -> "+helpVar); - - if( keepType ) { - helpVar.setInfo( realVar.tpe ); - rhs = EmptyTree; - } else { - helpVar.setInfo( definitions.ListClass.info /* LIST_TYPE(elementType)*/ ); - rhs = gen.mkNil; - } - - helpMap.put( realVar, helpVar ); - helpVar.setFlag(Flags.MUTABLE); - val varDef = ValDef( helpVar, rhs ); - //((ValDef) varDef).kind = Kinds.VAR; - helpVarDefs= varDef :: helpVarDefs; - - } - - def prependToHelpVar(realVar: Symbol, elem:Tree): Tree = { - val hv = refHelpVar( realVar ); - Assign( hv, gen.mkNewCons( /*elementType, */elem, hv )); - /* - return cf.Block(pos, - new Tree [] { - cf.debugPrintRuntime( "ASSIGN" ), - gen.Assign( hv, cf.newSeqCons( elem, hv )) - }, defs.UNIT_TYPE()); - */ - } - - protected def initializeSyms(): Unit = { - - this.funSym = owner.newLabel( pos, fresh.newName( "right" )); - - this.iterSym = owner.newVariable( pos, fresh.newName("iter")) - .setInfo( SeqTraceType( elementType )); - - this.stateSym = owner.newVariable ( pos, fresh.newName("q")) - .setInfo( definitions.IntClass.info ) ; - - this.curSym = owner.newVariable( pos, fresh.newName("cur")) - .setInfo( elementType ) ; - - this.targetSym = owner.newVariable( pos, fresh.newName("p")) - .setInfo( definitions.IntClass.info ) ; - - funSym.setInfo( - MethodType( scala.List ( // dummy symbol MethodType - SeqTraceType(elementType), - //funSym.newValueParameter( pos, fresh.newName("iter") /*, SeqTraceType elementType */), - definitions.IntClass.info), - //funSym.newValueParameter( pos, fresh.newName( "q" ) /*, definitions.IntClass.info */), - definitions.UnitClass.info)) // result - - } - - // load current elem and trace - override def loadCurrentElem(body: Tree): Tree = { - If( isEmpty( _iter() ), - run_finished( 0 ), // we are done - Block( scala.List ( - ValDef( this.targetSym, - SeqTrace_headState( Ident( iterSym))), - ValDef( this.curSym, - SeqTrace_headElem( Ident( iterSym )))), - body ) - ); - } - - /** see code_state0_NEW - */ - def code_state0(elseBody: Tree) = { // careful, map Int to Int - - If( Equals( _state(), Literal(0)), - code_state0_NEW(), - elseBody ); - - } - - /** this one is special, we check the first element of the trace - * and choose the next state depending only on the state part - */ - def code_state0_NEW(): Tree = { // careful, map Int to Int - - val hmap = dfa.deltaq( 0 ); // all the initial states - - var i = 0; - val n = hmap.keySet().size(); // all transitions defined - - val tmapTag = new TreeMap(); - val tmapBody = new TreeMap(); - var it = hmap.keySet().iterator(); - while(it.hasNext()) { - val targetL = it.next().asInstanceOf[Integer]; - val targetR = hmap.get( targetL ).asInstanceOf[Integer]; - - val I = new Integer( i ); - tmapTag.put( targetL, I ); - tmapBody.put( I, callFun( scala.List ( - SeqTrace_tail( _iter() ), - Literal( targetR.intValue() ) ))); - i = i + 1; - } - //i = 0; - - var ncases: scala.List[CaseDef] = Nil; - //val tags = new Array[Int]( n ); - //val targets = new Array[Tree]( n ); - var jt = tmapTag.keySet().iterator(); - while(jt.hasNext()) { - val tagI = jt.next().asInstanceOf[Integer]; - //tags( i ) = tagI.intValue(); - val I = tmapTag.get( tagI ).asInstanceOf[Integer]; - //targets( i ) = tmapBody.get( I ).asInstanceOf[Tree];; - ncases = CaseDef( Literal(tagI.intValue()), - tmapBody.get(I).asInstanceOf[Tree] ) :: ncases; - //i = i + 1 - } - //gen.Switch( gen.Ident( pos, targetSym ), - // tags, - // targets, - // code_error()/*cannot happen*/ ); - - Match(Ident(targetSym), ncases); - } - - override def currentMatches(label: Label): Tree = label match { - case LPair( target, theLab ) => - Equals( Literal(target.intValue() ), current() ); - case _ => - scala.Predef.error("expected Pair label"); - } - - - override def code_state_NEW(i: Int): Tree = { // precondition i != 0 - var stateBody = code_delta( i, DefaultLabel() ); - if( stateBody == null ) { - stateBody = code_error(); - } - val trans = dfa.deltaq( i ); - val tmapTag = new TreeMap(); - val tmapBody = new TreeMap(); - var j = 0; - var labs = dfa.labels().iterator(); - while(labs.hasNext()) { - val label = labs.next(); - val next = trans.get( label ).asInstanceOf[Integer]; - val action = code_delta( i, label.asInstanceOf[Label] ); - - if( action != null ) { - val J = new Integer( j ); - tmapTag.put( label.asInstanceOf[LPair].state, J ); - tmapBody.put( J, action ); - - stateBody = If( currentMatches( label.asInstanceOf[Label] ), - action, - stateBody); - } - j = j + 1; - } - val n = tmapTag.keySet().size(); - //j = 0; - //val tags = new Array[int]( n ); - //val targets = new Array[Tree]( n ); - var ncases: scala.List[CaseDef] = Nil; - val it = tmapTag.keySet().iterator(); - while(it.hasNext()) { - val tagI = it.next().asInstanceOf[Integer]; - //tags( j ) = tagI.intValue(); - val J = tmapTag.get( tagI ).asInstanceOf[Integer]; - //targets( j ) = tmapBody.get( J ).asInstanceOf[Tree]; - ncases = CaseDef(Literal(tagI.intValue()), - tmapBody.get( J ).asInstanceOf[Tree]) :: ncases; - //j = j + 1; - } - if( n > 0 ) - //gen.Switch( gen.Ident( pos, targetSym ), tags, targets, code_error() ); - Match(Ident( targetSym ), ncases); - else - code_error(); - } - - // calling the AlgebraicMatcher here - override def _cur_match(pat1: Tree): Tree = { - var pat = pat1; - //System.out.println("RTiS._cur_match("+pat.toString()+")"); - //System.out.println("calling algebraic matcher on type:"+pat.type); - - //System.err.println( "curT"+currentElem().type().widen() ); - val m = new PartialMatcher { - val owner = RightTracerInScala.this.owner; // , //funSym,//this.funSym, - val selector = currentElem(); //, - // result type defs.boolean_TYPE() ); - } - val freshenMap = new HashMap(); // sym2exp -> new sym - val helpMap3 = new HashMap(); // new sym -> original sym - - // "freshening": never use the same symbol more than once - // (in later invocations of _cur_match) - - var it = varsToExport.iterator(); - while(it.hasNext() ) { - val key = it.next().asInstanceOf[Symbol]; - if( key.name.toString().indexOf("$") == -1 ) { - this.helpMap2.put( key, helpMap.get( key )); - // "freshening" by appending string ( a bit dangerous ) - val newSym = key.cloneSymbol( owner /*funSym*/ ); - newSym.name = newTermName(key.name.toString() + "%") ; // erm - freshenMap.put( key, newSym ); - helpMap3.put( newSym, helpMap.get( key )); - //System.out.println( "key: "+ key + " key.owner:"+key.owner()); - //System.out.println( "newsym owner:"+newSym.owner()); - } else { - freshenMap.put( key, key ); - } - } - - //System.out.println("RightTracerInScala:: -pat :"+pat.toString()); - /* - System.out.println("RightTracerInScala - the seqVars"+seqVars); - System.out.println("RightTracerInScala - the varsToExport"+varsToExport); - */ - //System.out.println("RightTracerInScala::freshenMap :"+freshenMap); - - // "freshening" - - //@nsc @todo @todo @todo @todo - - //val tc = new TreeCloner( global, freshenMap, Type.IdMap ); - //pat = tc.transform( pat ); - //@nsc this commented out, is broken anyway. - - // val match case => ; true - // case _ => false - - - var ts: scala.List[Tree] = scala.List(); //new Array[Tree]( helpMap3.keySet().size() ); - //var j = 0; - var jt = helpMap3.keySet().iterator(); - while(jt.hasNext()) { - val vsym = jt.next().asInstanceOf[Symbol]; - val hv = helpMap3.get( vsym ).asInstanceOf[Symbol]; - //hv.setInfo( defs.LIST_TYPE( elementType ) ) ; DEBUG ALARM ? - ts = Assign( Ident(hv), Ident(vsym) ) :: ts; - //ts( j ) = gen.; - //j = j + 1; - // System.out.println( "the assign" + res[ j - 1 ] ); - } - - val theBody = Block(ts, Literal( true )); // just `true' - - am.construct( m, scala.List( - CaseDef( pat, theBody), // freshening - // if tree val matches pat -> update vars, return true - CaseDef(Ident(definitions.PatternWildcard), Literal(false))), - // else return false - true // do binding please - ); - - am.toTree(); - } - - /** returns translation of transition with label from i. - * returns null if there is no such transition(no translation needed) - */ - override def code_delta(i: Int , label: Label ): Tree = { - val hmap = dfa.deltaq( i ); - val ntarget = hmap.get( label ).asInstanceOf[Integer]; - var algMatchTree: Tree = null; - if( ntarget == null ) - return null; - - //System.out.println("delta("+i+","+label+")" ); - var theLab: Label = null; - label match { - case LPair ( state, lab2 )=> - //assert ntarget == state; - theLab = lab2; - lab2 match { - case TreeLabel( pat ) => - algMatchTree = _cur_match( pat ); - case _ => - } - case DefaultLabel() => - scala.Predef.error("bla"); // should not happen - } - //assert dfa.qbinders != null : "qbinders ?"; - - var vars = dfa.qbinders(i); - - //System.out.println("dfa.qbinders[ i ]"+vars); - - if (null == vars) vars = new Vector(); // TODO: make this more consistent - //assert vars != null; - - var stms = if (algMatchTree != null ) algMatchTree::Nil else Nil; - - var it = vars.iterator(); - while(it.hasNext()) { - val vble = it.next().asInstanceOf[Symbol]; - val rhs = gen.Ident( curSym ); - stms = prependToHelpVar( vble , rhs) :: stms; - } - - val value = callFun( scala.List( SeqTrace_tail( _iter() ), - Literal(ntarget.intValue()))); - - Block(stms, value ); - } - - override def stateWrap(i: Int): Tree = { - if (i == 0) - code_state0_NEW(); - else - code_state_NEW(i); - } - - /* returns statements that do the work of the right-transducer - */ - def getStms(trace: Tree, unit: CompilationUnit, body: Tree): Tree = { - - var stms: scala.List[Tree] = scala.List(); - val loopbody = code_body_NEW(); - - stms = ( - scala.List( - ValDef( iterSym, trace ), - ValDef( stateSym, Literal( 0 )) - ) ::: helpVarDefs - ::: scala.List( - LabelDef( - this.funSym, - scala.List ( - iterSym, - stateSym - ), - loopbody ) - )); - - // bind variables handled by this righttracer - var it = seqVars.iterator(); - while(it.hasNext()) - stms = stms ::: bindVar( it.next().asInstanceOf[Symbol] ) :: Nil; - - val treeCloner = new Transformer { - override def transform(tree1: Tree): Tree = { - val tree = super.transform(tree1); - if (tree.hasSymbol) { - val symbol = helpMap2.get(tree.symbol); - if (symbol != null) tree.setSymbol(symbol.asInstanceOf[Symbol]); - } - tree; - } - }; - - Block(stms, treeCloner.transform( body )); - } - - - /** return the accumulator. (same as in LeftTracerInScala) - * todo: move tree generation of Unit somewhere else - */ - override def run_finished(state: Int): Tree = Literal(()); - - def current() = Ident( targetSym ); - - def refHelpVar(realVar: Symbol) = { - val hv = helpMap.get( realVar ).asInstanceOf[Symbol]; - //assert hv != null : realVar; - Ident(hv); - } - - def assignToHelpVar(realVar: Symbol, rhs: Tree): Tree = { - val hv = refHelpVar(realVar); - Assign(hv, rhs); - } - - def bindVar(realVar: Symbol): Tree = { - val hv = refHelpVar(realVar); - /* - System.out.println("binding realVar.name "+realVar.name+" type:"+realVar.type()+" to hv type:"+hv.type()); - realVar.setOwner( owner ); - System.out.println("is same as realVar"+realVar.type().isSameAs( elementType )); - System.out.println("is same as hv"+realVar.type().isSameAs( hv.type() )); - if( realVar.type().isSameAs( elementType )) - return gen.ValDef( realVar, SeqList_head( hv )); - else - return gen.ValDef( realVar, hv ); - */ - if( isSameType(realVar.tpe, hv.tpe)) - ValDef( realVar, hv ); // e.g. x @ _* - else { - ValDef( realVar, SeqList_head( hv )); - } - } -} -} diff --git a/sources/scala/tools/nsc/matching/SequenceMatchers.scala b/sources/scala/tools/nsc/matching/SequenceMatchers.scala deleted file mode 100644 index d2d8aa7414..0000000000 --- a/sources/scala/tools/nsc/matching/SequenceMatchers.scala +++ /dev/null @@ -1,173 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ - -package scala.tools.nsc.matching; - -import java.util._ ; - -/** constructs a matcher for a sequence pattern. plays two roles in - * described in design pattern Builder. - * is the "Director" for "Builder" class BerrySethi. - * is the "Builder" for "Director" class TransMatch. - */ - -trait SequenceMatchers: TransMatcher { - - import global._; - - class SequenceMatcher { - - // Console.println("CONSTR SEQUENCEMATCHER"); - final val IGNORED = new Integer(42); - - var _m: PartialMatcher = _; - - var bbuild: BindingBerrySethi = null; - - /** collects variables - * @return all variables bound by this binding nfa - */ - def collectNfaVariables(nfa: NondetWordAutom): Set = { - val seqVars = new HashSet(); - var j = 0; - while(j < nfa.nstates) { - if( nfa.qbinders( j ) != null ) - seqVars.addAll( nfa.qbinders( j ) ); - j = j + 1 - } - seqVars; - } - - - /** translates the det/switching automaton to scala code - * precondition: pat.type() corresponds to element type - */ - def addBinderToBody( pat1:Tree , body:Tree ): Tree = { - if( bbuild == null ) - bbuild = new BindingBerrySethi; - - val elementType1 = getElemType_Sequence( pat1.tpe ); - - // (a) build *binding* nfa (sequential machine) - val left = bbuild.automatonFrom( pat1, IGNORED ); - val right = bbuild.revnfa; - - // (b) determinize + translate L - - val dLeft = new DetWordAutom( left ); - - val ltis = new LeftTracerInScala { - val dfa = dLeft; - val owner = _m.owner; - val selector = _m.selector; - val elementType = elementType1; - } - - val trace = ltis.getTrace(); - - // (c) determinize + translate R - - val dRight = new DetWordAutom( right, left, dLeft ); - - val seqVars1 = collectNfaVariables( left ); - //System.out.println("seqVars here are:"+seqVars); - val rtis = new RightTracerInScala { - val dfa = dRight; - val owner = _m.owner; - val pat = pat1; - val seqVars = seqVars1; - val elementType = elementType1; - } - - // !!! Tree stms2 = rtis.getStms( theTrace, cunit, body ); - // !!! gen.mkBlock_( body.pos, trace, stms2 ); - val stms2 = rtis.getStms( trace, cunit, body ); - stms2; - } - - private def buildNfas( pat:scala.List[Tree] ): Array[NondetWordAutom] = { - val build = new BerrySethi; - val manyNfa = new Array[NondetWordAutom]( pat.length ); - var i = 0; - val it = pat.elements; - while( i < pat.length ) { - manyNfa( i ) = build.automatonFrom( it.next, new Integer( i )); - i = i + 1; - //manyNfa[ i ].print(); - } - manyNfa; - } - - /** constructs a word recognizer from an array of patterns which - * should all be SequencePatterns ( no wildcard * ) - * precondition: pat.type corresponds to element type - * @param _m Matcher object, holds the result - * @param pat the (Sequence) patterns - * @param body the bodies - * @param defaultCase code that is run when nothing matches. may be null, it - * becomes a ThrowMatchError then - * @param doBinding flasg that indicates whether variables should be bound - */ - def construct(_m: PartialMatcher, pat: scala.List[Tree] , body: scala.List[Tree] , defcase1: Tree, doBinding: Boolean ): Unit = { - var defaultCase = defcase1; - this._m = _m; - //assert body.length == pat.length; - if( defaultCase == null ) - defaultCase = ThrowMatchError( _m.pos, resultType ); - - val seqType = pat( 0 ).tpe; - val elementType1 = getElemType_Sequence( seqType ); - - // STEP 1 - build nfas for each pattern - - val manyNfa = buildNfas( pat ); - - // STEP 2 - recognizing - - // (a) merge nfas into one if necessary - val nfa = if(pat.length > 1) - new NondetWordAutom( manyNfa ) - else - manyNfa( 0 ); - - //nfa.print(); - - // (b) determinize - val dfa1 = new DetWordAutom( nfa ); - - // (c) translate to scala code - val scalaAut = - new WordAutomInScala{ - val dfa = dfa1; - val owner = _m.owner; - val optim = settings.target == "jvm"; - val elementType = elementType1; - } - scalaAut.translate(); - - // STEP 3 - binding - - var newbody: scala.List[Tree] = Nil; - if( !doBinding ) - newbody = body; - else { // this is done in the body of the matching case - var i = 0; - while(i < body.length) { - if( !containsBinding( pat( i ) ) ) - newbody = body( i ) :: newbody; // no need for binding - else - newbody = addBinderToBody( pat( i ), body( i ) ) :: newbody; - i = i + 1; - } - newbody = newbody.reverse; - } - _m.tree = scalaAut.getMatcherSwitch( _m.selector, - defaultCase, - newbody ); - } // construct (PartialMatcher, Tree[], Tree[], Tree, boolean ) - - } // class SequenceMatcher -} diff --git a/sources/scala/tools/nsc/matching/StateSetComparator.scala b/sources/scala/tools/nsc/matching/StateSetComparator.scala deleted file mode 100644 index 99942f38d5..0000000000 --- a/sources/scala/tools/nsc/matching/StateSetComparator.scala +++ /dev/null @@ -1,34 +0,0 @@ -package scala.tools.nsc.matching ; - -import java.util.{Comparator, TreeSet} ; - -class StateSetComparator extends Comparator { - // use lexicographic order - def compare(o1: Any , o2: Any ): Int = { - /* - System.out.print("lexi" ); - System.out.print( o1 +" "); - System.out.println( o2 ); - */ - val it1 = o1.asInstanceOf[TreeSet].iterator(); - val it2 = o2.asInstanceOf[TreeSet].iterator(); - while( it1.hasNext() ) { - while( it2.hasNext() ) { - if( !it1.hasNext() ) - return -1; - - val i1 = it1.next().asInstanceOf[Integer].intValue(); - val i2 = it2.next().asInstanceOf[Integer].intValue(); - if( i1 < i2 ) - return -1; - else if ( i1 > i2 ) - return 1; - } - if( it1.hasNext() ) - return 1; - } - if( it2.hasNext() ) - return -1; - return 0; - } -} diff --git a/sources/scala/tools/nsc/matching/TransMatcher.scala b/sources/scala/tools/nsc/matching/TransMatcher.scala deleted file mode 100644 index bca478b0dc..0000000000 --- a/sources/scala/tools/nsc/matching/TransMatcher.scala +++ /dev/null @@ -1,301 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ -package scala.tools.nsc.matching; - -/** Translation of pattern matching - */ -abstract class TransMatcher extends transform.Transform -with PatternNodes -with CodeFactory -with PatternMatchers -with SequenceMatchers -with AlgebraicMatchers -with MatcherLabels -with BerrySethis -with DetWordAutoms -with NondetWordAutoms -with Autom2 -with WordAutoms -with LeftTracers -with RightTracers { - - import global._; - import definitions._; - import posAssigner.atPos; - import typer.typed; - - val phaseName = "transmatcher"; - - protected def newTransformer(unit: global.CompilationUnit): global.Transformer = { - cunit = unit; - new TransMatch - } - - /** container. classes AlgebraicMatcher and SequenceMatcher get input and - * store their results in here. resembles the 'Memento' design pattern, - * could also be named 'Liaison' - */ - abstract class PartialMatcher { - - /** owner of the code we create (input) - */ - val owner: Symbol; - - /** the selector value (input) - */ - val selector:Tree; - - /** tree representing the matcher (output) - */ - var tree: Tree = _ ; - - def pos: int = selector.pos; - - //assert( owner != null ) : "owner is null"; - //assert owner != Symbol.NONE ; - //this.owner = owner; - - //assert root != null; - //assert root.type != null; - //this.selector = root; - - //assert this.resultType != Type.NoType; - //this.resultType = resultType; - - //this.pos = root.pos; // for convenience only - - } - - var cunit: CompilationUnit = _; - - def fresh = cunit.fresh ; - - var currentOwner: Symbol = _; - - var resultType: Type = _; - - def containsBinding(pat: Tree): Boolean = { - var generatedVars = false; - - def handleVariableSymbol(sym: Symbol): Unit = - if (sym.name.toString().indexOf("$") == -1) { - generatedVars = true; // .add(sym); - } - - def isVariableName(name: Name): Boolean = - ( treeInfo.isVariableName(name) ) && ( name != nme.USCOREkw ) ; - - def isVariableSymbol(sym: Symbol): Boolean = - ( sym != null )&&( !sym.isPrimaryConstructor ); - - def traverse(tree: Tree): Unit = { - - tree match { - case x @ Ident(name) => - if(x.symbol != definitions.PatternWildcard) - error("shouldn't happen?!"); - - case Bind(name, subtree) => - var sym: Symbol = null; - - if (isVariableName(name) - && isVariableSymbol( {sym = tree.symbol; tree.symbol} )) - handleVariableSymbol(sym); - - traverse( subtree ); - - // congruence - - case Apply(fun, args) => args foreach traverse; - case Sequence(trees) => trees foreach traverse - case Star(arg) => traverse(arg) - case Typed(expr, tpe) => traverse(expr); // needed?? - - case _ : Select | - _ : Alternative | - _ : Select | - _ : Literal => ; // no variables - - case _ => - error("unknown pattern node:" + tree + " = " + tree.getClass()); - } - } - traverse(pat); - generatedVars; - } - - class TransMatch extends Transformer { - - /** a casedef with sequence subpatterns like - * - * case ..x @ ().. => body - * - * should be replaced straight away with - * - * case .. () .. => val x = Nil; body - */ - def isRegular(pats:List[CaseDef]): Pair[List[CaseDef],Boolean] = { - var existsReg = false; - var isReg = false; - var nilVars:List[Symbol] = null; - - def isRegular1(pat: Tree): Tree = pat match { - case Alternative(trees) => - copy.Alternative(pat, trees map { isRegular1 }); - - case Star(t) => isReg = true; copy.Star(pat, isRegular1(t) ); - - case Ident(_) => pat; - - case Bind( id, empt @ Sequence(List())) => - nilVars = pat.symbol /*id.symbol()*/ :: nilVars; - empt; - case Bind( n, pat1 ) => copy.Bind(pat, n, isRegular1( pat1 )); - - case Sequence( trees ) => - //isReg = isReg || ( trees.length == 0 ); - isReg = true; // cause there are ArrayValues now - copy.Sequence(pat, trees map { isRegular1 }); - - case ArrayValue( tt, List(b @ Bind(id, Star(wc @ Ident(nme.WILDCARD))))) => - //Console.println("OPTIMIZING"); - //Console.println(pat); - //Console.println(pat.tpe); - //Console.println(b.tpe); - b.symbol.setInfo(pat.tpe); - b.setType(pat.tpe); - val res = copy.Bind(b, id, wc); - //Console.println("====>"); - //Console.println(res); - res - - case ArrayValue( s, trees ) => - //Console.println("XXX ArrayValue, trees="+trees); - copy.ArrayValue( pat, s, (trees map { isRegular1 })); - - case Apply( fn, List(Sequence(List()))) => - pat; - - case Apply( fn, trees ) => - //Console.println(" IN isRegular, apply node "+pat.toString()); - //Console.println(" trees are:"+(trees map {x => x.getClass().toString()})); - copy.Apply( pat, fn, ( trees map { isRegular1 }) ) - - case Literal(_) => pat - case Select(_,_) => pat - case Typed(_,_) => pat - - //case _ => - // Console.println(pat); - // Console.println(pat.getClass()); - // scala.Predef.error(" what is this ? ") - } - - var res:List[CaseDef] = Nil; - val it = pats.elements; while(it.hasNext) { - nilVars = Nil; - val cdef = it.next; - val newt = isRegular1(cdef.pat); - existsReg = existsReg || isReg; - - val nbody = if(nilVars.isEmpty) cdef.body else - atPos(cdef.body.pos)( - Block(nilVars map { - x => ValDef(x, Ident(definitions.NilModule)) - }, cdef.body) - ); - - res = copy.CaseDef(cdef, newt, cdef.guard, nbody) :: res; - } - Pair(res.reverse, existsReg); - } - - - - def handle(sel:Tree, ocases:List[CaseDef]): Tree = { - - - // 1. is there a regular pattern? - - val Pair(cases, containsReg) = isRegular(ocases); - - // @todo: remove unused variables - - if(containsReg) { - // 2. replace nilVariables - //@todo: bring over AlgebraicMatcher - /* - val matcher = new PartialMatcher { - val global: TransMatcher.this.global.type = TransMatcher.this.global; - val owner = currentOwner; - val selector = sel ; - } - new AlgebraicMatcher() { - val tm: TransMatcher.this.type = TransMatcher.this; - }.construct( matcher, cases ); - matcher.tree - */ - System.out.println("" + sel + " match " + ocases); - scala.Predef.error("regular expressions not yet implemented"); - } else { - val pm = new PatternMatcher(); - pm.initialize(sel, currentOwner, true ); - pm.construct( cases ); - //if (global.log()) { - // global.log("internal pattern matching structure"); - // pm.print(); - //} - pm.toTree() - } - } - override def transform(tree: Tree): Tree = tree match { - /* // test code to generate forward jumps - case Match(selector, CaseDef(Ident(nme.WILDCARD), EmptyTree, exp)::Nil) => // inserting test-code - - val target1 = currentOwner.newLabel(tree.pos, "target1") - .setInfo(new MethodType(List(definitions.IntClass.tpe), definitions.IntClass.tpe)); - - val a = currentOwner.newValue(tree.pos, "a").setInfo(definitions.IntClass.tpe); - val x = currentOwner.newValueParameter(tree.pos, "x").setInfo(definitions.IntClass.tpe); - val y = currentOwner.newValueParameter(tree.pos, "y").setInfo(definitions.IntClass.tpe); - val target2 = currentOwner.newLabel(tree.pos, "target2") - .setInfo(new MethodType(List(definitions.IntClass.tpe, definitions.IntClass.tpe), definitions.IntClass.tpe)); - - val z = currentOwner.newValueParameter(tree.pos, "z").setInfo(definitions.IntClass.tpe); - typed { atPos(tree.pos) { Block( - List( - Apply(Ident(target2), List(Literal(Constant(1)),Literal(Constant(2)))), - LabelDef(target1, List(x), exp)), - LabelDef(target2, List(y,z), Apply(Select(Ident(y), nme.PLUS), List(Ident(z)))) - )}}; -*/ - - case Match(selector, cases) => - val nselector = transform(selector).setType(selector.tpe); - val ncases = cases map { transform }; -/* - Console.println("TransMatch translating cases: "); - for(val t <- cases) { - Console.println(t.pat.toString()); - Console.println("BODY "+t.body.toString()); - } -*/ - // @todo: remove from partial matcher - TransMatcher.this.currentOwner = currentOwner; - TransMatcher.this.resultType = tree.tpe; - //Console.println("TransMatcher currentOwner ="+currentOwner+")"); - //Console.println("TransMatcher selector.tpe ="+selector.tpe+")"); - //Console.println("TransMatcher resultType ="+resultType+")"); - val t_untyped = handle(nselector, ncases.asInstanceOf[List[CaseDef]]); - //Console.println("t_untyped "+t_untyped.toString()); - val t = typed { atPos(tree.pos) (t_untyped) }; - //Console.println("t typed "+t.toString()); - t - case _ => - super.transform(tree); - } - } -} diff --git a/sources/scala/tools/nsc/matching/WordAutoms.scala b/sources/scala/tools/nsc/matching/WordAutoms.scala deleted file mode 100644 index de17fc6445..0000000000 --- a/sources/scala/tools/nsc/matching/WordAutoms.scala +++ /dev/null @@ -1,146 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author buraq - */ -// $Id$ - -package scala.tools.nsc.matching; - -import java.util._ ; - -import scala.tools.nsc.util.Position; - -trait WordAutoms: TransMatcher { - - import global._ ; - /** translates a recognizer to scala code - */ - - /** constructor - * @param dfa the dfa that is to be translated - * @param elementType type of the objects in the sequence - * @param owner the owner of the pattern match - * @param cf code factory - * @param optim flag that indicates whether to optimize - * @return an object that translates the dfa - */ -abstract class WordAutomInScala extends Autom2Scala { - - val optim: Boolean; - - this.optimize = this.optimize && optim; - - var theLabelDef: Tree = _ ; - - def getMatcherSwitch(selector: Tree, failTree: Tree, body: scala.List[Tree] /*, resultType: Type*/ ): Tree = { - - var result: Tree = null; - var ncases: scala.List[CaseDef] = Nil; - val it = body.reverse.elements; - //val tags = new Array[int](body.length); - var i = body.length - 1; - while( i >= 0 ) { - //tags(i) = i; - ncases = CaseDef(Literal(i), it.next) :: ncases; - i = i - 1 - } - - ncases= ncases::: CaseDef(Ident(nme.WILDCARD),failTree) :: Nil; - result = Match( _swres(), ncases ); - - //} - - result = - Block( - scala.List ( - ValDef( iterSym, newIterator( selector.duplicate )), - ValDef( stateSym, Literal(0) ), - ValDef( resultSym, theLabelDef )), - result - ); - //unit.global.debugPrinter.print( result ); - result; - } - - protected def initializeSyms(): Unit = { // TEST - - this.funSym = owner.newLabel( pos, fresh.newName( "matcher" )); - - this.iterSym = owner.newVariable( pos, fresh.newName("iter")) - .setInfo( _seqIterType( elementType ) ) ; - - this.stateSym = owner.newVariable( pos, fresh.newName("q")) - .setInfo( definitions.IntClass.info ) ; - - this.resultSym = owner.newVariable( pos, fresh.newName("swRes")) - .setInfo( definitions.IntClass.info ) ; - - this.funSym.setInfo( MethodType(scala.List (definitions.IntClass.info), - definitions.IntClass.info )); - - this.curSym = owner.newVariable( pos, "cur" /*Names.cur*/ ) - .setInfo( elementType ); - - this.hasnSym = owner.newVariable( pos, nme.hasNext ) - .setInfo( definitions.BooleanClass.info ); - - } - - /** code for the return value of the automaton translation - */ - override def run_finished(state: Int): Tree = { // T E S T - if( dfa.isFinal(state)) - Literal(dfa.finals.get(new Integer(state)).asInstanceOf[Integer].intValue()); - else - Literal(FAIL); - } - - - // calling the /*AlgebraicMatcher*/PatternMatcher here - override def _cur_match(pat: Tree): Tree = { // TE ST - val m = new PartialMatcher { - val owner = WordAutomInScala.this.owner; /* owner*/ - val selector = currentElem(); /* root */ - // restyp definitions.BooleanClass.info /* restype */); - } - - am.construct( m, scala.List ( - CaseDef( pat, Literal( true )), - CaseDef( Ident(definitions.PatternWildcard), Literal( false )) ), - false); - am.toTree(); - } - - /** do the translation - */ - def translate(): Unit = { - initializeSyms(); - val tb = code_body_NEW(); - //theLabelDef = gen.DefDef(this.funSym, tb); - theLabelDef = LabelDef(this.funSym, scala.List( stateSym ), tb); - } - - /** ... - * @return returns translation of transition with label from i. - * returns null if there is no such transition - * (no translation needed) - */ - override def code_delta(i: Int, label: Label): Tree = { - val target = dfa.delta(i, label); - - if (target == null) - label match { - case DefaultLabel() => - code_error(); // this may not happen ! - case _ => - null; // not good - } - else if (target.intValue() == dfa.nstates() - 1) // that one is a dead state - code_fail(); - else - callFun(scala.List( Literal(target.intValue() ))); - } - -} -} - diff --git a/sources/scala/tools/nsc/models/Models.scala.xxx b/sources/scala/tools/nsc/models/Models.scala.xxx deleted file mode 100644 index e95976ed19..0000000000 --- a/sources/scala/tools/nsc/models/Models.scala.xxx +++ /dev/null @@ -1,189 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id: Trees.scala,v 1.35 2005/11/14 16:58:21 mcdirmid Exp $ -package scala.tools.nsc.models; - -import scala.tools.nsc.Global; -import scala.tools.nsc.ast.Trees; -import scala.tools.nsc.symtab.Flags; -import scala.tools.nsc.symtab.Names; - -[_trait_] abstract class Models { - val global : Global; - - import global._; - - abstract class Model { - } - abstract class HasTree extends Model { - var tree : Tree = _; - def update(tree0 : Tree): Boolean = { - tree = tree0; - false; - } - def replacedBy(tree0 : Tree) : Boolean = true; - } - class ImportMod extends HasTree { - def treex = tree.asInstanceOf[Import]; - - override def replacedBy(tree0 : Tree) : Boolean = if (super.replacedBy(tree0) && tree0.isInstanceOf[Import]) { - val tree1 = tree0.asInstanceOf[Import]; - tree1.tpe == treex.tpe; - } else false; - } - - abstract class Composite extends Model { - import scala.collection.mutable._; - class Members extends HashSet[HasTree] with ObservableSet[HasTree, Members] { - override def +=(elem: HasTree): Unit = super.+=(elem); - override def -=(elem: HasTree): Unit = super.-=(elem); - override def clear: Unit = super.clear; - } - object members extends Members; - - def isMember(tree : Tree) : Boolean = false; - - def update0(members1 : List[Tree]) : Boolean = { - val marked = new HashSet[HasTree]; - var updated = false; - for (val mmbr1 <- members1) { - var found = false; - for (val mmbr <- members) if (!found && mmbr.replacedBy(mmbr1)) { - found = true; - updated = mmbr.update(mmbr1) || updated; - marked += mmbr; - } - if (!found) { - updated = true; - val add = modelFor(mmbr1); - add.update(mmbr1); - members += (add); - marked += add; - } - } - val sz = members.size; - members.intersect(marked); - updated = updated || sz < members.size; - // check if anything was removed! - updated; - } - } - abstract class MemberMod extends HasTree { - def treex = tree.asInstanceOf[MemberDef]; - def flags = new Flags.Flag(treex.mods0); - def name : Name = { treex.name0; } - - override def replacedBy(tree0 : Tree) : Boolean = if (super.replacedBy(tree0) && tree0.isInstanceOf[MemberDef]) { - val tree1 = tree0.asInstanceOf[MemberDef]; - treex.name0 == tree1.name0; - } else false; - - override def update(tree0 : Tree): Boolean = { - val updated = tree == null || (treex.mods0 != tree0.asInstanceOf[MemberDef].mods0); - super.update(tree0) || updated; - } - } - abstract class MemberComposite extends MemberMod with Composite; - - abstract class HasClassObjects extends Composite { - override def isMember(tree : Tree) : Boolean = super.isMember(tree) || tree.isInstanceOf[ImplDef]; - } - abstract class ValOrDefMod extends MemberComposite with HasClassObjects { - def treey = tree.asInstanceOf[ValOrDefDef]; - override def replacedBy(tree0 : Tree) : Boolean = (super.replacedBy(tree0) && tree0.isInstanceOf[ValOrDefDef]); - - override def update(tree0 : Tree): Boolean = { - val tree1 = tree0.asInstanceOf[ValOrDefDef]; - val updated = tree == null || treex.tpe != tree1.tpe; - update0(flatten(tree1.rhs0, (tree2 : Tree) => isMember(tree2))); - super.update(tree0) || updated; - } - } - class ValMod extends ValOrDefMod { - def treez = tree.asInstanceOf[ValDef]; - override def replacedBy(tree0 : Tree) : Boolean = (super.replacedBy(tree0) && tree0.isInstanceOf[ValDef]); - } - class DefMod extends ValOrDefMod { - def treez = tree.asInstanceOf[DefDef]; - - override def replacedBy(tree0 : Tree) : Boolean = if (super.replacedBy(tree0) && tree0.isInstanceOf[DefDef]) { - val tree1 = tree0.asInstanceOf[DefDef]; - if (tree1.vparamss.length == treez.vparamss.length) { - val tpz = for (val vd <- treez.vparamss) yield for (val xd <- vd) yield xd.tpe; - val tp1 = for (val vd <- tree1.vparamss) yield for (val xd <- vd) yield xd.tpe; - tpz == tp1; - } else false; - } else false; - } - abstract class ImplMod extends MemberComposite with HasClassObjects { - def treey = tree.asInstanceOf[ImplDef]; - override def replacedBy(tree0 : Tree) : Boolean = (super.replacedBy(tree0) && tree0.isInstanceOf[ImplDef]); - override def isMember(tree : Tree) : Boolean = super.isMember(tree) || tree.isInstanceOf[ValOrDefDef] || tree.isInstanceOf[AliasTypeDef]; - - override def update(tree0 : Tree): Boolean = { - val tree1 = tree0.asInstanceOf[ImplDef]; - - var updated = update0(tree1.impl0.body); - - // XXX: ignore parents for now! - - (super.update(tree0) || updated) && !flags.isPrivate; - } - - - } - class ClassMod extends ImplMod { - def treez = tree.asInstanceOf[ClassDef]; - override def replacedBy(tree0 : Tree) : Boolean = (super.replacedBy(tree0) && tree0.isInstanceOf[ClassDef]); - - override def update(tree0 : Tree): Boolean = { - // XXX: type parameters and this type! - - - super.update(tree0); - } - } - class ObjectMod extends ImplMod { - def treez = tree.asInstanceOf[ModuleDef]; - override def replacedBy(tree0 : Tree) : Boolean = (super.replacedBy(tree0) && tree0.isInstanceOf[ModuleDef]); - } - class AliasTypeMod extends MemberMod { - def treey = tree.asInstanceOf[AliasTypeDef]; - override def replacedBy(tree0 : Tree) : Boolean = (super.replacedBy(tree0) && tree0.isInstanceOf[AliasTypeDef]); - } - class SourceMod(val unit : CompilationUnit) extends Composite with HasClassObjects { - override def isMember(tree : Tree) : Boolean = super.isMember(tree) || tree.isInstanceOf[Import]; - } - - - def flatten0(exprs : List[Tree], filter: (Tree) => Boolean) : List[Tree] = - for (val expr <- exprs; val t : Tree <- flatten(expr,filter)) yield t; - - def flatten(expr : Tree, filter: (Tree) => Boolean) : List[Tree] = - if (filter(expr)) expr :: Nil; else expr match { - case Block(stats,last) => flatten0(stats, filter) ::: flatten(last, filter); - case If(cond,thenp,elsep) => flatten(cond,filter) ::: flatten(thenp,filter) ::: flatten(elsep,filter); - case Assign(lhs,rhs) => flatten(rhs,filter); - case CaseDef(pat,guard,body) => flatten(body,filter); - case Return(expr0) => flatten(expr0,filter); - case Throw(expr0) => flatten(expr0,filter); - case Try(block,catches,finalizer) => flatten(block,filter) ::: flatten(finalizer,filter) ::: flatten0(catches, filter); - case Match(selector,cases) => flatten(selector,filter) ::: flatten0(cases, filter); - case Apply(fun,args) => flatten(fun,filter) ::: flatten0(args,filter); - case TypeApply(fun,args) => flatten(fun,filter) ::: flatten0(args,filter); - case _ => Nil; - } - - - def modelFor(tree: Tree): HasTree = tree match { - case _: ValDef => new ValMod(); - case _: DefDef => new DefMod(); - case _: ClassDef => new ClassMod(); - case _: ModuleDef => new ObjectMod(); - case _: AliasTypeDef => new AliasTypeMod(); - case _: Import => new ImportMod(); - } - -} diff --git a/sources/scala/tools/nsc/models/SemanticTokens.scala b/sources/scala/tools/nsc/models/SemanticTokens.scala deleted file mode 100644 index 51d127b54b..0000000000 --- a/sources/scala/tools/nsc/models/SemanticTokens.scala +++ /dev/null @@ -1,513 +0,0 @@ - -package scala.tools.nsc.models; - -import scala.tools.nsc.{Global => Compiler}; -import scala.tools.nsc.symtab.{Flags,Names}; -import scala.tools.nsc.util.{NameTransformer,Position,SourceFile}; -import scala.collection.mutable.{HashMap,HashSet}; - - -class SemanticTokens(val compiler: Compiler) { - import compiler._; - - abstract class Kind {} - object OBJECT extends Kind; - object CLASS extends Kind; - object DEF extends Kind; - object VAL extends Kind; - object VAR extends Kind; - object ARG extends Kind; - object TPARAM extends Kind; - - // static constants here. - - abstract class Token { - def length : Int; - - def prev : HasNext; - def next : HasPrev; - } - - [_trait_] abstract class HasNext extends Token { - var next0 : HasPrev = _; - def next = next0; - } - [_trait_] abstract class HasPrev extends Token { - var prev0 : HasNext = _; - def prev = prev0; - } - abstract class Actual extends HasNext with HasPrev { - def convertToGap : Pair[Int,Actual] = { - val nextGap = next.isInstanceOf[Gap]; - val prevGap = prev.isInstanceOf[Gap]; - if (prevGap) { - val ret = prev.length; - val gap = prev.asInstanceOf[Gap]; - gap.setLength(gap.length + length); - if (nextGap) { - gap.setLength(gap.length + next.length); - gap.next0 = next.next; - next.next.prev0 = gap; - } else { - gap.next0 = next; - next.prev0 = gap; - } - new Pair(ret,gap); - } else if (nextGap) { - val gap = next.asInstanceOf[Gap]; - gap.setLength(gap.length + length); - gap.prev0 = prev; - prev.next0 = gap; - new Pair(0,gap); - } else { - prev.next0 = next; - next.prev0 = prev; - val gap = new Gap(prev); - gap.setLength(length); - new Pair(0,gap); - } - } - def insert(prev1 : HasNext) = { - next0 = prev1.next; - prev0 = prev1; - prev0.next0 = this; - next0.prev0 = this; - } - } - final class Gap extends Actual { - def this(prev1 : HasNext) = { - this(); - insert(prev1); - } - override def toString() = "gap-" + length; - - var length0 : Int = -1; - def length : Int = length0; - def setLength(length1 : Int) = length0 = length1; - - // already gap - override def convertToGap : Pair[Int,Actual] = new Pair(0, this); - } - class Process(val unit : CompilationUnit) { - def source = unit.source; - - val symbols = new HashMap[Symbol,Info]; - - - class Info(val symbol : Symbol) { - var defined : Def = _; - val uses = new HashSet[Use]; - symbols.update(symbol, this); - } - def info(symbol : Symbol) : Info = if (symbols.contains(symbol)) symbols(symbol) else new Info(symbol); - - abstract class Semantic(val symbol : Symbol) extends Actual { - val name = NameTransformer.decode(symbol.name.toString()).toString().trim(); - assert(symbol != NoSymbol); - - - def length = name.length(); - def info : Info = if (symbols.contains(symbol)) symbols(symbol) else new Info(symbol); - - def kind = { - val term0 = symbol; - if (false) null; - else if (term0.isVariable) VAR; - else if (term0.isValueParameter) ARG; - else if (term0.isMethod) DEF; - else if (term0.isClass) CLASS; - else if (term0.isModule) OBJECT; - else if (term0.isValue ) VAL; - else if (term0.isTypeParameter) TPARAM; - else { - // System.err.println("UNRECOGNIZED SYMBOL: " + term0 + " " + name); - null; - } - }; - } - class Def(symbol0 : Symbol) extends Semantic(symbol0) { - info.defined = this; - override def toString() = "def-" + name + "-" + symbol.getClass(); - } - class Use(symbol0 : Symbol) extends Semantic(symbol0) { - info.uses += this; - - override def toString() = "use-" + name; - } - val list = new TokenList; - - build(unit.body); - - // ok start building.... - def build[T <: Tree](trees : List[T]) : Unit = for (val tree : T <- trees) build(tree); - - def build(tree0 : Tree) : Unit = { - tree0 match { - //case tree: SymTree => System.err.println("TREE: " + tree.getClass() + " " + tree.symbol + " " + (new Position(unit.source, tree.pos)).dbgString); - case _ => - } - if (tree0.pos != Position.NOPOS) tree0 match { - - - case tree : ImplDef => - val pos = tree.namePos(unit.source); - if (pos == Position.NOPOS) { - // inner types. - // System.err.println("NOPOS: " + tree.getClass() + " " + (new Position(unit.source, tree.pos)).dbgString); - //Thread.dumpStack(); - } else buildDef(tree.symbol, tree.namePos(unit.source)); - tree match { - case cdef : ClassDef => build(cdef.tparams); - case _ => ; - } - build(tree.impl.parents); - build(tree.impl.body); - case tree : ValOrDefDef => - if (tree.symbol.hasFlag(Flags.ACCESSOR)) { - // ignore - ; - } else { - { - val pos = if (tree.name.toString().equals("")) Position.NOPOS else tree.namePos(unit.source); - if (pos != Position.NOPOS) { - if (!tree.hasFlag(Flags.SYNTHETIC)) - buildDef(tree.symbol, pos); - } - } - - if (tree.isInstanceOf[DefDef]) { - val ddef = tree.asInstanceOf[DefDef]; - build(ddef.tparams); - - for (val l0 <- ddef.vparamss; val arg <- l0) { - - val pos0 = if (!unit.source.beginsWith(arg.pos, "val ")) arg.pos; - else unit.source.skipWhitespace(arg.pos + ("val ").length()); - buildDef(arg.symbol, pos0); - build(arg.tpt); - } - } - try { - build(tree.tpt); - } catch { - case e: Error => - System.err.println("VALDEF: " + tree + " " + tree.tpt + " " + tree.pos + " " + tree.tpt.pos); - throw e; - } - build(tree.rhs); - } - case tree : PackageDef => - //System.err.println("PACKAGE: " + tree.name); - if (false) { - val pos = tree.namePos(unit.source); - if (pos != Position.NOPOS) - buildDef(tree.symbol, pos); - } - build(tree.stats); - case tree : Function => - for (val arg <- tree.vparams) if (arg.pos != Position.NOPOS) { - val name = arg.name.toString().trim(); - val pos : Int = - if (unit.source.beginsWith(arg.pos, "val ")) unit.source.skipWhitespace(arg.pos + ("val ").length()); - else if (unit.source.content(arg.pos) == ':') { - var posx = arg.pos; - while (Character.isWhitespace(unit.source.content(posx - 1))) posx = posx - 1; - posx - name.length(); - } else arg.pos; - buildDef(arg.symbol, pos); - build(arg.tpt); - } - build(tree.body); - case tree : TypeTree => - val tree1 = if (tree.original != null) tree.original; else tree; - buildT(tree1, tree.tpe); - def buildT( tree : Tree, tpe : Type) : Unit = if (tree.pos != Position.NOPOS) tpe match { - case tpe0 : TypeRef => tree match { - case apt : AppliedTypeTree => - buildUse(tpe.symbol, apt.tpt.pos); - //System.err.println("APT: " + apt.tpt + " sym0=" + apt.tpt.symbol + " sym1=" + tpe0.sym + " " + " " + apt.args + " " + tpe0.args); - - buildTs (apt.args, tpe0.args); - case ident : Ident => buildUse(tpe0.sym, ident.pos); - case select : Select => - // System.err.println("BUILD_SELECT: " + select + " @ " + tpe0); - try { - build(select); - } catch { - case e : Error => - System.err.println("BUILD_SELECT: " + select + " @ " + tpe0 + " " + unit.source.dbg(select.pos)); - throw e; - } - case tpt : TypeTree => - //System.err.println("UNKNOWN TPT0: " + tpe0 + " " + tpe0.args + " " + tpt); - case sft : SelectFromTypeTree => - build(sft.qualifier); // XXX: broken - if (false) System.err.println("SFTT: " + sft + " sym=" + sft.symbol + " selector=" + sft.selector + " qual=" + sft.qualifier + " qual.sym=" + - sft.qualifier.symbol + - " qual.pos=" + unit.source.dbg(sft.qualifier.pos) + " symbol=" + sft.symbol + " type=" + tpe0 + - " type.sym=" + tpe0.symbol); - case _ => System.err.println("UNKNOWN TPT2: " + tree + " vs. " + tpe0 + " " + tree.getClass() + " " + unit.source.content(tree.pos)); - } - case tpe0 : MethodType => tree match { - case tpt: TypeTree => - if (tpt.original != null) buildT(tpt.original, tpe); - else { - System.err.println("UNKNOWN TPT3: " + tree + " vs. " + tpe0 + " " + unit.source.content(tree.pos)); - } - case ident : Ident => buildT(ident, tpe0.resultType); - case select : Select => buildT(select, tpe0.resultType); - case _ => System.err.println("UNKNOWN TPE: " + tree + " vs. " + tpe0 + " " + tree.getClass()); - } - case _ => // System.err.println("UNKNOWN: " + tree + " " + (if (tree != null) tree.getClass() else null) + " vs. " + tpe + " " + (if (tpe != null) tpe.getClass() else null) + " " + (if (tree != null) tree.pos else null)); - }; - def buildTs(trees : List[Tree], types : List[Type]): Unit = if (!trees.isEmpty || !types.isEmpty) { - buildT (trees.head, types.head); - buildTs(trees.tail, types.tail); - }; - case tree : AbsTypeDef => buildDef(tree.symbol, tree.namePos); - case tree : Bind => buildDef(tree.symbol, tree.pos); - build(tree.body); - case tree : Ident => buildUse(tree.symbol, tree.pos); - case tree : Select => - // System.err.println("SELECT: " + tree.qualifier + " ** " + tree.symbol + " " + selectPos(tree)); - try { - build(tree.qualifier); - } catch { - case e : Error => System.err.println("SELECTQ: " + tree + " " + tree.qualifier + " " + unit.source.dbg(tree.qualifier.pos)); throw e; - } - try { - if (tree.pos >= unit.source.content.length) - System.err.println("BAD_SELECT_QUALIFIER " + tree + " @ " + tree.pos); - else buildUse(tree.symbol, selectPos(tree)); - } catch { - case e : Error => System.err.println("SELECTU: " + tree + " " + tree.symbol + " " + unit.source.dbg(tree.pos)); throw e; - } - case tree : GenericApply => - //System.err.println("APPLY-FUN: " + tree.fun0 + " " + tree.args0); - build(tree.fun0); - //System.err.println("APPLY-ARG: " + tree.fun0 + " " + tree.args0); - build(tree.args0); - case tree : Typed => build(tree.expr); build(tree.tpt); - case tree : Import => - //System.err.println("IMPORT: " + tree.expr + " " + tree.selectors); - - build(tree.expr); - case tree : Block => build(tree.stats); build(tree.expr); - case tree : CaseDef => - build(tree.pat); build(tree.guard); build(tree.body); - case tree : Sequence => build(tree.trees); - case tree : Assign => build(tree.lhs); build(tree.rhs); - case tree : If => build(tree.cond); build(tree.thenp); build(tree.elsep); - case tree : New => build(tree.tpt); - case tree : Match => build(tree.selector); build(tree.cases); - case tree : Return => build(tree.expr); - case tree : LabelDef => build(tree.rhs); - case tree : Throw => build(tree.expr); - case tree : Try => build(tree.block); build(tree.catches); build(tree.finalizer); - case tree : Literal => ; - case tree : This => ; - case tree : Super => ; - case _ => ; - if (tree0 != EmptyTree) - System.err.println("BAIL: " + tree0.pos + " " + tree0 + " " + tree0.getClass()); - } - } - def buildUse(term : Symbol, pos : Int) = buildSym(term, pos, false); - def buildDef(term : Symbol, pos : Int) = buildSym(term, pos, true); - - def buildSym(term : Symbol, pos : Int, isDef : Boolean) : Unit = if (term.hasFlag(Flags.ACCESSOR)) buildSym(term.accessed, pos, isDef) - else if (pos == Position.NOPOS) { - System.err.println("NOPOS: " + term); - Thread.dumpStack(); - } else if (term != NoSymbol) { - val name = NameTransformer.decode(term.name.toString()).toString().trim(); - val buf = unit.source.content; - val cs = name.toChars; - var idx = 0; - if (cs.length + pos > buf.length) { - return; - } - else while (idx < cs.length) - if (buf(pos + idx) != cs(idx)) { - // System.err.println("BAD SYM: " + term + " " + term.getClass()); - return; - } - else idx = idx + 1; - - list.put(pos, (if (isDef) new Def(term) else new Use(term))); - } - def selectPos(tree : Select): Int = if (tree.pos == Position.NOPOS) Position.NOPOS else { - val buf = unit.source.content; - if (tree.pos >= buf.length) { - System.err.println(""+tree + "@" + tree.pos + " not in " + unit.source.file.getName() + "[" + buf.length + "]"); - Thread.dumpStack(); - throw new Error(); - } - - val pos = - if (buf(tree.pos) != '.') tree.pos; - else { - def f(x : Int) : Int = { - if (Character.isWhitespace(buf(x))) f(x + 1); - else x; - } - f(tree.pos + 1); - } - pos; - }; - class TokenList { - object begin extends HasNext { - def prev = this; - def length = 0; - } - object end extends HasPrev { - def next = this; - def length = 0; - } - // initialize - begin.next0 = end; - end.prev0 = begin; - - - def tokenAt(offset : Int) = { - //System.err.println("CURSOR-0: " + cursor.offset); - cursor.seek(offset); - //System.err.println("CURSOR-1: " + cursor.offset + " " + cursor.token + " " + offset); - - if (cursor.token.isInstanceOf[Semantic]) cursor.token.asInstanceOf[Semantic]; - else null; - }; - def put(offset : Int, tok : Actual) : Unit = tok match { - case tok0 : Semantic => put(offset, tok0); - case gap : Gap => ; - } - - - def put(offset : Int, tok : Semantic) :Unit = { - cursor.seek(offset); - if (cursor.token == end) { - assert(offset >= cursor.offset); - if (offset > cursor.offset) { - // add a gap. - val gap = new Gap(end.prev); - gap.setLength(offset - cursor.offset); - cursor.offset = offset; - } - // append. - tok.insert(end.prev); - cursor.offset = cursor.offset + tok.length; - - } else if (!cursor.token.isInstanceOf[Gap]) { - val sem = cursor.token.asInstanceOf[Semantic]; - if (sem.symbol == tok.symbol) return; - if (sem.symbol != tok.symbol && - sem.symbol.getClass() == tok.symbol.getClass() && - sem.symbol.pos == tok.symbol.pos) return; - - System.err.println("NOT_GAP: " + sem.symbol + " " + sem.symbol.getClass() + " " + unit.source.dbg(sem.symbol.pos) + " " + sem.symbol.flags); - System.err.println("NOT_GAP: " + tok.symbol + " " + tok.symbol.getClass() + " " + unit.source.dbg(tok.symbol.pos) + " " + tok.symbol.flags); - System.err.println("LIST: " + this); - System.err.println("POS: " + unit.source.dbg(offset)); - - - Thread.dumpStack(); - throw new Error(); - } else { - val gap = cursor.token.asInstanceOf[Gap]; - if (!(offset - cursor.offset + tok.length <= gap.length)) { - System.err.println("LIST =" + this); - System.err.println("OFFSET=" + offset + " " + tok + " " + tok.length); - System.err.println(" " + cursor.offset + " " + gap.length); - throw new Error(); - } - if (offset == cursor.offset) { - // replace or prepend - tok.prev0 = gap.prev0; - if (tok.length == gap.length) { // replace gap - tok.next0 = gap.next0; - } else { - gap.setLength(gap.length - tok.length); - tok.next0 = gap; - } - tok.next0.prev0 = tok; - tok.prev0.next0 = tok; - cursor.token = tok; - } else { - // append - val diff = (cursor.offset + gap.length) - (offset + tok.length); - - gap.setLength(gap.length - tok.length - diff); - tok.prev0 = gap; - tok.next0 = gap.next; - tok.next0.prev0 = tok; - tok.prev0.next0 = tok; - if (diff != 0) { - val gap0 = new Gap(tok); - gap0.setLength(diff); - } - } - } - // System.err.println("PUT: " + this); - } - override def toString() = { - var node = begin.next; - var str = ""; - while (node != end) { - str = str + " " + node; - node = node.next; - } - str; - }; - object cursor { - var token : Token = end; - var offset : Int = 0; - - def next : Unit = if (token == end) end else { - offset = offset + token.length; - token = token.next; - } - def prev : Unit = if (token.prev == begin) token else { - offset = offset - token.prev.length; - token = token.prev; - } - def seek(soffset : Int) : Unit = if (soffset == 0) { - token = begin.next; - offset = 0; - } else { - assert(soffset > 0); - while (offset > soffset) prev; - while (offset + token.length <= soffset && token != end) { - val len0 = offset; - next; - } - } - def convertToGap = if (token.isInstanceOf[Actual]) { - val ret = token.asInstanceOf[Actual].convertToGap; - offset = offset - ret._1; - token = ret._2; - } - } - // add or delete characters - def adjust(offset: Int, /* where */ - length: Int, /* how many characters are modified */ - to : Int /* length of new string */) = { - cursor.seek(offset); - if (cursor.token != end) { - cursor.convertToGap; - while (cursor.offset + cursor.token.length < offset + length && cursor.token.next != end) { - val save = cursor.offset; - cursor.next; - cursor.convertToGap; - assert(cursor.offset == save); - } - if (length != to && cursor.token != end) { - val diff = to - length; - val gap = cursor.token.asInstanceOf[Gap]; - gap.setLength(gap.length + diff); - }; - } - } - }; - } -} - diff --git a/sources/scala/tools/nsc/models/Signatures.scala b/sources/scala/tools/nsc/models/Signatures.scala deleted file mode 100644 index 3a779a7021..0000000000 --- a/sources/scala/tools/nsc/models/Signatures.scala +++ /dev/null @@ -1,65 +0,0 @@ - -package scala.tools.nsc.models; - -import scala.tools.nsc.{Global => Compiler}; -import scala.tools.nsc.symtab.{Flags,Names}; -import scala.tools.nsc.util.{NameTransformer,Position,SourceFile}; -import scala.collection.mutable.{HashMap,HashSet}; - -class Signatures(val compiler: Compiler) { - import compiler._; - - class Signature(val name : String, val children : List[Signature]) { - def asString : String = name + "[" + asString0(children) + "]"; - } - def sort(sigs : List[Signature]) = - sigs.sort((l0,l1) => l0.name.compareTo(l1.name) > 0); - - def asString0(sigs : List[Signature]) : String = { - var ret = ""; - for (val sig <- sort(sigs)) - ret = ret + sig.asString; - ret; - } - - def signature(unit : CompilationUnit): String = asString0(signature(unit.body, Nil)); - - def signature(trees : List[Tree]) : List[Signature] = { - var ret : List[Signature] = Nil; - for (val tree <- trees) ret = signature(tree, ret); - ret; - } - def signature(tree0 : Tree, rest : List[Signature]) : List[Signature] = tree0 match { - case tree : MemberDef => if (!tree.mods.isPrivate) { - val name = "" + tree.name + "::" + tree.mods; - val children : List[Signature] = (tree match { - case impl : ImplDef => - val supers = new Signature("$$supers", signature(impl.impl.parents)); - val body = new Signature("$$body", signature(impl.impl.body)); - val ret = supers :: body :: Nil; - (impl match { - case cdef : ClassDef => new Signature("$$tparams", signature(cdef.tparams)) :: ret; - case _ => ret; - }); - case vdef : ValOrDefDef => - val ret = signature(vdef.tpt, Nil); - (vdef match { - case ddef : DefDef => - val tparams = new Signature("$$tparams", signature(ddef.tparams)); - var vparamss : List[Signature] = Nil; - for (val list <- ddef.vparamss) vparamss = signature(list) ::: vparamss; - tparams :: vparamss; - case _ => ret; - }); - case pdef : PackageDef => signature(pdef.stats); - case _ => Nil; - }); - new Signature(name, children) :: rest; - - } else rest; - case tree : TypeTree => new Signature("" + tree.tpe, Nil) :: rest; - case _ => rest; - } - - -} diff --git a/sources/scala/tools/nsc/reporters/AbstractReporter.scala b/sources/scala/tools/nsc/reporters/AbstractReporter.scala deleted file mode 100644 index c2953e0a5c..0000000000 --- a/sources/scala/tools/nsc/reporters/AbstractReporter.scala +++ /dev/null @@ -1,55 +0,0 @@ -/* ____ ____ ____ ____ ______ *\ -** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala ** -** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL ** -** /_____/\____/\___/\____/____/ ** -\* */ - -// $Id$ - -package scala.tools.nsc.reporters; -import scala.collection.mutable.HashSet; -import scala.tools.nsc.util.Position; - -/** - * This reporter implements filtering. - */ -abstract class AbstractReporter extends Reporter { - private val positions = new HashSet[Position](); - - def display(pos : Position, msg : String, severity : Severity) : Unit; - var prompt : Boolean = false; - var verbose : Boolean = false; - var nowarn : Boolean = false; - def displayPrompt : Unit; - - // XXX: while is pos ignored? - protected def info0(pos : Position, msg : String, severity : Severity, force : Boolean) : Unit = severity match { - case INFO => if (force || verbose) display(pos, msg, severity); - case WARNING => { - val hidden = testAndLog(pos); - if (!nowarn) { - if (!hidden || prompt) display(pos, msg, severity); - if (prompt) displayPrompt; - } - } - case ERROR => { - val hidden = testAndLog(pos); - if (!hidden || prompt) display(pos, msg, severity); - if (prompt) displayPrompt; - } - } - - //######################################################################## - // Private Methods - - /** Logs a position and returns true if it was already logged. */ - private def testAndLog(pos : Position) : Boolean = { - if (pos == null) return false; - if (pos.column == 0) return false; - if (positions.contains(pos)) return true; - positions += (pos); - return false; - } - - //######################################################################## -} diff --git a/sources/scala/tools/nsc/reporters/ConsoleReporter.scala b/sources/scala/tools/nsc/reporters/ConsoleReporter.scala deleted file mode 100644 index f759b66bec..0000000000 --- a/sources/scala/tools/nsc/reporters/ConsoleReporter.scala +++ /dev/null @@ -1,133 +0,0 @@ -/* ____ ____ ____ ____ ______ *\ -** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala ** -** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL ** -** /_____/\____/\___/\____/____/ ** -\* */ - -// $Id$ - -package scala.tools.nsc.reporters; -import scala.tools.nsc.util.Position; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.IOException; -import java.io.PrintWriter; - -/** - * This class implements a Reporter that displays messages on a text - * console. - */ -class ConsoleReporter(reader : BufferedReader, writer : PrintWriter) extends AbstractReporter { - //######################################################################## - // Public Fields - - /** Whether a short file name should be displayed before errors */ - var shortname : Boolean = false; - - def label(severity : Severity): String = severity match { - case ERROR => "error"; - case WARNING => "warning"; - case INFO => null; - }; - def clabel(severity : Severity) = { - val label0 = label(severity); - if (label0 == null) ""; else label0 + ": "; - } - - - - //######################################################################## - // Public Constructors - def this() = this( - new BufferedReader(new InputStreamReader(System.in)), - new PrintWriter(System.err, true)); - - //######################################################################## - // Public Methods - Count - - - /** Returns the number of errors issued totally as a string */ - def getCountString(severity : Severity) : String = getCountString0(count(severity), label(severity));; - /** Returns a string meaning "n elements". */ - def getCountString0(n : Int, elements : String) : String = - n match { - case 0 => "no " + elements + "s"; - case 1 => "one " + elements; - case 2 => "two " + elements + "s"; - case 3 => "three " + elements + "s"; - case 4 => "four " + elements + "s"; - case _ => "" + n + " " + elements + "s"; - } - - - //######################################################################## - // Public Methods - Print - - /** Prints the message. */ - def printMessage(msg : String) = writer.println(msg); - - /** Prints the message with the given position indication. */ - def printMessage(pos : Position, msg : String) : Unit = { - if (pos != null) { - val buf = new StringBuffer(msg); - buf.insert(0, " "); - if (pos.line != Position.NOLINE) - buf.insert(0, ":" + pos.line); - val file = pos.source.file; - buf.insert(0, if (shortname) file.getName() else file.getPath()); - printMessage(buf.toString()); - printSourceLine(pos); - } else printMessage(msg); - } - - def print(pos : Position, msg : String, severity : Severity) = printMessage(pos, clabel(severity) + msg); - - def printSourceLine(pos : Position) = if (pos != null && pos.offset != Position.NOPOS) { - printMessage(pos.lineContent); - printColumnMarker(pos); - } - /** Prints the column marker of the given position. */ - def printColumnMarker(pos : Position) = if (pos != null) { - val buffer = new StringBuffer(pos.column); - var i = 1; - while (i < pos.column) { - buffer.append(' '); - i = i + 1; - } - if (pos.column > 0) buffer.append('^'); - printMessage(buffer.toString()); - } - - /** Prints the number of errors and warnings if their are non-zero. */ - def printSummary() = { - if (warnings > 0) printMessage(getCountString(WARNING) + " found"); - if ( errors > 0) printMessage(getCountString(ERROR ) + " found"); - } - - //######################################################################## - // Public Methods - Display - def display(pos : Position, msg : String, severity : Severity) : Unit = { - incr(severity); - print(pos, msg, severity); - }; - def displayPrompt : Unit = try { - var continue = true; - while (continue) { - writer.print("r)esume, a)bort: "); - writer.flush(); - var line = reader.readLine(); - if (line != null) { - line = line.toLowerCase(); - if ("abort".startsWith(line)) - throw new Error("user abort"); - if ("resume".startsWith(line)) continue = false; - } - } - } catch { - case ex: IOException => { - ex.printStackTrace(); - throw new Error("input read error"); - } - } -} diff --git a/sources/scala/tools/nsc/reporters/Reporter.scala b/sources/scala/tools/nsc/reporters/Reporter.scala deleted file mode 100644 index 950e1a2c6f..0000000000 --- a/sources/scala/tools/nsc/reporters/Reporter.scala +++ /dev/null @@ -1,46 +0,0 @@ -/* ____ ____ ____ ____ ______ *\ -** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala ** -** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL ** -** /_____/\____/\___/\____/____/ ** -\* */ - -// $Id$ - -package scala.tools.nsc.reporters; -import scala.tools.nsc.util.Position; - - -/** - * This interface provides methods to issue information, warning and - * error messages. - */ -abstract class Reporter { - abstract class Severity(val code : Int); - object INFO extends Severity(0); - object WARNING extends Severity(1); - object ERROR extends Severity(2); - - def reset : Unit = { - errors = 0; - warnings = 0; - - } - def count(severity : Severity): Int = severity match { - case ERROR => errors; - case WARNING => warnings; - case INFO => 0; - }; - def incr(severity : Severity): Unit = severity match { - case ERROR => errors = errors + 1; - case WARNING => warnings = warnings + 1;; - case INFO => {} - }; - var errors : Int = 0; - var warnings : Int = 0; - - protected def info0(pos : Position, msg : String, severity : Severity, force : Boolean) : Unit; - - def info(pos : Position, msg : String, force : Boolean) : Unit = info0(pos, msg, INFO , force); - def warning(pos : Position, msg : String ) : Unit = info0(pos, msg, WARNING, false); - def error(pos : Position, msg : String ) : Unit = info0(pos, msg, ERROR, false); -} diff --git a/sources/scala/tools/nsc/reporters/ReporterTimer.scala b/sources/scala/tools/nsc/reporters/ReporterTimer.scala deleted file mode 100644 index 5c0cfd4092..0000000000 --- a/sources/scala/tools/nsc/reporters/ReporterTimer.scala +++ /dev/null @@ -1,27 +0,0 @@ -/* ____ ____ ____ ____ ______ *\ -** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala ** -** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL ** -** /_____/\____/\___/\____/____/ ** -\* */ - -// $Id$ - -package scala.tools.nsc.reporters; -import scala.tools.util.AbstractTimer; - -/** - * This class implements a timer that uses a Reporter to issue - * timings. - */ -class ReporterTimer(_reporter : Reporter) extends AbstractTimer { - //######################################################################## - // Private Fields - private val reporter = _reporter; - //######################################################################## - // Public Methods - - def issue(msg : String, duration : Long) = - reporter.info(null, "[" + msg + " in " + duration + "ms]", false); - - //######################################################################## -} diff --git a/sources/scala/tools/nsc/reporters/StoreReporter.scala b/sources/scala/tools/nsc/reporters/StoreReporter.scala deleted file mode 100644 index e4734fcee7..0000000000 --- a/sources/scala/tools/nsc/reporters/StoreReporter.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* ____ ____ ____ ____ ______ *\ -** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala ** -** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002, LAMP/EPFL ** -** /_____/\____/\___/\____/____/ ** -\* */ - -// $Id$ - -package scala.tools.nsc.reporters; -import scala.tools.nsc.util.Position; -import scala.collection.mutable.HashSet; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.IOException; -import java.io.PrintWriter; - -/** - * This class implements a Reporter that displays messages on a text - * console. - */ -class StoreReporter extends Reporter { - - class Info(val pos: Position, val msg: String, val severity: Severity) { - override def toString() = "pos: " + pos + " " + msg + " " + severity; - } - - val infos = new HashSet[Info]; - - protected def info0(pos : Position, msg : String, severity : Severity, force : Boolean) : Unit = if (!force) { - infos += new Info(pos, msg, severity); - incr(severity); - } - override def reset = { - super.reset; - infos.clear; - } -} diff --git a/sources/scala/tools/nsc/symtab/Constants.scala b/sources/scala/tools/nsc/symtab/Constants.scala deleted file mode 100644 index 3a6746cf61..0000000000 --- a/sources/scala/tools/nsc/symtab/Constants.scala +++ /dev/null @@ -1,191 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ - -// $Id$ - -package scala.tools.nsc.symtab; - -import classfile.PickleFormat._; - -[_trait_] abstract class Constants: SymbolTable { - - import definitions._; - - final val UnitTag = LITERALunit - LITERAL; - final val BooleanTag = LITERALboolean - LITERAL; - final val ByteTag = LITERALbyte - LITERAL; - final val ShortTag = LITERALshort - LITERAL; - final val CharTag = LITERALchar - LITERAL; - final val IntTag = LITERALint - LITERAL; - final val LongTag = LITERALlong - LITERAL; - final val FloatTag = LITERALfloat - LITERAL; - final val DoubleTag = LITERALdouble - LITERAL; - final val StringTag = LITERALstring - LITERAL; - final val NullTag = LITERALnull - LITERAL; - final val ZeroTag = LITERALzero - LITERAL; - - case class Constant(value: Any) { - val tag: int = - if (value.isInstanceOf[unit]) UnitTag - else if (value.isInstanceOf[boolean]) BooleanTag - else if (value.isInstanceOf[byte]) ByteTag - else if (value.isInstanceOf[short]) ShortTag - else if (value.isInstanceOf[char]) CharTag - else if (value.isInstanceOf[int]) IntTag - else if (value.isInstanceOf[long]) LongTag - else if (value.isInstanceOf[float]) FloatTag - else if (value.isInstanceOf[double]) DoubleTag - else if (value.isInstanceOf[String]) StringTag - else if (value == null) NullTag - else throw new Error("bad constant value: " + value); - - def tpe: Type = tag match { - case UnitTag => UnitClass.tpe - case BooleanTag => BooleanClass.tpe - case ByteTag => ByteClass.tpe - case ShortTag => ShortClass.tpe - case CharTag => CharClass.tpe - case IntTag => IntClass.tpe - case LongTag => LongClass.tpe - case FloatTag => FloatClass.tpe - case DoubleTag => DoubleClass.tpe - case StringTag => StringClass.tpe - case NullTag => AllRefClass.tpe - } - - /** We need the equals method to take account of tags as well as values */ - override def equals(other: Any): boolean = other match { - case that: Constant => this.value == that.value && this.tag == that.tag - case _ => false - } - - def booleanValue: boolean = - if (tag == BooleanTag) value.asInstanceOf$erased[boolean] - else throw new Error("value " + value + " is not a boolean"); - - def byteValue: byte = tag match { - case ByteTag => value.asInstanceOf$erased[byte] - case ShortTag => value.asInstanceOf$erased[short].asInstanceOf[byte] - case CharTag => value.asInstanceOf$erased[char].asInstanceOf[byte] - case IntTag => value.asInstanceOf$erased[int].asInstanceOf[byte] - case LongTag => value.asInstanceOf$erased[long].asInstanceOf[byte] - case FloatTag => value.asInstanceOf$erased[float].asInstanceOf[byte] - case DoubleTag => value.asInstanceOf$erased[double].asInstanceOf[byte] - case _ => throw new Error("value " + value + " is not a byte") - } - - def shortValue: short = tag match { - case ByteTag => value.asInstanceOf$erased[byte].asInstanceOf[short] - case ShortTag => value.asInstanceOf$erased[short] - case CharTag => value.asInstanceOf$erased[char].asInstanceOf[short] - case IntTag => value.asInstanceOf$erased[int].asInstanceOf[short] - case LongTag => value.asInstanceOf$erased[long].asInstanceOf[short] - case FloatTag => value.asInstanceOf$erased[float].asInstanceOf[short] - case DoubleTag => value.asInstanceOf$erased[double].asInstanceOf[short] - case _ => throw new Error("value " + value + " is not a short") - } - - def charValue: char = tag match { - case ByteTag => value.asInstanceOf$erased[byte].asInstanceOf[char] - case ShortTag => value.asInstanceOf$erased[short].asInstanceOf[char] - case CharTag => value.asInstanceOf$erased[char] - case IntTag => value.asInstanceOf$erased[int].asInstanceOf[char] - case LongTag => value.asInstanceOf$erased[long].asInstanceOf[char] - case FloatTag => value.asInstanceOf$erased[float].asInstanceOf[char] - case DoubleTag => value.asInstanceOf$erased[double].asInstanceOf[char] - case _ => throw new Error("value " + value + " is not a char") - } - - def intValue: int = tag match { - case ByteTag => value.asInstanceOf$erased[byte].asInstanceOf[int] - case ShortTag => value.asInstanceOf$erased[short].asInstanceOf[int] - case CharTag => value.asInstanceOf$erased[char].asInstanceOf[int] - case IntTag => value.asInstanceOf$erased[int] - case LongTag => value.asInstanceOf$erased[long].asInstanceOf[int] - case FloatTag => value.asInstanceOf$erased[float].asInstanceOf[int] - case DoubleTag => value.asInstanceOf$erased[double].asInstanceOf[int] - case _ => throw new Error("value " + value + " is not an int") - } - - def longValue: long = tag match { - case ByteTag => value.asInstanceOf$erased[byte].asInstanceOf[long] - case ShortTag => value.asInstanceOf$erased[short].asInstanceOf[long] - case CharTag => value.asInstanceOf$erased[char].asInstanceOf[long] - case IntTag => value.asInstanceOf$erased[int].asInstanceOf[long] - case LongTag => value.asInstanceOf$erased[long] - case FloatTag => value.asInstanceOf$erased[float].asInstanceOf[long] - case DoubleTag => value.asInstanceOf$erased[double].asInstanceOf[long] - case _ => throw new Error("value " + value + " is not a long") - } - - def floatValue: float = tag match { - case ByteTag => value.asInstanceOf$erased[byte].asInstanceOf[float] - case ShortTag => value.asInstanceOf$erased[short].asInstanceOf[float] - case CharTag => value.asInstanceOf$erased[char].asInstanceOf[float] - case IntTag => value.asInstanceOf$erased[int].asInstanceOf[float] - case LongTag => value.asInstanceOf$erased[long].asInstanceOf[float] - case FloatTag => value.asInstanceOf$erased[float] - case DoubleTag => value.asInstanceOf$erased[double].asInstanceOf[float] - case _ => throw new Error("value " + value + " is not a float") - } -/* - def doubleValue: double = { - System.out.println("doubleValue " + tag + " " + value); - tag match { - case ByteTag => System.out.println("Byte"); value.asInstanceOf$erased[byte].asInstanceOf[double] - case ShortTag => System.out.println("Short"); value.asInstanceOf$erased[short].asInstanceOf[double] - case CharTag => System.out.println("Char"); value.asInstanceOf$erased[char].asInstanceOf[double] - case IntTag => System.out.println("Int"); value.asInstanceOf$erased[int].asInstanceOf[double] - case LongTag => System.out.println("Long"); value.asInstanceOf$erased[long].asInstanceOf[double] - case FloatTag => System.out.println("Float"); value.asInstanceOf$erased[float].asInstanceOf[double] - case DoubleTag => System.out.println("Double"); value.asInstanceOf$erased[double] - case _ => System.out.println("error"); throw new Error("value " + value + " is not a double") - } - } -*/ - def doubleValue: double = tag match { - case ByteTag => value.asInstanceOf$erased[byte].asInstanceOf[double] - case ShortTag => value.asInstanceOf$erased[short].asInstanceOf[double] - case CharTag => value.asInstanceOf$erased[char].asInstanceOf[double] - case IntTag => value.asInstanceOf$erased[int].asInstanceOf[double] - case LongTag => value.asInstanceOf$erased[long].asInstanceOf[double] - case FloatTag => value.asInstanceOf$erased[float].asInstanceOf[double] - case DoubleTag => value.asInstanceOf$erased[double] - case _ => throw new Error("value " + value + " is not a double") - } - - /** Convert constant value to conform to given type */ - def convertTo(pt: Type): Constant = { - val target = pt.symbol; - if (target == tpe.symbol) - this - else if (target == ByteClass && ByteTag <= tag && tag <= IntTag && - -128 <= intValue && intValue <= 127) - Constant(byteValue) - else if (target == ShortClass && ByteTag <= tag && tag <= IntTag && - -32768 <= intValue && intValue <= 32767) - Constant(shortValue) - else if (target == CharClass && ByteTag <= tag && tag <= IntTag && - 0 <= intValue && intValue <= 65635) - Constant(charValue) - else if (target == IntClass && ByteTag <= tag && tag <= IntTag) - Constant(intValue) - else if (target == LongClass && ByteTag <= tag && tag <= LongTag) - Constant(longValue) - else if (target == FloatClass && ByteTag <= tag && tag <= FloatTag) - Constant(floatValue) - else if (target == DoubleClass && ByteTag <= tag && tag <= DoubleTag) - Constant(doubleValue) - else null - } - - def stringValue: String = - if (value == null) "null" else value.toString(); - - override def hashCode(): int = - if (value == null) 0 else value.hashCode() * 41 + 17; - } - -} diff --git a/sources/scala/tools/nsc/symtab/Definitions.scala b/sources/scala/tools/nsc/symtab/Definitions.scala deleted file mode 100644 index 36d34f76f1..0000000000 --- a/sources/scala/tools/nsc/symtab/Definitions.scala +++ /dev/null @@ -1,417 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.symtab; - -import scala.tools.nsc.util.Position; -import collection.mutable.HashMap; -import Flags._; - -[_trait_] abstract class Definitions: SymbolTable { - - object definitions { - - // root packages and classes - var RootClass: Symbol = _; - var EmptyPackage: Symbol = _; - var EmptyPackageClass: Symbol = _; - var emptypackagescope: Scope = null; //debug - - var JavaPackage: Symbol = _; - var JavaLangPackage: Symbol = _; - var ScalaPackage: Symbol = _; - var ScalaPackageClass: Symbol = _; - - var AnyClass: Symbol = _; - var AnyValClass: Symbol = _; - var ObjectClass: Symbol = _; - - var AnyRefClass: Symbol = _; - - var AllRefClass: Symbol = _; - var AllClass: Symbol = _; - - var StringClass: Symbol = _; - var ThrowableClass: Symbol = _; - - // the scala value classes - var UnitClass: Symbol = _; - var BooleanClass: Symbol = _; - def Boolean_not = getMember(BooleanClass, nme.ZNOT); - def Boolean_and = getMember(BooleanClass, nme.ZAND); - def Boolean_or = getMember(BooleanClass, nme.ZOR); - var ByteClass: Symbol = _; - var ShortClass: Symbol = _; - var CharClass: Symbol = _; - var IntClass: Symbol = _; - var LongClass: Symbol = _; - var FloatClass: Symbol = _; - var DoubleClass: Symbol = _; - - // the scala reference classes - var ScalaObjectClass: Symbol = _; - def ScalaObjectClass_tag = getMember(ScalaObjectClass, nme.tag ); - var AttributeClass: Symbol = _; - var RefClass: Symbol = _; - var TypedCodeClass: Symbol = _; - var PartialFunctionClass: Symbol = _; - var IterableClass: Symbol = _; - def Iterable_next = getMember(IterableClass, "next"); - def Iterable_hasNext = getMember(IterableClass, "hasNext"); - var IteratorClass: Symbol = _; - var SeqClass: Symbol = _; - def Seq_length = getMember(SeqClass, "length"); - var ListClass: Symbol = _; - def List_isEmpty = getMember(ListClass, "isEmpty"); - def List_head = getMember(ListClass, "head"); - def List_tail = getMember(ListClass, "tail"); - var ArrayClass: Symbol = _; - var TypeClass: Symbol = _; - var SerializableClass: Symbol = _; - var PredefModule: Symbol = _; - var ConsoleModule: Symbol = _; - var MatchErrorClass: Symbol = _; - var MatchErrorModule: Symbol = _; - def MatchError_fail = getMember(MatchErrorModule, "fail"); - def MatchError_report = getMember(MatchErrorModule, "report"); - var ScalaRunTimeModule: Symbol = _; - def SeqFactory = getMember(ScalaRunTimeModule, "Seq"); - var RepeatedParamClass: Symbol = _; - var ByNameParamClass: Symbol = _; - var TraitClass: Symbol = _; - - val MaxTupleArity = 9; - val MaxFunctionArity = 9; - var TupleClass: Array[Symbol] = _; - def tupleField(n:int, j:int) = getMember(TupleClass(n), "_" + j); - var FunctionClass: Array[Symbol] = _; - def functionApply(n:int) = getMember(FunctionClass(n), "apply"); - - def tupleType(elems: List[Type]) = - if (elems.length <= MaxTupleArity) { - val sym = TupleClass(elems.length); - typeRef(sym.typeConstructor.prefix, sym, elems) - } else NoType; - - - def functionType(formals: List[Type], restpe: Type) = - if (formals.length <= MaxFunctionArity) { - val sym = FunctionClass(formals.length); - typeRef(sym.typeConstructor.prefix, sym, formals ::: List(restpe)) - } else NoType; - - - def isTupleType(tp: Type): boolean = tp match { - case TypeRef(_, sym, elems) => - elems.length <= MaxTupleArity && sym == TupleClass(elems.length); - case _ => - false - } - - def isFunctionType(tp: Type): boolean = tp match { - case TypeRef(_, sym, args) => - ((args.length > 0) && (args.length - 1 <= MaxFunctionArity) && - (sym == FunctionClass(args.length - 1))) - case _ => - false - } - - def seqType(arg: Type) = - typeRef(SeqClass.typeConstructor.prefix, SeqClass, List(arg)); - - def NilModule: Symbol = getModule("scala.Nil"); - def ConsClass: Symbol = getClass("scala.$colon$colon"); - - // members of class scala.Any - var Any_== : Symbol = _; - var Any_!= : Symbol = _; - var Any_equals : Symbol = _; - var Any_hashCode : Symbol = _; - var Any_toString : Symbol = _; - var Any_isInstanceOf: Symbol = _; - var Any_asInstanceOf: Symbol = _; - var Any_isInstanceOfErased: Symbol = _; - var Any_asInstanceOfErased: Symbol = _; - - // members of class java.lang.{Object, String} - var Object_eq : Symbol = _; - var Object_ne : Symbol = _; - var Object_== : Symbol = _; - var Object_!= : Symbol = _; - var Object_synchronized: Symbol = _; - var Object_isInstanceOf: Symbol = _; - var Object_asInstanceOf: Symbol = _; - def Object_equals = getMember(ObjectClass, nme.equals_); - def Object_hashCode = getMember(ObjectClass, nme.hashCode_); - def Object_toString = getMember(ObjectClass, nme.toString_); - - var String_+ : Symbol = _; - - // members of class scala.Iterator - var Iterator_next : Symbol = _; - var Iterator_hasNext : Symbol = _; - - // pattern wildcard - var PatternWildcard: Symbol = _; - - // boxed classes - var BoxedArrayClass: Symbol = _; - var BoxedAnyArrayClass: Symbol = _; - var BoxedObjectArrayClass: Symbol = _; - var BoxedNumberClass: Symbol = _; - var BoxedUnitClass: Symbol = _; - var BoxedUnitModule: Symbol = _; - def BoxedUnit_UNIT = getMember(BoxedUnitModule, "UNIT"); - var ObjectRefClass: Symbol = _; - - // special attributes - var SerializableAttr: Type = _; - - - def getModule(fullname: Name): Symbol = - getModuleOrClass(fullname, true); - - def getClass(fullname: Name): Symbol = - getModuleOrClass(fullname, false); - - def getMember(owner: Symbol, name: Name) = { - val result = owner.info.nonPrivateMember(name); - if (result == NoSymbol) - throw new FatalError(owner.toString() + " does not have a member " + name); - result - } - - private def getModuleOrClass(fullname: Name, module: boolean): Symbol = { - var sym = RootClass; - var i = 0; - var j = fullname.pos('.', i); - while (j < fullname.length) { - sym = sym.info.nonPrivateMember(fullname.subName(i, j)); - i = j + 1; - j = fullname.pos('.', i) - } - val result = - if (module) sym.info.nonPrivateMember(fullname.subName(i, j)).suchThat(.hasFlag(MODULE)); - else sym.info.nonPrivateMember(fullname.subName(i, j).toTypeName); - if (result == NoSymbol) - throw new FatalError((if (module) "object " else "class ") + fullname + " not found."); - result - } - - private def newClass(owner: Symbol, name: Name, parents: List[Type]): Symbol = { - val clazz = owner.newClass(Position.NOPOS, name.toTypeName); - clazz.setInfo(ClassInfoType(parents, new Scope(), clazz)); - owner.info.decls.enter(clazz); - clazz - } - - private def newCovariantPolyClass(owner: Symbol, name: Name, parent: Symbol => Type): Symbol = { - val clazz = newClass(owner, name, List()); - val tparam = newTypeParam(clazz, 0) setFlag COVARIANT; - clazz.setInfo( - PolyType( - List(tparam), - ClassInfoType(List(parent(tparam)), new Scope(), clazz))) - } - - private def newAlias(owner: Symbol, name: Name, alias: Type): Symbol = { - val tpsym = owner.newAliasType(Position.NOPOS, name.toTypeName); - tpsym.setInfo(alias); - owner.info.decls.enter(tpsym); - tpsym - } - - private def newMethod(owner: Symbol, name: Name): Symbol = { - val msym = owner.newMethod(Position.NOPOS, name.encode); - owner.info.decls.enter(msym); - msym - } - - private def newMethod(owner: Symbol, name: Name, formals: List[Type], restpe: Type): Symbol = - newMethod(owner, name).setInfo(MethodType(formals, restpe)); - - private def newPolyMethod(owner: Symbol, name: Name, tcon: Symbol => Type): Symbol = { - val msym = newMethod(owner, name); - val tparam = newTypeParam(msym, 0); - msym.setInfo(PolyType(List(tparam), tcon(tparam))) - } - - private def newTypeParam(owner: Symbol, index: int): Symbol = - owner.newTypeParameter(Position.NOPOS, "T" + index) - .setInfo(TypeBounds(AllClass.typeConstructor, AnyClass.typeConstructor)); - - val boxedClass = new HashMap[Symbol, Symbol]; - val boxedArrayClass = new HashMap[Symbol, Symbol]; - val refClass = new HashMap[Symbol, Symbol]; - private val abbrvTag = new HashMap[Symbol, char]; - - private def getValueClass(name: String, tag: char): Symbol = { - val result = getClass("scala." + name); - boxedClass(result) = getClass("scala.runtime.Boxed" + name); - if (name != "Unit") { - boxedArrayClass(result) = getClass("scala.runtime.Boxed" + name + "Array"); - refClass(result) = getClass("scala.runtime." + name + "Ref"); - } - abbrvTag(result) = tag; - result - } - - /** Is symbol a value class? */ - def isValueClass(sym: Symbol): boolean = boxedClass contains sym; - - /** Is symbol a value class? */ - def isNumericValueClass(sym: Symbol): boolean = - isValueClass(sym) && sym != BooleanClass && sym != UnitClass; - - /** Is symbol a value or array class? */ - def isUnboxedClass(sym: Symbol): boolean = isValueClass(sym) || sym == ArrayClass; - - def signature(tp: Type): String = { - def flatNameString(sym: Symbol, separator: char): String = - if (sym.owner.isPackageClass) sym.fullNameString('.') - else flatNameString(sym.owner, separator) + "$" + sym.simpleName; - def signature1(tp: Type): String = { - if (tp.symbol == ArrayClass) "[" + signature1(tp.typeArgs.head); - else if (isValueClass(tp.symbol)) String.valueOf(abbrvTag(tp.symbol)) - else "L" + flatNameString(tp.symbol, '/') + ";" - } - if (tp.symbol == ArrayClass) signature1(tp); - else flatNameString(tp.symbol, '.') - } - - private var isInitialized = false; - - def init: unit = { - if (isInitialized) return; - isInitialized = true; - RootClass = - NoSymbol.newClass(Position.NOPOS, nme.ROOT.toTypeName) - .setFlag(FINAL | MODULE | PACKAGE | JAVA).setInfo(rootLoader); - - EmptyPackage = - RootClass.newPackage(Position.NOPOS, nme.EMPTY_PACKAGE_NAME).setFlag(FINAL); - EmptyPackageClass = EmptyPackage.moduleClass; - EmptyPackageClass.setInfo(ClassInfoType(List(), new Scope(), EmptyPackageClass)); - - EmptyPackage.setInfo(EmptyPackageClass.tpe); - RootClass.info.decls.enter(EmptyPackage); - - JavaPackage = getModule("java"); - JavaLangPackage = getModule("java.lang"); - ScalaPackage = getModule("scala"); - ScalaPackageClass = ScalaPackage.tpe.symbol; - - AnyClass = newClass(ScalaPackageClass, "Any", List()); - AnyValClass = getClass("scala.AnyVal") setFlag SEALED; - ObjectClass = getClass("java.lang.Object"); - - AnyRefClass = newAlias(ScalaPackageClass, "AnyRef", ObjectClass.typeConstructor); - - AllRefClass = newClass(ScalaPackageClass, "AllRef", List(AnyRefClass.typeConstructor)) - .setFlag(ABSTRACT | TRAIT | FINAL); - - AllClass = newClass(ScalaPackageClass, "All", List(AnyClass.typeConstructor)) - .setFlag(ABSTRACT | TRAIT | FINAL); - - StringClass = getClass("java.lang.String"); - ThrowableClass = getClass("java.lang.Throwable"); - - // the scala value classes - UnitClass = getValueClass("Unit", 'V'); - BooleanClass = getValueClass("Boolean", 'Z'); - ByteClass = getValueClass("Byte", 'B'); - ShortClass = getValueClass("Short", 'S'); - CharClass = getValueClass("Char", 'C'); - IntClass = getValueClass("Int", 'I'); - LongClass = getValueClass("Long", 'L'); - FloatClass = getValueClass("Float", 'F'); - DoubleClass = getValueClass("Double", 'D'); - - // the scala reference classes - ScalaObjectClass = getClass("scala.ScalaObject"); - AttributeClass = getClass("scala.Attribute"); - RefClass = getClass("scala.Ref"); - TypedCodeClass = getClass("scala.reflect.TypedCode"); - PartialFunctionClass = getClass("scala.PartialFunction"); - IterableClass = getClass("scala.Iterable"); - IteratorClass = getClass("scala.Iterator"); - SeqClass = getClass("scala.Seq"); - ListClass = getClass("scala.List"); - ArrayClass = getClass("scala.Array"); - TypeClass = getClass("scala.Type"); - SerializableClass = getClass("java.io.Serializable"); - PredefModule = getModule("scala.Predef"); - ConsoleModule = getModule("scala.Console"); - MatchErrorClass = getClass("scala.MatchError"); - MatchErrorModule = getModule("scala.MatchError"); - ScalaRunTimeModule = getModule("scala.runtime.ScalaRunTime"); - RepeatedParamClass = newCovariantPolyClass( - ScalaPackageClass, nme.REPEATED_PARAM_CLASS_NAME, - tparam => typeRef(SeqClass.typeConstructor.prefix, SeqClass, List(tparam.typeConstructor))); - ByNameParamClass = newCovariantPolyClass( - ScalaPackageClass, nme.BYNAME_PARAM_CLASS_NAME, tparam => AnyClass.typeConstructor); - TraitClass = getClass("scala._trait_"); - TupleClass = new Array(MaxTupleArity + 1); - for (val i <- List.range(1, MaxTupleArity + 1)) - TupleClass(i) = getClass("scala.Tuple" + i); - FunctionClass = new Array(MaxFunctionArity + 1); - for (val i <- List.range(0, MaxFunctionArity + 1)) - FunctionClass(i) = getClass("scala.Function" + i); - - // members of class scala.Any - Any_== = newMethod( - AnyClass, "==", List(AnyClass.typeConstructor), BooleanClass.typeConstructor) setFlag FINAL; - Any_!= = newMethod( - AnyClass, "!=", List(AnyClass.typeConstructor), BooleanClass.typeConstructor) setFlag FINAL; - Any_equals = newMethod( - AnyClass, "equals", List(AnyClass.typeConstructor), BooleanClass.typeConstructor); - Any_hashCode = newMethod( - AnyClass, "hashCode", List(), IntClass.typeConstructor); - Any_toString = newMethod( - AnyClass, "toString", List(), StringClass.typeConstructor); - - Any_isInstanceOf = newPolyMethod( - AnyClass, "isInstanceOf", tparam => BooleanClass.typeConstructor) setFlag FINAL; - Any_asInstanceOf = newPolyMethod( - AnyClass, "asInstanceOf", tparam => tparam.typeConstructor) setFlag FINAL; - Any_isInstanceOfErased = newPolyMethod( - AnyClass, "isInstanceOf$erased", tparam => BooleanClass.typeConstructor) setFlag FINAL; - Any_asInstanceOfErased = newPolyMethod( - AnyClass, "asInstanceOf$erased", tparam => tparam.typeConstructor) setFlag FINAL; - - // members of class java.lang.{Object, String} - Object_== = newMethod( - ObjectClass, "==", List(AnyRefClass.typeConstructor), BooleanClass.typeConstructor) setFlag FINAL; - Object_!= = newMethod( - ObjectClass, "!=", List(AnyRefClass.typeConstructor), BooleanClass.typeConstructor) setFlag FINAL; - Object_eq = newMethod( - ObjectClass, "eq", List(AnyRefClass.typeConstructor), BooleanClass.typeConstructor) setFlag FINAL; - Object_ne = newMethod( - ObjectClass, "ne", List(AnyRefClass.typeConstructor), BooleanClass.typeConstructor) setFlag FINAL; - Object_synchronized = newPolyMethod( - ObjectClass, "synchronized", tparam => MethodType(List(tparam.typeConstructor), tparam.typeConstructor)) setFlag FINAL; - Object_isInstanceOf = newPolyMethod( - ObjectClass, "$isInstanceOf", - tparam => MethodType(List(), BooleanClass.typeConstructor)) setFlag FINAL; - Object_asInstanceOf = newPolyMethod( - ObjectClass, "$asInstanceOf", - tparam => MethodType(List(), tparam.typeConstructor)) setFlag FINAL; - String_+ = newMethod( - StringClass, "+", List(AnyClass.typeConstructor), StringClass.typeConstructor) setFlag FINAL; - - PatternWildcard = NoSymbol.newValue(Position.NOPOS, "_").setInfo(AllClass.typeConstructor); - - BoxedArrayClass = getClass("scala.runtime.BoxedArray"); - BoxedAnyArrayClass = getClass("scala.runtime.BoxedAnyArray"); - BoxedObjectArrayClass = getClass("scala.runtime.BoxedObjectArray"); - BoxedNumberClass = getClass("scala.runtime.BoxedNumber"); - BoxedUnitClass = getClass("scala.runtime.BoxedUnit"); - BoxedUnitModule = getModule("scala.runtime.BoxedUnit"); - ObjectRefClass = getClass("scala.runtime.ObjectRef"); - - SerializableAttr = getClass("scala.serializable").tpe; - } - } -} diff --git a/sources/scala/tools/nsc/symtab/Flags.scala b/sources/scala/tools/nsc/symtab/Flags.scala deleted file mode 100644 index 2627640d2e..0000000000 --- a/sources/scala/tools/nsc/symtab/Flags.scala +++ /dev/null @@ -1,191 +0,0 @@ -/* NSC -- new scala compiler - * Copyright 2005 LAMP/EPFL - * @author Martin Odersky - */ -// $Id$ -package scala.tools.nsc.symtab; - -object Flags { - - // modifiers - final val IMPLICIT = 0x00000001; - final val FINAL = 0x00000002; - final val PRIVATE = 0x00000004; - final val PROTECTED = 0x00000008; - - final val SEALED = 0x00000010; - final val OVERRIDE = 0x00000020; - final val CASE = 0x00000040; - final val ABSTRACT = 0x00000080; // abstract class, or used in conjunction - // with abstract override. - // Note difference to DEFERRED! - - final val DEFERRED = 0x00000100; // was `abstract' for members - final val METHOD = 0x00000200; // a method - final val MODULE = 0x00000400; // symbol is module or class implementing a module - final val INTERFACE = 0x00000800; // symbol is an interface - - final val MUTABLE = 0x00001000; // symbol is a mutable variable. - final val PARAM = 0x00002000; // symbol is a (value or type) parameter to a method - final val PACKAGE = 0x00004000; // symbol is a java package - final val DEPRECATED = 0x00008000; // symbol is deprecated. - - final val COVARIANT = 0x00010000; // symbol is a covariant type variable - final val CONTRAVARIANT = 0x00020000; // symbol is a contravariant type variable - final val ABSOVERRIDE = 0x00040000; // combination of abstract & override - final val LOCAL = 0x00080000; // symbol is local to current class. - // pre: PRIVATE is also set - - final val JAVA = 0x00100000; // symbol was defined by a Java class - final val SYNTHETIC = 0x00200000; // symbol is compiler-generated - final val STABLE = 0x00400000; // functions that are assumed to be stable - // (typically, access methods for valdefs) - final val STATIC = 0x00800000; // static field, method or class - - final val CASEACCESSOR = 0x01000000; // symbol is a case parameter (or its accessor) - final val TRAIT = 0x02000000; // symbol is a trait - final val BRIDGE = 0x04000000; // function is a bridge method. Set by Erasure - final val ACCESSOR = 0x08000000; // a value or variable accessor - - final val SUPERACCESSOR = 0x10000000; // a super accessor - final val PARAMACCESSOR = 0x20000000; // for value definitions: is an access method for a final val parameter - // for parameters: is a val parameter - - final val CAPTURED = 0x40000000; // variable is accessed from nested function. Set by LambdaLift - final val BYNAMEPARAM = 0x40000000; // parameter is by name - - final val LABEL = 0x80000000L; // method symbol is a label. Set by TailCall - final val INCONSTRUCTOR = 0x80000000L; // class symbol is defined in this/superclass constructor. - - final val IS_ERROR = 0x100000000L; // symbol is an error symbol - final val OVERLOADED = 0x200000000L; // symbol is overloaded - final val LIFTED = 0x400000000L; // class has been lifted out to package level - // local value has been lifted out to class level - //todo: make LIFTED = latePRIVATE? - - final val MIXEDIN = 0x800000000L; // member has been mixed in - - final val EXPANDEDNAME = 0x1000000000L; // name has been expanded with class suffix - final val IMPLCLASS = 0x2000000000L; // symbol is an implementation class - final val TRANS_FLAG = 0x4000000000L; // transient flag guaranteed to be reset after each phase. - - final val LOCKED = 0x8000000000L; // temporary flag to catch cyclic dependencies - - final val InitialFlags = 0x000000FFFFFFFFFFL; // flags that are enabled from phase 1. - final val LateFlags = 0x000FFF0000000000L; // flags that override flags in 0xFFF. - final val AntiFlags = 0x7FF0000000000000L; // flags that cancel flags in 0x7FF - final val LateShift = 40L; - final val AntiShift = 52L; - - // late flags (set by a transformer phase) - final val latePRIVATE = (PRIVATE: long) << LateShift; - final val lateDEFERRED = (DEFERRED: long) << LateShift; - final val lateINTERFACE = (INTERFACE: long) << LateShift; - final val lateMODULE = (MODULE: long) << LateShift; - final val lateFINAL = (FINAL: long) << LateShift; - final val lateMETHOD = (METHOD: long) << LateShift; - final val notPRIVATE = (PRIVATE: long) << AntiShift; - final val notPROTECTED = (PROTECTED: long) << AntiShift; - final val notABSTRACT = (ABSTRACT: long) << AntiShift; - final val notOVERRIDE = (OVERRIDE: long) << AntiShift; - final val notMETHOD = (METHOD: long) << AntiShift; - - final val STATICMODULE = lateMODULE; - final val STATICMEMBER = notOVERRIDE; - - - // masks - /** This flags can be set when class or module symbol is first created. */ - final val TopLevelCreationFlags = - MODULE | PACKAGE | FINAL | JAVA; - - final val ExplicitFlags = // these modifiers can be set explicitly in source programs. - PRIVATE | PROTECTED | ABSTRACT | FINAL | SEALED | OVERRIDE | CASE | IMPLICIT | ABSOVERRIDE; - - final val PrintableFlags = // these modifiers appear in TreePrinter output. - (ExplicitFlags | LOCAL | SYNTHETIC | STABLE | CASEACCESSOR | ACCESSOR | - SUPERACCESSOR | PARAMACCESSOR | BRIDGE | STATIC); - - final val FieldFlags = MUTABLE | CASEACCESSOR | PARAMACCESSOR | STATIC | FINAL; - - final val AccessFlags = PRIVATE | PROTECTED; - final val VARIANCES = COVARIANT | CONTRAVARIANT; - final val ConstrFlags = JAVA; - final val PickledFlags = 0xFFFFFFFF; - - /** Module flags inherited by their module-class */ - final val ModuleToClassFlags = AccessFlags | PACKAGE | CASE; - - def flagsToString(flags: long, suffixes: List[Pair[long, String]]): String = - (for (val i <- List.range(0, 63)) yield { - var s = flagToString(flags & (1L << i)); - suffixes.find(._1.==(i)) match { - case Some(Pair(i, suffix)) => s = s + "[" + suffix + "]" - case None => - } - s - }).filter("" !=).mkString("", " ", ""); - - def flagsToString(flags: long): String = flagsToString(flags, List()); - - private def flagToString(flag: long): String = { - if (flag == LABEL) "