| 1 | /* |
| 2 | * Copyright 2010 The Closure Compiler Authors. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package com.google.javascript.jscomp; |
| 18 | |
| 19 | import com.google.common.base.Function; |
| 20 | import com.google.common.base.Preconditions; |
| 21 | import com.google.javascript.jscomp.graph.LatticeElement; |
| 22 | |
| 23 | import java.util.List; |
| 24 | |
| 25 | /** |
| 26 | * Defines a way join a list of LatticeElements. |
| 27 | */ |
| 28 | interface JoinOp<L extends LatticeElement> extends Function<List<L>, L> { |
| 29 | |
| 30 | /** |
| 31 | * An implementation of {@code JoinOp} that makes it easy to join to |
| 32 | * lattice elements at a time. |
| 33 | */ |
| 34 | static abstract class BinaryJoinOp<L extends LatticeElement> |
| 35 | implements JoinOp<L> { |
| 36 | @Override |
| 37 | public final L apply(List<L> values) { |
| 38 | Preconditions.checkArgument(!values.isEmpty()); |
| 39 | int size = values.size(); |
| 40 | if (size == 1) { |
| 41 | return values.get(0); |
| 42 | } else if (size == 2) { |
| 43 | return apply(values.get(0), values.get(1)); |
| 44 | } else { |
| 45 | int mid = computeMidPoint(size); |
| 46 | return apply( |
| 47 | apply(values.subList(0, mid)), |
| 48 | apply(values.subList(mid, size))); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Creates a new lattice that will be the join of two input lattices. |
| 54 | * |
| 55 | * @return The join of {@code latticeA} and {@code latticeB}. |
| 56 | */ |
| 57 | abstract L apply(L latticeA, L latticeB); |
| 58 | |
| 59 | /** |
| 60 | * Finds the midpoint of a list. The function will favor two lists of |
| 61 | * even length instead of two lists of the same odd length. The list |
| 62 | * must be at least length two. |
| 63 | * |
| 64 | * @param size Size of the list. |
| 65 | */ |
| 66 | static int computeMidPoint(int size) { |
| 67 | int midpoint = size >>> 1; |
| 68 | if (size > 4) { |
| 69 | /* Any list longer than 4 should prefer an even split point |
| 70 | * over the true midpoint, so that [0,6] splits at 2, not 3. */ |
| 71 | midpoint &= -2; // (0xfffffffe) clears low bit so midpoint is even |
| 72 | } |
| 73 | return midpoint; |
| 74 | } |
| 75 | } |
| 76 | } |