001    /*
002     * Copyright 2010-2015 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.kotlin.cli.jvm.repl;
018    
019    import com.google.common.collect.Maps;
020    import org.jetbrains.annotations.NotNull;
021    import org.jetbrains.kotlin.resolve.jvm.JvmClassName;
022    import org.jetbrains.org.objectweb.asm.ClassReader;
023    import org.jetbrains.org.objectweb.asm.util.TraceClassVisitor;
024    
025    import java.io.PrintWriter;
026    import java.util.Map;
027    
028    public class ReplClassLoader extends ClassLoader {
029    
030        private final Map<JvmClassName, byte[]> classes = Maps.newLinkedHashMap();
031    
032        public ReplClassLoader(@NotNull ClassLoader parent) {
033            super(parent);
034        }
035    
036        @NotNull
037        @Override
038        protected Class<?> findClass(@NotNull String name) throws ClassNotFoundException {
039            byte[] classBytes = classes.get(JvmClassName.byFqNameWithoutInnerClasses(name));
040            if (classBytes != null) {
041                return defineClass(name, classBytes, 0, classBytes.length);
042            }
043            else {
044                return super.findClass(name);
045            }
046        }
047    
048        public void addClass(@NotNull JvmClassName className, @NotNull byte[] bytes) {
049            byte[] oldBytes = classes.put(className, bytes);
050            if (oldBytes != null) {
051                throw new IllegalStateException("Rewrite at key " + className);
052            }
053        }
054    
055        public void dumpClasses(@NotNull PrintWriter writer) {
056            for (byte[] classBytes : classes.values()) {
057                new ClassReader(classBytes).accept(new TraceClassVisitor(writer), 0);
058            }
059        }
060    
061    }