001    /*
002     * Copyright 2010-2013 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.jet.lang.types;
018    
019    public enum Variance {
020        INVARIANT("", true, true, 0),
021        IN_VARIANCE("in", true, false, -1),
022        OUT_VARIANCE("out", false, true, +1);
023    
024        private final String label;
025        private final boolean allowsInPosition;
026        private final boolean allowsOutPosition;
027        private final int superpositionFactor;
028    
029        Variance(String label, boolean allowsInPosition, boolean allowsOutPosition, int superpositionFactor) {
030            this.label = label;
031            this.allowsInPosition = allowsInPosition;
032            this.allowsOutPosition = allowsOutPosition;
033            this.superpositionFactor = superpositionFactor;
034        }
035    
036        public boolean allowsInPosition() {
037            return allowsInPosition;
038        }
039    
040        public boolean allowsOutPosition() {
041            return allowsOutPosition;
042        }
043    
044        public Variance superpose(Variance other) {
045            int r = this.superpositionFactor * other.superpositionFactor;
046            switch (r) {
047                case  0: return INVARIANT;
048                case -1: return IN_VARIANCE;
049                case +1: return OUT_VARIANCE;
050            }
051            throw new IllegalStateException();
052        }
053    
054        public Variance opposite() {
055            switch (this) {
056                case INVARIANT:
057                    return INVARIANT;
058                case IN_VARIANCE:
059                    return OUT_VARIANCE;
060                case OUT_VARIANCE:
061                    return IN_VARIANCE;
062            }
063            throw new IllegalStateException("Impossible variance: " + this);
064        }
065    
066        @Override
067        public String toString() {
068            return label;
069        }
070    }