001    /*
002     * Copyright 2001-2008 Sun Microsystems, Inc.  All Rights Reserved.
003     * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004     *
005     * This code is free software; you can redistribute it and/or modify it
006     * under the terms of the GNU General Public License version 2 only, as
007     * published by the Free Software Foundation.  Sun designates this
008     * particular file as subject to the "Classpath" exception as provided
009     * by Sun in the LICENSE file that accompanied this code.
010     *
011     * This code is distributed in the hope that it will be useful, but WITHOUT
012     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013     * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
014     * version 2 for more details (a copy is included in the LICENSE file that
015     * accompanied this code).
016     *
017     * You should have received a copy of the GNU General Public License version
018     * 2 along with this work; if not, write to the Free Software Foundation,
019     * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020     *
021     * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022     * CA 95054 USA or visit www.sun.com if you need additional information or
023     * have any questions.
024     */
025    
026    package com.sun.tools.javac.util;
027    
028    import java.util.*;
029    
030    /**
031     * Support for an abstract context, modelled loosely after ThreadLocal
032     * but using a user-provided context instead of the current thread.
033     *
034     * <p>Within the compiler, a single Context is used for each
035     * invocation of the compiler.  The context is then used to ensure a
036     * single copy of each compiler phase exists per compiler invocation.
037     *
038     * <p>The context can be used to assist in extending the compiler by
039     * extending its components.  To do that, the extended component must
040     * be registered before the base component.  We break initialization
041     * cycles by (1) registering a factory for the component rather than
042     * the component itself, and (2) a convention for a pattern of usage
043     * in which each base component registers itself by calling an
044     * instance method that is overridden in extended components.  A base
045     * phase supporting extension would look something like this:
046     *
047     * <p><pre>
048     * public class Phase {
049     *     protected static final Context.Key<Phase> phaseKey =
050     *         new Context.Key<Phase>();
051     *
052     *     public static Phase instance(Context context) {
053     *         Phase instance = context.get(phaseKey);
054     *         if (instance == null)
055     *             // the phase has not been overridden
056     *             instance = new Phase(context);
057     *         return instance;
058     *     }
059     *
060     *     protected Phase(Context context) {
061     *         context.put(phaseKey, this);
062     *         // other intitialization follows...
063     *     }
064     * }
065     * </pre>
066     *
067     * <p>In the compiler, we simply use Phase.instance(context) to get
068     * the reference to the phase.  But in extensions of the compiler, we
069     * must register extensions of the phases to replace the base phase,
070     * and this must be done before any reference to the phase is accessed
071     * using Phase.instance().  An extended phase might be declared thus:
072     *
073     * <p><pre>
074     * public class NewPhase extends Phase {
075     *     protected NewPhase(Context context) {
076     *         super(context);
077     *     }
078     *     public static void preRegister(final Context context) {
079     *         context.put(phaseKey, new Context.Factory<Phase>() {
080     *             public Phase make() {
081     *                 return new NewPhase(context);
082     *             }
083     *         });
084     *     }
085     * }
086     * </pre>
087     *
088     * <p>And is registered early in the extended compiler like this
089     *
090     * <p><pre>
091     *     NewPhase.preRegister(context);
092     * </pre>
093     *
094     *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
095     *  you write code that depends on this, you do so at your own risk.
096     *  This code and its internal interfaces are subject to change or
097     *  deletion without notice.</b>
098     */
099    public class Context {
100        /** The client creates an instance of this class for each key.
101         */
102        public static class Key<T> {
103            // note: we inherit identity equality from Object.
104        }
105    
106        /**
107         * The client can register a factory for lazy creation of the
108         * instance.
109         */
110        public static interface Factory<T> {
111            T make();
112        };
113    
114        /**
115         * The underlying map storing the data.
116         * We maintain the invariant that this table contains only
117         * mappings of the form
118         * Key<T> -> T or Key<T> -> Factory<T> */
119        private Map<Key<?>,Object> ht = new HashMap<Key<?>,Object>();
120    
121        /** Set the factory for the key in this context. */
122        public <T> void put(Key<T> key, Factory<T> fac) {
123            checkState(ht);
124            Object old = ht.put(key, fac);
125            if (old != null)
126                throw new AssertionError("duplicate context value");
127        }
128    
129        /** Set the value for the key in this context. */
130        public <T> void put(Key<T> key, T data) {
131            if (data instanceof Factory<?>)
132                throw new AssertionError("T extends Context.Factory");
133            checkState(ht);
134            Object old = ht.put(key, data);
135            if (old != null && !(old instanceof Factory<?>) && old != data && data != null)
136                throw new AssertionError("duplicate context value");
137        }
138    
139        /** Get the value for the key in this context. */
140        public <T> T get(Key<T> key) {
141            checkState(ht);
142            Object o = ht.get(key);
143            if (o instanceof Factory<?>) {
144                Factory<?> fac = (Factory<?>)o;
145                o = fac.make();
146                if (o instanceof Factory<?>)
147                    throw new AssertionError("T extends Context.Factory");
148                assert ht.get(key) == o;
149            }
150    
151            /* The following cast can't fail unless there was
152             * cheating elsewhere, because of the invariant on ht.
153             * Since we found a key of type Key<T>, the value must
154             * be of type T.
155             */
156            return Context.<T>uncheckedCast(o);
157        }
158    
159        public Context() {}
160    
161        private Map<Class<?>, Key<?>> kt = new HashMap<Class<?>, Key<?>>();
162    
163        private <T> Key<T> key(Class<T> clss) {
164            checkState(kt);
165            Key<T> k = uncheckedCast(kt.get(clss));
166            if (k == null) {
167                k = new Key<T>();
168                kt.put(clss, k);
169            }
170            return k;
171        }
172    
173        public <T> T get(Class<T> clazz) {
174            return get(key(clazz));
175        }
176    
177        public <T> void put(Class<T> clazz, T data) {
178            put(key(clazz), data);
179        }
180        public <T> void put(Class<T> clazz, Factory<T> fac) {
181            put(key(clazz), fac);
182        }
183    
184        /**
185         * TODO: This method should be removed and Context should be made type safe.
186         * This can be accomplished by using class literals as type tokens.
187         */
188        @SuppressWarnings("unchecked")
189        private static <T> T uncheckedCast(Object o) {
190            return (T)o;
191        }
192    
193        public void dump() {
194            for (Object value : ht.values())
195                System.err.println(value == null ? null : value.getClass());
196        }
197    
198        public void clear() {
199            ht = null;
200            kt = null;
201        }
202    
203        private static void checkState(Map<?,?> t) {
204            if (t == null)
205                throw new IllegalStateException();
206        }
207    }