repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
cst
cst-master/src/main/java/br/unicamp/cst/support/InterfaceAdapter.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.support; import com.google.gson.*; import java.lang.reflect.Type; /** * * @author rgudwin */ public final class InterfaceAdapter<T> implements JsonSerializer<T>, JsonDeserializer<T> { public JsonElement serialize(T object, Type interfaceType, JsonSerializationContext context) { final JsonObject wrapper = new JsonObject(); wrapper.addProperty("type", object.getClass().getName()); wrapper.add("data", context.serialize(object)); return wrapper; } public T deserialize(JsonElement elem, Type interfaceType, JsonDeserializationContext context) throws JsonParseException { final JsonObject wrapper = (JsonObject) elem; final JsonElement typeName = get(wrapper, "type"); final JsonElement data = get(wrapper, "data"); final Type actualType = typeForName(typeName); return context.deserialize(data, actualType); } private Type typeForName(final JsonElement typeElem) { try { return Class.forName(typeElem.getAsString()); } catch (ClassNotFoundException e) { throw new JsonParseException(e); } } private JsonElement get(final JsonObject wrapper, String memberName) { final JsonElement elem = wrapper.get(memberName); if (elem == null) throw new JsonParseException("no '" + memberName + "' member found in what was expected to be an interface wrapper"); return elem; } }
2,067
40.36
143
java
cst
cst-master/src/main/java/br/unicamp/cst/support/ProfileInfo.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.support; /** * * @author rgudwin */ public class ProfileInfo { long executionTime; long callingTime; long lastCallingTime; public ProfileInfo(long executionTime, long callingTime, long lastCallingTime) { this.executionTime = executionTime; this.callingTime = callingTime; this.lastCallingTime = lastCallingTime; } }
986
34.25
97
java
cst
cst-master/src/main/java/br/unicamp/cst/support/Profiler.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * R. R. Gudwin ******************************************************************************/ package br.unicamp.cst.support; /** * * @author rgudwin */ public class Profiler { long before; long after; public void begin() { before = System.currentTimeMillis(); } public void end() { after = System.currentTimeMillis(); } public void printDifference() { System.out.println("Time elapsed: "+(after-before)+" ms"); } public void printDifference(String pre) { System.out.println(pre+" Time elapsed: "+(after-before)+" ms"); } }
1,019
25.153846
80
java
cst
cst-master/src/main/java/br/unicamp/cst/support/TimeStamp.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.support; import java.sql.Time; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * * @author gudwin */ public class TimeStamp { long t; static long tzero = getLongTimeStamp("00:00:00"); static long start_time; public TimeStamp(long n) { t = n; } public TimeStamp(String ts) { try { t = Time.valueOf(ts).getTime(); } catch (Exception e) { System.out.println(e); } } public static void setStartTime() { start_time = System.currentTimeMillis(); } public static long getTimeSinceStart() { return(System.currentTimeMillis()-start_time); } public static String getDelaySinceStart() { return(getTimeSinceStart("HH:mm:ss.S")); } public static String getTimeSinceStart(String format) { return(getStringTimeStamp(getTimeSinceStart(),format)); } public static boolean isParseable(String s, String f) { Date date=null; SimpleDateFormat sdf = new SimpleDateFormat(f); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); try { date = sdf.parse(s); } catch (Exception e) { } if (date != null) return(true); else return(false); } public static long getLongTimeStamp(String ts) { if (isParseable(ts, "HH:mm:ss")) return(getLongTimeStamp(ts,"HH:mm:ss")); else if (isParseable(ts, "HH:mm")) return(getLongTimeStamp(ts,"HH:mm")); else if (isParseable(ts, "dd/MM/yyyy HH:mm:ss")) return(getLongTimeStamp(ts,"dd/MM/yyyy HH:mm:ss")); else if (isParseable(ts, "dd/MM/yyyy HH:mm")) return(getLongTimeStamp(ts,"dd/MM/yyyy HH:mm")); else if (isParseable(ts, "dd/MM/yy HH:mm:ss")) return(getLongTimeStamp(ts,"dd/MM/yy HH:mm:ss")); else if (isParseable(ts, "dd/MM/yy HH:mm")) return(getLongTimeStamp(ts,"dd/MM/yy HH:mm")); else if (isParseable(ts, "dd/MM/yyyy")) return(getLongTimeStamp(ts,"dd/MM/yyyy")); else if (isParseable(ts, "dd/MM/yy")) return(getLongTimeStamp(ts,"dd/MM/yy")); else if (isParseable(ts, "d/M/yy")) return(getLongTimeStamp(ts,"d/M/yy")); else if (isParseable(ts, "M/d/yyyy")) return(getLongTimeStamp(ts,"M/d/yyyy")); else if (isParseable(ts, "M/d/yy")) return(getLongTimeStamp(ts,"M/d/yy")); else return(0L); } public static long getLongTimeStamp(String ts, String format) { long tst=0; try { SimpleDateFormat df = new SimpleDateFormat(format); df.setTimeZone(TimeZone.getTimeZone("GMT")); tst = df.parse(ts).getTime(); } catch (Exception e) { System.out.println(e); } return tst; } public static String getStringTimeStamp(long tl, String fs) { String s; SimpleDateFormat df = new SimpleDateFormat(fs); df.setTimeZone(TimeZone.getTimeZone("GMT")); s = df.format(tl); return(s); } public static String getStringTimeStamp(long tl) { return getStringTimeStamp(tl,"dd/MM/yyyy HH:mm:ss.SSS"); } public static long getLongDelay(String ts) { long tst=0; tst = TimeStamp.getLongTimeStamp(ts); //tzero = TimeStamp.getLongTimeStamp("00:00:00"); return(tst-tzero); } public static String getTime(long t) { return(getStringTimeStamp(t,"HH:mm")); } public static String getDate(long t) { return(getStringTimeStamp(t,"dd/MM/yyyy")); } public static String getDateTime(long t) { return(getStringTimeStamp(t,"dd/MM/yyyy HH:mm")); } public static void printTime(long t) { System.out.print(getTime(t)); } public static void printDate(long t) { System.out.print(getDate(t)); } public static void printDateTime(long t) { System.out.print(getDateTime(t)); } public static int getInt(String s) { return(Integer.parseInt(s)); } public static double getDouble(String s) { return(Double.parseDouble(s)); } public static boolean getBoolean(String s) { return(Boolean.parseBoolean(s)); } public static long getCanonicalTime(long t) { String time = getTime(t); long tm = getLongTimeStamp(time); return(tm); } public static boolean isInPeriod(long t, String ini, String fim) { String time = getTime(t); //long zero = getLongTimeStamp("00:00"); //long vq = getLongTimeStamp("24:00"); long ti = getLongTimeStamp(ini); long tf = getLongTimeStamp(fim); long tm = getLongTimeStamp(time); if (tf < ti) { // Verificar até meia noite e depois de 0:00 até fim if (tm > ti || tm < tf) return(true); else return(false); } else { if (tm > ti && tm < tf) return(true); else return(false); } } public static String now() { long timestamp = System.currentTimeMillis(); return(getStringTimeStamp(timestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } }
5,630
31.929825
107
java
cst
cst-master/src/main/java/br/unicamp/cst/support/ToString.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.support; import java.util.Date; /** * * @author rgudwin */ public class ToString { public static String from(Object n) { String s=null; if (n == null) s = "<NULL>"; else if (n instanceof Long) { long i = (long) n; s = String.format("%d",i); } else if (n instanceof Integer) { int i = (int) n; s = String.format("%d",i); } else if (n instanceof Float) { float d = (float) n; s = String.format("%4.2f", d); } else if (n instanceof Double) { double d = (double) n; s = String.format("%4.2f", d); } else if (n instanceof Byte) { byte b = (byte) n; s = String.format("%x", b); } else if (n instanceof Short) { short sh = (short) n; s = String.format("%d", sh); } else if (n instanceof Boolean) { boolean b = (boolean) n; if (b == true) s = "true"; else s = "false"; } else if (n instanceof Date) { Date d = (Date) n; s = TimeStamp.getStringTimeStamp(d.getTime(),"dd/MM/yyyy HH:mm:ss.SSS"); } else if (n instanceof String) { s = (String) n; } return(s); } public static String fromArray(Object n) { String s=null; if (n == null) s = "<NULL>"; else if (n instanceof double[]) { double[] value = (double[]) n; if (value.length == 1) s = String.format("%4.2f",value[0]); else if (value.length == 2) s = String.format("%4.2f,%4.2f",value[0],value[1]); else if (value.length == 3) s = String.format("%4.2f,%4.2f,%4.2f",value[0],value[1],value[2]); else if (value.length == 4) s = String.format("%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3]); else if (value.length == 5) s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4]); else if (value.length == 6) s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4],value[5]); else if (value.length > 6) s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f...",value[0],value[1],value[2],value[3],value[4],value[5]); } else if (n instanceof float[]) { float[] value = (float[]) n; if (value.length == 1) s = String.format("%4.2f",value[0]); else if (value.length == 2) s = String.format("%4.2f,%4.2f",value[0],value[1]); else if (value.length == 3) s = String.format("%4.2f,%4.2f,%4.2f",value[0],value[1],value[2]); else if (value.length == 4) s = String.format("%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3]); else if (value.length == 5) s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4]); else if (value.length == 6) s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4],value[5]); else if (value.length > 6) s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f...",value[0],value[1],value[2],value[3],value[4],value[5]); } return(s); } public static String el(String name, int i) { String s = name +"["+i+"]"; return(s); } public static String getSimpleName(String fullname) { String[] mc = fullname.split("\\."); String simplename = mc[mc.length-1]; return (simplename); } }
4,520
37.974138
130
java
cst
cst-master/src/main/java/br/unicamp/cst/support/ToTxt.java
/* * /******************************************************************************* * * Copyright (c) 2012 DCA-FEEC-UNICAMP * * All rights reserved. This program and the accompanying materials * * are made available under the terms of the GNU Lesser Public License v3 * * which accompanies this distribution, and is available at * * http://www.gnu.org/licenses/lgpl.html * * * * Contributors: * * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation * ******************************************************************************/ package br.unicamp.cst.support; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.logging.Level; import java.util.logging.Logger; public class ToTxt { /** * printToFile. Function to print on txt. * @param object map to print * @param filename name to write txt file * @param debug boolean that indicates if log should be printed * @param time_graph timestep * * @author leolellisr **/ private ToTxt() { throw new IllegalStateException("Utility class"); } public static void printToFile(Object object,String filename, boolean debug, int time_graph){ String user_dir = System.getProperty("user.dir"); File dir = new File(user_dir+"/tests"); if (!dir.exists()) { dir.mkdir(); if(debug) Logger.getAnonymousLogger().log(Level.INFO, "dir created: {0}", new Object[]{dir}); } DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"); LocalDateTime now = LocalDateTime.now(); try(FileWriter fw = new FileWriter(user_dir+ File.separator+filename,true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter out = new PrintWriter(bw)) { out.println(dtf.format(now)+"_"+"_"+time_graph+" "+ object); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
2,163
33.349206
106
java
cst
cst-master/src/test/java/br/unicamp/cst/attention/BottomUpFeapMapCodeletTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.attention; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import br.unicamp.cst.support.TimeStamp; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Test for Codelet implementation of Feature Maps generated by the Attentional System of * Conscious Attention-Based Integrated Model (CONAIM). The maps, from a bottom- * up perspective, provide information that present saliences in the state to * which attention should be oriented to and that, if attended, will enhance the * corresponding region in the attentional map for a certain time and inhibit * it in the sequence (inhibition of return). From a top-down perspective, * depending on the system goal and on the attentional dynamic current state * (orienting, selecting or sustaining), voluntary attention can be directed to * a region of space or object in two ways: by deliberative enhancing a region * in the attentional map or by adjusting the weights that define the * contribution of each feature dimension. * * @author L. L. Rossi (leolellisr) * @see Codelet * @see MemoryObject * @see SensorBufferCodelet */ public class BottomUpFeapMapCodeletTest { /** * Test class initialization for the Bottom-Up Feature Map. Creates a test * mind, with 1 input and 1 output. The codelet to be tested is initialized as * a BottomUpFM and inserted into the created mind. * Input and output are added to the codelet and it is set to * publish-subscribe. The mind is then initiated. * */ public MemoryObject source; public MemoryObject destination; BottomUpFM testFeapMapCodelet, testFeapMapCodelet2; public BottomUpFeapMapCodeletTest() { Mind testMind = new Mind(); source = testMind.createMemoryObject("SOURCE"); //source.setI(0); destination = testMind.createMemoryObject("DESTINATION"); destination.setI(new CopyOnWriteArrayList<Float>()); testFeapMapCodelet = new BottomUpFM(0, "DESTINATION", 100, 16, 255, 4, 4, 3, 0, false, true); testMind.insertCodelet(testFeapMapCodelet); testFeapMapCodelet.addInput(source); testFeapMapCodelet.addOutput(destination); testFeapMapCodelet.setIsMemoryObserver(true); source.addMemoryObserver(testFeapMapCodelet); testFeapMapCodelet2 = new BottomUpFM(0, "DESTINATION", 100, 16, 255, 4, 4, 3, 0, true, false); testMind.insertCodelet(testFeapMapCodelet2); testFeapMapCodelet2.addInput(source); testFeapMapCodelet2.addOutput(destination); testFeapMapCodelet2.setIsMemoryObserver(true); source.addMemoryObserver(testFeapMapCodelet2); testMind.start(); //List fulllist = (List)destination.getI(); } /* * Test 1: After sensor separation, input have all elements equal to 100. * With no saliences, the output array will only have elements equals 0. * * Test 2: After sensor separation, input have the following elements: * [[70.0, 210.0, 140.0, 140.0], * [70.0, 210.0, 140.0, 140.0], * [70.0, 210.0, 140.0, 140.0], * [70.0, 210.0, 140.0, 140.0]] * Performing the average pool operation and normalization, the following * array is obtained: * [[0.0, 0.27450982, 0.0, 0.0], * [0.0, 0.27450982, 0.0, 0.0], * [0.0, 0.27450982, 0.0, 0.0], * [0.0, 0.27450982, 0.0, 0.0]] * * Test 3: After sensor separation, input have the following elements: * [[0, 255, 0, 255], * [0, 255, 0, 255], * [0, 255, 0, 255], * [0, 255, 0, 255]] * Performing the average pool operation and normalization, the following * array is obtained: * [[0.0, 0.5, 0.0, 0.5], * [0.0, 0.5, 0.0, 0.5], * [0.0, 0.5, 0.0, 0.5], * [0.0, 0.5, 0.0, 0.5]] */ @Test public void testFeapMapCodelet() { BottomUpFeapMapCodeletTest test = new BottomUpFeapMapCodeletTest(); //for (int i=0;i<64;i++) { System.out.println("Testing ... "); long oldtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); // Test 1 CopyOnWriteArrayList<Float> arrList_test = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 16*3; i++) { arrList_test.add((float) (i%3)*50+100); } CopyOnWriteArrayList<Float> arrList_goal = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 16; i++) { arrList_goal.add((float) 0.0); } long newtimestamp = test.destination.getTimestamp(); test.testFeapMapCodelet.resetTriggers(); test.source.setI(arrList_test); while(test.testFeapMapCodelet.steps < 1) { newtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp during: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); System.out.println(" Input 1: "+test.source.getI()); System.out.print(" Output 1: "+ test.destination.getI()); System.out.print(" \n Goal 1: "+arrList_goal); List fulllist = (List) test.destination.getI(); if (fulllist != null && fulllist.size() > 0) { //printList(fulllist); System.out.println(" sizef: "+((List)(test.destination.getI())).size()+"\n"); assertEquals(fulllist.size(),16); assertEquals(fulllist,arrList_goal); } // Test 2 oldtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); arrList_test = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < (int)16/2*3; i++) { arrList_test.add((float)70*((i % 2) + 1)); arrList_test.add((float)70*((i % 2) + 2)); } arrList_goal = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 4; i++) { arrList_goal.add((float) 0.0); arrList_goal.add((float) 0.27450982); arrList_goal.add((float) 0.0); arrList_goal.add((float) 0.0); } newtimestamp = test.destination.getTimestamp(); test.testFeapMapCodelet.resetTriggers(); test.source.setI(arrList_test); while(test.testFeapMapCodelet.steps < 1) { newtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } System.out.println(" Input 2: "+test.source.getI()); System.out.print(" Output 2: "+ test.destination.getI()); System.out.print(" \n Goal 2: "+arrList_goal); fulllist = (List) test.destination.getI(); if (fulllist != null && fulllist.size() > 0) { //printList(fulllist); System.out.println(" sizef: "+((List)(test.destination.getI())).size()+"\n"); assertEquals(fulllist.size(),16); assertEquals(fulllist,arrList_goal); } // Test 3 oldtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); arrList_test = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 8*3; i++) { arrList_test.add((float) 0); arrList_test.add((float) 255); } arrList_goal = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 8; i++) { arrList_goal.add((float) 0); arrList_goal.add((float) 0.5); } newtimestamp = test.destination.getTimestamp(); test.testFeapMapCodelet.resetTriggers(); test.source.setI(arrList_test); while(test.testFeapMapCodelet.steps < 1) { newtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } System.out.println(" Input 3: "+test.source.getI()); System.out.print(" Output 3: "+ test.destination.getI()); System.out.print(" \n Goal 3: "+arrList_goal); fulllist = (List) test.destination.getI(); if (fulllist != null && fulllist.size() > 0) { //printList(fulllist); System.out.println(" sizef: "+fulllist.size()+"\n"); assertEquals(fulllist.size(),16); assertEquals(fulllist,arrList_goal); } //} } }
10,673
42.925926
167
java
cst
cst-master/src/test/java/br/unicamp/cst/attention/CombFeapMapCodeletTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.attention; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import br.unicamp.cst.support.TimeStamp; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * * Test for Codelet implementation of Feature Maps generated by the Attentional System of * Conscious Attention-Based Integrated Model (CONAIM). The combined feature * map is a weighted sum of the previous defined feature maps (bottom-up and * top-down). * @author L. L. Rossi (leolellisr) * @see Codelet * @see MemoryObject * @see FeatMapCodelet * @see CombFeatMapCodelet * @see CFM */ public class CombFeapMapCodeletTest { public MemoryObject source,source2,source3,weights; public MemoryObject destination,destination_type; public CFM testFeapMapCodelet, testFeapMapCodelet2; /** * Test class initialization for the Combined Feature Map. Creates a test * mind, with 4 inputs (3 sources and 1 weight) and 2 outputs. The codelet * to be tested is initialized as a CFM and inserted into the created mind. * Inputs and outputs are added to the codelet and it is set to * publish-subscribe. The mind is then initiated. * */ public CombFeapMapCodeletTest() { Mind testMind = new Mind(); weights = testMind.createMemoryObject("FM_WEIGHTS"); source = testMind.createMemoryObject( "SOURCE"); source2 = testMind.createMemoryObject("SOURCE2"); source3 = testMind.createMemoryObject("SOURCE3"); //source.setI(0); destination_type = testMind.createMemoryObject("TYPE"); destination_type.setI(new CopyOnWriteArrayList<Float>()); destination = testMind.createMemoryObject("COMB_FM"); destination.setI(new CopyOnWriteArrayList<Float>()); CopyOnWriteArrayList<String> FMnames = new CopyOnWriteArrayList<>(); FMnames.add("SOURCE"); FMnames.add("SOURCE2"); FMnames.add("SOURCE3"); testFeapMapCodelet = new CFM(FMnames, 100, 16, false, true); testMind.insertCodelet(testFeapMapCodelet); testFeapMapCodelet.addInput(source); testFeapMapCodelet.addInput(source2); testFeapMapCodelet.addInput(source3); testFeapMapCodelet.addInput(weights); testFeapMapCodelet.addOutput(destination); testFeapMapCodelet.addOutput(destination_type); testFeapMapCodelet.setIsMemoryObserver(true); source.addMemoryObserver(testFeapMapCodelet); source2.addMemoryObserver(testFeapMapCodelet); source3.addMemoryObserver(testFeapMapCodelet); weights.addMemoryObserver(testFeapMapCodelet); testFeapMapCodelet2 = new CFM(FMnames, 100, 16, true, false); testMind.insertCodelet(testFeapMapCodelet2); testFeapMapCodelet2.addInput(source); testFeapMapCodelet2.addInput(source2); testFeapMapCodelet2.addInput(source3); testFeapMapCodelet2.addInput(weights); testFeapMapCodelet2.addOutput(destination); testFeapMapCodelet2.addOutput(destination_type); testFeapMapCodelet2.setIsMemoryObserver(true); source.addMemoryObserver(testFeapMapCodelet2); source2.addMemoryObserver(testFeapMapCodelet2); source3.addMemoryObserver(testFeapMapCodelet2); weights.addMemoryObserver(testFeapMapCodelet2); testMind.start(); //List fulllist = (List)destination.getI(); } /** * Test 1. Inputs have sequential elements from 1 to 4. The weight vector is * initialized with 1s only. Thus, the output element will be the sum of the * elements of the same position [3, 6, 9, 12 ...]. * * Test 2. Inputs have elements equal to 1. The weight vector is initialized * with 1s only. Thus, the output element will be the sum of elements of the * same position [3, 3, 3, 3 ...]. * * Test 3. Inputs have elements equal to 1. The weight vector is initialized * with sequential elements from 1 to 3. Thus, the output element will be the * sum of elements in the same position [1*1+1*2+1* 3=6, 6, 6, 6...] * */ @Test public void testCombFeapMapCodelet() { CombFeapMapCodeletTest test = new CombFeapMapCodeletTest(); System.out.println("Testing ... "); long oldtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); CopyOnWriteArrayList<CopyOnWriteArrayList<Float>> arrList_test = new CopyOnWriteArrayList<CopyOnWriteArrayList<Float>>(); // Test 1 CopyOnWriteArrayList<Float> arrList_i = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 4*4; i++) { arrList_i.add((float)(i % 4) + 1); } CopyOnWriteArrayList<Float> arrList_goal = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 4; i++) { arrList_goal.add((float) 3.0); arrList_goal.add((float) 6.0); arrList_goal.add((float) 9.0); arrList_goal.add((float) 12.0); } arrList_test.add(arrList_i); System.out.println("arrList_test: "+arrList_test.size()+" arrList_i: "+arrList_i.size()+" arrList_goal: "+arrList_goal.size()); CopyOnWriteArrayList<Float> arrList_weig = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 3; i++) { arrList_weig.add((float) 1.0); } long newtimestamp = test.destination.getTimestamp(); test.testFeapMapCodelet.resetTriggers(); test.source.setI(arrList_test); //sleep(10); System.out.println("source: "+"steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(test.source.getTimestamp(),"dd/MM/yyyy HH:mm:ss.SSS")); test.source2.setI(arrList_test); //sleep(10); System.out.println("source2: "+"steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(test.source2.getTimestamp(),"dd/MM/yyyy HH:mm:ss.SSS")); test.source3.setI(arrList_test); //sleep(10); System.out.println("source3: "+"steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(test.source3.getTimestamp(),"dd/MM/yyyy HH:mm:ss.SSS")); test.weights.setI(arrList_weig); //sleep(10); System.out.println("source: "+"steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(test.weights.getTimestamp(),"dd/MM/yyyy HH:mm:ss.SSS")); while(test.testFeapMapCodelet.steps < 4) { newtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp while waiting: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); System.out.println(" Inputs 11: "+((List)((List)(test.source.getI())).get(0))+"\n size: "+((List)((List)(test.source.getI())).get(0)).size()); System.out.println(" Inputs 12: "+((List)((List)(test.source2.getI())).get(0))+"\n size: "+((List)((List)(test.source2.getI())).get(0)).size()); System.out.println(" Inputs 13: "+((List)((List)(test.source3.getI())).get(0))+"\n size: "+((List)((List)(test.source3.getI())).get(0)).size()); System.out.println(" weights 1: "+test.weights.getI()+" size: "+((List)(test.weights.getI())).size()); System.out.println(" Output 1: "+ test.destination.getI()); System.out.println(" Goal 1: "+arrList_goal); List fulllist = (List) test.destination.getI(); if (fulllist != null && fulllist.size() > 0) { System.out.println(" sizef: "+fulllist.size()+"\n"); assertEquals(((List)(test.destination.getI())).size(),16); assertEquals(((List)(test.destination.getI())),arrList_goal); } // Test 2 oldtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); arrList_i = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 4*4; i++) { arrList_i.add((float) 1); } arrList_goal = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 16; i++) { arrList_goal.add((float) 3.0); } newtimestamp = test.destination.getTimestamp(); test.testFeapMapCodelet.resetTriggers(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); //arrList_test = new CopyOnWriteArrayList<CopyOnWriteArrayList<Float>>(); arrList_test.add(arrList_i); //System.out.println(arrList_test); System.out.println("arrList_test: "+arrList_test.size()+" arrList_i: "+arrList_i.size()+" arrList_goal: "+arrList_goal.size()); test.source.setI(arrList_test); //sleep(10); System.out.println("source: "+"steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(test.source.getTimestamp(),"dd/MM/yyyy HH:mm:ss.SSS")); test.source2.setI(arrList_test); //sleep(10); System.out.println("source2: "+"steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(test.source2.getTimestamp(),"dd/MM/yyyy HH:mm:ss.SSS")); test.source3.setI(arrList_test); //sleep(10); System.out.println("source3: "+"steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(test.source3.getTimestamp(),"dd/MM/yyyy HH:mm:ss.SSS")); arrList_weig = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 3; i++) { arrList_weig.add((float) 1.0); } test.weights.setI(arrList_weig); //sleep(10); System.out.println("source: "+"steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(test.weights.getTimestamp(),"dd/MM/yyyy HH:mm:ss.SSS")); while(test.testFeapMapCodelet.steps < 4) { newtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp while waiting: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); System.out.println(" Inputs 21: "+((List)((List)(test.source.getI())).get(1))+"\n size: "+((List)((List)(test.source.getI())).get(1)).size()); System.out.println(" Inputs 22: "+((List)((List)(test.source2.getI())).get(1))+"\n size: "+((List)((List)(test.source2.getI())).get(1)).size()); System.out.println(" Inputs 23: "+((List)((List)(test.source3.getI())).get(1))+"\n size: "+((List)((List)(test.source3.getI())).get(1)).size()); System.out.println(" weights 2: "+test.weights.getI()+((List)(test.weights.getI())).size()); System.out.print(" Output 2: "+ test.destination.getI()); fulllist = (List) test.destination.getI(); if (fulllist != null && fulllist.size() > 0) { System.out.println(" sizef: "+((List)(test.destination.getI())).size()+"\n"); assertEquals(fulllist.size(),16); assertEquals(fulllist,arrList_goal); } // Test 3 oldtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); arrList_i = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 16; i++) { arrList_i.add((float) 1); } arrList_goal = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 16; i++) { arrList_goal.add((float) 6.0); } newtimestamp = test.destination.getTimestamp(); test.testFeapMapCodelet.resetTriggers(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); //arrList_test = new CopyOnWriteArrayList<CopyOnWriteArrayList<Float>>(); arrList_test.add(arrList_i); System.out.println("arrList_test: "+arrList_test.size()+" arrList_i: "+arrList_i.size()+" arrList_goal: "+arrList_goal.size()); test.source.setI(arrList_test); //sleep(10); test.source2.setI(arrList_test); //sleep(10); test.source3.setI(arrList_test); //sleep(10); arrList_weig = new CopyOnWriteArrayList<Float>(); for (int i = 1; i < 4; i++) { arrList_weig.add((float) i); } test.weights.setI(arrList_weig); while(test.testFeapMapCodelet.steps < 4) { newtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp while waiting: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); System.out.println(" Inputs 31: "+((List)((List)(test.source.getI())).get(2))+"\n size: "+((List)((List)(test.source.getI())).get(2)).size()); System.out.println(" Inputs 32: "+((List)((List)(test.source2.getI())).get(2))+"\n size: "+((List)((List)(test.source2.getI())).get(2)).size()); System.out.println(" Inputs 33: "+((List)((List)(test.source3.getI())).get(2))+"\n size: "+((List)((List)(test.source3.getI())).get(2)).size()); System.out.println(" weights 3: "+test.weights.getI()+"\n size: "+((List)(test.weights.getI())).size()); System.out.print(" Output 3: "+ test.destination.getI()); fulllist = (List) test.destination.getI(); if (fulllist != null && fulllist.size() > 0) { System.out.println(" sizef: "+fulllist.size()+"\n"); assertEquals(fulllist.size(),16); assertEquals(fulllist,arrList_goal); } } private void sleep(int time) { try{ Thread.sleep(time); } catch(Exception e){e.printStackTrace();} } }
16,335
54.376271
189
java
cst
cst-master/src/test/java/br/unicamp/cst/attention/TopDownFeapMapCodeletTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.attention; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import br.unicamp.cst.support.TimeStamp; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Test for Codelet implementation of Top-Down Feature Maps generated by the * Attentional System of Conscious Attention-Based Integrated Model (CONAIM). * * @see Codelet * @see MemoryObject * @see FeatMapCodelet * @author L. L. Rossi (leolellisr) */ public class TopDownFeapMapCodeletTest { private static Logger log = LoggerFactory.getLogger(TopDownFeapMapCodeletTest.class); public MemoryObject source; public MemoryObject destination; public TopDownFM testFeapMapCodelet, testFeapMapCodelet2; /** * Test class initialization for the Top-Down Feature Map. Creates a test * mind, with 1 input and 1 output. The codelet to be tested is initialized as * a TopDownFM and inserted into the created mind. * Input and output are added to the codelet and it is set to * publish-subscribe. The mind is then initiated. * */ public TopDownFeapMapCodeletTest() { Mind testMind = new Mind(); source = testMind.createMemoryObject("SOURCE"); destination = testMind.createMemoryObject("DESTINATION"); destination.setI(new CopyOnWriteArrayList<Float>()); CopyOnWriteArrayList<Float> goal = new CopyOnWriteArrayList<>(); goal.add((float) 255); goal.add((float) 0); goal.add((float) 0); testFeapMapCodelet = new TopDownFM(0, "DESTINATION", 100, 16, goal, 255, 16, 4, 3, false); testMind.insertCodelet(testFeapMapCodelet); testFeapMapCodelet.addInput(source); testFeapMapCodelet.addOutput(destination); testFeapMapCodelet.setIsMemoryObserver(true); source.addMemoryObserver(testFeapMapCodelet); testFeapMapCodelet2 = new TopDownFM(0, "DESTINATION", 100, 16, goal, 255, 16, 4, 3, true); testMind.insertCodelet(testFeapMapCodelet2); testFeapMapCodelet2.addInput(source); testFeapMapCodelet2.addOutput(destination); testFeapMapCodelet2.setIsMemoryObserver(true); source.addMemoryObserver(testFeapMapCodelet2); testMind.start(); } /** * * Input. Array with 768 elements representing a 16 x 16 resolution vision * sensor with 256 pixels in 3 color channels. The pixel arrangement of the * sensor is as follows: * [[R_1_1, G_1_1, B_1_1, R_1_2, ..., R_1_16, G_1_16, B_1_16], * [R_2_1, G_2_1, B_2_1, R_2_2, ..., R_2_16, G_2_16, B_2_16], * ... * [R_16_1, G_16_1, B_16_1, R_16_2, ..., R_16_16, G_16_16, B_16_16]] * * Output. Array with 16 elements representing the vision sensor separated * into 16 regions (4x4). * * Test 1: Input have all elements equal to 255. With no saliences, the * output array will only have elements equals 0. * * Test 2: Input have first 192 elements equal to 100 (64 for each channel), * then next 192 elements are equal to [0, 100, 100], * then next 192 elements are equal to [100, 0, 100], * then next 192 elements are equal to [100, 100, 0]. * * Performing the average pool operation on each of the color channels, the * following arrays are obtained: * Red channel: * [[100, 100, 100, 100], * [0, 0, 0, 0], * [100, 100, 100, 100], * [100, 100, 100, 100]] * * Green channel: * [[100, 100, 100, 100], * [100, 100, 100, 100], * [0, 0, 0, 0], * [100, 100, 100, 100]] * * Blue channel: * [[100, 100, 100, 100], * [100, 100, 100, 100], * [100, 100, 100, 100], * [0, 0, 0, 0]] * * When comparing the values obtained with the operation with the desired * goal, it is observed that the most distant values are in the red channel. * Using the comparison values, we get an output of: * [[0.25, 0.25, 0.25, 0.25], * [0, 0, 0, 0], * [0.25, 0.25, 0.25, 0.25], * [0.25, 0.25, 0.25, 0.25]] * * Test 3: Input have first 192 elements equal to [125, 0, 0], * then next 192 elements are equal to [0, 100, 0], * then next 192 elements are equal to [0, 0, 200], * then next 192 elements are equal to [0, 0, 255]. * * Performing the average pool operation on each of the color channels, the * following arrays are obtained: * Red channel: * [[125, 125, 125, 125], * [0, 0, 0, 0], * [0, 0, 0, 0], * [0, 0, 0, 0]] * * Green channel: * [[0, 0, 0, 0], * [100, 100, 100, 100], * [0, 0, 0, 0], * [0, 0, 0, 0]] * * Blue channel: * [[0, 0, 0, 0], * [0, 0, 0, 0], * [200, 200, 200, 200], * [255, 255, 255, 255]] * * When comparing the values obtained with the operation with the desired * goal, it is observed that the most distant values are in the red and blue channels. * Using the comparison values, we get an output of: * [[0.5, 0.5, 0.5, 0.5], * [0, 0, 0, 0], * [0, 0, 0, 0], * [0, 0, 0, 0]] * * Test 4: Input have elements equal to [255, 0, 0]. * * Performing the average pool operation on each of the color channels, the * following arrays are obtained: * Red channel: * [[255, 255, 255, 255], * [255, 255, 255, 255], * [255, 255, 255, 255], * [255, 255, 255, 255]] * * Green channel: * [[0, 0, 0, 0], * [0, 0, 0, 0], * [0, 0, 0, 0], * [0, 0, 0, 0]] * * Blue channel: * [[0, 0, 0, 0], * [0, 0, 0, 0], * [0, 0, 0, 0], * [0, 0, 0, 0]] * * When comparing the values obtained with the operation with the desired * goal, it is observed that all values are equal the goal. * Using the comparison values, we get an output of: * [[1, 1, 1, 1], * [1, 1, 1, 1], * [1, 1, 1, 1], * [1, 1, 1, 1]] */ @Test public void testTopDownFeapMapCodelet() { TopDownFeapMapCodeletTest test = new TopDownFeapMapCodeletTest(); System.out.println("Testing ... "); // Test 1 CopyOnWriteArrayList<Float> arrList_test = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 256*3; i++) { arrList_test.add((float) 255); } CopyOnWriteArrayList<Float> arrList_goal = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 16; i++) { arrList_goal.add((float) 0); } long oldtimestamp = test.destination.getTimestamp(); System.out.println("steps"+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); long newtimestamp = test.destination.getTimestamp(); test.testFeapMapCodelet.resetTriggers(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); test.source.setI(arrList_test); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); while(test.testFeapMapCodelet.steps < 1) { newtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp during: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } System.out.println("steps: "+test.testFeapMapCodelet.steps); System.out.println(" Input 1: "+test.source.getI()+" \n size: "+((List)(test.source.getI())).size()); System.out.println(" Output 1: "+ test.destination.getI()); System.out.println(" Goal 1:"+arrList_goal); System.out.println("steps: "+test.testFeapMapCodelet.steps); List fulllist = (List) test.destination.getI(); System.out.println("steps: "+test.testFeapMapCodelet.steps); if (fulllist != null && fulllist.size() > 0) { System.out.println(" sizef: "+((List)(fulllist)).size()+"\n"); assertEquals(fulllist.size(),16); assertEquals(fulllist,arrList_goal); } System.out.println("steps: "+test.testFeapMapCodelet.steps); // Test 2 oldtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); arrList_test = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < (int)(256/4); i++) { arrList_test.add((float) 100); arrList_test.add((float) 100); arrList_test.add((float) 100); } for (int i = (int)(256/4); i < (int)(256/4*2); i++) { arrList_test.add((float) 0); arrList_test.add((float) 100); arrList_test.add((float) 100); } for (int i = (int)(256/4*2); i < (int)(256/4*3); i++) { arrList_test.add((float) 100); arrList_test.add((float) 0); arrList_test.add((float) 100); } for (int i = (int)(256/4*3); i < 256; i++) { arrList_test.add((float) 100); arrList_test.add((float) 100); arrList_test.add((float) 0); } arrList_goal = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 4; i++) { arrList_goal.add((float) 0.25); } for (int i = 0; i < 4; i++) { arrList_goal.add((float) 0.0); } for (int i = 0; i < 8; i++) { arrList_goal.add((float) 0.25); } System.out.println("steps: "+test.testFeapMapCodelet.steps); newtimestamp = test.destination.getTimestamp(); test.testFeapMapCodelet.resetTriggers(); System.out.println("steps: "+test.testFeapMapCodelet.steps); test.source.setI(arrList_test); System.out.println("steps: "+test.testFeapMapCodelet.steps); while(test.testFeapMapCodelet.steps < 1) { newtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } System.out.println("steps: "+test.testFeapMapCodelet.steps); System.out.println(" Input 2: "+test.source.getI()+" \n size: "+((List)(test.source.getI())).size()); System.out.print("\n Output 2: "+ test.destination.getI()); System.out.println("\n Goal 2:"+arrList_goal); fulllist = (List) test.destination.getI(); if (fulllist != null && fulllist.size() > 0) { System.out.println(" sizef: "+((List)(test.destination.getI())).size()+"\n"); assertEquals(fulllist.size(),16); assertEquals(fulllist,arrList_goal); } oldtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); // Test 3 arrList_test = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < (int)(256/4); i++) { arrList_test.add((float) 125); arrList_test.add((float) 0); arrList_test.add((float) 0); } for (int i = (int)(256/4); i < (int)(256/4*2); i++) { arrList_test.add((float) 0); arrList_test.add((float) 100); arrList_test.add((float) 0); } for (int i = (int)(256/4*2); i < (int)(256/4*3); i++) { arrList_test.add((float) 0); arrList_test.add((float) 0); arrList_test.add((float) 200); } for (int i = (int)(256/4*3); i < 256; i++) { arrList_test.add((float) 0); arrList_test.add((float) 0); arrList_test.add((float) 255); } arrList_goal = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 4; i++) { arrList_goal.add((float) 0.5); } for (int i = 0; i < 12; i++) { arrList_goal.add((float) 0.0); } newtimestamp = test.destination.getTimestamp(); test.testFeapMapCodelet.resetTriggers(); test.source.setI(arrList_test); while(test.testFeapMapCodelet.steps < 1) { newtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } System.out.println(" Input 3: "+test.source.getI()+" \n size: "+((List)(test.source.getI())).size()); System.out.println("\n Output 3: "+ test.destination.getI()); System.out.println("\n Goal 3:"+arrList_goal); fulllist = (List) test.destination.getI(); if (fulllist != null && fulllist.size() > 0) { System.out.println(" sizef: "+((List)(test.destination.getI())).size()+"\n"); assertEquals(fulllist.size(),16); assertEquals(fulllist,arrList_goal); } // Test 4 oldtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); arrList_test = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < (int)(256); i++) { arrList_test.add((float) 255); arrList_test.add((float) 0); arrList_test.add((float) 0); } arrList_goal = new CopyOnWriteArrayList<Float>(); for (int i = 0; i < 16; i++) { arrList_goal.add((float) 1); } System.out.println("steps: "+test.testFeapMapCodelet.steps); newtimestamp = test.destination.getTimestamp(); test.testFeapMapCodelet.resetTriggers(); System.out.println("steps: "+test.testFeapMapCodelet.steps); test.source.setI(arrList_test); System.out.println("steps: "+test.testFeapMapCodelet.steps); while(test.testFeapMapCodelet.steps < 1) { newtimestamp = test.destination.getTimestamp(); System.out.println("steps: "+test.testFeapMapCodelet.steps+" Timestamp after: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } System.out.println("steps: "+test.testFeapMapCodelet.steps); System.out.println(" Input 4: "+test.source.getI()+" \n size: "+((List)(test.source.getI())).size()); System.out.print("\n Output 4: "+ test.destination.getI()); System.out.println("\n Goal 4:"+arrList_goal); fulllist = (List) test.destination.getI(); if (fulllist != null && fulllist.size() > 0) { System.out.println(" sizef: "+((List)(test.destination.getI())).size()+"\n"); assertEquals(fulllist.size(),16); assertEquals(fulllist,arrList_goal); } } }
16,976
44.272
167
java
cst
cst-master/src/test/java/br/unicamp/cst/behavior/glas/TestGlasSequence.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * @author Klaus Raizer * */ public class TestGlasSequence { @Test public void testAddingEventsToSequence() { GlasSequence mySequence = new GlasSequence(); int stimulus0=0; int action0 = 0; double reward0 = 0.5; GlasEvent myEvent = new GlasEvent(stimulus0,action0,reward0); mySequence.addEvent(myEvent); int stimulus1=1; int action1 = 2; double reward1 = -0.5; myEvent = new GlasEvent(stimulus1,action1,reward1); mySequence.addEvent(myEvent); ArrayList<GlasEvent> newSequence= mySequence.getEvents(); GlasEvent event0 = newSequence.get(0); GlasEvent event1 = newSequence.get(1); assertTrue(event0.getStimulus()==stimulus0); assertTrue(event0.getAction()==action0); assertTrue(event0.getReward()==reward0); assertTrue(event1.getStimulus()==stimulus1); assertTrue(event1.getAction()==action1); assertTrue(event1.getReward()==reward1); } }
1,655
22
82
java
cst
cst-master/src/test/java/br/unicamp/cst/behavior/glas/TestGlasStateMachine.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * @author Klaus Raizer * */ public class TestGlasStateMachine { //Solution chromossome for the 1AX task static int nNodes = 7; static int nActions = 3; static int nStimuli = 7; static int[] sampled_stimuli = {1,4,3,5,2,3,4, 6,1,4,3,5,2,3, 4,6,2,4,3,5,1, 5,4,6,2,3,3,6}; static int[] selected_actions = {1,1,1,2,1,1,1, 2,2,1,1,1,1,0, 1,2,1,1,1,1,1, 1,1,1,1,1,1,2}; //Some wrong choices static double[] rewards_received = {1,1,1,10,1,1,1, 10,-1,1,1,-10,1,-1, 1,10,1,1,1,1,1, 1,1,1,1,1,1,-10}; static double expected_reward_for_good_solution=51; // @Test // public void testGoodSolution_known() { // // int[] good_solution_phenotype= {0,1,1,2,3,4,5, 0,2,1,4,3,6,5, 0,1,1,1,1,2,2}; // int[] good_solution_actions= {1,1,1,2,1,1,1, 2,1,1,1,2,1,1, 1,2,1,1,1,1,1, 1,1,1,1,1,1,1}; // int [] good_solution_expected_nodes_history= {3,3,5,7,2,2,4, 6,3,3,5,7,2,2, 4,6,2,4,4,4,3, 3,3,3,2,2,2,2}; // // // StateMachine sm = new StateMachine(good_solution_phenotype); // // sm.reset(); // // int[] local_selected_actions = sm.runStimuli(sampled_stimuli); // // int[] local_nodes_history = sm.getNodes_history(); // // int a=1; // a=2; // // // assertTrue(local_selected_actions.length==good_solution_actions.length); // // // for(int index=0; index<local_nodes_history.length;index++){ // assertTrue(local_nodes_history[index]==good_solution_expected_nodes_history[index]); // } // // } // // @Test // public void testBadSolution28() { // // int[] bad_solution_phenotype= {0,1,2,3,4,5,2, 0,1,4,5,2,6,3, 0,1,1,2,1,2,0}; // int[] bad_solution_expected_nodes_history= {2,3,3,4,5,5,5, 6,2,3,3,4,5,5, 5,6,2,3,3,4,2, 2,3,3,3,3,3,3}; // // //// int[] good_solution_phenotype= {0,1,1,2,3,4,5, 0,2,1,4,3,6,5, 0,1,1,1,1,2,2}; //// int[] good_solution_actions= {1,1,1,2,1,1,1, 2,1,1,1,2,1,1, 1,2,1,1,1,1,1, 1,1,1,1,1,1,1}; //// int [] good_solution_expected_nodes_history= {3,3,5,7,2,2,4, 6,3,3,5,7,2,2, 4,6,2,4,4,4,3, 3,3,3,2,2,2,2}; // // // StateMachine sm = new StateMachine(bad_solution_phenotype); // // sm.reset(); // // int[] local_selected_actions = sm.runStimuli(sampled_stimuli); // // int[] local_nodes_history = sm.getNodes_history(); // // int a=1; // a=2; // // // // // for(int index=0; index<local_nodes_history.length;index++){ // assertTrue(local_nodes_history[index]==bad_solution_expected_nodes_history[index]); // } // // } @Test public void testGoBackToOriginalSN(){ int[] good_solution_phenotype= {0,1,1,2,3,4,5, 0,2,1,4,3,6,5, 0,1,1,1,1,2,2}; int[] good_solution_actions= {1,1,1,2,1,1,1, 2,1,1,1,2,1,1, 1,2,1,1,1,1,1, 1,1,1,1,1,1,1}; int [] good_solution_expected_nodes_history= {3,3,5,7,2,2,4, 6,3,3,5,7,2,2, 4,6,2,4,4,4,3, 3,3,3,2,2,2,2}; GlasActionSelection sm = new GlasActionSelection(good_solution_phenotype); sm.reset(); int stim=3333; //Unknown int current_node_minus_1 = 7-1; System.out.println("Before: "+current_node_minus_1); current_node_minus_1=sm.goBackToOriginalSN(current_node_minus_1,stim); System.out.println("After: "+current_node_minus_1); System.out.println("Should be: "+(3-1)); assertTrue(current_node_minus_1==(3-1)); //TODO Reproduce here the anomalous case from solution 28 } int[] solution_chromossome={0, 1, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 0, 1, 1, 1, 1, 2, 2}; int[] known_types = {0, 1, 1, 2, 2, 3, 3}; // 0 1 2 3 4 5 6 // 0 1 2 a b x y //0 means unknown // 0 1 2 // 0 L R // @Test // public void testStateMachineUpdateNodesTypes() { // StateMachine sm=new StateMachine(solution_chromossome); // // // // int[] nodes_types = sm.getNodes_types(); // // assertTrue(nodes_types.length==known_types.length); // for (int i=0; i<known_types.length;i++){ // assertTrue(nodes_types[i]==known_types[i]); // } // // } // @Test public void testActionSelection(){ int[] sample_stimuli = {1,4,3,5,2,3,4,6}; //1 b a x 2 a b y int[] expected_actions = {1,1,1,2,1,1,1,2}; GlasActionSelection sm = new GlasActionSelection(solution_chromossome); sm.reset(); int[] selected_actions = sm.runStimuli(sample_stimuli); assertTrue(selected_actions.length==expected_actions.length); for(int i=0;i<selected_actions.length;i ++){ assertTrue(expected_actions[i]==selected_actions[i]); } } // // // @Test // public void testActionSelection2(){ // // int[] sample_stimuli2 = {2,1,3,3,5,4,6,3,5}; //"21AAXBYAX" "LLLLRLLLR" // int[] expected_actions2 = {1,1,1,1,2,1,1,1,2}; // // StateMachine sm = new StateMachine(solution_chromossome); // // sm.reset(); // // int[] selected_actions = sm.runStimuli(sample_stimuli2); // // assertTrue(selected_actions.length==expected_actions2.length); // for(int i=0;i<selected_actions.length;i ++){ // assertTrue(expected_actions2[i]==selected_actions[i]); // } // // } // // @Test // public void testActionSelection3(){ // // // // 0 1 2 3 4 5 6 // // 0 1 2 a b x y //0 means unknown // // // 0 1 2 // // 0 L R // //Here, 9 and 8 are unknown, and should be ignored // int[] sample_stimuli2 = {1,2,9,4,8,6}; //"12CBZY" "LLLR" // int[] expected_actions2 = {1,1,0,1,0,2}; // // StateMachine sm = new StateMachine(solution_chromossome); // // sm.reset(); // // int[] selected_actions = sm.runStimuli(sample_stimuli2); // // assertTrue(selected_actions.length==expected_actions2.length); // for(int i=0;i<selected_actions.length;i ++){ // assertTrue(expected_actions2[i]==selected_actions[i]); // } // // } // // // // @Test // public void testActionSelection4(){ ////TODO It seems like he came back to 1 at the middle //// int[] sample_stimuli = {1, 4, 3, 5, 2, 3, 4, 6, 1, 4, 3, 5, 2, 3, 4, 6}; //// int[] expected_actions = {1, 1, 1, 2, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2}; // int[] sample_stimuli = {1, 4, 3, 5, 2, 3, 4, 6, 3, 5, 1, 4, 6, 2, 3, 6}; // int[] expected_actions = {1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1}; // // StateMachine sm = new StateMachine(solution_chromossome); // // sm.reset(); // // int[] selected_actions = sm.runStimuli(sample_stimuli); // // assertTrue(selected_actions.length==expected_actions.length); // for(int i=0;i<selected_actions.length;i ++){ // assertTrue(expected_actions[i]==selected_actions[i]); // } // // } }
7,118
28.057143
118
java
cst
cst-master/src/test/java/br/unicamp/cst/behavior/glas/TestGlassFitness.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class TestGlassFitness { static int nNodes = 7; static int nActions = 3; static int nStimuli = 7; static int[] sample_stimuli = {1, 4, 3, 5, 2, 3, 4, 6, 1, 4, 3, 5, 2, 3, 4, 6, 2, 4, 3, 5, 1, 5, 4, 6, 2, 3, 3, 6}; static int[] expected_actions = {1, 1, 1, 2, 1, 1, 1, 2, 2, 1, 1, 1, 1, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2}; //Some wrong choices static double[] rewards = {1, 1, 1,10, 1, 1, 1,10, -1, 1, 1,-10, 1, -1, 1,10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-10}; static double expected_reward_for_good_solution=51; //without heuristics // static double expected_reward_for_good_solution=51.75; //with heuristics @Test public void testGoodSolution_known() { int[] good_solution_phenotype={0, 1, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 0, 1, 1, 1, 1, 2, 2}; GlasSequence mySequence = new GlasSequence(); for(int e=0;e<sample_stimuli.length;e++){ mySequence.addEvent(new GlasEvent(sample_stimuli[e],expected_actions[e],rewards[e])); } Individual indi =new Individual(nNodes, nStimuli, nActions); indi.setChromossome(good_solution_phenotype); double fit=indi.getFitness(mySequence); System.out.println("testGoodSolution_known fit: "+fit); // assertTrue(expected_reward_for_good_solution<=fit); } @Test public void testGoodSolution18() { int[] good_solution_phenotype={0, 1, 1, 3, 2, 5, 4, 0, 2, 1, 3, 4, 6, 5, 0, 1, 1, 1, 1, 2, 2}; GlasSequence mySequence = new GlasSequence(); for(int e=0;e<sample_stimuli.length;e++){ mySequence.addEvent(new GlasEvent(sample_stimuli[e],expected_actions[e],rewards[e])); } Individual indi =new Individual(nNodes, nStimuli, nActions); indi.setChromossome(good_solution_phenotype); double fit=indi.getFitness(mySequence); System.out.println("testGoodSolution18 fit: "+fit); // assertTrue(expected_reward_for_good_solution<=fit); } @Test public void testBadSolution28() { int[] bad_solution_phenotype={0, 1, 2, 3, 4, 5, 2, 0, 1, 4, 5, 2, 6, 3, 0, 1, 1, 2, 1, 2, 0}; GlasSequence mySequence = new GlasSequence(); for(int e=0;e<sample_stimuli.length;e++){ mySequence.addEvent(new GlasEvent(sample_stimuli[e],expected_actions[e],rewards[e])); } Individual indi =new Individual(nNodes, nStimuli, nActions); indi.setChromossome(bad_solution_phenotype); double fit=indi.getFitness(mySequence); System.out.println("testBadSolution28 fit: "+fit); assertTrue(expected_reward_for_good_solution>fit); } @Test public void testBadSolution0() { int[] bad_solution_phenotype={0, 1, 2, 2, 4, 5, 6, 0, 1, 3, 4, 5, 2, 6, 0, 1, 1, 1, 2, 1, 2}; GlasSequence mySequence = new GlasSequence(); for(int e=0;e<sample_stimuli.length;e++){ mySequence.addEvent(new GlasEvent(sample_stimuli[e],expected_actions[e],rewards[e])); } Individual indi =new Individual(nNodes, nStimuli, nActions); indi.setChromossome(bad_solution_phenotype); double fit=indi.getFitness(mySequence); System.out.println("testBadSolution0 fit: "+fit); assertTrue(expected_reward_for_good_solution>fit); } @Test public void testBadSolution24() { int[] bad_solution_phenotype={0, 1, 1, 3, 3, 5, 3, 0, 1, 3, 2, 4, 6, 5, 0, 1, 1, 0, 1, 2, 2}; GlasSequence mySequence = new GlasSequence(); for(int e=0;e<sample_stimuli.length;e++){ mySequence.addEvent(new GlasEvent(sample_stimuli[e],expected_actions[e],rewards[e])); } Individual indi =new Individual(nNodes, nStimuli, nActions); indi.setChromossome(bad_solution_phenotype); double fit=indi.getFitness(mySequence); System.out.println("testBadSolution24 fit: "+fit); assertTrue(expected_reward_for_good_solution>fit); } @Test public void testExp1N7S3(){ int[] bad_solution_phenotype={0, 1, 1, 2, 3, 5, 4, 0, 1, 2, 3, 4, 6, 5, 0, 1, 1, 1, 1, 2, 2}; GlasSequence mySequence = new GlasSequence(); for(int e=0;e<sample_stimuli.length;e++){ mySequence.addEvent(new GlasEvent(sample_stimuli[e],expected_actions[e],rewards[e])); } Individual indi =new Individual(nNodes, nStimuli, nActions); indi.setChromossome(bad_solution_phenotype); double fit=indi.getFitness(mySequence); System.out.println("testGoodSolution Exp1N7S3 fit: "+fit); // assertTrue(expected_reward_for_good_solution<=fit); } @Test public void testExp1N7S2(){ int[] bad_solution_phenotype={0, 1, 2, 2, 3, 4, 2, 0, 1, 6, 4, 2, 5, 3, 0, 1, 2, 1, 1, 2, 1}; GlasSequence mySequence = new GlasSequence(); for(int e=0;e<sample_stimuli.length;e++){ mySequence.addEvent(new GlasEvent(sample_stimuli[e],expected_actions[e],rewards[e])); } Individual indi =new Individual(nNodes, nStimuli, nActions); indi.setChromossome(bad_solution_phenotype); double fit=indi.getFitness(mySequence); System.out.println("testBadSolution Exp1N7S2 fit: "+fit); assertTrue(expected_reward_for_good_solution>fit); } @Test public void testSimilar(){ int[] s0={0, 1, 2, 3, 1, 5, 6, 0, 1, 3, 5, 2, 4, 6, 0, 1, 1, 2, 1, 1, 2}; int[] s3={0, 1, 1, 2, 3, 4, 5, 0, 2, 1, 4, 3, 6, 5, 0, 1, 1, 1, 1, 2, 2}; GlasSequence mySequence = new GlasSequence(); for(int e=0;e<sample_stimuli.length;e++){ mySequence.addEvent(new GlasEvent(sample_stimuli[e],expected_actions[e],rewards[e])); } Individual indi0 =new Individual(nNodes, nStimuli, nActions); indi0.setChromossome(s0); double fit0=indi0.getFitness(mySequence); System.out.println("s0 fit: "+fit0); Individual indi3 =new Individual(nNodes, nStimuli, nActions); indi3.setChromossome(s3); double fit3=indi3.getFitness(mySequence); System.out.println("s3 fit: "+fit3); assertTrue(fit0==fit3); } @Test public void testN8(){ int[] s0={0,1,1,3,4,1,6,2, 0,6,1,3,5,2,4,6, 0,1,1,1,2,1,1,2}; int[] s2={0,1,2,1,1,4,3,6, 0,1,3,2,1,4,5,6, 0,1,1,1,2,1,2,2}; GlasSequence mySequence = new GlasSequence(); for(int e=0;e<sample_stimuli.length;e++){ mySequence.addEvent(new GlasEvent(sample_stimuli[e],expected_actions[e],rewards[e])); } Individual indi0 =new Individual(nNodes, nStimuli, nActions); indi0.setChromossome(s0); double fit0=indi0.getFitness(mySequence); System.out.println("s0 fit: "+fit0); Individual indi2 =new Individual(nNodes, nStimuli, nActions); indi2.setChromossome(s2); double fit2=indi2.getFitness(mySequence); System.out.println("s2 fit: "+fit2); assertTrue(fit0<fit2); } // @Test // public void fitWithPrune(){ // // int[] sample_stimuli_2 = {1, 4, 3, 5, 2, 3, 4, 6, 1, 4, 3, 5, 2, 3, 4, 6, 2, 4, 3, 5, 1, 5, 4, 6, 2, 3, 3, 6}; // int[] expected_actions_2 = {1, 1, 1, 2, 1, 1, 1, 2, 2, 1, 1, 1, 1, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2}; //Some wrong choices // double[] rewards_2 = {1, 1, 1,10, 1, 1, 1,10, -1, 1, 1,-10, 1, -1, 1,10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-10}; // // Sequence mySequence = new Sequence(); // for(int e=0;e<sample_stimuli.length;e++){ // mySequence.addEvent(new Event(sample_stimuli[e],expected_actions[e],rewards[e])); // } // // int[] xp2_n7_s2= {0,1,1,2,4,3,6, 0,2,1,4,6,3,5, 0,1,1,1,2,1,2}; // // int[] xp2_n8_s5= {0,1,2,3,1,3,5,7, 0,2,4,3,1,6,3,5, 0,1,1,1,1,2,1,2}; // // int[] xp2_n9_s8= {0,1,1,2,4,4,3,4,7, 0,2,1,4,4,3,3,6,5, 0,1,1,1,2,1,1,2,2};//fit=51.821429 // int[] xp2_n9_s17={0,1,2,3,1,5,6,3,6, 0,2,4,3,1,3,5,6,2, 0,1,1,1,1,1,2,2,0};//fit=51.821429 // // // Individual indi_xp2_n7_s2 =new Individual(7, nStimuli, nActions); // indi_xp2_n7_s2.setChromossome(xp2_n7_s2); // double fit_xp2_n7_s2=indi_xp2_n7_s2.getFitness(mySequence); // System.out.println("xp2_n7_s2 fit: "+fit_xp2_n7_s2); // // Individual indi_xp2_n8_s5 =new Individual(8, nStimuli, nActions); // indi_xp2_n8_s5.setChromossome(xp2_n8_s5); // double fit_xp2_n8_s5=indi_xp2_n8_s5.getFitness(mySequence); // System.out.println("xp2_n8_s5 fit: "+fit_xp2_n8_s5); // // Individual indi_xp2_n9_s8 =new Individual(9, nStimuli, nActions); // indi_xp2_n9_s8.setChromossome(xp2_n9_s8); // double fit_xp2_n9_s8=indi_xp2_n9_s8.getFitness(mySequence); // System.out.println("xp2_n9_s8 fit: "+fit_xp2_n9_s8); // // Individual indi_xp2_n9_s17 =new Individual(9, nStimuli, nActions); // indi_xp2_n9_s17.setChromossome(xp2_n9_s17); // double fit_xp2_n9_s17=indi_xp2_n9_s17.getFitness(mySequence); // System.out.println("xp2_n9_s17 fit: "+fit_xp2_n9_s17); //// //// //// //// // --- Pruning --- ////// ////// Individual pruned_indi_xp2_n8_s5 =new Individual(nNodes, nStimuli, nActions); ////// indi_xp2_n8_s5.setChromossome(xp2_n8_s5); ////// double fit_xp2_n8_s5=indi_xp2_n8_s5.getFitness(mySequence); ////// System.out.println("xp2_n8_s5 fit: "+fit_xp2_n8_s5); ////// //// //// //// int[] temp_individual = xp2_n8_s5; //// //// nNodes=temp_individual.length/3; //// //// StateMachine my_sm = new StateMachine(temp_individual); //// my_sm.reset(); //// int[] selected_actions = my_sm.runStimuli(sample_stimuli); //// int[] nodes_history = my_sm.getNodes_history();//TODO is there a way to prevent node 4 from being visited here? //// int[] nodes_types = my_sm.getNodes_types(); //// //// //// //// Set<Integer> nodes_to_be_pruned = new HashSet<Integer>(); //// for(int i = 1;i<=nNodes;i++){ //// nodes_to_be_pruned.add(i); //// } //// nodes_to_be_pruned.remove(1); //Node 1 is the root //// for(Integer node:nodes_history){ //// nodes_to_be_pruned.remove(node); //// } //// //// //// Pruner my_pruner = new Pruner(temp_individual); //// int[] pruned_individual_int = my_pruner.pruneNodes(nodes_to_be_pruned); //// //// //// Individual pruned_individual =new Individual(8, nStimuli, nActions); //// pruned_individual.setChromossome(pruned_individual_int); //// double pruned_individual_fit=pruned_individual.getFitness(mySequence); //// System.out.println("pruned_ fit: "+pruned_individual_fit); //// //// // } // }
10,649
29.255682
146
java
cst
cst-master/src/test/java/br/unicamp/cst/behavior/glas/TestLearner_Convergence.java
/******************************************************************************* * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation ******************************************************************************/ package br.unicamp.cst.behavior.glas; import br.unicamp.cst.learning.glas.GlasLearner; import org.junit.jupiter.api.Test; public class TestLearner_Convergence { static int nNodes = 7; //static int nNodes = 7; static int nReRuns=10; static int nActions = 3; static int nStimuli = 7; static int[] sample_stimuli = {1, 4, 3, 5, 2, 3, 4, 6, 1, 4, 3, 5, 2, 3, 4, 6, 2, 4, 3, 5, 1, 5, 4, 6, 2, 3, 3, 6}; static int[] expected_actions = {1, 1, 1, 2, 1, 1, 1, 2, 2, 1, 1, 1, 1, 0, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2}; //Some wrong choices static double[] rewards = {1, 1, 1,10, 1, 1, 1,10, -1, 1, 1,-10, 1, -1, 1,10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-10}; static int[] known_final_solution={1, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 1, 1, 1, 2, 2}; @Test public void test() { System.out.println("Testing convergence... "); boolean show_gui = false; GlasSequence mySequence = new GlasSequence(); for(int e=0;e<sample_stimuli.length;e++){ mySequence.addEvent(new GlasEvent(sample_stimuli[e],expected_actions[e],rewards[e])); } GlasLearner myLearner = new GlasLearner(nNodes, nStimuli, nActions); myLearner.setShow_gui(show_gui); myLearner.setnReRuns(nReRuns); // int max_number_reRuns=500; //int max_number_reRuns=500; // int nParticles = 1000; //int nParticles = 1000; // // myLearner.setMax_number_reRuns(max_number_reRuns); // myLearner.setnParticles(nParticles); myLearner.learnSequence(mySequence); int[] best_found_int = myLearner.getBest_found_solution(); double best_found_fit = myLearner.getBest_found_fit(); double[] best_found_double=new double[best_found_int.length]; for(int i=0;i<best_found_double.length;i++){ best_found_double[i]=((double)best_found_int[i]); } System.out.println("Best solution found (fit= "+best_found_fit+" ): "); System.out.print("["); for(int i=0;i<best_found_double.length;i++){ System.out.print((int)best_found_double[i]+" "); } System.out.println("]"); // GLASplot glasPlot_merged_solution = new GLASplot(best_found_double); // glasPlot_merged_solution.setPlotTitle("best_found"); // glasPlot_merged_solution.plot(); // System.out.println(myLearner.getBest_found_fit()); // assertTrue(myLearner.getBest_found_fit()>=50.1428); //// 50.1428 if(show_gui){ while(true){ try { Thread.currentThread(); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
3,064
31.606383
146
java
cst
cst-master/src/test/java/br/unicamp/cst/consciousness/HighActivationCodelet.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.consciousness; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; /** * @author andre * */ public class HighActivationCodelet extends Codelet{ public HighActivationCodelet(String name) { setName(name); } @Override public void accessMemoryObjects() { // TODO Auto-generated method stub } @Override public void calculateActivation() { try{ setActivation(0.95d); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } } @Override public void proc() { // TODO Auto-generated method stub } }
1,237
24.265306
97
java
cst
cst-master/src/test/java/br/unicamp/cst/consciousness/LowActivationCodelet.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.consciousness; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; /** * @author andre * */ public class LowActivationCodelet extends Codelet{ public LowActivationCodelet(String name) { setName(name); } @Override public void accessMemoryObjects() { // TODO Auto-generated method stub } @Override public void calculateActivation() { try{ setActivation(0.1d); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } } @Override public void proc() { // TODO Auto-generated method stub } }
1,232
24.6875
97
java
cst
cst-master/src/test/java/br/unicamp/cst/consciousness/MediumActivationCodelet.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.consciousness; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; /** * @author andre * */ public class MediumActivationCodelet extends Codelet{ public MediumActivationCodelet(String name) { setName(name); } @Override public void accessMemoryObjects() { // TODO Auto-generated method stub } @Override public void calculateActivation() { try{ setActivation(0.5d); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } } @Override public void proc() { // TODO Auto-generated method stub } }
1,240
24.326531
97
java
cst
cst-master/src/test/java/br/unicamp/cst/consciousness/SpotlightBroadcastControllerTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.consciousness; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import org.junit.jupiter.api.AfterAll; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; /** * @author andre * */ public class SpotlightBroadcastControllerTest { @BeforeAll public static void beforeAllTestMethods() { } @AfterAll public static void afterAllTestMethods() { } @Test public void testSpotlightBroadcastController() throws InterruptedException { Mind mind = new Mind(); HighActivationCodelet highActivationCodelet = new HighActivationCodelet("HighActivationCodelet"); MemoryObject memoryHighActivation = mind.createMemoryObject(highActivationCodelet.getName()); highActivationCodelet.addOutput(memoryHighActivation); mind.insertCodelet(highActivationCodelet); MediumActivationCodelet mediumActivationCodelet = new MediumActivationCodelet("MediumActivationCodelet"); MemoryObject memoryMediumActivation = mind.createMemoryObject(mediumActivationCodelet.getName()); mediumActivationCodelet.addOutput(memoryMediumActivation); mind.insertCodelet(mediumActivationCodelet); LowActivationCodelet lowActivationCodelet = new LowActivationCodelet("LowActivationCodelet"); MemoryObject memoryLowActivation = mind.createMemoryObject(lowActivationCodelet.getName()); lowActivationCodelet.addOutput(memoryLowActivation); mind.insertCodelet(lowActivationCodelet); SpotlightBroadcastController spotlightBroadcastController = new SpotlightBroadcastController(mind.getCodeRack()); mind.insertCodelet(spotlightBroadcastController); mind.start(); String messageExpected = "Winner message"; memoryHighActivation.setI(messageExpected); Thread.sleep(2000); Memory actualLowActivationMemory = lowActivationCodelet.getBroadcast(highActivationCodelet.getName()); String actualLowActivationMessage = (String) actualLowActivationMemory.getI(); assertEquals(messageExpected, actualLowActivationMessage); Memory actualMediumActivationMemory = mediumActivationCodelet.getBroadcast(highActivationCodelet.getName()); String actualMediumActivationMessage = (String) actualMediumActivationMemory.getI(); assertEquals(messageExpected,actualMediumActivationMessage); Thread.sleep(1000); mind.shutDown(); } }
3,226
35.670455
118
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/CoalitionTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.entities; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * @author wander * */ public class CoalitionTest { Codelet testCodelet = new Codelet() { @Override public void accessMemoryObjects() {} @Override public void proc() { System.out.println("proc method ran correctly!"); } @Override public void calculateActivation() {} }; Codelet otherCodelet = new Codelet() { @Override public void accessMemoryObjects() {} @Override public void proc() { System.out.println("proc method ran correctly!"); } @Override public void calculateActivation() {} }; @Test public void calculateActivationTest(){ Coalition coalition = new Coalition(Arrays.asList(testCodelet, otherCodelet)); try { coalition.getCodeletsList().get(0).setActivation(1.0); } catch (CodeletActivationBoundsException e) { e.printStackTrace(); } assertEquals(0.5, coalition.calculateActivation(), 0); } @Test public void setCodeletListTest(){ Coalition coalition = new Coalition(Arrays.asList(testCodelet)); List<Codelet> listTest = Arrays.asList(testCodelet, otherCodelet); coalition.setCodeletsList(listTest); assertEquals(listTest, coalition.getCodeletsList()); } @Test public void activationTest(){ Coalition coalition = new Coalition(Arrays.asList(testCodelet)); Double activationTest = 0.8; coalition.setActivation(activationTest); assertEquals(0.8, coalition.getActivation(), 0); } @Test public void toStringTest(){ List<Codelet> listTest = Arrays.asList(testCodelet, otherCodelet); Coalition coalition = new Coalition(Arrays.asList(testCodelet, otherCodelet)); coalition.setActivation(0.8); String expectMessage = "Coalition [activation=" + 0.8 + ", " + ("codeletsList=" + listTest) + "]"; assertTrue(expectMessage.contains(coalition.toString())); } }
2,960
29.525773
106
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/CodeRackTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.entities; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * @author wander * */ public class CodeRackTest { Codelet testCodelet = new Codelet() { @Override public void accessMemoryObjects() {} @Override public void proc() { System.out.println("proc method ran correctly!"); } @Override public void calculateActivation() {} }; Codelet otherCodelet = new Codelet() { @Override public void accessMemoryObjects() {} @Override public void proc() { System.out.println("proc method ran correctly!"); } @Override public void calculateActivation() {} }; @Test public void setAllCodeletTest(){ CodeRack codeRack = new CodeRack(); List<Codelet> testList = Arrays.asList(testCodelet, otherCodelet); codeRack.setAllCodelets(testList); assertEquals(testList, codeRack.getAllCodelets()); } @Test public void insertCodeletTest(){ CodeRack codeRack = new CodeRack(); List<Codelet> testList = Arrays.asList(testCodelet); codeRack.insertCodelet(testCodelet); assertEquals(testList, codeRack.getAllCodelets()); } @Test public void createCodeletTest(){ CodeRack codeRack = new CodeRack(); List<Memory> memInputTest = Arrays.asList(new MemoryObject(), new MemoryObject()); List<Memory> memOutputTest = Arrays.asList(new MemoryObject()); codeRack.createCodelet(0.5, null, memInputTest, memOutputTest, testCodelet); assertEquals(testCodelet, codeRack.getAllCodelets().get(0)); } @Test public void destroyCodeletTest(){ CodeRack codeRack = new CodeRack(); List<Memory> memInputTest = Arrays.asList(new MemoryObject(), new MemoryObject()); List<Memory> memOutputTest = Arrays.asList(new MemoryObject()); codeRack.createCodelet(0.5, null, memInputTest, memOutputTest, testCodelet); codeRack.destroyCodelet(testCodelet); assertEquals(0, codeRack.getAllCodelets().size()); } @Test public void startStopTest(){ CodeRack codeRack = new CodeRack(); List<Codelet> testList = Arrays.asList(testCodelet, otherCodelet); codeRack.setAllCodelets(testList); codeRack.start(); assertTrue(codeRack.getAllCodelets().get(0).isLoop()); codeRack.stop(); assertFalse(codeRack.getAllCodelets().get(0).isLoop()); } }
3,358
29.536364
97
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/CodeletContainerTest.java
package br.unicamp.cst.core.entities; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class CodeletContainerTest { class CodeletToTestOne extends Codelet { private int counter = 0; public int getCounter() { return counter; } public CodeletToTestOne(String name) { setName(name); } @Override public void accessMemoryObjects() { } @Override public void calculateActivation() { activation = counter; } @Override public void proc() { counter++; if (this.outputs != null && !this.outputs.isEmpty()) { this.outputs.get(0).setI("CODELET 1 OUTPUT"); } } } class CodeletToTestTwo extends Codelet { private int counter = 0; public int getCounter() { return counter; } public CodeletToTestTwo(String name) { setName(name); } @Override public void accessMemoryObjects() { } @Override public void calculateActivation() { } @Override public void proc() { counter = counter + 2; } } class CodeletToTestThree extends Codelet { private int counter = 0; public int getCounter() { return counter; } public CodeletToTestThree(String name) { setName(name); } @Override public void accessMemoryObjects() { } @Override public void calculateActivation() { } @Override public void proc() { counter = counter + 3; if (this.outputs != null && !this.outputs.isEmpty()) { this.outputs.get(0).setI("CODELET 3 OUTPUT"); } } } private void sleep(int timestep) { try { Thread.sleep(timestep); } catch(InterruptedException e) { e.printStackTrace(); } } @Test public void noMemoryChangeTest() { // no codelet runs Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memory1 = mind.createMemoryObject("MEMORY1", 0.12); MemoryObject memory2 = mind.createMemoryObject("MEMORY2", 0.32); MemoryObject memory3 = mind.createMemoryObject("MEMORY3", 0.32); MemoryObject memory4 = mind.createMemoryObject("MEMORY4", 0.32); codeletOne.addInput(memory1); codeletOne.addBroadcast(memory2); codeletTwo.addBroadcast(memory3); codeletThree.addInput(memory4); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); mind.insertCodelet(codeletOne); mind.insertCodelet(codeletTwo); mind.insertCodelet(codeletThree); mind.start(); sleep(2000); mind.shutDown(); assertEquals(0, codeletContainer.getOutputs().size()); assertEquals(new ArrayList<Memory>(), codeletContainer.getOutputs()); assertEquals(new ArrayList<Memory>(), codeletContainer.getOutputs()); assertEquals(new ArrayList<Memory>(), codeletContainer.getOutputs()); assertEquals(0, codeletContainer.getEvaluation(), 0); } @Test public void noMemoryChangeButCodeletAddedIsStartedTest() { // no codelet runs Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memory1 = mind.createMemoryObject("MEMORY1", 0.12); MemoryObject memory2 = mind.createMemoryObject("MEMORY2", 0.32); MemoryObject memory3 = mind.createMemoryObject("MEMORY3", 0.32); MemoryObject memory4 = mind.createMemoryObject("MEMORY4", 0.32); codeletOne.addInput(memory1); codeletOne.addBroadcast(memory2); codeletTwo.addBroadcast(memory3); codeletThree.addInput(memory4); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, true); mind.insertCodelet(codeletOne); mind.insertCodelet(codeletTwo); mind.insertCodelet(codeletThree); mind.start(); sleep(2000); mind.shutDown(); assertEquals(0, codeletContainer.getOutputs().size()); assertEquals(new ArrayList<Memory>(), codeletContainer.getOutputs()); assertEquals(new ArrayList<Memory>(), codeletContainer.getOutputs()); assertEquals(new ArrayList<Memory>(), codeletContainer.getOutputs()); assertEquals(0, codeletContainer.getEvaluation(), 0); } @Test public void runningCodeletChangingInputTest() { // changes the codelet container input Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memoryInput1 = mind.createMemoryObject("MEMORY_INPUT_1", 0.12); MemoryObject memoryInput2 = mind.createMemoryObject("MEMORY_INPUT_2", 0.32); MemoryObject memoryInput3 = mind.createMemoryObject("MEMORY_INPUT_3", 0.32); MemoryObject memoryInput4 = mind.createMemoryObject("MEMORY_INPUT_4", 0.32); MemoryObject memoryOutput1 = mind.createMemoryObject("MEMORY_OUTPUT_1", 0.22); MemoryObject memoryOutput2 = mind.createMemoryObject("MEMORY_OUTPUT_2", 0.22); MemoryObject memoryOutput3 = mind.createMemoryObject("MEMORY_OUTPUT_3", 0.22); codeletOne.addInput(memoryInput1); codeletOne.addBroadcast(memoryInput2); codeletOne.addOutput(memoryOutput1); codeletTwo.addBroadcast(memoryInput3); codeletTwo.addOutput(memoryOutput2); codeletThree.addInput(memoryInput4); codeletThree.addOutput(memoryOutput3); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); mind.insertCodelet(codeletOne); mind.insertCodelet(codeletTwo); mind.insertCodelet(codeletThree); codeletContainer.setI(10); mind.start(); sleep(2000); mind.shutDown(); for (Codelet codelet : codeletContainer.getAll()) { for (Memory mem : codelet.getInputs()) { assertEquals(10, mem.getI()); } } for (Codelet codelet : codeletContainer.getAll()) { for (Memory mem : codelet.getBroadcast()) { assertEquals(0.32, mem.getI()); } } assertEquals(3, codeletContainer.getOutputs().size()); List<Memory> expectedOutputs = new ArrayList<Memory>(); expectedOutputs.add(memoryOutput1); expectedOutputs.add(memoryOutput2); expectedOutputs.add(memoryOutput3); assertArrayEquals(expectedOutputs.toArray(), codeletContainer.getOutputs().toArray()); assertEquals(0.22, codeletContainer.getOutputs().get(1).getI()); assertEquals("MEMORY_OUTPUT_3", codeletContainer.getOutputs().get(2).getName()); assertEquals(0, codeletContainer.getEvaluation(), 0); } @Test public void runningCodeletChangingInputCodeletStartedWhenAddedTest() { // changes the codelet container input Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memoryInput1 = mind.createMemoryObject("MEMORY_INPUT_1", 0.12); MemoryObject memoryInput2 = mind.createMemoryObject("MEMORY_INPUT_2", 0.32); MemoryObject memoryInput3 = mind.createMemoryObject("MEMORY_INPUT_3", 0.32); MemoryObject memoryInput4 = mind.createMemoryObject("MEMORY_INPUT_4", 0.32); MemoryObject memoryOutput1 = mind.createMemoryObject("MEMORY_OUTPUT_1", 0.22); MemoryObject memoryOutput2 = mind.createMemoryObject("MEMORY_OUTPUT_2", 0.22); MemoryObject memoryOutput3 = mind.createMemoryObject("MEMORY_OUTPUT_3", 0.22); codeletOne.addInput(memoryInput1); codeletOne.addBroadcast(memoryInput2); codeletOne.addOutput(memoryOutput1); codeletTwo.addBroadcast(memoryInput3); codeletTwo.addOutput(memoryOutput2); codeletThree.addInput(memoryInput4); codeletThree.addOutput(memoryOutput3); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, true); codeletContainer.setI(10); sleep(2000); for (Codelet codelet : codeletContainer.getAll()) { for (Memory mem : codelet.getInputs()) { assertEquals(10, mem.getI()); } } for (Codelet codelet : codeletContainer.getAll()) { for (Memory mem : codelet.getBroadcast()) { assertEquals(0.32, mem.getI()); } } CodeletToTestOne codeletToTestOne = (CodeletToTestOne) codeletContainer.getCodelet("Codelet 1"); assertEquals(7, codeletToTestOne.getCounter()); assertEquals(3, codeletContainer.getOutputs().size()); List<Memory> expectedOutputs = new ArrayList<Memory>(); expectedOutputs.add(memoryOutput1); expectedOutputs.add(memoryOutput2); expectedOutputs.add(memoryOutput3); assertArrayEquals(expectedOutputs.toArray(), codeletContainer.getOutputs().toArray()); assertEquals(0.22, codeletContainer.getOutputs().get(1).getI()); assertEquals("MEMORY_OUTPUT_3", codeletContainer.getOutputs().get(2).getName()); assertEquals(0, codeletContainer.getEvaluation(), 0); } @Test public void addCodeletsToCodeletContainerTest() { // changes the codelet container input Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memoryInput1 = mind.createMemoryObject("MEMORY_INPUT_1", 0.12); MemoryObject memoryInput2 = mind.createMemoryObject("MEMORY_INPUT_2", 0.32); MemoryObject memoryInput3 = mind.createMemoryObject("MEMORY_INPUT_3", 0.32); MemoryObject memoryInput4 = mind.createMemoryObject("MEMORY_INPUT_4", 0.32); MemoryObject memoryOutput1 = mind.createMemoryObject("MEMORY_OUTPUT_1", 0.22); MemoryObject memoryOutput2 = mind.createMemoryObject("MEMORY_OUTPUT_2", 0.22); MemoryObject memoryOutput3 = mind.createMemoryObject("MEMORY_OUTPUT_3", 0.22); codeletOne.addInput(memoryInput1); codeletOne.addBroadcast(memoryInput2); codeletOne.addOutput(memoryOutput1); codeletTwo.addBroadcast(memoryInput3); codeletTwo.addOutput(memoryOutput2); codeletThree.addInput(memoryInput4); codeletThree.addOutput(memoryOutput3); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(); codeletContainer.addCodelet(codeletOne, false); codeletContainer.addCodelet(codeletTwo, false); codeletContainer.addCodelet(codeletThree, false); assertEquals(3, codeletContainer.getOutputs().size()); List<Memory> expectedOutputs = new ArrayList<Memory>(); expectedOutputs.add(memoryOutput1); expectedOutputs.add(memoryOutput2); expectedOutputs.add(memoryOutput3); assertArrayEquals(expectedOutputs.toArray(), codeletContainer.getOutputs().toArray()); assertEquals("MEMORY_OUTPUT_1", codeletContainer.getOutputs().get(0).getName()); assertEquals("MEMORY_OUTPUT_2", codeletContainer.getOutputs().get(1).getName()); assertEquals("MEMORY_OUTPUT_3", codeletContainer.getOutputs().get(2).getName()); assertEquals(3, codeletContainer.getCodelet(codeletOne.getName()).outputs.size()); assertEquals(3, codeletContainer.getCodelet(codeletTwo.getName()).outputs.size()); assertEquals(3, codeletContainer.getCodelet(codeletThree.getName()).outputs.size()); assertEquals(2, codeletContainer.getInputs().size()); List<Memory> expectedInputs = new ArrayList<Memory>(); expectedInputs.add(memoryInput1); expectedInputs.add(memoryInput4); assertArrayEquals(expectedInputs.toArray(), codeletContainer.getInputs().toArray()); assertEquals("MEMORY_INPUT_1", codeletContainer.getInputs().get(0).getName()); assertEquals("MEMORY_INPUT_4", codeletContainer.getInputs().get(1).getName()); assertEquals(2, codeletContainer.getCodelet(codeletOne.getName()).inputs.size()); assertEquals(2, codeletContainer.getCodelet(codeletThree.getName()).inputs.size()); assertEquals(2, codeletContainer.getBroadcast().size()); List<Memory> expectedBroadcast = new ArrayList<Memory>(); expectedBroadcast.add(memoryInput2); expectedBroadcast.add(memoryInput3); assertArrayEquals(expectedBroadcast.toArray(), codeletContainer.getBroadcast().toArray()); assertEquals("MEMORY_INPUT_2", codeletContainer.getBroadcast().get(0).getName()); assertEquals("MEMORY_INPUT_3", codeletContainer.getBroadcast().get(1).getName()); assertEquals(2, codeletContainer.getCodelet(codeletOne.getName()).broadcast.size()); assertEquals(2, codeletContainer.getCodelet(codeletTwo.getName()).broadcast.size()); } @Test public void addCodeletsToCodeletContainerWhichHasInputsAndOuputsTest() { // changes the codelet container input Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memoryInput1 = mind.createMemoryObject("MEMORY_INPUT_1", 0.12); MemoryObject memoryInput2 = mind.createMemoryObject("MEMORY_INPUT_2", 0.32); MemoryObject memoryInput3 = mind.createMemoryObject("MEMORY_INPUT_3", 0.32); MemoryObject memoryInput4 = mind.createMemoryObject("MEMORY_INPUT_4", 0.32); MemoryObject memoryOutput1 = mind.createMemoryObject("MEMORY_OUTPUT_1", 0.22); MemoryObject memoryOutput2 = mind.createMemoryObject("MEMORY_OUTPUT_2", 0.22); MemoryObject memoryOutput3 = mind.createMemoryObject("MEMORY_OUTPUT_3", 0.22); CodeletContainer codeletContainer = new CodeletContainer(); ArrayList<Memory> newInputs = new ArrayList<Memory>(); newInputs.add(memoryInput1); newInputs.add(memoryInput4); codeletContainer.setInputs(newInputs); ArrayList<Memory> newOutputs = new ArrayList<Memory>(); newOutputs.add(memoryOutput1); newOutputs.add(memoryOutput2); newOutputs.add(memoryOutput3); codeletContainer.setOutputs(newOutputs); codeletContainer.addCodelet(codeletOne, false); codeletContainer.addCodelet(codeletTwo, false); codeletContainer.addCodelet(codeletThree, false); assertEquals(3, codeletContainer.getOutputs().size()); List<Memory> expectedOutputs = new ArrayList<Memory>(); expectedOutputs.add(memoryOutput1); expectedOutputs.add(memoryOutput2); expectedOutputs.add(memoryOutput3); assertArrayEquals(expectedOutputs.toArray(), codeletContainer.getOutputs().toArray()); assertEquals("MEMORY_OUTPUT_1", codeletContainer.getOutputs().get(0).getName()); assertEquals("MEMORY_OUTPUT_2", codeletContainer.getOutputs().get(1).getName()); assertEquals("MEMORY_OUTPUT_3", codeletContainer.getOutputs().get(2).getName()); assertEquals(3, codeletContainer.getCodelet(codeletOne.getName()).outputs.size()); assertEquals(3, codeletContainer.getCodelet(codeletTwo.getName()).outputs.size()); assertEquals(3, codeletContainer.getCodelet(codeletThree.getName()).outputs.size()); assertEquals(2, codeletContainer.getInputs().size()); List<Memory> expectedInputs = new ArrayList<Memory>(); expectedInputs.add(memoryInput1); expectedInputs.add(memoryInput4); assertArrayEquals(expectedInputs.toArray(), codeletContainer.getInputs().toArray()); assertEquals("MEMORY_INPUT_1", codeletContainer.getInputs().get(0).getName()); assertEquals("MEMORY_INPUT_4", codeletContainer.getInputs().get(1).getName()); assertEquals(2, codeletContainer.getCodelet(codeletOne.getName()).inputs.size()); assertEquals(2, codeletContainer.getCodelet(codeletThree.getName()).inputs.size()); } @Test public void removeCodeletsFromCodeletContainerTest() { // changes the codelet container input Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memoryInput1 = mind.createMemoryObject("MEMORY_INPUT_1", 0.12); MemoryObject memoryInput2 = mind.createMemoryObject("MEMORY_INPUT_2", 0.32); MemoryObject memoryInput3 = mind.createMemoryObject("MEMORY_INPUT_3", 0.32); MemoryObject memoryInput4 = mind.createMemoryObject("MEMORY_INPUT_4", 0.32); MemoryObject memoryOutput1 = mind.createMemoryObject("MEMORY_OUTPUT_1", 0.22); MemoryObject memoryOutput2 = mind.createMemoryObject("MEMORY_OUTPUT_2", 0.22); MemoryObject memoryOutput3 = mind.createMemoryObject("MEMORY_OUTPUT_3", 0.22); codeletOne.addInput(memoryInput1); codeletOne.addBroadcast(memoryInput2); codeletOne.addOutput(memoryOutput1); codeletTwo.addBroadcast(memoryInput3); codeletTwo.addOutput(memoryOutput2); codeletThree.addInput(memoryInput4); codeletThree.addOutput(memoryOutput3); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); assertEquals(3, codeletContainer.getOutputs().size()); List<Memory> expectedOutputs = new ArrayList<Memory>(); expectedOutputs.add(memoryOutput1); expectedOutputs.add(memoryOutput2); expectedOutputs.add(memoryOutput3); assertArrayEquals(expectedOutputs.toArray(), codeletContainer.getOutputs().toArray()); assertEquals("MEMORY_OUTPUT_1", codeletContainer.getOutputs().get(0).getName()); assertEquals("MEMORY_OUTPUT_2", codeletContainer.getOutputs().get(1).getName()); assertEquals("MEMORY_OUTPUT_3", codeletContainer.getOutputs().get(2).getName()); assertEquals(3, codeletContainer.getCodelet(codeletOne.getName()).outputs.size()); assertEquals(3, codeletContainer.getCodelet(codeletTwo.getName()).outputs.size()); assertEquals(3, codeletContainer.getCodelet(codeletThree.getName()).outputs.size()); assertEquals(2, codeletContainer.getInputs().size()); List<Memory> expectedInputs = new ArrayList<Memory>(); expectedInputs.add(memoryInput1); expectedInputs.add(memoryInput4); assertArrayEquals(expectedInputs.toArray(), codeletContainer.getInputs().toArray()); assertEquals("MEMORY_INPUT_1", codeletContainer.getInputs().get(0).getName()); assertEquals("MEMORY_INPUT_4", codeletContainer.getInputs().get(1).getName()); assertEquals(2, codeletContainer.getCodelet(codeletOne.getName()).inputs.size()); assertEquals(2, codeletContainer.getCodelet(codeletThree.getName()).inputs.size()); assertEquals(2, codeletContainer.getBroadcast().size()); List<Memory> expectedBroadcast = new ArrayList<Memory>(); expectedBroadcast.add(memoryInput2); expectedBroadcast.add(memoryInput3); assertArrayEquals(expectedBroadcast.toArray(), codeletContainer.getBroadcast().toArray()); assertEquals("MEMORY_INPUT_2", codeletContainer.getBroadcast().get(0).getName()); assertEquals("MEMORY_INPUT_3", codeletContainer.getBroadcast().get(1).getName()); assertEquals(2, codeletContainer.getCodelet(codeletOne.getName()).broadcast.size()); assertEquals(2, codeletContainer.getCodelet(codeletTwo.getName()).broadcast.size()); codeletContainer.removeCodelet(codeletOne); assertEquals(2, codeletContainer.getOutputs().size()); expectedOutputs = new ArrayList<Memory>(); expectedOutputs.add(memoryOutput2); expectedOutputs.add(memoryOutput3); assertArrayEquals(expectedOutputs.toArray(), codeletContainer.getOutputs().toArray()); assertEquals(2, codeletContainer.getCodelet(codeletTwo.getName()).outputs.size()); assertEquals(2, codeletContainer.getCodelet(codeletThree.getName()).outputs.size()); assertEquals(1, codeletContainer.getInputs().size()); expectedInputs = new ArrayList<Memory>(); expectedInputs.add(memoryInput4); assertArrayEquals(expectedInputs.toArray(), codeletContainer.getInputs().toArray()); assertEquals("MEMORY_INPUT_4", codeletContainer.getInputs().get(0).getName()); assertEquals(1, codeletContainer.getCodelet(codeletThree.getName()).inputs.size()); assertEquals(1, codeletContainer.getBroadcast().size()); expectedBroadcast = new ArrayList<Memory>(); expectedBroadcast.add(memoryInput3); assertArrayEquals(expectedBroadcast.toArray(), codeletContainer.getBroadcast().toArray()); assertEquals("MEMORY_INPUT_3", codeletContainer.getBroadcast().get(0).getName()); assertEquals(1, codeletContainer.getCodelet(codeletTwo.getName()).broadcast.size()); codeletContainer.removeCodelet(codeletTwo); assertEquals(1, codeletContainer.getOutputs().size()); expectedOutputs = new ArrayList<Memory>(); expectedOutputs.add(memoryOutput3); assertArrayEquals(expectedOutputs.toArray(), codeletContainer.getOutputs().toArray()); assertEquals(1, codeletContainer.getCodelet(codeletThree.getName()).outputs.size()); assertEquals(1, codeletContainer.getInputs().size()); expectedInputs = new ArrayList<Memory>(); expectedInputs.add(memoryInput4); assertArrayEquals(expectedInputs.toArray(), codeletContainer.getInputs().toArray()); assertEquals("MEMORY_INPUT_4", codeletContainer.getInputs().get(0).getName()); assertEquals(1, codeletContainer.getCodelet(codeletThree.getName()).inputs.size()); assertEquals(0, codeletContainer.getBroadcast().size()); assertEquals(0, codeletContainer.getCodelet(codeletThree.getName()).broadcast.size()); } @Test public void getEvaluationTest() { Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memory1 = mind.createMemoryObject("MEMORY1", 0.12); MemoryObject memory2 = mind.createMemoryObject("MEMORY2", 0.32); MemoryObject memory3 = mind.createMemoryObject("MEMORY3", 0.32); MemoryObject memory4 = mind.createMemoryObject("MEMORY4", 0.32); codeletOne.addInput(memory1); codeletOne.addBroadcast(memory2); codeletTwo.addBroadcast(memory3); codeletThree.addInput(memory4); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); Double testValue = 100.0; mind.insertCodelet(codeletOne); mind.insertCodelet(codeletTwo); mind.insertCodelet(codeletThree); memory1.setEvaluation(testValue); codeletContainer.setI(10); mind.start(); sleep(2000); mind.shutDown(); assertEquals(testValue, codeletContainer.getEvaluation()); } @Test public void getActivationTest() { Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memory1 = mind.createMemoryObject("MEMORY1", 0.12); MemoryObject memory2 = mind.createMemoryObject("MEMORY2", 0.32); MemoryObject memory3 = mind.createMemoryObject("MEMORY3", 0.32); MemoryObject memory4 = mind.createMemoryObject("MEMORY4", 0.32); codeletOne.addInput(memory1); codeletOne.addBroadcast(memory2); codeletTwo.addBroadcast(memory3); codeletThree.addInput(memory4); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); double testValue = 6.0; mind.insertCodelet(codeletOne); mind.insertCodelet(codeletTwo); mind.insertCodelet(codeletThree); memory1.setEvaluation(testValue); codeletContainer.setI(10); mind.start(); sleep(2000); mind.shutDown(); assertEquals(testValue, codeletContainer.getActivation(), 0); } @Test public void setInputsTest() { Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memory1 = mind.createMemoryObject("MEMORY1", 0.12); MemoryObject memory2 = mind.createMemoryObject("MEMORY2", 0.32); MemoryObject memory3 = mind.createMemoryObject("MEMORY3", 0.32); MemoryObject memory4 = mind.createMemoryObject("MEMORY4", 0.32); codeletOne.addInput(memory1); codeletOne.addBroadcast(memory2); codeletTwo.addBroadcast(memory3); codeletThree.addInput(memory4); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); mind.insertCodelet(codeletOne); mind.insertCodelet(codeletTwo); mind.insertCodelet(codeletThree); ArrayList<Memory> newInputs = new ArrayList<Memory>(); newInputs.add(memory1); codeletContainer.setInputs(newInputs); assertEquals(newInputs, codeletContainer.getInputs()); } @Test public void setOutputsTest() { Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memory1 = mind.createMemoryObject("MEMORY1", 0.12); MemoryObject memory2 = mind.createMemoryObject("MEMORY2", 0.32); MemoryObject memory3 = mind.createMemoryObject("MEMORY3", 0.32); MemoryObject memory4 = mind.createMemoryObject("MEMORY4", 0.32); codeletOne.addInput(memory1); codeletOne.addBroadcast(memory2); codeletTwo.addBroadcast(memory3); codeletThree.addInput(memory4); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); mind.insertCodelet(codeletOne); mind.insertCodelet(codeletTwo); mind.insertCodelet(codeletThree); ArrayList<Memory> newOutputs = new ArrayList<Memory>(); newOutputs.add(memory1); codeletContainer.setOutputs(newOutputs); assertEquals(newOutputs, codeletContainer.getOutputs()); } @Test public void setBroadcastTest() { Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memory1 = mind.createMemoryObject("MEMORY1", 0.12); MemoryObject memory2 = mind.createMemoryObject("MEMORY2", 0.32); MemoryObject memory3 = mind.createMemoryObject("MEMORY3", 0.32); MemoryObject memory4 = mind.createMemoryObject("MEMORY4", 0.32); codeletOne.addInput(memory1); codeletOne.addBroadcast(memory2); codeletTwo.addBroadcast(memory3); codeletThree.addInput(memory4); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); mind.insertCodelet(codeletOne); mind.insertCodelet(codeletTwo); mind.insertCodelet(codeletThree); ArrayList<Memory> newBroadcast = new ArrayList<Memory>(); newBroadcast.add(memory1); codeletContainer.setBroadcast(newBroadcast); assertEquals(newBroadcast, codeletContainer.getBroadcast()); } @Test public void setNameTest() { CodeletContainer codeletContainer = new CodeletContainer(); codeletContainer.setName("Container"); assertEquals("Container", codeletContainer.getName()); } @Test public void setTypeTest() { CodeletContainer codeletContainer = new CodeletContainer(); codeletContainer.setType("Container"); assertEquals("Container", codeletContainer.getName()); } @Test public void setEvaluationTest() { Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Mind mind = new Mind(); MemoryObject memory1 = mind.createMemoryObject("MEMORY1", 0.12); codeletOne.addInput(memory1); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); codeletContainer.setEvaluation(5.0);; assertEquals(5.0, codeletContainer.getCodelet("Codelet 1").getInputs().get(0).getEvaluation(),0); } @Test public void addMemoryObserverTest() { Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memory1 = mind.createMemoryObject("MEMORY1", 0.12); MemoryObject memory2 = mind.createMemoryObject("MEMORY2", 0.32); MemoryObject memory3 = mind.createMemoryObject("MEMORY3", 0.32); MemoryObject memory4 = mind.createMemoryObject("MEMORY4", 0.32); codeletOne.setIsMemoryObserver(true); codeletOne.addInput(memory1); codeletOne.addBroadcast(memory2); codeletTwo.addBroadcast(memory3); codeletThree.addInput(memory4); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); codeletContainer.addMemoryObserver(codeletOne); mind.insertCodelet(codeletOne); mind.insertCodelet(codeletTwo); mind.insertCodelet(codeletThree); codeletContainer.setI(10); mind.start(); sleep(2000); mind.shutDown(); CodeletToTestOne codeletToTestOne = (CodeletToTestOne) codeletContainer.getCodelet("Codelet 1"); assertEquals(6, codeletToTestOne.getCounter()); } @Test public void getTimestampTest() { Codelet codeletOne = new CodeletToTestOne("Codelet 1"); Codelet codeletTwo = new CodeletToTestTwo("Codelet 2"); Codelet codeletThree = new CodeletToTestThree("Codelet 3"); Mind mind = new Mind(); MemoryObject memory1 = mind.createMemoryObject("MEMORY1", 0.12); MemoryObject memory2 = mind.createMemoryObject("MEMORY2", 0.32); MemoryObject memory3 = mind.createMemoryObject("MEMORY3", 0.32); MemoryObject memory4 = mind.createMemoryObject("MEMORY4", 0.32); codeletOne.addInput(memory1); codeletOne.addBroadcast(memory2); codeletTwo.addBroadcast(memory3); codeletThree.addInput(memory4); ArrayList<Codelet> codeletContainerArray = new ArrayList<Codelet>(); codeletContainerArray.add(codeletOne); codeletContainerArray.add(codeletTwo); codeletContainerArray.add(codeletThree); CodeletContainer codeletContainer = new CodeletContainer(codeletContainerArray, false); mind.insertCodelet(codeletOne); mind.insertCodelet(codeletTwo); mind.insertCodelet(codeletThree); codeletContainer.setI(10); mind.start(); sleep(2000); mind.shutDown(); assertEquals(true, codeletContainer.getTimestamp().doubleValue() > 1); } }
32,082
35.334088
99
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/CodeletTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.entities; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; import br.unicamp.cst.core.exceptions.CodeletThresholdBoundsException; import java.util.Arrays; import java.util.List; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * @author wander * */ public class CodeletTest { // This class contains tests covering some core Codelet methods // This method is used to generate a new Codelet private Codelet generateCodelet() { Codelet testCodelet = new Codelet() { @Override public void accessMemoryObjects() {} @Override public void proc() { //ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); //System.setOut(new PrintStream(outputStreamCaptor)); System.out.println("running the proc() method!"); } @Override public void calculateActivation() {} }; return(testCodelet); } @Test public void testExceptionOnRun() { Codelet testCodelet = generateCodelet(); System.out.println("testando"); } @Test public void getIsLoopTest(){ Codelet testCodelet = generateCodelet(); // Any instantiated Codelet, if not changed, should be looping assertTrue(testCodelet.isLoop()); } @Test public void upperActivationBoundException(){ Codelet testCodelet = generateCodelet(); Exception exception = assertThrows(CodeletActivationBoundsException.class, () -> { testCodelet.setActivation(2.0); }); String expectedMessage = "Codelet activation set to value > 1.0"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); assertEquals(1.0, testCodelet.getActivation(), 0); } @Test public void lowerActivationBoundException(){ Codelet testCodelet = generateCodelet(); Exception exception = assertThrows(CodeletActivationBoundsException.class, () -> { testCodelet.setActivation(-0.8); }); String expectedMessage = "Codelet activation set to value < 0.0"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); assertEquals(0.0, testCodelet.getActivation(), 0); } @Test public void setInputsTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyInputs = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.setInputs(dummyInputs); assertEquals(2, testCodelet.getInputs().size()); } @Test public void getInputTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyInputs = Arrays.asList(new MemoryObject(), new MemoryObject()); dummyInputs.get(0).setName("testName1"); testCodelet.setInputs(dummyInputs); assertEquals(dummyInputs.get(0), testCodelet.getInput("testName1")); } @Test public void getInputNullTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyInputs = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.setInputs(dummyInputs); assertNull(testCodelet.getInput("testName2")); } @Test public void addInputsTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyInputs = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.addInputs(dummyInputs); assertEquals(2, testCodelet.getInputs().size()); } @Test public void removesInputTest(){ Codelet testCodelet = generateCodelet(); Memory toRemove = new MemoryObject(); testCodelet.addInput(toRemove); assertEquals(1, testCodelet.getInputs().size()); testCodelet.removesInput(toRemove); assertEquals(0, testCodelet.getInputs().size()); } @Test public void removeFromInputTest(){ Codelet testCodelet = generateCodelet(); List<Memory> toRemove = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.addInputs(toRemove); assertEquals(2, testCodelet.getInputs().size()); testCodelet.removeFromInput(toRemove); assertEquals(0, testCodelet.getInputs().size()); } @Test public void removeFromOutputTest(){ Codelet testCodelet = generateCodelet(); List<Memory> toRemove = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.addOutputs(toRemove); assertEquals(2, testCodelet.getOutputs().size()); testCodelet.removeFromOutput(toRemove); assertEquals(0, testCodelet.getOutputs().size()); } @Test public void addOutputsTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyOutputs = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.addOutputs(dummyOutputs); assertEquals(2, testCodelet.getOutputs().size()); } @Test public void getOutputsTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyOutputs = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.addOutputs(dummyOutputs); assertEquals(dummyOutputs, testCodelet.getOutputs()); } @Test public void getOutputTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyOutputs = Arrays.asList(new MemoryObject(), new MemoryObject()); dummyOutputs.get(0).setName("testName3"); testCodelet.addOutputs(dummyOutputs); assertEquals(dummyOutputs.get(0), testCodelet.getOutput("testName3")); } @Test public void getOutputNullReturnTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyOutputs = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.addOutputs(dummyOutputs); assertNull(testCodelet.getOutput("testName4")); } @Test public void getOutputEnableFalseTest(){ boolean exceptionThrown = false; Codelet testCodelet = null; try { testCodelet = generateCodelet(); testCodelet.setName("thisCodeletWillFail"); List<Memory> dummyOutputs = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.setOutputs(dummyOutputs); testCodelet.getOutput("testType", 3); // This line will raise an exception Mind mind = new Mind(); mind.insertCodelet(testCodelet); mind.start(); // Thread.sleep(1000); // } catch (Exception e) { // e.printStackTrace(); // } mind.shutDown(); } catch (Exception e) { // why this exception is not being thrown ? System.out.println("Passei aqui"); exceptionThrown = true; } //assertTrue(exceptionThrown); If I uncomment this line, the test fails ... for some reason the exception is not being caught assertFalse(testCodelet.getEnabled()); testCodelet.setEnabled(true); assertTrue(testCodelet.getEnabled()); } @Test public void setOutputsTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyOutputs = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.setOutputs(dummyOutputs); assertEquals(2, testCodelet.getOutputs().size()); } @Test public void getInputsOfTypeTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyInputs = Arrays.asList(new MemoryObject(), new MemoryObject(), new MemoryObject(), new MemoryObject()); dummyInputs.get(0).setName("toGet"); dummyInputs.get(1).setName("toGet"); testCodelet.addInputs(dummyInputs); assertEquals(2, testCodelet.getInputsOfType("toGet").size()); } @Test public void getOutputsOfTypeTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyOutputs = Arrays.asList(new MemoryObject(), new MemoryObject(), new MemoryObject(), new MemoryObject()); dummyOutputs.get(0).setName("toGet"); dummyOutputs.get(1).setName("toGet"); testCodelet.addOutputs(dummyOutputs); assertEquals(2, testCodelet.getOutputsOfType("toGet").size()); } @Test public void getBroadcastNullTest(){ Codelet testCodelet = generateCodelet(); assertNull(testCodelet.getBroadcast("testName5")); } @Test public void getBroadcastTypeTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyOutputs = Arrays.asList(new MemoryObject(), new MemoryObject()); dummyOutputs.get(0).setName("testName6"); testCodelet.addBroadcasts(dummyOutputs); assertEquals(dummyOutputs.get(0), testCodelet.getBroadcast("testName6", 0)); } @Test public void getBroadcastTypeIndexTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyOutputs = Arrays.asList(new MemoryObject(), new MemoryObject()); dummyOutputs.get(0).setName("testName"); dummyOutputs.get(1).setName("testName"); testCodelet.addBroadcasts(dummyOutputs); assertEquals(dummyOutputs.get(1), testCodelet.getBroadcast("testName", 1)); } @Test public void addBroadcastsTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyOutputs = Arrays.asList(new MemoryObject(), new MemoryObject()); testCodelet.addBroadcasts(dummyOutputs); assertEquals(2, testCodelet.getBroadcast().size()); } @Test public void getThreadNameTest(){ Codelet testCodelet = generateCodelet(); Thread.currentThread().setName("newThreadName"); assertEquals("newThreadName", testCodelet.getThreadName()); } @Test public void toStringTest(){ Codelet testCodelet = generateCodelet(); List<Memory> dummyInputs = Arrays.asList(new MemoryObject(), new MemoryObject()); List<Memory> dummyBroadcasts = Arrays.asList(new MemoryObject(), new MemoryObject()); String expectedString = "Codelet [activation=" + 0.5 + ", " + "name=" + "testName" + ", " + ("broadcast=" + dummyBroadcasts.subList(0, Math.min(dummyBroadcasts.size(), 10)) + ", ") + ("inputs=" + dummyInputs.subList(0, Math.min(dummyInputs.size(), 10)) + ", ") + ("outputs=" + "[]") + "]"; testCodelet.setName("testName"); try{testCodelet.setActivation(0.5);} catch (Exception e){ e.printStackTrace(); } testCodelet.setInputs(dummyInputs); testCodelet.setBroadcast(dummyBroadcasts); assertEquals(expectedString, testCodelet.toString()); } @Test public void setThresholdTest(){ Codelet testCodelet = generateCodelet(); try { testCodelet.setThreshold(0.5); } catch (CodeletThresholdBoundsException e) { e.printStackTrace(); } assertEquals(0.5, testCodelet.getThreshold(), 0); } @Test public void upperThresholdBoundTest(){ Codelet testCodelet = generateCodelet(); Exception exception = assertThrows(CodeletThresholdBoundsException.class, () -> { testCodelet.setThreshold(2.0); }); String expectedMessage = "Codelet threshold set to value > 1.0"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); assertEquals(1.0, testCodelet.getThreshold(), 0); } @Test public void lowerThresholdBoundTest(){ Codelet testCodelet = generateCodelet(); Exception exception = assertThrows(CodeletThresholdBoundsException.class, () -> { testCodelet.setThreshold(-1.0); }); String expectedMessage = "Codelet threshold set to value < 0.0"; String actualMessage = exception.getMessage(); assertTrue(actualMessage.contains(expectedMessage)); assertEquals(0.0, testCodelet.getThreshold(), 0); } @Test public void getTimeStepTest(){ Codelet testCodelet = generateCodelet(); testCodelet.setTimeStep(222); assertEquals(222, testCodelet.getTimeStep()); } @Test public void runProfilingTest(){ Codelet testCodelet = generateCodelet(); testCodelet.setProfiling(true); ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); System.setOut(new PrintStream(outputStreamCaptor)); Mind mind = new Mind(); mind.insertCodelet(testCodelet); mind.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } assertTrue(testCodelet.isProfiling()); } }
13,892
34.623077
135
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/DisconnectedCodeletTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.entities; import org.junit.jupiter.api.Test; /** * @author andre * */ public class DisconnectedCodeletTest { String message = ""; @Test public void testDisconnectedCodelet() { Codelet disconnectedCodelet = new Codelet() { @Override public void accessMemoryObjects() { } @Override public void proc() { } @Override public void calculateActivation() { } }; disconnectedCodelet.setName("Disconnected Codelet"); try { System.out.println("Starting the codelet ..."); disconnectedCodelet.start(); disconnectedCodelet.getInput("TYPE", 0); disconnectedCodelet.stop(); }catch(Exception e) { message = e.getMessage(); System.out.println("Testing DisconnectedCodelet:"+e.getMessage()); //assertEquals(e.getMessage(), "This Codelet could not find a memory object it needs: Disconnected Codelet"); } //assertEquals(message, "This Codelet could not find a memory object it needs: Disconnected Codelet"); disconnectedCodelet.stop(); System.out.println("Codelet stopped !"); } }
1,915
29.412698
118
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/MemoryBufferTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.entities; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * @author wander * */ public class MemoryBufferTest { @Test public void basicCallTest(){ RawMemory rawMemory = new RawMemory(); MemoryBuffer memoryBuffer = new MemoryBuffer(3, rawMemory); List<MemoryObject> testList = Arrays.asList(new MemoryObject(), new MemoryObject(), new MemoryObject()); testList.get(0).setType("memory_0"); testList.get(1).setType("memory_1"); testList.get(2).setType("memory_2"); memoryBuffer.putList(testList); assertEquals(3, memoryBuffer.size()); assertEquals(memoryBuffer.get(), memoryBuffer.getAll()); assertEquals(testList.get(2), memoryBuffer.getMostRecent()); assertEquals(testList.get(0), memoryBuffer.getOldest()); } @Test public void putsMoreThanMaxTest(){ RawMemory rawMemory = new RawMemory(); MemoryBuffer memoryBuffer = new MemoryBuffer(3, rawMemory); List<MemoryObject> testList = Arrays.asList(new MemoryObject(), new MemoryObject(), new MemoryObject(), new MemoryObject()); testList.get(0).setType("memory_0"); testList.get(1).setType("memory_1"); testList.get(2).setType("memory_2"); testList.get(3).setType("memory_3"); memoryBuffer.putList(testList); assertEquals(3, memoryBuffer.size()); assertEquals(memoryBuffer.get(), memoryBuffer.getAll()); assertEquals(testList.get(1), memoryBuffer.get().get(0)); memoryBuffer.put(new MemoryObject()); assertEquals(testList.get(2), memoryBuffer.get().get(0)); } @Test public void putPopTest(){ RawMemory rawMemory = new RawMemory(); MemoryBuffer memoryBuffer = new MemoryBuffer(3, rawMemory); MemoryObject testMemory = new MemoryObject(); testMemory.setType("memory_0"); memoryBuffer.put(testMemory); assertEquals(testMemory, memoryBuffer.pop()); assertEquals(0, memoryBuffer.size()); } @Test public void nullOldestAndNewestTest(){ RawMemory rawMemory = new RawMemory(); MemoryBuffer memoryBuffer = new MemoryBuffer(3, rawMemory); assertNull(memoryBuffer.getOldest()); assertNull(memoryBuffer.getMostRecent()); } @Test public void removeAndClearTest(){ RawMemory rawMemory = new RawMemory(); MemoryBuffer memoryBuffer = new MemoryBuffer(3, rawMemory); List<MemoryObject> testList = Arrays.asList(new MemoryObject(), new MemoryObject(), new MemoryObject()); testList.get(0).setType("memory_0"); testList.get(1).setType("memory_1"); testList.get(2).setType("memory_2"); memoryBuffer.putList(testList); memoryBuffer.remove(testList.get(1)); assertEquals(2, memoryBuffer.size()); assertEquals(testList.get(2), memoryBuffer.get().get(1)); memoryBuffer.clear(); assertEquals(0, memoryBuffer.size()); } @Test public void pintStatusTest(){ RawMemory rawMemory = new RawMemory(); MemoryBuffer memoryBuffer = new MemoryBuffer(3, rawMemory); List<MemoryObject> testList = Arrays.asList(new MemoryObject()); testList.get(0).setType("memory_0"); memoryBuffer.putList(testList); String expectedMessage = "###### Memory Buffer ########\n# Content: [MemoryObject [idmemoryobject=null, timestamp=null, evaluation=0.0, I=null, name=memory_0]]" + "\n# Size: 1\n###############################"; ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); System.setOut(new PrintStream(outputStreamCaptor)); memoryBuffer.printStatus(); assertTrue(outputStreamCaptor.toString().trim().contains(expectedMessage)); } }
4,733
35.137405
170
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/MemoryContainerTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.entities; import br.unicamp.cst.core.entities.MemoryContainer.Policy; import java.util.function.BinaryOperator; import java.util.function.Predicate; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * @author andre * */ public class MemoryContainerTest { @Test public void testMemoryContainerContent() { Memory memoryContainer = new MemoryContainer("TYPE"); ((MemoryContainer) memoryContainer).setI(71L, 0.1D, "TYPE"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE"); assertEquals(75L, memoryContainer.getI()); } @Test public void testMemoryContainerSize() { Memory memoryContainer = new MemoryContainer("TYPE"); ((MemoryContainer) memoryContainer).setI(71L, 0.1D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE3"); assertEquals(2, ((MemoryContainer) memoryContainer).getAllMemories().size()); } @Test public void setTypeTest(){ MemoryContainer memoryContainer = new MemoryContainer(); memoryContainer.setType("TYPE"); assertEquals("TYPE", memoryContainer.getName()); memoryContainer = new MemoryContainer(); memoryContainer.setName("TYPE2"); assertEquals("TYPE2", memoryContainer.getName()); memoryContainer = new MemoryContainer("TYPE3"); assertEquals("TYPE3", memoryContainer.getName()); } @Test public void getTypeTest(){ MemoryContainer memoryContainer = new MemoryContainer("TYPE-Container"); memoryContainer.setI("value",1.0,"TYPE"); assertEquals(memoryContainer.getI("TYPE"),"value"); System.out.println("-- This test will raise a warning ..."); assertNull(memoryContainer.getI("TYPE2")); } @Test public void getITest() { Memory memoryContainer = new MemoryContainer("TYPE"); ((MemoryContainer) memoryContainer).setI(71L, 0.1D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(70L, 0.3D, "TYPE3"); assertEquals(70L, ((MemoryContainer) memoryContainer).getI()); assertEquals(75L, ((MemoryContainer) memoryContainer).getI(0)); System.out.println("-- This test will raise a warning ..."); assertNull(((MemoryContainer) memoryContainer).getI(2)); // This test will raise a warning for index greater than the number of stored memories assertEquals(70L, ((MemoryContainer) memoryContainer).getI("TYPE3")); } @Test public void getIPredicateTest() { Memory memoryContainer = new MemoryContainer("TYPE"); ((MemoryContainer) memoryContainer).setI(71L, 0.1D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(70L, 0.3D, "TYPE3"); ((MemoryContainer) memoryContainer).setI(70L, 0.25D); Predicate<Memory> pred = new Predicate<Memory>() { @Override public boolean test(Memory memory) { return memory.getName().equals("TYPE2"); } }; assertEquals(75L, ((MemoryContainer) memoryContainer).getI(pred)); } @Test public void getIAccumulatorTest() { Memory memoryContainer = new MemoryContainer("TYPE"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(70L, 0.3D, "TYPE3"); ((MemoryContainer) memoryContainer).setI(80L); BinaryOperator<Memory> binaryOperator = (mem1,mem2) -> mem1.getEvaluation() <= mem2.getEvaluation() ? mem1 : mem2; assertEquals(80L, ((MemoryContainer) memoryContainer).getI(binaryOperator)); } @Test public void setISpecificTest() { Memory memoryContainer = new MemoryContainer("TYPE"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(70L, 0.3D, "TYPE3"); ((MemoryContainer) memoryContainer).setI(80L); ((MemoryContainer) memoryContainer).setI(60L, 1); ((MemoryContainer) memoryContainer).setI(90L, 0.5D, 2); assertEquals(60L, ((MemoryContainer) memoryContainer).getI(1)); assertEquals(90L, ((MemoryContainer) memoryContainer).getI()); assertEquals(0.5D, ((MemoryContainer) memoryContainer).getEvaluation(), 0); } @Test public void setEvaluationTest() { Memory memoryContainer = new MemoryContainer("TYPE"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(70L, 0.3D, "TYPE3"); ((MemoryContainer) memoryContainer).setI(90L, 0.5D, 2); assertEquals(70L, ((MemoryContainer) memoryContainer).getI()); ((MemoryContainer) memoryContainer).setEvaluation(0.5D, 0); assertEquals(75L, ((MemoryContainer) memoryContainer).getI()); } @Test public void setEvaluationLastTest() { Memory memoryContainer = new MemoryContainer("TYPE"); System.out.println("-- This test will raise a warning ..."); memoryContainer.setEvaluation(2.0); assertEquals(memoryContainer.getEvaluation(),null); memoryContainer.setI("message"); memoryContainer.setEvaluation(2.0); assertEquals(memoryContainer.getEvaluation(),2.0); } @Test public void getTimestampNotValidTest() { Memory memoryContainer = new MemoryContainer("TYPE"); System.out.println("-- This test will raise a warning ..."); Long ts = memoryContainer.getTimestamp(); assertEquals(ts,null); memoryContainer.setI("message"); ts = memoryContainer.getTimestamp(); assertTrue(ts != null); } @Test public void addTest() { Memory memoryContainer = new MemoryContainer("TYPE"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(70L, 0.3D, "TYPE3"); ((MemoryContainer) memoryContainer).add(new MemoryObject()); assertEquals(3, ((MemoryContainer) memoryContainer).getAllMemories().size()); } @Test public void getInternalTest() { Memory memoryContainer = new MemoryContainer("TYPE"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(70L, 0.3D, "TYPE3"); assertEquals(75L, ((MemoryContainer) memoryContainer).getInternalMemory("TYPE2").getI()); assertNull(((MemoryContainer) memoryContainer).getInternalMemory("TYPE4")); } @Test public void getTimestampTest() { Memory memoryContainer = new MemoryContainer("TYPE"); ((MemoryContainer) memoryContainer).setI(75L, 0.2D, "TYPE2"); ((MemoryContainer) memoryContainer).setI(70L, 0.3D, "TYPE3"); assertEquals(((MemoryContainer) memoryContainer).getInternalMemory("TYPE3").getTimestamp(), ((MemoryContainer) memoryContainer).getTimestamp()); } @Test public void testMaxPolicy() { MemoryContainer memoryContainer = new MemoryContainer("MAX"); memoryContainer.setPolicy(Policy.MAX); int m1 = memoryContainer.setI(1, 0.2D); int m2 = memoryContainer.setI(2, 0.4D); int m3 = memoryContainer.setI(3, 0.8D); int i = (int) memoryContainer.getI(); assertEquals(i,3); memoryContainer.setEvaluation(0.1); i = (int) memoryContainer.getI(); assertEquals(i,2); memoryContainer.setEvaluation(0.1); i = (int) memoryContainer.getI(); assertEquals(i,1); memoryContainer.setEvaluation(0.1D,m1); memoryContainer.setEvaluation(0.1D,m2); memoryContainer.setEvaluation(0.1D,m3); for (int j=0;j<20;j++) { int m = (int) memoryContainer.getI(); boolean ver = (m == 1 || m == 2 || m == 3); assertEquals(ver,true); //System.out.println("max: "+m); } memoryContainer.setEvaluation(0.05D,m1); for (int j=0;j<20;j++) { int m = (int) memoryContainer.getI(); boolean ver = (m == 2 || m == 3); assertEquals(ver,true); //System.out.println("max2: "+m); } } @Test public void testMaxUniquePolicy() { MemoryContainer memoryContainer = new MemoryContainer("MAX"); memoryContainer.setPolicy(Policy.MAX); memoryContainer.setI(1); Integer i = (Integer) memoryContainer.getI(); assertEquals(i,1); } @Test public void testMinPolicy() { MemoryContainer memoryContainer = new MemoryContainer("MIN"); memoryContainer.setPolicy(Policy.MIN); int m1 = memoryContainer.setI(1, 0.2D); int m2 = memoryContainer.setI(2, 0.4D); int m3 = memoryContainer.setI(3, 0.8D); int i = (int) memoryContainer.getI(); assertEquals(i,1); memoryContainer.setEvaluation(0.9); i = (int) memoryContainer.getI(); assertEquals(i,2); memoryContainer.setEvaluation(0.9); i = (int) memoryContainer.getI(); assertEquals(i,3); memoryContainer.setEvaluation(0.1D,m1); memoryContainer.setEvaluation(0.1D,m2); memoryContainer.setEvaluation(0.1D,m3); for (int j=0;j<20;j++) { int m = (int) memoryContainer.getI(); boolean ver = (m == 1 || m == 2 || m == 3); assertEquals(ver,true); //System.out.println("min: "+m); } memoryContainer.setEvaluation(0.2D,m1); for (int j=0;j<20;j++) { int m = (int) memoryContainer.getI(); boolean ver = (m == 2 || m == 3); assertEquals(ver,true); //System.out.println("min2: "+m); } } @Test public void testRandomProportionalPolicy() { MemoryContainer memoryContainer = new MemoryContainer("RANDOMPROPORTIONAL"); memoryContainer.setPolicy(Policy.RANDOM_PROPORTIONAL); memoryContainer.setI(1, 0.2D); // 14% memoryContainer.setI(2, 0.4D); // 28% memoryContainer.setI(3, 0.8D); // 57% int count[] = new int[3]; for (int i=0;i<1000;i++) { int j = (int) memoryContainer.getI(); count[j-1]++; } //System.out.println("[0]: "+count[0]+" [1]: "+count[1]+" [2]: "+count[2]); assertEquals(count[0]<count[1],true); assertEquals(count[1]<count[2],true); memoryContainer.setEvaluation(0.8D,0); memoryContainer.setEvaluation(0.4D,1); memoryContainer.setEvaluation(0.2D,2); count = new int[3]; for (int i=0;i<1000;i++) { int j = (int) memoryContainer.getI(); count[j-1]++; } //System.out.println("[0]: "+count[0]+" [1]: "+count[1]+" [2]: "+count[2]); assertEquals(count[0]>count[1],true); assertEquals(count[1]>count[2],true); memoryContainer.setI(1,0.5,0); memoryContainer.setI(2,0.0,1); memoryContainer.setI(3,0.0,2); for (int i=0;i<5;i++) { int j = (int) memoryContainer.getI(); assertEquals(j,1); } memoryContainer.setI(1,0.0,0); memoryContainer.setI(2,0.5,1); memoryContainer.setI(3,0.0,2); for (int i=0;i<5;i++) { int j = (int) memoryContainer.getI(); assertEquals(j,2); } memoryContainer.setI(1,0.0,0); memoryContainer.setI(2,0.0,1); memoryContainer.setI(3,0.5,2); for (int i=0;i<5;i++) { int j = (int) memoryContainer.getI(); assertEquals(j,3); } memoryContainer.setI(1,0.0,0); memoryContainer.setI(2,0.0,1); memoryContainer.setI(3,0.0,2); count = new int[3]; for (int i=0;i<30;i++) { int j = (int) memoryContainer.getI(); count[j-1]++; } //System.out.println("[0]: "+count[0]+" [1]: "+count[1]+" [2]: "+count[2]); assertEquals(count[0]>0,true); assertEquals(count[1]>0,true); assertEquals(count[2]>0,true); } @Test public void testRandomFlat() { MemoryContainer memoryContainer = new MemoryContainer("RANDOMFLAT"); memoryContainer.setPolicy(Policy.RANDOM_FLAT); memoryContainer.setI(1, 0.2D); // 14% memoryContainer.setI(2, 0.4D); // 28% memoryContainer.setI(3, 0.8D); // 57% int count[] = new int[3]; for (int i=0;i<1000;i++) { int j = (int) memoryContainer.getI(); count[j-1]++; } assertEquals(count[0]>0,true); assertEquals(count[1]>0,true); assertEquals(count[2]>0,true); } @Test public void testIteratePolicy() { MemoryContainer memoryContainer = new MemoryContainer("ITERATE"); memoryContainer.setPolicy(Policy.ITERATE); System.out.println("-- This test will raise a warning ..."); Integer k = (Integer) memoryContainer.getI(); assertNull(k); memoryContainer.setI(1); memoryContainer.setI(2); memoryContainer.setI(3); for (int i=0;i<9;i++) { int j = (int) memoryContainer.getI(); assertEquals(j,i%3+1); } } @Test public void testGetEvaluation() { MemoryContainer memoryContainer = new MemoryContainer("TEST"); assertEquals(memoryContainer.get(-1),null); assertEquals(memoryContainer.get(0),null); assertEquals(memoryContainer.get(10),null); assertEquals(memoryContainer.getName(),"TEST"); memoryContainer.setName("TEST-NEW"); assertEquals(memoryContainer.getName(),"TEST-NEW"); memoryContainer.setType("TEST-NEW"); assertEquals(memoryContainer.getName(),"TEST-NEW"); // Testing the getEvaluation without any included MemoryObject assertEquals(memoryContainer.getEvaluation(),null); assertEquals(memoryContainer.getEvaluation(0),null); assertEquals(memoryContainer.getEvaluation(1),null); assertEquals(memoryContainer.getPolicy(),Policy.MAX); Double res = memoryContainer.getEvaluation(); assertEquals(res,null); memoryContainer.setI(1); memoryContainer.setEvaluation(0.5); assertEquals(memoryContainer.getEvaluation(),0.5); assertEquals(memoryContainer.getEvaluation(0),0.5); memoryContainer.setPolicy(Policy.ITERATE); assertEquals(memoryContainer.getPolicy(),Policy.ITERATE); int i = (int) memoryContainer.getI(); assertEquals(i,1); i = (int) memoryContainer.getLastI(); assertEquals(i,1); MemoryObject mo = (MemoryObject) memoryContainer.getLast(); i = (int) mo.getI(); assertEquals(i,1); memoryContainer.setEvaluation(0.6,0); assertEquals(memoryContainer.getEvaluation(),0.6); assertEquals(memoryContainer.getEvaluation(0),0.6); } @Test public void testGetTimestamp() { MemoryContainer memoryContainer = new MemoryContainer("TEST"); // Without any initialization, the timestamp must be null assertEquals(memoryContainer.getTimestamp(),null); System.out.println("This test will raise a warning..."); assertEquals(memoryContainer.getTimestamp(0),null); System.out.println("This test will raise a warning..."); assertEquals(memoryContainer.getTimestamp(1),null); // after we initialize the container, the timestamp must be something different from null memoryContainer.setI(1); assertEquals(memoryContainer.getTimestamp()!=null,true); assertEquals(memoryContainer.getTimestamp(0)!=null,true); // nevertheless, if we go further, it should remain null System.out.println("This test will raise a warning..."); assertEquals(memoryContainer.getTimestamp(1),null); assertEquals(memoryContainer.get(0).getI(),memoryContainer.getI()); } @Test public void testDoubleIndirection() { MemoryContainer mc1 = new MemoryContainer("TEST1"); MemoryContainer mc2 = new MemoryContainer("TEST2"); mc2.setI(0); mc1.add(mc2); assertEquals(mc1.getI(),0); mc1.setI(1,0.5,0); assertEquals(mc1.getI(),1); mc1.setEvaluation(0.6,0); assertEquals(mc1.getEvaluation(),0.6); } }
18,194
38.554348
145
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/MemoryObjectTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.entities; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * @author wander * */ public class MemoryObjectTest { @Test public void idTest(){ MemoryObject mo = new MemoryObject(); mo.setIdmemoryobject(2000L); assertEquals(2000L, (long)mo.getIdmemoryobject()); } @Test public void toStringTest(){ MemoryObject mo = new MemoryObject(); Object I = new Object(); mo.setIdmemoryobject(2000L); mo.setEvaluation(0.8); mo.setI(I); mo.setType("testName"); String expectedString = "MemoryObject [idmemoryobject=" + 2000L + ", timestamp=" + mo.getTimestamp() + ", evaluation=" + 0.8 + ", I=" + I + ", name=" + "testName" + "]"; assertEquals(expectedString, mo.toString()); } @Test public void hashCodeTest(){ MemoryObject mo = new MemoryObject(); Object I = new Object(); Double eval = 0.8; Long id = 2000L; String name = "testName"; mo.setIdmemoryobject(id); mo.setEvaluation(eval); mo.setI(I); mo.setType(name); final int prime = 31; int expectedValue = 1; expectedValue = prime * expectedValue + (I.hashCode()); expectedValue = prime * expectedValue + (eval.hashCode()); expectedValue = prime * expectedValue + (id.hashCode()); expectedValue = prime * expectedValue + (name.hashCode()); expectedValue = prime * expectedValue + ((mo.getTimestamp() == null) ? 0 : mo.getTimestamp().hashCode()); assertEquals(expectedValue, mo.hashCode()); } @Test public void equalsTest(){ MemoryObject mo = new MemoryObject(); MemoryObject otherMO = new MemoryObject(); MemoryObject thirdMO = new MemoryObject(); MemoryObject fourthMO = new MemoryObject(); mo.setI(0.0); otherMO.setI(0.0); thirdMO.setI(1.0); assertNotEquals(fourthMO, mo); assertNotEquals(mo, thirdMO); mo.setEvaluation(0.0); otherMO.setEvaluation(0.0); thirdMO.setEvaluation(1.0); fourthMO.setI(0.0); fourthMO.setEvaluation(null); assertNotEquals(fourthMO, mo); assertNotEquals(mo, thirdMO); mo.setIdmemoryobject(1000L); otherMO.setIdmemoryobject(2000L); thirdMO.setIdmemoryobject(2000L); fourthMO.setEvaluation(0.0); fourthMO.setIdmemoryobject(null); assertNotEquals(fourthMO, mo); assertNotEquals(mo, otherMO); otherMO.setIdmemoryobject(1000L); fourthMO.setIdmemoryobject(1000L); mo.setType("firstName"); otherMO.setType("firstName"); thirdMO.setType("secondName"); assertNotEquals(fourthMO, mo); assertNotEquals(mo, thirdMO); fourthMO.setType("firstName"); mo.setTimestamp(100L); otherMO.setTimestamp(100L); thirdMO.setTimestamp(200L); fourthMO.setTimestamp(null); assertNotEquals(fourthMO, mo); assertNotEquals(mo, thirdMO); fourthMO.setTimestamp(200L); assertNotEquals(fourthMO, mo); assertEquals(mo, otherMO); } @Test public void equalsFalseNullTest(){ MemoryObject mo = new MemoryObject(); MemoryObject otherMO = new MemoryObject(); MemoryObject thirdMO = new MemoryObject(); MemoryObject fourthMO = new MemoryObject(); Mind mind = new Mind(); /* * id * id * name * timestamp * timestamp * */ mo.setI(0.0); otherMO.setI(0.0); thirdMO.setI(1.0); assertFalse(fourthMO.equals(mo)); assertFalse(mo.equals(thirdMO)); mo.setEvaluation(0.0); otherMO.setEvaluation(0.0); thirdMO.setEvaluation(1.0); assertFalse(fourthMO.equals(mo)); assertFalse(mo.equals(thirdMO)); mo.setIdmemoryobject(1000L); otherMO.setIdmemoryobject(1000L); thirdMO.setIdmemoryobject(2000L); assertFalse(fourthMO.equals(mo)); assertFalse(mo.equals(thirdMO)); mo.setType("firstName"); otherMO.setType("firstName"); thirdMO.setType("secondName"); assertFalse(fourthMO.equals(mo)); assertFalse(mo.equals(thirdMO)); mo.setTimestamp(100L); otherMO.setTimestamp(100L); thirdMO.setTimestamp(200L); fourthMO.setTimestamp(null); assertFalse(fourthMO.equals(mo)); assertFalse(mo.equals(thirdMO)); assertTrue(mo.equals(otherMO)); } }
5,477
26.666667
126
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/MemoryTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.entities; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; /** * @author wander * */ public class MemoryTest { Memory testMemory = new Memory() { Object I = null; Double evaluation = 0.0; String name = ""; Long timestamp = 10L; @Override public Object getI() { return this.I; } @Override public int setI(Object info) { this.I = info; return 0; } @Override public Double getEvaluation() { return this.evaluation; } @Override public String getName() { return this.name; } @Override public void setName(String type) { this.name = type; } @Override public void setType(String type) { this.name = type; } @Override public void setEvaluation(Double eval) { this.evaluation = eval; } @Override public Long getTimestamp() { return this.timestamp; } @Override public void addMemoryObserver(MemoryObserver memoryObserver) { // TODO Auto-generated method stub } @Override public void removeMemoryObserver(MemoryObserver memoryObserver) { // TODO Auto-generated method stub } }; @Test public void getSetITest(){ assertNull(testMemory.getI()); Double testValue = 100.0; testMemory.setI(testValue); assertEquals(testValue, testMemory.getI()); List<Memory> testList= Arrays.asList(new MemoryObject(), new MemoryObject()); testMemory.setI(testList); assertEquals(testList, testMemory.getI()); } @Test public void getSetTypeTest(){ testMemory.setType("TYPE"); assertEquals("TYPE", testMemory.getName()); } @Test public void getSetEvalTest(){ Double testValue = 100.0; testMemory.setEvaluation(testValue); assertEquals(testValue, testMemory.getEvaluation()); } @Test public void getTimestampTest(){ assertEquals(10L, (long)testMemory.getTimestamp()); } }
2,997
23.57377
97
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/MindTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.entities; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; /** * @author wander * */ public class MindTest { Codelet testCodelet = new Codelet() { @Override public void accessMemoryObjects() {} @Override public void proc() { //ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); //System.setOut(new PrintStream(outputStreamCaptor)); System.out.println("proc method ran correctly!"); } @Override public void calculateActivation() {} }; @Test public void createCodeletGroupTest(){ Mind mind = new Mind(); mind.createCodeletGroup("testGroup"); assertTrue(mind.getCodeletGroups().containsKey("testGroup")); } @Test public void createMemoryGroupTest(){ Mind mind = new Mind(); mind.createMemoryGroup("testGroup"); assertTrue(mind.getMemoryGroups().containsKey("testGroup")); } @Test public void insertCodeletWGroupTest(){ Mind mind = new Mind(); mind.createCodeletGroup("testGroup"); mind.insertCodelet(testCodelet, "testGroup"); assertEquals(1,mind.getCodeRack().getAllCodelets().size()); assertTrue(mind.getCodeletGroups().containsKey("testGroup")); assertEquals(testCodelet, mind.getCodeletGroupList("testGroup").get(0)); } @Test public void registerMemoryWGroupTest(){ Mind mind = new Mind(); MemoryObject mo = new MemoryObject(); mind.createMemoryGroup("testGroup"); mind.registerMemory(mo, "testGroup"); assertTrue(mind.getMemoryGroups().containsKey("testGroup")); assertEquals(mo, mind.getMemoryGroups().get("testGroup").get(0)); assertEquals(1, mind.getMemoryGroupList("testGroup").size()); } @Test public void registerMemoryByNnameTest(){ Mind mind = new Mind(); MemoryObject mo = new MemoryObject(); mo.setType("testName"); mind.createMemoryGroup("testGroup"); mind.rawMemory.addMemory(mo); mind.registerMemory("testName", "testGroup"); assertTrue(mind.getMemoryGroups().containsKey("testGroup")); assertEquals(mo, mind.getMemoryGroups().get("testGroup").get(0)); assertEquals(1, mind.getMemoryGroups().get("testGroup").size()); } }
3,090
32.236559
97
java
cst
cst-master/src/test/java/br/unicamp/cst/core/entities/RawMemoryTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.entities; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class RawMemoryTest { @Test public void getAllOfTypeTest(){ RawMemory rawMemory = new RawMemory(); List<Memory> testList = Arrays.asList(new MemoryObject(), new MemoryObject(), new MemoryObject(), new MemoryObject()); testList.get(0).setType("TYPE"); testList.get(1).setType("TYPE"); rawMemory.setAllMemoryObjects(testList); assertEquals(2, rawMemory.getAllOfType("TYPE").size()); assertEquals(testList.subList(0,2), rawMemory.getAllOfType("TYPE")); } @Test public void printContentTest(){ RawMemory rawMemory = new RawMemory(); MemoryObject mem = new MemoryObject(); mem.setType("TYPE"); mem.setIdmemoryobject(100L); rawMemory.addMemory(mem); String expectedMessage = "MemoryObject [idmemoryobject=" + 100L + ", timestamp=" + mem.getTimestamp() + ", evaluation=" + 0.0 + ", I=" + null + ", name=" + "TYPE" + "]"; ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); System.setOut(new PrintStream(outputStreamCaptor)); rawMemory.printContent(); assertTrue(outputStreamCaptor.toString().trim().contains(expectedMessage)); } @Test public void createAndDestroyMemoryObjectTest(){ RawMemory rawMemory = new RawMemory(); rawMemory.createMemoryObject("TYPE"); assertEquals(1, rawMemory.size()); rawMemory.destroyMemoryObject(rawMemory.getAllMemoryObjects().get(0)); assertEquals(0, rawMemory.size()); } @Test public void shutdownTest(){ RawMemory rawMemory = new RawMemory(); List<Memory> testList = Arrays.asList(new MemoryObject(), new MemoryObject(), new MemoryObject(), new MemoryObject()); rawMemory.setAllMemoryObjects(testList); assertEquals(4, rawMemory.size()); rawMemory.shutDown(); assertEquals(0, rawMemory.size()); } }
2,858
35.189873
127
java
cst
cst-master/src/test/java/br/unicamp/cst/core/profiler/TestComplexMemoryObjectInfo.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation * **********************************************************************************************/ package br.unicamp.cst.core.profiler; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * * @author rgudwin */ public class TestComplexMemoryObjectInfo { public long testlong; public int testint; public float testfloat; public double testdouble; public byte testbyte; public short testshort; public boolean testboolean; public String testString="Test"; public Date testdate=new Date(); public int[] testintarray = new int[10]; public long[] testlongarray = new long[10]; public float[] testfloatarray = new float[10]; public double[] testdoublearray = new double[10]; public short[] testshortarray = new short[10]; public byte[] testbytearray = new byte[10]; public boolean[] testbooleanarray = new boolean[10]; public TestComplexMemoryObjectInfo complextest; public TestComplexMemoryObjectInfo[] complextestarray = new TestComplexMemoryObjectInfo[3]; public List<TestComplexMemoryObjectInfo> complextestlist = new ArrayList<>(); public List<Double> complextestlist2 = new ArrayList<>(); public TestComplexMemoryObjectInfo() { complextestlist2.add(3.14); complextestlist2.add(0.12); } public String toString() { return(testString); } public int equals(TestComplexMemoryObjectInfo other) { int ret = 0; if (testlong != other.testlong || testint != other.testint || testfloat != other.testfloat || testdouble != other.testdouble || testbyte != other.testbyte || testshort != other.testshort || testboolean != other.testboolean) ret = 1; if (!testString.equals(other.testString)) ret = 2; if (!testdate.equals(other.testdate)) ret = 3; if (testintarray.length != other.testintarray.length) ret = 4; else { for (int i=0;i<testintarray.length;i++) if (testintarray[i] != other.testintarray[i]) ret = 5; } if (testlongarray.length != other.testlongarray.length) ret = 6; else { for (int i=0;i<testlongarray.length;i++) if (testlongarray[i] != other.testlongarray[i]) ret = 7; } if (testfloatarray.length != other.testfloatarray.length) ret = 8; else { for (int i=0;i<testfloatarray.length;i++) if (testfloatarray[i] != other.testfloatarray[i]) ret = 9; } if (testdoublearray.length != other.testdoublearray.length) ret = 10; else { for (int i=0;i<testdoublearray.length;i++) if (testdoublearray[i] != other.testdoublearray[i]) ret = 11; } if (complextest == null && other.complextest != null) ret = 12; if (complextest != null && other.complextest == null) ret = 13; if (complextest != null && other.complextest != null) if (complextest.equals(other.complextest) != 0) ret = 14; if (complextestarray.length != other.complextestarray.length) ret = 15; else { for (int i=0;i<complextestarray.length;i++) { if (complextestarray[i] == null && other.complextestarray[i] != null) ret = 16; if (complextestarray[i] != null && other.complextestarray[i] == null) ret = 17; if (complextestarray[i] != null && other.complextestarray[i] != null) if (complextestarray[i].equals(other.complextestarray[i]) != 0) ret = 18; } } if (complextestlist == null && other.complextestlist != null) ret = 19; if (complextestlist != null && other.complextestlist == null) ret = 20; if (complextestlist != null && complextestlist != null) { if (complextestlist.size() != other.complextestlist.size()) ret = 21; for (int i=0;i<complextestlist.size();i++) { if (complextestlist.get(i).equals(other.complextestlist.get(i)) != 0) ret = 22; } } if (complextestlist2 == null && other.complextestlist2 != null) ret = 19; if (complextestlist2 != null && other.complextestlist2 == null) ret = 20; if (complextestlist2 != null && complextestlist2 != null) { if (complextestlist2.size() != other.complextestlist2.size()) ret = 21; for (int i=0;i<complextestlist2.size();i++) { if ((double)complextestlist2.get(i) != (double)other.complextestlist2.get(i)) ret = 22; } } return(ret); } }
5,280
43.008333
103
java
cst
cst-master/src/test/java/br/unicamp/cst/core/profiler/TestMemoryObserver.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.core.profiler; import java.util.ArrayList; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.MemoryContainer; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; import br.unicamp.cst.representation.idea.Idea; import java.util.logging.Level; import java.util.logging.Logger; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; class CodeletToTest extends Codelet { private int counter = 0; public int getCounter() { return counter; } public CodeletToTest(String name) { setName(name); } @Override public void accessMemoryObjects() { } @Override public void calculateActivation() { } @Override public void proc() { counter++; } } public class TestMemoryObserver { @Test public void noMemoryChangeTest() throws InterruptedException { // Codelet runs being a Memory Observer, in this case memory info does not // change, so codelet wont run Mind m = new Mind(); MemoryObject m1 = m.createMemoryObject("M1", 0.12); MemoryObject m2 = m.createMemoryObject("M2", 0.32); MemoryObject m3 = m.createMemoryObject("M3", 0.44); MemoryObject m4 = m.createMemoryObject("M4", 0.52); MemoryObject m5 = m.createMemoryObject("M5", 0.12); MemoryContainer m6 = m.createMemoryContainer("C1"); MemoryContainer m7 = m.createMemoryContainer("C2"); TestComplexMemoryObjectInfo mComplex = new TestComplexMemoryObjectInfo(); mComplex.complextest = new TestComplexMemoryObjectInfo(); for (int i = 0; i < 3; i++) mComplex.complextestarray[i] = new TestComplexMemoryObjectInfo(); MemoryObject mo = new MemoryObject(); mo.setType("TestObject"); mo.setI(mComplex); m7.setI(0.55, 0.23); m6.setI(0.33, 0.22); m6.setI(0.12, 0.13); m6.setI(m7); CodeletToTest c = new CodeletToTest("Codelet 1"); c.setIsMemoryObserver(true); c.addInput(m1); c.addInput(m2); c.addOutput(m3); c.addOutput(m4); c.addBroadcast(m5); c.addBroadcast(mo); mo.addMemoryObserver(c); m.insertCodelet(c); CodeletToTest c2 = new CodeletToTest("Codelet 2"); c2.setIsMemoryObserver(true); c2.addInput(m4); c2.addInput(m5); c2.addOutput(m6); c2.addOutput(m3); c2.addBroadcast(m5); mo.addMemoryObserver(c); m.insertCodelet(c2); m.start(); Thread.sleep(2000); m.shutDown(); assertEquals(0, c.getCounter()); assertEquals(0, c2.getCounter()); } @Test public void usualRunTest() throws InterruptedException { // Codelet runs being a Memory Observer, and memories inputs are changed Mind m = new Mind(); MemoryObject m1 = m.createMemoryObject("M1", 0.12); MemoryObject m2 = m.createMemoryObject("M2", 0.32); MemoryObject m3 = m.createMemoryObject("M3", 0.44); MemoryObject m4 = m.createMemoryObject("M4", 0.52); MemoryObject m5 = m.createMemoryObject("M5", 0.12); MemoryContainer m6 = m.createMemoryContainer("C1"); MemoryContainer m7 = m.createMemoryContainer("C2"); MemoryContainer m8 = m.createMemoryContainer("C3"); m7.add(m4); m8.add(m7); TestComplexMemoryObjectInfo mComplex = new TestComplexMemoryObjectInfo(); mComplex.complextest = new TestComplexMemoryObjectInfo(); for (int i = 0; i < 3; i++) mComplex.complextestarray[i] = new TestComplexMemoryObjectInfo(); MemoryObject mo = new MemoryObject(); mo.setType("TestObject"); mo.setI(mComplex); m7.setI(0.55, 0.23); m6.setI(0.33, 0.22); m6.setI(0.12, 0.13); m6.setI(m7); CodeletToTest c = new CodeletToTest("Codelet 1"); c.setIsMemoryObserver(true); c.addInput(m1); c.addInput(m2); c.addOutput(m3); c.addOutput(m4); c.addBroadcast(m5); c.addBroadcast(mo); mo.addMemoryObserver(c); m.insertCodelet(c); CodeletToTest c2 = new CodeletToTest("Codelet 2"); c2.setIsMemoryObserver(true); c2.addInput(m4); c2.addInput(m7); c2.addInput(m5); c2.addOutput(m6); c2.addOutput(m3); c2.addBroadcast(m5); mo.addMemoryObserver(c2); m8.addMemoryObserver(c2); m.insertCodelet(c2); m.start(); mo.setI(10); m8.setI(100, 0); Thread.sleep(2000); m.shutDown(); assertEquals(1, c.getCounter()); assertEquals(2, c2.getCounter()); } @Test public void multipleMemoryChangesTest() throws InterruptedException { // Codelet runs being a Memory Observer, and memories inputs are changed Mind m = new Mind(); MemoryObject m1 = m.createMemoryObject("M1", 0.12); MemoryObject m2 = m.createMemoryObject("M2", 0.32); MemoryObject m3 = m.createMemoryObject("M3", 0.44); MemoryObject m4 = m.createMemoryObject("M4", 0.52); MemoryObject m5 = m.createMemoryObject("M5", 0.12); MemoryContainer m6 = m.createMemoryContainer("C1"); MemoryContainer m7 = m.createMemoryContainer("C2"); TestComplexMemoryObjectInfo mComplex = new TestComplexMemoryObjectInfo(); mComplex.complextest = new TestComplexMemoryObjectInfo(); for (int i = 0; i < 3; i++) mComplex.complextestarray[i] = new TestComplexMemoryObjectInfo(); MemoryObject mo = new MemoryObject(); mo.setType("TestObject"); mo.setI(mComplex); m7.setI(0.55, 0.23); m6.setI(0.33, 0.22); m6.setI(0.12, 0.13); m6.setI(m7); CodeletToTest c = new CodeletToTest("Codelet 1"); c.setIsMemoryObserver(true); c.addInput(m1); c.addInput(m2); c.addOutput(m3); c.addOutput(m4); c.addBroadcast(m5); c.addBroadcast(mo); mo.addMemoryObserver(c); m2.addMemoryObserver(c); m4.addMemoryObserver(c); m.insertCodelet(c); CodeletToTest c2 = new CodeletToTest("Codelet 2"); c2.setIsMemoryObserver(true); c2.addInput(m4); c2.addInput(m5); c2.addOutput(m6); c2.addOutput(m3); c2.addBroadcast(m5); m.insertCodelet(c2); m.start(); mo.setI(10); mo.setI(4); m2.setI(1); m4.setI(2); Thread.sleep(2000); m.shutDown(); assertEquals(4, c.getCounter()); assertEquals(1, c2.getCounter()); } @Test public void addSameMemoryTest() throws InterruptedException { // Codelet runs being a Memory Observer, and memories inputs are changed, add same memory more than once Mind m = new Mind(); MemoryObject m1 = m.createMemoryObject("M1", 0.12); MemoryObject m2 = m.createMemoryObject("M2", 0.32); MemoryObject m3 = m.createMemoryObject("M3", 0.44); MemoryObject m4 = m.createMemoryObject("M4", 0.52); MemoryObject m5 = m.createMemoryObject("M5", 0.12); MemoryContainer m6 = m.createMemoryContainer("C1"); MemoryContainer m7 = m.createMemoryContainer("C2"); TestComplexMemoryObjectInfo mComplex = new TestComplexMemoryObjectInfo(); mComplex.complextest = new TestComplexMemoryObjectInfo(); for (int i = 0; i < 3; i++) mComplex.complextestarray[i] = new TestComplexMemoryObjectInfo(); MemoryObject mo = new MemoryObject(); mo.setType("TestObject"); mo.setI(mComplex); m7.setI(0.55, 0.23); m6.setI(0.33, 0.22); m6.setI(0.12, 0.13); m6.setI(m7); CodeletToTest c = new CodeletToTest("Codelet 1"); c.setIsMemoryObserver(true); mo.addMemoryObserver(c); mo.addMemoryObserver(c); m2.addMemoryObserver(c); m2.addMemoryObserver(c); m4.addMemoryObserver(c); m.insertCodelet(c); CodeletToTest c2 = new CodeletToTest("Codelet 2"); c2.setIsMemoryObserver(true); c2.setProfiling(true); ArrayList<Memory> memories = new ArrayList<Memory>(); memories.add(m4); memories.add(m4); memories.add(m5); c2.addInputs(memories); c2.addOutput(m6); c2.addOutput(m3); ArrayList<Memory> broadcasts = new ArrayList<Memory>(); broadcasts.add(m5); broadcasts.add(m5); c2.addBroadcasts(broadcasts); m.insertCodelet(c2); m.start(); for (int i = 0; i < 60; i++) { mo.setI(i); mo.setI(i); m2.setI(i); m4.setI(i); } Thread.sleep(2000); m.shutDown(); assertEquals(240, c.getCounter()); assertEquals(60, c2.getCounter()); assertTrue(c2.isProfiling()); } @Test public void usualRunWithMemoryContainerTest() throws InterruptedException { // Using a Memory Container to use setI and notify codelets Mind m = new Mind(); MemoryObject m1 = m.createMemoryObject("M1", 0.12); MemoryObject m2 = m.createMemoryObject("M2", 0.32); MemoryObject m3 = m.createMemoryObject("M3", 0.44); MemoryObject m4 = m.createMemoryObject("M4", 0.52); MemoryObject m5 = m.createMemoryObject("M5", 0.12); MemoryContainer m7 = m.createMemoryContainer("C2"); MemoryContainer m8 = m.createMemoryContainer("C3"); m7.add(m4); m8.add(m7); TestComplexMemoryObjectInfo mComplex = new TestComplexMemoryObjectInfo(); mComplex.complextest = new TestComplexMemoryObjectInfo(); for (int i = 0; i < 3; i++) mComplex.complextestarray[i] = new TestComplexMemoryObjectInfo(); MemoryObject mo = new MemoryObject(); mo.setType("TestObject"); mo.setI(mComplex); CodeletToTest c = new CodeletToTest("Codelet 1"); c.setIsMemoryObserver(true); c.addInput(m1); c.addInput(m2); c.addOutput(m3); c.addOutput(m4); c.addBroadcast(m5); c.addBroadcast(mo); mo.addMemoryObserver(c); m.insertCodelet(c); CodeletToTest c2 = new CodeletToTest("Codelet 2"); c2.setIsMemoryObserver(true); c2.addInput(m4); c2.addInput(m7); c2.addInput(m5); c2.addOutput(m3); c2.addBroadcast(m5); mo.addMemoryObserver(c2); m8.addMemoryObserver(c2); m.insertCodelet(c2); m.start(); //setI in Memory Container and verify if Codelet was notified m8.setI(100, 0); m7.setI(0.55, 0.23); Thread.sleep(2000); m.shutDown(); assertEquals(0, c.getCounter()); assertEquals(1, c2.getCounter()); } @Test public void changeOfRegimeTestMemoryObject() { Mind m = new Mind(); MemoryObject input = m.createMemoryObject("INPUT_NUMBER", 0.12); MemoryObject output = m.createMemoryObject("OUTPUT_NUMBER", 0.32); Codelet c = new Codelet() { MemoryObject input_number; MemoryObject output_number; public int counter = 0; @Override public void accessMemoryObjects() { input_number = (MemoryObject) this.getInput("INPUT_NUMBER"); output_number = (MemoryObject) this.getOutput("OUTPUT_NUMBER"); } @Override public void calculateActivation() { try { double a = counter; setActivation(a/100); } catch (CodeletActivationBoundsException ex) { Logger.getLogger(TestMemoryObserver.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void proc() { System.out.println("Processing"); int n = (int) input_number.getI(); output_number.setI(n+1); counter++; } }; c.addInput(input); c.addOutput(output); m.insertCodelet(c); c.setPublishSubscribe(true); m.start(); //setI in Memory Container and verify if Codelet was notified long ts = output.getTimestamp(); input.setI(0); while(ts == output.getTimestamp()); int nout = (int) output.getI(); System.out.println("Result: "+output.getI()); assertEquals(nout,1); c.setPublishSubscribe(false); ts = output.getTimestamp(); while(ts == output.getTimestamp()); System.out.println("Result: "+output.getI()+" "+c.getActivation()); m.shutDown(); //assertEquals(0, c.getCounter()); } @Test public void changeOfRegimeTestMemoryContainer() { Mind m = new Mind(); MemoryContainer input = m.createMemoryContainer("INPUT_NUMBER"); MemoryObject output = m.createMemoryObject("OUTPUT_NUMBER", 0.32); Codelet c = new Codelet() { MemoryContainer input_number; MemoryObject output_number; public int counter = 0; @Override public void accessMemoryObjects() { input_number = (MemoryContainer) this.getInput("INPUT_NUMBER"); output_number = (MemoryObject) this.getOutput("OUTPUT_NUMBER"); } @Override public void calculateActivation() { try { double a = counter; setActivation(a/100); } catch (CodeletActivationBoundsException ex) { Logger.getLogger(TestMemoryObserver.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Calculating activation: "+getActivation()); } @Override public void proc() { System.out.println("Processing"); int n = (int) input_number.getI(); output_number.setI(n+1); counter++; try { double a = counter; setActivation(a/100); } catch (CodeletActivationBoundsException ex) { Logger.getLogger(TestMemoryObserver.class.getName()).log(Level.SEVERE, null, ex); } } }; c.addInput(input); c.addOutput(output); m.insertCodelet(c); input.setI(0); c.setPublishSubscribe(true); m.start(); //setI in Memory Container and verify if Codelet was notified long ts = output.getTimestamp(); input.setI(0,0); while(ts == output.getTimestamp()); int nout = (int) output.getI(); System.out.println("Result: "+output.getI()+" "+c.getActivation()); assertEquals(nout,1); c.setPublishSubscribe(false); ts = output.getTimestamp(); while(ts == output.getTimestamp()); System.out.println("Result: "+output.getI()+" "+c.getActivation()); m.shutDown(); //assertEquals(0, c.getCounter()); } }
15,087
33.135747
109
java
cst
cst-master/src/test/java/br/unicamp/cst/io/rest/TestCodelet.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation * **********************************************************************************************/ package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.exceptions.CodeletActivationBoundsException; /** * * @author gudwin * */ public class TestCodelet extends Codelet{ boolean ascending = true; public TestCodelet(String name) { setName(name); } @Override public void accessMemoryObjects() { } @Override public void calculateActivation() { double currentactivation = getActivation(); if (ascending) { try { setActivation(getActivation()+0.1); } catch (CodeletActivationBoundsException e) { ascending = !ascending; } } else { try { setActivation(getActivation()-0.1); } catch (CodeletActivationBoundsException e) { ascending = !ascending; } } } @Override public void proc() { } }
1,611
26.793103
98
java
cst
cst-master/src/test/java/br/unicamp/cst/io/rest/TestCodeletJson.java
package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.MemoryObject; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; public class TestCodeletJson { Codelet interCodelet = new Codelet() { Memory in; Memory out; Memory broad; @Override public void accessMemoryObjects() { if (in == null) { this.in = this.getInput("M3"); } if (out == null) { this.out = this.getOutput("M4"); } if(broad == null){ this.broad = this.getBroadcast("M4"); } } @Override public void calculateActivation() { } @Override public void proc() { } }; @Test public void testCod(){ Memory m3 = new MemoryObject(); m3.setName("M3"); Memory m4 = new MemoryObject(); m4.setName("M4"); interCodelet.addInput(m3); interCodelet.addOutput(m4); interCodelet.addBroadcast(m4); interCodelet.setName("name"); CodeletJson codeletJson = new CodeletJson(interCodelet, "testGroup"); List<MemoryJson> inputs = codeletJson.getInputs(); List<MemoryJson> outputs = codeletJson.getOutputs(); List<MemoryJson> broadcast = codeletJson.getBroadcast(); String group = codeletJson.getGroup(); String name = codeletJson.getName(); assertEquals(m3.getName(), inputs.get(0).name); assertEquals(m4.getName(), outputs.get(0).name); assertEquals(m4.getName(), broadcast.get(0).name); assertEquals(group, "testGroup"); assertEquals(interCodelet.getName(), name); } }
1,879
25.478873
77
java
cst
cst-master/src/test/java/br/unicamp/cst/io/rest/TestHttpCodelet.java
package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.*; import org.junit.jupiter.api.Test; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Random; import static org.junit.jupiter.api.Assertions.*; public class TestHttpCodelet { Mind m1; Mind m2; HttpCodelet restSensoryTestCodelet = new HttpCodelet() { //Memory @Override public void accessMemoryObjects() { } @Override public void calculateActivation() { } @Override public void proc() { try { String msg = this.sendGET("http://127.0.0.1:60000"); System.out.println(msg); System.out.println("got from: " + "http://127.0.0.1:60000"); }catch (Exception e){e.printStackTrace();} } }; HttpCodelet restMotorTestCodelet = new HttpCodelet() { HashMap<String, String> params = new HashMap<>(); final Random r = new Random(); final Double I = 2.0; //(double) (5 + r.nextInt(500)); @Override public void accessMemoryObjects() { params.put("I", "2.0"); params.put("evaluation", "3.0"); } @Override public void calculateActivation() { } @Override public void proc() { StringBuilder sbParams = new StringBuilder(); Double eval = (double)(2 + r.nextInt(50)); params.replace("I", I.toString()); params.replace("evaluation", eval.toString()); int i = 0; for (String key : params.keySet()) { try { if (i != 0){ sbParams.append("&"); } sbParams.append(key).append("=") .append(URLEncoder.encode(params.get(key), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } i++; } try { String paramsString = sbParams.toString(); this.sendPOST("http://127.0.0.1:60000", paramsString, null); System.out.println("send to: " + "http://127.0.0.1:60000"); }catch (Exception e){e.printStackTrace();} } }; public Mind prepareMind(int portOut, int portIn, int partnerPortOut, int partnerPortIn, double outI, double toGetI, String baseIP) { String baseURL = "http://" + baseIP + ":"; String partnerURLOut = baseURL + partnerPortOut+"/"; String partnerURLIn = baseURL + partnerPortIn+"/"; HttpCodelet restSensoryTestCodelet = new HttpCodelet() { //Memory @Override public void accessMemoryObjects() { } @Override public void calculateActivation() { } @Override public void proc() { try { String msg = this.sendGET("http://127.0.0.1:60000"); System.out.println(msg); System.out.println("got from: " + partnerURLOut); }catch (Exception e){e.printStackTrace();} } }; HttpCodelet restMotorTestCodelet = new HttpCodelet() { HashMap<String, String> params = new HashMap<>(); final Random r = new Random(); final Double I = outI; //(double) (5 + r.nextInt(500)); @Override public void accessMemoryObjects() { params.put("I", "2.0"); params.put("evaluation", "3.0"); } @Override public void calculateActivation() { } @Override public void proc() { StringBuilder sbParams = new StringBuilder(); Double eval = (double)(2 + r.nextInt(50)); params.replace("I", I.toString()); params.replace("evaluation", eval.toString()); int i = 0; for (String key : params.keySet()) { try { if (i != 0){ sbParams.append("&"); } sbParams.append(key).append("=") .append(URLEncoder.encode(params.get(key), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } i++; } try { String paramsString = sbParams.toString(); this.sendPOST("http://127.0.0.1:60000", paramsString, null); System.out.println("send to: " + partnerURLIn); }catch (Exception e){e.printStackTrace();} } }; Codelet interCodelet = new Codelet() { Memory in; Memory out; @Override public void accessMemoryObjects() { if(in == null){ this.in = this.getInput("M3"); } if(out == null){ this.out = this.getOutput("M4"); } } @Override public void calculateActivation() {} @Override public void proc() { Object testNum = in.getI(); if (testNum != null){ out.setI((double)testNum); } } }; Mind m = new Mind(); //RESTMemory m1 = m.createRESTMemory("M1", baseIP, portIn); //m1.setI(1); RESTMemory m1; if (baseIP.equals("localhost")){ m1 = m.createRESTMemory("M1", portIn); } else{ m1 = m.createRESTMemory("M1", baseIP, portIn); } m1.setI(1); MemoryObject m2 = m.createMemoryObject("M2", 2.0); MemoryObject m3 = m.createMemoryObject("M3", null); MemoryObject m4 = m.createMemoryObject("M4", null); RESTMemory m5; if (baseIP.equals("localhost")){ m5 = m.createRESTMemory("M5", portOut); } else{ m5 = m.createRESTMemory("M5", baseIP, portOut); } m5.setI(toGetI); MemoryContainer m6 = m.createMemoryContainer("C1"); MemoryContainer m7 = m.createMemoryContainer("C2"); m7.setI(7.55, 0.23); m6.setI(6.33, 0.22); m6.setI(6.12, 0.13); m6.add(m7); //dummy RESTMemory m8 = new RESTMemory(portOut); m8.setIdmemoryobject(1l); m8.setName("M8"); m.getRawMemory().addMemory(m8); //REST Sensory that will use GET on another agent motor memory restSensoryTestCodelet.addInput(m1); restSensoryTestCodelet.addOutput(m2); restSensoryTestCodelet.setProfiling(true); m.insertCodelet(restSensoryTestCodelet); // simple "pass" Codelet interCodelet.addInput(m3); interCodelet.addOutput(m4); m.insertCodelet(interCodelet); // simple motor that writes on a memory that will listen to GET methods Codelet c2 = new TestCodelet("Motor1"); c2.addInput(m4); c2.addOutput(m5); m.insertCodelet(c2); // REST Motor Codelet that will write on another agent Sensory Memory restMotorTestCodelet.addInput(m4); //sends to partner url in m.insertCodelet(restMotorTestCodelet); return(m); } @Test public void testError() { try{Thread.sleep(2000); }catch (Exception e){e.printStackTrace();} Exception exception1 = assertThrows(ConnectException.class, () -> { restMotorTestCodelet.sendPOST("http://127.0.0.1:6000", "2", null); }); Exception exception2 = assertThrows(ConnectException.class, () -> { restMotorTestCodelet.sendGET("http://127.0.0.1:6000"); }); } }
8,150
28.320144
136
java
cst
cst-master/src/test/java/br/unicamp/cst/io/rest/TestMemoryJson.java
package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.MemoryObject; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class TestMemoryJson { @Test public void testEquals() { MemoryObject memoryObject = new MemoryObject(); memoryObject.setName("test"); String group = "group"; MemoryJson m1 = new MemoryJson(memoryObject); MemoryJson m2 = new MemoryJson(memoryObject, group); assertEquals(memoryObject.getName(), m1.name); assertEquals(memoryObject.getName(), m2.name); assertEquals(group, m2.group); } }
703
21.709677
60
java
cst
cst-master/src/test/java/br/unicamp/cst/io/rest/TestREST.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation * **********************************************************************************************/ package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.MemoryContainer; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import br.unicamp.cst.support.InterfaceAdapter; import br.unicamp.cst.support.TimeStamp; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * * @author rgudwin */ public class TestREST { Mind m; public TestREST() { } void updateMemoryObject(MemoryObject mo) { double value = (double) mo.getI(); mo.setI(value+0.01); } void updateMemoryContainer(MemoryContainer mc) { for (Memory mem : mc.getAllMemories()) { if (mem.getClass().getCanonicalName().equalsIgnoreCase("br.unicamp.cst.core.entities.MemoryObject")) { updateMemoryObject((MemoryObject)mem); //System.out.println("Updating subnode"); } } } void updateMind() { //System.out.println("Updating Mind"); for (Memory mem : m.getRawMemory().getAllMemoryObjects()) { if (mem.getClass().getCanonicalName().equalsIgnoreCase("br.unicamp.cst.core.entities.MemoryObject")) { updateMemoryObject((MemoryObject)mem); } if (mem.getClass().getCanonicalName().equalsIgnoreCase("br.unicamp.cst.core.entities.MemoryContainer")) { updateMemoryContainer((MemoryContainer)mem); } } } public void StartTimer() { Timer t = new Timer(); TestREST.mainTimerTask tt = new TestREST.mainTimerTask(this); t.scheduleAtFixedRate(tt, 0, 100); } public void tick() { if (m != null) { updateMind(); } else { System.out.println("Mind is null"); } //System.out.println("update"); } class mainTimerTask extends TimerTask { TestREST wov; boolean enabled = true; public mainTimerTask(TestREST wovi) { wov = wovi; } public void run() { if (enabled) { wov.tick(); } } public void setEnabled(boolean value) { enabled = value; } } public Mind prepareMind() { Mind m = new Mind(); m.createCodeletGroup("Sensory"); m.createCodeletGroup("Perception"); m.createCodeletGroup("Behavioral"); m.createCodeletGroup("Motivational"); m.createCodeletGroup("Motor"); m.createMemoryGroup("Sensory"); m.createMemoryGroup("Motor"); MemoryObject m1 = m.createMemoryObject("M1", 1.12); m.registerMemory(m1,"Sensory"); MemoryObject m2 = m.createMemoryObject("M2", 2.32); m.registerMemory(m2,"Sensory"); MemoryObject m3 = m.createMemoryObject("M3", 3.44); m.registerMemory(m3,"Sensory"); MemoryObject m4 = m.createMemoryObject("M4", 4.52); m.registerMemory(m4,"Sensory"); MemoryObject m5 = m.createMemoryObject("M5", 5.12); m.registerMemory(m5,"Sensory"); MemoryContainer m6 = m.createMemoryContainer("C1"); m.registerMemory(m6,"Motor"); MemoryContainer m7 = m.createMemoryContainer("C2"); m.registerMemory(m7,"Motor"); int mc1 = m7.setI(7.55, 0.23); int mc2 = m6.setI(6.33, 0.22); int mc3 = m6.setI(6.12, 0.13); int mc4 = m6.add(m7); //System.out.println("Memories: "+mc1+" "+mc2+" "+mc3+" "+mc4); Codelet c = new TestCodelet("Sensor1"); c.addInput(m1); c.addInput(m2); c.addOutput(m3); c.addOutput(m4); c.addBroadcast(m5); //c.setCodeletProfiler("profile/", "c.json", "Mind 1", 10, null, CodeletsProfiler.FileFormat.JSON); m.insertCodelet(c,"Sensory"); Codelet c2 = new TestCodelet("Motor1"); c2.addInput(m4); c2.addInput(m5); c2.addOutput(m6); c2.addOutput(m3); c2.addBroadcast(m5); //c2.setCodeletProfiler("profile/", "c2.json", "Mind 1", 10, null, CodeletsProfiler.FileFormat.JSON); c.setProfiling(true); m.insertCodelet(c2,"Motor"); Codelet mot1 = new TestCodelet("Curiosity"); mot1.addInput(m7); mot1.addOutput(m5); m.insertCodelet(mot1,"Motivational"); Codelet mot2 = new TestCodelet("Fear"); mot2.addInput(m3); mot2.addOutput(m4); try {mot2.setActivation(1.0);} catch(Exception e){} m.insertCodelet(mot2,"Motivational"); Codelet mot3 = new TestCodelet("Anger"); mot3.addInput(m1); mot3.addOutput(m2); try {mot3.setActivation(0.5);} catch(Exception e){} m.insertCodelet(mot3,"Motivational"); m.start(); return(m); } public Mind prepareMindWithoutGroups() { Mind m = new Mind(); MemoryObject m1 = m.createMemoryObject("M1", 1.12); MemoryObject m2 = m.createMemoryObject("M2", 2.32); MemoryObject m3 = m.createMemoryObject("M3", 3.44); MemoryObject m4 = m.createMemoryObject("M4", 4.52); MemoryObject m5 = m.createMemoryObject("M5", 5.12); MemoryContainer m6 = m.createMemoryContainer("C1"); MemoryContainer m7 = m.createMemoryContainer("C2"); int mc1 = m7.setI(7.55, 0.23); int mc2 = m6.setI(6.33, 0.22); int mc3 = m6.setI(6.12, 0.13); int mc4 = m6.add(m7); //System.out.println("Memories: "+mc1+" "+mc2+" "+mc3+" "+mc4); Codelet c = new TestCodelet("Sensor1"); c.addInput(m1); c.addInput(m2); c.addOutput(m3); c.addOutput(m4); c.addBroadcast(m5); //c.setCodeletProfiler("profile/", "c.json", "Mind 1", 10, null, CodeletsProfiler.FileFormat.JSON); m.insertCodelet(c); Codelet c2 = new TestCodelet("Motor1"); c2.addInput(m4); c2.addInput(m5); c2.addOutput(m6); c2.addOutput(m3); c2.addBroadcast(m5); //c2.setCodeletProfiler("profile/", "c2.json", "Mind 1", 10, null, CodeletsProfiler.FileFormat.JSON); c.setProfiling(true); m.insertCodelet(c2); Codelet mot1 = new TestCodelet("Curiosity"); mot1.addInput(m7); mot1.addOutput(m5); m.insertCodelet(mot1); Codelet mot2 = new TestCodelet("Fear"); mot2.addInput(m3); mot2.addOutput(m4); try {mot2.setActivation(1.0);} catch(Exception e){} m.insertCodelet(mot2); Codelet mot3 = new TestCodelet("Anger"); mot3.addInput(m1); mot3.addOutput(m2); try {mot3.setActivation(0.5);} catch(Exception e){} m.insertCodelet(mot3); m.start(); return(m); } private static final String USER_AGENT = "Mozilla/5.0"; private String GET_URL; private static int port; private String sendGET() { String message = ""; int responseCode=0; HttpURLConnection con=null; try { URL obj = new URL(GET_URL); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); //con.setRequestProperty("User-Agent", USER_AGENT); responseCode = con.getResponseCode(); if (responseCode != 200) System.out.println("GET Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // success BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); message = response.toString(); } else { System.out.println("GET request not worked"); } } catch (java.net.ConnectException e) { System.out.println("Connection refused"); } catch (Exception e) { e.printStackTrace(); } return(message); } private void processTest() { String mes; for (int i=0;i<10;i++) { mes = sendGET(); Gson gson = new GsonBuilder().registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryObject>()) .registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryContainer>()) .setPrettyPrinting().create(); MindJson mj = gson.fromJson(mes,MindJson.class); if (mj != null && mj.memories != null) { assertEquals(mj.memories.size(),7); MemoryJson c = mj.memories.get(0); assertEquals(c.name,"C1"); c = mj.memories.get(1); assertEquals(c.name,"C2"); for(int j=2;j<7;j++) { MemoryJson mm = mj.memories.get(j); String sname = "M"+(j-1); assertEquals(mm.name,sname); } assertEquals(mj.codelets.size(),5); String time = TimeStamp.getStringTimeStamp(mj.memories.get(0).timestamp,"dd/MM/YYYY HH:mm:ss.SSS zzz"); System.out.println("i: "+i+" time: "+time+" memories: "+mj.memories.size()+" codelets: "+mj.codelets.size()); } else System.out.println("Problem detected while reading back the information"); } } private void processTestWithoutGroups() { String mes; for (int i=0;i<10;i++) { mes = sendGET(); Gson gson = new GsonBuilder().registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryObject>()) .registerTypeAdapter(Memory.class, new InterfaceAdapter<MemoryContainer>()) .setPrettyPrinting().create(); MindJson mj = gson.fromJson(mes,MindJson.class); if (mj != null && mj.memories != null) { assertEquals(mj.memories.size(),7); for(int j=0;j<5;j++) { MemoryJson mm = mj.memories.get(j); String sname = "M"+(j+1); assertEquals(mm.name,sname); } MemoryJson c = mj.memories.get(5); assertEquals(c.name,"C1"); c = mj.memories.get(6); assertEquals(c.name,"C2"); assertEquals(mj.codelets.size(),5); String time = TimeStamp.getStringTimeStamp(mj.memories.get(0).timestamp,"dd/MM/YYYY HH:mm:ss.SSS zzz"); System.out.println("i: "+i+" time: "+time+" memories: "+mj.memories.size()+" codelets: "+mj.codelets.size()); } else System.out.println("Problem detected while reading back the information"); } } @Test public void testRest1() { Random r = new Random(); // Finding a random port higher than 5000 port = 5000 + r.nextInt(50000); GET_URL = "http://localhost:"+port+"/"; TestREST tr = new TestREST(); tr.m = prepareMind(); tr.StartTimer(); System.out.println("Creating a server in port "+port); RESTServer rs = new RESTServer(tr.m,port,true); processTest(); } @Test public void testRest2() { Random r = new Random(); // Finding a random port higher than 5000 port = 5000 + r.nextInt(50000); GET_URL = "http://localhost:"+port+"/"; TestREST tr = new TestREST(); tr.m = prepareMind(); tr.StartTimer(); System.out.println("Creating a server in port "+port); RESTServer rs = new RESTServer(tr.m,port); processTest(); } @Test public void testRest3() { Random r = new Random(); // Finding a random port higher than 5000 port = 5000 + r.nextInt(50000); GET_URL = "http://localhost:"+port+"/"; TestREST tr = new TestREST(); tr.m = prepareMind(); tr.StartTimer(); System.out.println("Creating a server in port "+port); RESTServer rs = new RESTServer(tr.m,port,true,"*"); processTest(); } @Test public void testRest4() { Random r = new Random(); // Finding a random port higher than 5000 port = 5000 + r.nextInt(50000); GET_URL = "http://localhost:"+port+"/"; TestREST tr = new TestREST(); tr.m = prepareMindWithoutGroups(); tr.StartTimer(); System.out.println("Creating a server in port "+port); RESTServer rs = new RESTServer(tr.m,port,true); processTestWithoutGroups(); } @Test public void testRest5() { Random r = new Random(); // Finding a random port higher than 5000 port = 5000 + r.nextInt(50000); GET_URL = "http://localhost:"+port+"/"; TestREST tr = new TestREST(); tr.m = prepareMindWithoutGroups(); tr.StartTimer(); System.out.println("Creating a server in port "+port); RESTServer rs = new RESTServer(tr.m,port); processTestWithoutGroups(); } @Test public void testRest6() { Random r = new Random(); // Finding a random port higher than 5000 port = 5000 + r.nextInt(50000); GET_URL = "http://localhost:"+port+"/"; TestREST tr = new TestREST(); tr.m = prepareMindWithoutGroups(); tr.StartTimer(); System.out.println("Creating a server in port "+port); RESTServer rs = new RESTServer(tr.m,port,true,"*"); processTestWithoutGroups(); } @Test public void testRest7() { Random r = new Random(); // Finding a random port higher than 5000 port = 5000 + r.nextInt(50000); GET_URL = "http://localhost:"+port+"/"; TestREST tr = new TestREST(); tr.m = prepareMind(); tr.StartTimer(); System.out.println("Creating a server in port "+port); RESTServer rs = new RESTServer(tr.m,port,true,"*",500L); processTest(); } @Test public void testRest8() { Random r = new Random(); // Finding a random port higher than 5000 port = 5000 + r.nextInt(50000); GET_URL = "http://localhost:"+port+"/"; TestREST tr = new TestREST(); tr.m = prepareMindWithoutGroups(); tr.StartTimer(); System.out.println("Creating a server in port "+port); RESTServer rs = new RESTServer(tr.m,port,true,"*",500L); processTestWithoutGroups(); } }
15,797
35.825175
125
java
cst
cst-master/src/test/java/br/unicamp/cst/io/rest/TestRESTMemory.java
package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.*; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Random; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class TestRESTMemory { Mind m1; Mind m2; public Mind prepareMind(int portOut, int portIn, int partnerPortOut, int partnerPortIn, double outI, double toGetI, String baseIP) { String baseURL = "http://" + baseIP + ":"; String partnerURLOut = baseURL + partnerPortOut+"/"; String partnerURLIn = baseURL + partnerPortIn+"/"; HttpCodelet restSensoryTestCodelet = new HttpCodelet() { //Memory @Override public void accessMemoryObjects() { } @Override public void calculateActivation() { } @Override public void proc() { try { String msg = this.sendGET(partnerURLOut); System.out.println(msg); System.out.println("got from: " + partnerURLOut); }catch (Exception e){e.printStackTrace();} } }; HttpCodelet restMotorTestCodelet = new HttpCodelet() { HashMap<String, String> params = new HashMap<>(); final Random r = new Random(); final Double I = outI; //(double) (5 + r.nextInt(500)); @Override public void accessMemoryObjects() { params.put("I", "2.0"); params.put("evaluation", "3.0"); } @Override public void calculateActivation() { } @Override public void proc() { Double eval = (double)(2 + r.nextInt(50)); params.replace("I", I.toString()); params.replace("evaluation", eval.toString()); String paramsString = prepareParams(params); try { this.sendPOST(partnerURLIn, paramsString, null); System.out.println("send to: " + partnerURLIn); }catch (Exception e){e.printStackTrace();} } }; Codelet interCodelet = new Codelet() { Memory in; Memory out; @Override public void accessMemoryObjects() { if(in == null){ this.in = this.getInput("M3"); } if(out == null){ this.out = this.getOutput("M4"); } } @Override public void calculateActivation() {} @Override public void proc() { Object testNum = in.getI(); if (testNum != null){ out.setI((double)testNum); } } }; Mind m = new Mind(); //RESTMemory m1 = m.createRESTMemory("M1", baseIP, portIn); //m1.setI(1); RESTMemory m1; if (baseIP.equals("localhost")){ m1 = m.createRESTMemory("M1", portIn); } else{ m1 = m.createRESTMemory("M1", baseIP, portIn); } m1.setI(1); MemoryObject m2 = m.createMemoryObject("M2", 2.0); MemoryObject m3 = m.createMemoryObject("M3", null); MemoryObject m4 = m.createMemoryObject("M4", null); RESTMemory m5; if (baseIP.equals("localhost")){ m5 = m.createRESTMemory("M5", portOut); } else{ m5 = m.createRESTMemory("M5", baseIP, portOut); } m5.setI(toGetI); MemoryContainer m6 = m.createMemoryContainer("C1"); MemoryContainer m7 = m.createMemoryContainer("C2"); m7.setI(7.55, 0.23); m6.setI(6.33, 0.22); m6.setI(6.12, 0.13); m6.add(m7); //dummy RESTMemory m8 = new RESTMemory(portOut+1); m8.setIdmemoryobject(2l); m8.setName("M8"); m.getRawMemory().addMemory(m8); //REST Sensory that will use GET on another agent motor memory restSensoryTestCodelet.addInput(m1); restSensoryTestCodelet.addOutput(m2); restSensoryTestCodelet.setProfiling(true); m.insertCodelet(restSensoryTestCodelet); // simple "pass" Codelet interCodelet.addInput(m3); interCodelet.addOutput(m4); m.insertCodelet(interCodelet); // simple motor that writes on a memory that will listen to GET methods Codelet c2 = new TestCodelet("Motor1"); c2.addInput(m4); c2.addOutput(m5); m.insertCodelet(c2); // REST Motor Codelet that will write on another agent Sensory Memory restMotorTestCodelet.addInput(m4); //sends to partner url in m.insertCodelet(restMotorTestCodelet); return(m); } @Test public void testRestHostname() throws IOException { //String baseIP = "192.xxx.xxx.x"; //String baseIP = "172.xx.x.x"; String baseIP = "127.0.0.1"; //String baseIP = "localhost"; Random r = new Random(); // Finding a random port higher than 5000 int portIn1 = 5000 + r.nextInt(50000); int portIn2 = 5000 + r.nextInt(50000); int portOut1 = 5000 + r.nextInt(50000); int portOut2 = 5000 + r.nextInt(50000); TestRESTMemory tr = new TestRESTMemory(); double outI1 = (5 + r.nextInt(500)); double toGetI1 = (5 + r.nextInt(500)); double outI2 = (5 + r.nextInt(500)); double toGetI2 =(5 + r.nextInt(500)); tr.m1 = prepareMind(portOut1, portIn1, portOut2, portIn2, outI1, toGetI1, baseIP); tr.m2 = prepareMind(portOut2, portIn2, portOut1, portIn1, outI2, toGetI2, baseIP); tr.m1.start(); tr.m2.start(); try{Thread.sleep(2000); }catch (Exception e){e.printStackTrace();} assertEquals(tr.m1.getRawMemory().getAllOfType("M5").get(0).getI(), toGetI1); assertEquals(Double.parseDouble((String) tr.m2.getRawMemory().getAllOfType("M1").get(0).getI()), outI1, 0.0); assertEquals(tr.m2.getRawMemory().getAllOfType("M5").get(0).getI(), toGetI2); assertEquals(Double.parseDouble((String) tr.m1.getRawMemory().getAllOfType("M1").get(0).getI()), outI2, 0.0); } @Test public void testRestLocalhost() throws IOException { String baseIP = "localhost"; Random r = new Random(); // Finding a random port higher than 5000 int portIn1 = 5000 + r.nextInt(50000); int portIn2 = 5000 + r.nextInt(50000); int portOut1 = 5000 + r.nextInt(50000); int portOut2 = 5000 + r.nextInt(50000); TestRESTMemory tr = new TestRESTMemory(); double outI1 = (5 + r.nextInt(500)); double toGetI1 = (5 + r.nextInt(500)); double outI2 = (5 + r.nextInt(500)); double toGetI2 =(5 + r.nextInt(500)); tr.m1 = prepareMind(portOut1, portIn1, portOut2, portIn2, outI1, toGetI1, "localhost"); tr.m2 = prepareMind(portOut2, portIn2, portOut1, portIn1, outI2, toGetI2, "localhost"); tr.m1.start(); tr.m2.start(); MemoryObject m = new MemoryObject(); m.setName("testName"); MemoryContainer memoryContainer = new MemoryContainer(); memoryContainer.add(m); MemoryContainerJson memoryContainerJson = new MemoryContainerJson(memoryContainer, "group"); try{Thread.sleep(2000); }catch (Exception e){e.printStackTrace();} assertEquals(tr.m1.getRawMemory().getAllOfType("M5").get(0).getI(), toGetI1); assertEquals(Double.parseDouble((String) tr.m2.getRawMemory().getAllOfType("M1").get(0).getI()), outI1, 0.0); assertEquals(tr.m2.getRawMemory().getAllOfType("M5").get(0).getI(), toGetI2); assertEquals(Double.parseDouble((String) tr.m1.getRawMemory().getAllOfType("M1").get(0).getI()), outI2, 0.0); RESTMemory m8 = (RESTMemory) tr.m2.getRawMemory().getAllOfType("M8").get(0); assertEquals(m8.getIdmemoryobject(), 2l); assertEquals(memoryContainerJson.memories.get(0).name, m.getName()); } }
8,385
31.63035
136
java
cst
cst-master/src/test/java/br/unicamp/cst/io/rest/TestRESTMemoryContainer.java
package br.unicamp.cst.io.rest; import br.unicamp.cst.core.entities.*; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.HashMap; import java.util.Random; import static org.junit.jupiter.api.Assertions.assertEquals; public class TestRESTMemoryContainer { Mind m1; Mind m2; public Mind prepareMind(int portOut, int portIn, int partnerPortOut, int partnerPortIn, double outI, double toGetI, String baseIP) { String baseURL = "http://" + baseIP + ":"; String partnerURLOut = baseURL + partnerPortOut+"/"; String partnerURLIn = baseURL + partnerPortIn+"/"; HttpCodelet restSensoryTestCodelet = new HttpCodelet() { //Memory @Override public void accessMemoryObjects() { } @Override public void calculateActivation() { } @Override public void proc() { try { String msg = this.sendGET(partnerURLOut); System.out.println(msg); System.out.println("got from: " + partnerURLOut); }catch (Exception e){e.printStackTrace();} } }; HttpCodelet restMotorTestCodelet = new HttpCodelet() { HashMap<String, String> params = new HashMap<>(); final Random r = new Random(); final Double I = outI; //(double) (5 + r.nextInt(500)); @Override public void accessMemoryObjects() { params.put("I", "2.0"); params.put("evaluation", "3.0"); } @Override public void calculateActivation() { } @Override public void proc() { Double eval = (double)(2 + r.nextInt(50)); params.replace("I", I.toString()); params.replace("evaluation", eval.toString()); String paramsString = prepareParams(params); try { this.sendPOST(partnerURLIn, paramsString, null); System.out.println("send to: " + partnerURLIn); }catch (Exception e){e.printStackTrace();} } }; Codelet interCodelet = new Codelet() { Memory in; Memory out; @Override public void accessMemoryObjects() { if(in == null){ this.in = this.getInput("M3"); } if(out == null){ this.out = this.getOutput("M4"); } } @Override public void calculateActivation() {} @Override public void proc() { Object testNum = in.getI(); if (testNum != null){ out.setI((double)testNum); } } }; Mind m = new Mind(); //RESTMemory m1 = m.createRESTMemory("M1", baseIP, portIn); //m1.setI(1); RESTMemoryContainer m1; if (baseIP.equals("localhost")){ m1 = m.createRESTMemoryContainer("M1", portIn); } else{ m1 = m.createRESTMemoryContainer("M1", baseIP, portIn); } m1.setI(1); MemoryObject m2 = m.createMemoryObject("M2", 2.0); MemoryObject m3 = m.createMemoryObject("M3", null); MemoryObject m4 = m.createMemoryObject("M4", null); RESTMemoryContainer m5; if (baseIP.equals("localhost")){ m5 = m.createRESTMemoryContainer("M5", portOut); } else{ m5 = m.createRESTMemoryContainer("M5", baseIP, portOut); } m5.setI(toGetI); MemoryContainer m6 = m.createMemoryContainer("C1"); MemoryContainer m7 = m.createMemoryContainer("C2"); m7.setI(7.55, 0.23); m6.setI(6.33, 0.22); m6.setI(6.12, 0.13); m6.add(m7); //dummy RESTMemoryContainer m8 = new RESTMemoryContainer(portOut+1); //m8.setIdmemoryobject(2l); m8.setName("M8"); m8.setI("2"); m.getRawMemory().addMemory(m8); //REST Sensory that will use GET on another agent motor memory restSensoryTestCodelet.addInput(m1); restSensoryTestCodelet.addOutput(m2); restSensoryTestCodelet.setProfiling(true); m.insertCodelet(restSensoryTestCodelet); // simple "pass" Codelet interCodelet.addInput(m3); interCodelet.addOutput(m4); m.insertCodelet(interCodelet); // simple motor that writes on a memory that will listen to GET methods Codelet c2 = new TestCodelet("Motor1"); c2.addInput(m4); c2.addOutput(m5); m.insertCodelet(c2); // REST Motor Codelet that will write on another agent Sensory Memory restMotorTestCodelet.addInput(m4); //sends to partner url in m.insertCodelet(restMotorTestCodelet); return(m); } @Test public void testRestHostname() throws IOException { //String baseIP = "192.xxx.xxx.x"; //String baseIP = "172.xx.x.x"; String baseIP = "127.0.0.1"; //String baseIP = "localhost"; Random r = new Random(); // Finding a random port higher than 5000 int portIn1 = 5000 + r.nextInt(50000); int portIn2 = 5000 + r.nextInt(50000); int portOut1 = 5000 + r.nextInt(50000); int portOut2 = 5000 + r.nextInt(50000); TestRESTMemoryContainer tr = new TestRESTMemoryContainer(); double outI1 = (5 + r.nextInt(500)); double toGetI1 = (5 + r.nextInt(500)); double outI2 = (5 + r.nextInt(500)); double toGetI2 =(5 + r.nextInt(500)); tr.m1 = prepareMind(portOut1, portIn1, portOut2, portIn2, outI1, toGetI1, baseIP); tr.m2 = prepareMind(portOut2, portIn2, portOut1, portIn1, outI2, toGetI2, baseIP); tr.m1.start(); tr.m2.start(); try{Thread.sleep(2000); }catch (Exception e){e.printStackTrace();} assertEquals(tr.m1.getRawMemory().getAllOfType("M5").get(0).getI(), toGetI1); assertEquals(Double.parseDouble((String) tr.m2.getRawMemory().getAllOfType("M1").get(0).getI()), outI1, 0.0); assertEquals(tr.m2.getRawMemory().getAllOfType("M5").get(0).getI(), toGetI2); assertEquals(Double.parseDouble((String) tr.m1.getRawMemory().getAllOfType("M1").get(0).getI()), outI2, 0.0); } @Test public void testRestLocalhost() throws IOException { String baseIP = "localhost"; Random r = new Random(); // Finding a random port higher than 5000 int portIn1 = 5000 + r.nextInt(50000); int portIn2 = 5000 + r.nextInt(50000); int portOut1 = 5000 + r.nextInt(50000); int portOut2 = 5000 + r.nextInt(50000); TestRESTMemoryContainer tr = new TestRESTMemoryContainer(); double outI1 = (5 + r.nextInt(500)); double toGetI1 = (5 + r.nextInt(500)); double outI2 = (5 + r.nextInt(500)); double toGetI2 =(5 + r.nextInt(500)); tr.m1 = prepareMind(portOut1, portIn1, portOut2, portIn2, outI1, toGetI1, "localhost"); tr.m2 = prepareMind(portOut2, portIn2, portOut1, portIn1, outI2, toGetI2, "localhost"); tr.m1.start(); tr.m2.start(); MemoryObject m = new MemoryObject(); m.setName("testName"); MemoryContainer memoryContainer = new MemoryContainer(); memoryContainer.add(m); MemoryContainerJson memoryContainerJson = new MemoryContainerJson(memoryContainer, "group"); try{Thread.sleep(2000); }catch (Exception e){e.printStackTrace();} assertEquals(tr.m1.getRawMemory().getAllOfType("M5").get(0).getI(), toGetI1); assertEquals(Double.parseDouble((String) tr.m2.getRawMemory().getAllOfType("M1").get(0).getI()), outI1, 0.0); assertEquals(tr.m2.getRawMemory().getAllOfType("M5").get(0).getI(), toGetI2); assertEquals(Double.parseDouble((String) tr.m1.getRawMemory().getAllOfType("M1").get(0).getI()), outI2, 0.0); RESTMemoryContainer m8 = (RESTMemoryContainer) tr.m2.getRawMemory().getAllOfType("M8").get(0); //assertEquals(m8.getIdmemoryobject(), 2l); assertEquals(memoryContainerJson.memories.get(0).name, m.getName()); } }
8,414
32
136
java
cst
cst-master/src/test/java/br/unicamp/cst/language/NameGeneratorTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.language; import org.junit.jupiter.api.Test; /** * @author suelen * */ public class NameGeneratorTest { @Test public void testNameGenerator() { int cont = 0; while (cont < 10) { NameGenerator ng = new NameGenerator(); System.out.println(" >> " + ng.generateWord()); cont++; } } }
970
27.558824
97
java
cst
cst-master/src/test/java/br/unicamp/cst/representation/idea/HabitExecutionerCodeletTest.java
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package br.unicamp.cst.representation.idea; import br.unicamp.cst.core.entities.MemoryContainer; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import java.util.ArrayList; import java.util.List; import java.util.Random; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import org.junit.jupiter.api.Test; /** * * @author rgudwin */ public class HabitExecutionerCodeletTest { Mind m; MemoryContainer mc; MemoryObject moi; MemoryObject moo; public HabitExecutionerCodeletTest() { m = new Mind(); mc = m.createMemoryContainer("HabitsMemory"); Idea sh = new Idea("Summer"); sh.setValue(summer); sh.setScope(2); Idea dh = new Idea("Decrementer"); dh.setValue(decrementer); dh.setScope(2); mc.setI(sh); mc.setI(dh); moi = m.createMemoryObject("InputIdeasMemory"); moo = m.createMemoryObject("OutputIdeasMemory"); HabitExecutionerCodelet hec = new HabitExecutionerCodelet(); hec.addInput(mc); hec.addInput(moi); hec.addOutput(moo); hec.setPublishSubscribe(true); m.insertCodelet(hec); m.start(); } Habit summer = new Habit() { @Override public Idea exec(Idea idea) { Idea adder = idea.get("value.add"); int valuetoadd=0; if (adder != null && adder.getValue() instanceof Integer) { valuetoadd = (int) adder.getValue(); } if (idea.get("value").getValue() instanceof Integer) { int number = (int) idea.get("value").getValue(); Idea modifiedIdea = new Idea("incremented",number+valuetoadd); return(modifiedIdea); } System.out.println("Something wrong happened"); return(null); } }; Habit decrementer = new Habit() { @Override public Idea exec(Idea idea) { Idea adder = idea.get("value.add"); int valuetodec=0; if (adder != null && adder.getValue() instanceof Integer) { valuetodec = (int) adder.getValue(); } if (idea.get("value").getValue() instanceof Integer) { int number = (int) idea.get("value").getValue(); Idea modifiedIdea = new Idea("decremented",number-valuetodec); return(modifiedIdea); } System.out.println("Something wrong happened"); return(null); } }; private void doTest() { Object oo; Random r = new Random(); for (int k=0;k<100;k++) { int major = r.nextInt(100); if (major < 50) { mc.setEvaluation(0.7,0); mc.setEvaluation(0.3,1); } else { mc.setEvaluation(0.3,0); mc.setEvaluation(0.7,1); } int minor = r.nextInt(10); Idea i = new Idea("value",major); i.add(new Idea("add",minor)); moi.setI(i); long ti = moi.getTimestamp(); while(moo.getTimestamp() < ti) System.out.print("."); oo = moo.getI(); if (oo != null) { Idea ooi = (Idea) oo; int sum = (int) ooi.getValue(); Idea ih = (Idea) mc.getLastI(); int op; String ops; if (ih.getName().equals("Summer")) { op = 0; ops = "+"; } else { op = 1; ops = "-"; } System.out.println(ih+" "+major+ops+minor+"="+sum); if (op == 0) assertEquals(sum,major+minor); else assertEquals(sum,major-minor); } else fail("The output memory object is null"); } } @Test public void testHabitExecutionerCodeletMAX() { HabitExecutionerCodeletTest test = new HabitExecutionerCodeletTest(); mc.setPolicy(MemoryContainer.Policy.MAX); System.out.println("\nTesting the MAX Policy - Sums for < 50 Decs for > 50"); doTest(); } @Test public void testHabitExecutionerCodeletMIN() { HabitExecutionerCodeletTest test = new HabitExecutionerCodeletTest(); mc.setPolicy(MemoryContainer.Policy.MIN); System.out.println("\nTesting the MIN Policy - Sums for > 50 Decs for < 50"); doTest(); } @Test public void testHabitExecutionerCodeletIterate() { HabitExecutionerCodeletTest test = new HabitExecutionerCodeletTest(); mc.setPolicy(MemoryContainer.Policy.ITERATE); System.out.println("\nTesting the ITERATE Policy - Iterate Sums and Decs"); doTest(); } @Test public void testHabitExecutionerCodeletRandom() { HabitExecutionerCodeletTest test = new HabitExecutionerCodeletTest(); mc.setPolicy(MemoryContainer.Policy.RANDOM_FLAT); System.out.println("\nTesting the RANDOM_FLAT Policy - Sums and Decs at Random"); doTest(); } }
5,577
33.645963
101
java
cst
cst-master/src/test/java/br/unicamp/cst/representation/idea/TestCategory.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.representation.idea; import java.util.Arrays; import java.util.List; import java.util.Random; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * * @author rgudwin */ public class TestCategory { Idea evenIdea; Idea oddIdea; private Category createEvenNumber() { Category even = new Category() { @Override public double membership(Idea idea) { //Check if belongs to category return membershipDegree; if (idea.getValue() instanceof Integer) { int number = (int) idea.getValue(); if (number % 2 == 0) return(1.0); } return(0.0); } @Override public Idea getInstance(Idea constraints) { // Create an instance of the category based on constraints int number = new Random().nextInt(); Idea evenNumber = new Idea("even_number",number*2); return(evenNumber); } }; return(even); } private Category createOddNumber() { Category odd = new Category() { @Override public double membership(Idea idea) { //Check if belongs to category return membershipDegree; if (idea.getValue() instanceof Integer) { int number = (int) idea.getValue(); if (number % 2 != 0) return(1.0); } return(0.0); } @Override public Idea getInstance(Idea constraints) { // Create an instance of the category based on constraints int number = new Random().nextInt(); Idea oddNumber = new Idea("odd_number",number*2+1); return(oddNumber); } }; return(odd); } public TestCategory() { // Creating a concept for even numbers evenIdea = new Idea("evenIdea",createEvenNumber(),"Property",2); // Creating a concept for odd numbers oddIdea = new Idea("oddIdea",createOddNumber(),"Property",2); } @Test public void testRawCategoryIdeas() { TestCategory tc = new TestCategory(); // Getting the category for even numbers Category even = (Category) tc.evenIdea.getValue(); // Getting the category for odd numbers Category odd = (Category) tc.oddIdea.getValue(); System.out.println("Testing the instantiation of 'even numbers' from raw Category ..."); for (int i=0;i<100;i++) { Idea newevennumber = even.getInstance(null); System.out.print(" "+newevennumber.getValue()); assertEquals(even.membership(newevennumber),1.0); assertEquals(odd.membership(newevennumber),0.0); } System.out.println("\nTesting the instantiation of 'odd numbers' from raw Category ..."); for (int i=0;i<100;i++) { Idea newoddnumber = odd.getInstance(null); System.out.print(" "+newoddnumber.getValue()); assertEquals(even.membership(newoddnumber),0.0); assertEquals(odd.membership(newoddnumber),1.0); } System.out.println("\nfinished !"); } @Test public void testCategoryIdeasDirect() { // Creating a category for even numbers TestCategory tc = new TestCategory(); System.out.println("Testing if indeed even and odd are categories"); assertEquals(tc.evenIdea.isCategory(),true); assertEquals(tc.oddIdea.isCategory(),true); Idea id = new Idea(); System.out.println("Testing if a complete new Idea is not a category"); assertEquals(id.isCategory(),false); System.out.println("Testing the instantiation of 'even numbers' from a category idea ..."); for (int i=0;i<100;i++) { Idea newevennumber = tc.evenIdea.getInstance(null); System.out.print(" "+newevennumber.getValue()); assertEquals(tc.evenIdea.membership(newevennumber),1.0); assertEquals(tc.oddIdea.membership(newevennumber),0.0); } System.out.println("\nTesting the instantiation of 'odd numbers' from a category idea ..."); for (int i=0;i<100;i++) { Idea newoddnumber = tc.oddIdea.getInstance(null); System.out.print(" "+newoddnumber.getValue()); assertEquals(tc.evenIdea.membership(newoddnumber),0.0); assertEquals(tc.oddIdea.membership(newoddnumber),1.0); } System.out.println("\nfinished !"); } private Category createInterval(int mi,int ma) { Category interval = new Category() { public int min=mi; public int max=ma; @Override public double membership(Idea idea) { //Check if belongs to category return membershipDegree; if (idea.getValue() instanceof Integer) { int number = (int) idea.getValue(); if (number >= min && number <= max) return(1.0); } return(0.0); } @Override public Idea getInstance(Idea constraints) { int minimum = min; int maximum = max; if (constraints != null) { for (Idea i : constraints.getL()) { if (i.getName().equals("min") && i.getValue() instanceof Integer && (int)i.getValue() > min) { minimum = (int) i.getValue(); } if (i.getName().equals("max") && i.getValue() instanceof Integer && (int)i.getValue() < max) { maximum = (int) i.getValue(); } } } // Create an instance of the category based on constraints Idea i; do { int number = new Random().nextInt(maximum-minimum+1)+minimum; i = new Idea("number",number); } while(membership(i) == 0); return(i); } }; return(interval); } @Test public void testParameterizedIdeas() { System.out.println("Testing the creation of interval (0,100) without constraints"); Category interval = createInterval(0,100); for (int i=0;i<100;i++) { Idea i1 = interval.getInstance(null); assertEquals(interval.membership(i1),1.0); System.out.print(" "+i1.getValue()); } Idea c1 = new Idea("min",10); Idea c2 = new Idea("max",20); Idea[] co = {c1, c2}; Idea constraint = new Idea("constraint"); constraint.add(c1); constraint.add(c2); System.out.println("\nTesting the creation of interval (0,100) with constraints (10,20)"); for (int i=0;i<100;i++) { Idea i1 = interval.getInstance(constraint); assertEquals(interval.membership(i1),1.0); System.out.print(" "+i1.getValue()); } System.out.println("\nfinished !"); System.out.println("Testing the creation of interval (0,100) with constraints (30,50)"); Idea inter = new Idea("interval",interval); inter.add(c1); inter.add(c2); c1.setValue(30); c2.setValue(50); for (int i=0;i<100;i++) { Idea i1 = inter.getInstance(); assertEquals(inter.membership(i1),1.0); System.out.print(" "+i1.getValue()); } System.out.println("\nfinished !"); } }
8,335
39.270531
118
java
cst
cst-master/src/test/java/br/unicamp/cst/representation/idea/TestHabit.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.representation.idea; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import java.util.ArrayList; import java.util.List; import java.util.Random; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * * @author rgudwin */ public class TestHabit { Idea incrementIdea; Idea decrementIdea; public TestHabit() { Habit increment = new Habit() { @Override public Idea exec(Idea idea) { //Check if belongs to category return membershipDegree; if (idea.getValue() instanceof Integer) { int number = (int) idea.getValue(); Idea modifiedIdea = new Idea("incremented",number+1); return(modifiedIdea); } return(null); } }; // Creating a habit of incrementing integer numbers incrementIdea = new Idea("evenIdea",increment,"Property",2); // Creating a category for odd numbers Habit decrement = new Habit() { @Override public Idea exec(Idea idea) { //Check if belongs to category return membershipDegree; if (idea.getValue() instanceof Integer) { int number = (int) idea.getValue(); Idea modifiedIdea = new Idea("incremented",number-1); return(modifiedIdea); } return(null); } }; // Creating a habit of decrementing integer numbers decrementIdea = new Idea("evenIdea",decrement,"Property",2); } @Test public void testHabitIdeas() { // Creating a category for even numbers TestHabit tc = new TestHabit(); Habit increment = (Habit) tc.incrementIdea.getValue(); Habit decrement = (Habit) tc.decrementIdea.getValue(); System.out.println("Creating and testing increment habits ..."); for (int i=0;i<100;i++) { int rnumber = new Random().nextInt(); Idea newnumber = new Idea("number",rnumber); Idea modnumber = increment.exec(newnumber); System.out.print(" "+newnumber.getValue()+"->"+modnumber.getValue()); int tt = (int) newnumber.getValue(); assertEquals(modnumber.getValue(),tt+1); } System.out.println("\nCreating and testing decrement habits ..."); for (int i=0;i<100;i++) { Idea newnumber = new Idea("number",new Random().nextInt()); Idea modnumber = decrement.exec(newnumber); System.out.print(" "+newnumber.getValue()+"->"+modnumber.getValue()); int tt = (int) newnumber.getValue(); assertEquals(modnumber.getValue(),tt-1); } System.out.println("\nfinished !"); } @Test public void testHabitIdeasDirect() { // Creating a category for even numbers TestHabit tc = new TestHabit(); System.out.println("Creating and testing increment habits from idea ..."); for (int i=0;i<100;i++) { int rnumber = new Random().nextInt(); Idea newnumber = new Idea("number",rnumber); Idea modnumber = tc.incrementIdea.exec(newnumber); System.out.print(" "+newnumber.getValue()+"->"+modnumber.getValue()); int tt = (int) newnumber.getValue(); assertEquals(modnumber.getValue(),tt+1); } System.out.println("\nCreating and testing decrement habits from idea..."); for (int i=0;i<100;i++) { Idea newnumber = new Idea("number",new Random().nextInt()); Idea modnumber = tc.decrementIdea.exec(newnumber); System.out.print(" "+newnumber.getValue()+"->"+modnumber.getValue()); int tt = (int) newnumber.getValue(); assertEquals(modnumber.getValue(),tt-1); } System.out.println("\nfinished !"); } @Test public void testHabitIdeasDirectWithOp0() { // Creating a category for even numbers TestHabit tc = new TestHabit(); System.out.println("Creating and testing increment habits using mind..."); for (int i=0;i<100;i++) { int rnumber = new Random().nextInt(); Idea orignumber = new Idea("number",rnumber); Idea modnumber = tc.incrementIdea.exec(orignumber); System.out.print(" "+orignumber.getValue()+"->"+modnumber.getValue()); int tt = (int) orignumber.getValue(); assertEquals(modnumber.getValue(),tt+1); } System.out.println("\nCreating and testing decrement habits using mind..."); for (int i=0;i<100;i++) { Idea newnumber = new Idea("number",new Random().nextInt()); Idea modnumber = tc.decrementIdea.exec(newnumber); System.out.print(" "+newnumber.getValue()+"->"+modnumber.getValue()); int tt = (int) newnumber.getValue(); assertEquals(modnumber.getValue(),tt-1); } System.out.println("\nfinished !"); } private Idea getRandomNumberIdea() { int rnumber = new Random().nextInt(); Idea orignumber = new Idea("number",rnumber); return(orignumber); } @Test public void testHabitExecutionerCodelet() { TestHabit tc = new TestHabit(); Idea id = new Idea(); assertEquals(id.isLeaf(),true); id.add(new Idea("leaf")); assertEquals(id.isLeaf(),false); assertEquals(id.isHabit(),false); assertEquals(tc.incrementIdea.isHabit(),true); assertEquals(tc.decrementIdea.isHabit(),true); Mind testMind = new Mind(); MemoryObject input_number = testMind.createMemoryObject("INPUT_NUMBER"); MemoryObject input_habit = testMind.createMemoryObject("INPUT_HABIT",tc.incrementIdea); MemoryObject output = testMind.createMemoryObject("OUTPUT_NUMBER"); Codelet c = new Codelet() { Idea input_number; Idea habit; MemoryObject output_mo; @Override public void accessMemoryObjects() { MemoryObject input1 = (MemoryObject) this.getInput("INPUT_NUMBER"); input_number = (Idea) input1.getI(); MemoryObject input2 = (MemoryObject) this.getInput("INPUT_HABIT"); habit = (Idea) input2.getI(); output_mo = (MemoryObject) this.getOutput("OUTPUT_NUMBER"); } @Override public void calculateActivation() { // not used } @Override public void proc() { Idea result = habit.exec(input_number); output_mo.setI(result); } }; c.addInput(input_number); c.addInput(input_habit); c.addOutput(output); c.setIsMemoryObserver(true); input_number.setI(getRandomNumberIdea()); input_number.addMemoryObserver(c); input_habit.addMemoryObserver(c); testMind.start(); for (int i=0;i<200;i++) { Idea orignumber = getRandomNumberIdea(); int rnumber = (int) orignumber.getValue(); input_number.setI(orignumber); int result = rnumber; while (result == rnumber) { Idea iresult = (Idea) output.getI(); result = (int) iresult.getValue(); } assertEquals(result,rnumber+1); } } }
8,221
39.502463
97
java
cst
cst-master/src/test/java/br/unicamp/cst/representation/idea/TestIdea.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.representation.idea; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import javax.swing.tree.DefaultMutableTreeNode; import br.unicamp.cst.core.profiler.TestComplexMemoryObjectInfo; import java.util.HashMap; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.Test; public class TestIdea { List<TestComplexMemoryObjectInfo> l; public Idea initialize() { Idea node = new Idea("Test","",0); node.add(new Idea("child1","",0)).add(new Idea("subchild1",3.14,1)).add(new Idea("subsubchild1","whatthe...")); double variable[] = new double[3]; node.add(new Idea("child2","I2",0)).add(new Idea("array",new double[]{3.4, 2.2, 1.23})); node.add(new Idea("child3",3.1416d,1)); node.add(new Idea("child4",null,2)); System.out.println(node.toStringFull()); return(node); } void print(String s,Idea o) { if (o != null) { if (o.getValue() != null) System.out.println("get(\""+s+"\") : "+o.getName()+" -> "+o.getValue().toString()); else System.out.println("get(\""+s+"\") : "+o.getName()+" -> null"); } else System.out.println("get(\""+s+"\") : "+"null"); } @Test public void testGet() { System.out.println("\n Starting the testGet ..."); Idea n = initialize(); Idea o = n.get("child1"); System.out.println(); print("child1",o); o = n.get("child1.subchild1"); print("child1.subchild1",o); o = n.get("child1.subchild1.subsubchild1"); print("child1.subchild1.subsubchild1",o); o = n.get("child2"); print("child2",o); o = n.get("child2.array"); print("child2.array",o); o = n.get("child3"); print("child3",o); o = n.get("child4"); print("child4",o); } @Test public void testIdea() { System.out.println("\n Starting the testIdea ..."); Idea ln = new Idea("a"); Idea ln2 = new Idea("b"); Idea ln3 = new Idea("c"); ln.add(ln2); ln2.add(ln3); Idea v1 = new Idea("v","3"); ln.add(v1); ln2.add(v1); ln3.add(v1); System.out.println(ln.toStringFull()); Date d = new Date(); Idea complexnode = Idea.createIdea("complexnode","",0); System.out.println("Adding the object date within complexnode"); complexnode.addObject(d,"complexnode.date"); DefaultMutableTreeNode dt = new DefaultMutableTreeNode(d); System.out.println("Adding the object defaultMutableTreeNode within complexnode"); complexnode.addObject(dt, "teste.defaultMutableTreeNode"); System.out.println("Adding the object complexnode within itself with the name recursion"); complexnode.addObject(complexnode,"complexnode.recursion"); //IdeaPanel wmp = new IdeaPanel(Idea.createIdea("Root","[S1]",0),true); System.out.println("Adding the object wmpanel within complexnode"); //complexnode.addObject(wmp, "complexnode.wmpanel"); TestComplexMemoryObjectInfo ttt = new TestComplexMemoryObjectInfo(); ttt.testbyte = 10; ttt.testshort = 0xa; ttt.testlong = 23; ttt.testint = 3; ttt.testfloat = 3.12f; ttt.testdouble = 3.21; ttt.testboolean = true; for (int i=0;i<ttt.testdoublearray.length;i++) ttt.testdoublearray[i] = i*0.1; for (int i=0;i<ttt.testfloatarray.length;i++) ttt.testfloatarray[i] = i*0.1f; for (int i=0;i<ttt.testlongarray.length;i++) ttt.testlongarray[i] = i*2; for (int i=0;i<ttt.testintarray.length;i++) ttt.testintarray[i] = i*2; for (short i=0;i<ttt.testshortarray.length;i++) ttt.testshortarray[i] = i; for (byte i=0;i<ttt.testbytearray.length;i++) ttt.testbytearray[i] = i; System.out.println("Adding the object complex within complexnode"); complexnode.addObject(ttt,"complexnode.complex"); System.out.println("Finished creation of objects"); System.out.println(complexnode.toStringFull()); TestComplexMemoryObjectInfo returned = (TestComplexMemoryObjectInfo) complexnode.getObject("complex", "br.unicamp.cst.core.profiler.TestComplexMemoryObjectInfo"); System.out.println("Recovered object: "+returned.toString()); System.out.println("Returned: "+returned.testdate); System.out.println("ttt: "+ttt.testdate); System.out.println("ttt: "+ttt); System.out.println("returned: "+returned); System.out.println("returned.equals(ttt): "+returned.equals(ttt)); assertEquals(returned.equals(ttt),0); double[] nt = new double[3]; nt[0] = 1.2; nt[1] = 2.3; nt[2] = 3.1; Idea i_nt = Idea.createIdea("novo","", 0); i_nt.addObject(nt,"d"); System.out.println(i_nt.toStringFull()); double[] ntr = (double[]) i_nt.getObject("d","double[]"); System.out.println("nt: "+nt[0]+" "+nt[1]+" "+nt[2]); l = new ArrayList<TestComplexMemoryObjectInfo>(); l.add(new TestComplexMemoryObjectInfo()); l.add(new TestComplexMemoryObjectInfo()); l.add(new TestComplexMemoryObjectInfo()); l.get(1).complextestlist2.set(0, 7.88); l.get(1).complextestlist2.set(1, 8.88); l.get(2).complextestlist2.set(0, 5.44); l.get(2).complextestlist2.set(1, 6.44); System.out.println("Testing if complextestlist2 is there ..."+l.get(1).complextestlist2.get(0)+" "+l.get(2).complextestlist2.get(1)); Idea node = Idea.createIdea("root","", 0); Field stringListField=null; try {stringListField = TestIdea.class.getDeclaredField("l");} catch(Exception e) { e.printStackTrace();} ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType(); Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0]; System.out.println("Classe: "+l.getClass().getTypeParameters()+" "+stringListClass.getCanonicalName()); node.reset(); node.addObject(l,"lista"); System.out.println(node.toStringFull(true)); TestComplexMemoryObjectInfo[] l2 = (TestComplexMemoryObjectInfo[]) node.getObject("lista", "br.unicamp.cst.core.profiler.TestComplexMemoryObjectInfo[]"); if (l2.length == 3) System.out.println("Yes ! I got 3 objects !!!"); List<TestComplexMemoryObjectInfo> l3; if (l2 != null) l3 = Arrays.asList(l2); else System.out.println("Unfortunately I was not able to recover the list"); List<String> ls = new ArrayList<>(); for (String s : Idea.repo.keySet()) { ls.add(s); } Collections.sort(ls); for (String s : ls) { System.out.println(s); } } /* 0 - AbstractObject * 1 - Property * 2 - Link or Reference to another Idea * 3 - QualityDimension * 4 - Episode * 5 - Composite * 6 - Aggregate * 7 - Configuration * 8 - TimeStep * 9 - PropertyCategory * 10 - ObjectCategory * 11 - EpisodeCategory */ @Test public void testIdea2() { Idea idea = new Idea("idea","idea","AbstractObject",1); assertEquals(idea.getType(),0); idea = new Idea("idea","idea","Property",1); assertEquals(idea.getType(),1); idea = new Idea("idea","idea","Link",1); assertEquals(idea.getType(),2); idea = new Idea("idea","idea","QualityDimension",1); assertEquals(idea.getType(),3); idea = new Idea("idea","idea","Episode",1); assertEquals(idea.getType(),4); idea = new Idea("idea","idea","Composite",1); assertEquals(idea.getType(),5); idea = new Idea("idea","idea","Aggregate",1); assertEquals(idea.getType(),6); idea = new Idea("idea","idea","Configuration",1); assertEquals(idea.getType(),7); idea = new Idea("idea","idea","TimeStep",1); assertEquals(idea.getType(),8); idea = new Idea("idea","idea","Property",2); assertEquals(idea.getType(),9); idea = new Idea("idea","idea","AbstractObject",2); assertEquals(idea.getType(),10); idea = new Idea("idea","idea","Episode",2); assertEquals(idea.getType(),11); idea = new Idea("idea","idea","Property",0); assertEquals(idea.getType(),12); idea = new Idea("idea","idea","AbstractObject",0); assertEquals(idea.getType(),13); idea = new Idea("idea","idea","Episode",0); assertEquals(idea.getType(),14); idea = new Idea("idea","idea","Action",0); assertEquals(idea.getType(),15); idea = new Idea("idea","idea","Action",1); assertEquals(idea.getType(),16); idea = new Idea("idea","idea","Action",2); assertEquals(idea.getType(),17); idea = new Idea("idea","idea","Goal",0); assertEquals(idea.getType(),18); idea = new Idea("idea","idea",0,"Episode",0); idea.setCategory("Property"); idea.setScope(1); assertEquals(idea.getCategory().equalsIgnoreCase("Property"),true); assertEquals(idea.getScope(),1); assertEquals(Idea.guessType(null, 0),0); } @Test public void testIsMethods() { Idea i = new Idea(); i.setName("test"); assertEquals(i.getName(),"test"); i.setValue(null); assertEquals(i.getValue(),null); assertEquals(i.isLong(),false); assertEquals(i.isBoolean(),false); assertEquals(i.isInteger(),false); assertEquals(i.isString(),false); assertEquals(i.isHashMap(),false); assertEquals(i.isNumber(),false); assertEquals(i.getInstance(),null); assertEquals(i.membership(null),0.0); assertEquals(i.exec(null),null); i.setValue(1D); assertEquals(i.isDouble(),true); assertEquals(i.isNumber(),true); assertEquals(i.isInteger(),false); assertEquals(i.isBoolean(),false); assertEquals(i.isString(),false); assertEquals(i.isHashMap(),false); assertEquals(i.getResumedValue()," 1.0"); i.setValue(1F); assertEquals(i.isFloat(),true); assertEquals(i.isNumber(),true); assertEquals(i.getResumedValue()," 1.0"); i.setValue(1L); assertEquals(i.isLong(),true); assertEquals(i.isNumber(),true); assertEquals(i.getResumedValue(),"1"); i.setValue(true); assertEquals(i.isBoolean(),true); i.setValue(1); assertEquals(i.isInteger(),true); assertEquals(i.isNumber(),true); assertEquals(i.getResumedValue(),"1"); i.setValue(""); assertEquals(i.isString(),true); i.setValue(new HashMap()); assertEquals(i.isHashMap(),true); assertEquals(i.isType(0),true); i.setType(1); assertEquals(i.isType(0),false); assertEquals(i.isType(1),true); } @Test public void cloneTest() { Idea i = new Idea("test","value",12,"category",2); long n1,n2,n3,n4,n5,n6; n1 = i.getId(); Idea sub1 = new Idea("sub","value1",13,"category1",1); n2 = sub1.getId(); Idea sub2 = new Idea("sub2","value2",14,"category2",0); n3 = sub2.getId(); assertNotEquals(n1,n2); assertNotEquals(n1,n3); assertNotEquals(n2,n3); i.add(sub1); sub1.add(sub2); Idea i2 = i.clone(); n4 = i2.getId(); assertEquals(i2.getName(),"test"); assertEquals(i2.getValue(),"value"); assertEquals(i2.getType(),12); assertEquals(i2.getCategory(),"category"); assertEquals(i2.getScope(),2); assertEquals(i2.toString(),"test"); Idea i3 = i2.get("sub"); n5 = i3.getId(); assertEquals(i3.getName(),"sub"); assertEquals(i3.getValue(),"value1"); assertEquals(i3.getType(),13); assertEquals(i3.getCategory(),"category1"); assertEquals(i3.getScope(),1); i3 = i2.get("sub.sub2"); n6 = i3.getId(); assertEquals(i3.getName(),"sub2"); assertEquals(i3.getValue(),"value2"); assertEquals(i3.getType(),14); assertEquals(i3.getCategory(),"category2"); assertEquals(i3.getScope(),0); assertNotEquals(n1,n4); assertNotEquals(n2,n5); assertNotEquals(n3,n6); i3 = i2.get("what?"); assertEquals(i3,null); } @Test public void testSetL() { Idea i = new Idea(); Idea i2 = new Idea("sub1"); Idea i3 = new Idea("sub2"); List<Idea> l = new ArrayList<>(); l.add(i2); l.add(i3); i.setL(l); assertEquals(i.get("sub1"),i2); assertEquals(i.get("sub2"),i3); } @Test public void testConvertStringValue() { Idea i = new Idea("test","2"); assertEquals(i.getValue(),2); i = new Idea("test","3.0"); assertEquals(i.getValue(),3.0); } @Test public void testCreateIdea() { Idea i = Idea.createIdea("test", l, 0); Idea i2 = Idea.createIdea("test", l, 1); Idea i3 = Idea.createIdea("test", l, 1); Idea i4 = Idea.createIdea("test", l, 1); assertNotEquals(i,i2); assertEquals(i2,i3); assertEquals(i2,i4); System.out.println("REPO: "); Idea.repo.forEach((key, value) -> { System.out.println("Key=" + key + ", Value=" + value.getName()+","+value.getType()); }); } @Test public void testCreateJavaObject() { double d = (double) Idea.createJavaObject("java.lang.Double"); assertEquals(d,0); float f = (float) Idea.createJavaObject("java.lang.Float"); assertEquals(f,0); int i = (int) Idea.createJavaObject("java.lang.Integer"); assertEquals(i,0); long l = (long) Idea.createJavaObject("java.lang.Long"); assertEquals(l,0); short s = (short) Idea.createJavaObject("java.lang.Short"); assertEquals(s,0); boolean b = (boolean) Idea.createJavaObject("java.lang.Boolean"); assertEquals(b,false); byte by = (byte) Idea.createJavaObject("java.lang.Byte"); assertEquals(by,0); Object o = Idea.createJavaObject("whatever"); assertEquals(o,null); } }
15,388
39.497368
170
java
cst
cst-master/src/test/java/br/unicamp/cst/representation/owrl/AbstractObjectTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.representation.owrl; import org.junit.jupiter.api.Test; /** * Created by du on 30/05/17. */ public class AbstractObjectTest { public void setUp() { System.out.println("########## AFFORDANCE TESTS ##########"); } @Test public void testDynamicAffordanceDetect() { //------------- Objeto 1 -------------------------- AbstractObject robot = new AbstractObject("Robot"); AbstractObject sensor = new AbstractObject("Sensor"); Property position = new Property("position"); position.addQualityDimension(new QualityDimension("x", 0.5)); position.addQualityDimension(new QualityDimension("y", 0.6)); sensor.addProperty(position); robot.addCompositePart(sensor); Property color = new Property("Color"); color.addQualityDimension(new QualityDimension("R", 255.0)); color.addQualityDimension(new QualityDimension("G", 0.0)); color.addQualityDimension(new QualityDimension("B", 0.0)); robot.addProperty(color); AbstractObject actuator = new AbstractObject("Actuator"); actuator.addProperty(new Property("velocity", new QualityDimension("intensity", -0.12))); robot.addCompositePart(actuator); AbstractObject sonar = new AbstractObject("Sonar"); sonar.addProperty(new Property("Distance", new QualityDimension("value", 215.0))); robot.addAggregatePart(sonar); AbstractObject gps = new AbstractObject("GPS"); Property coordinates = new Property("Coordinates"); coordinates.addQualityDimension(new QualityDimension("x", 12.0)); coordinates.addQualityDimension(new QualityDimension("y", 76.0)); coordinates.addQualityDimension(new QualityDimension("z", 50.0)); gps.addProperty(coordinates); robot.addAggregatePart(gps); //------------- Objeto 2 -------------------------- AbstractObject robot2 = new AbstractObject("Robot1"); Property newcolor = new Property("Color"); newcolor.addQualityDimension(new QualityDimension("R", 0.0)); newcolor.addQualityDimension(new QualityDimension("G", 255.0)); newcolor.addQualityDimension(new QualityDimension("B", 255.0)); robot2.addProperty(newcolor); AbstractObject actuator1 = new AbstractObject("Actuator"); actuator1.addProperty(new Property("velocity", new QualityDimension("intensity", -0.12))); robot2.addCompositePart(actuator1); AbstractObject temperatureSensor = new AbstractObject("Temperature Sensor"); temperatureSensor.addProperty(new Property("temperature", new QualityDimension("value", 35.0))); robot2.addCompositePart(temperatureSensor); AbstractObject radio = new AbstractObject("Radio"); radio.addProperty(new Property("frequency", new QualityDimension("value", 89.9))); robot2.addAggregatePart(radio); AbstractObject gps1 = new AbstractObject("GPS"); Property coordinates1 = new Property("Coordinates"); coordinates1.addQualityDimension(new QualityDimension("x", 12.0)); coordinates1.addQualityDimension(new QualityDimension("y", 88.0)); coordinates1.addQualityDimension(new QualityDimension("z", 50.0)); gps1.addProperty(coordinates1); robot2.addAggregatePart(gps1); //------------- Objeto 3 -------------------------- AbstractObject robot3 = new AbstractObject("Robot2"); Property colorRobot3 = new Property("Color"); colorRobot3.addQualityDimension(new QualityDimension("R", 254.0)); colorRobot3.addQualityDimension(new QualityDimension("G", 200.0)); colorRobot3.addQualityDimension(new QualityDimension("B", 255.0)); robot3.addProperty(colorRobot3); AbstractObject actuator2 = new AbstractObject("Actuator"); actuator2.addProperty(new Property("velocity", new QualityDimension("intensity", -0.22))); robot3.addCompositePart(actuator2); AbstractObject temperatureSensor1 = new AbstractObject("Temperature Sensor"); temperatureSensor1.addProperty(new Property("temperature", new QualityDimension("value", 32.0))); robot3.addCompositePart(temperatureSensor1); AbstractObject radio1 = new AbstractObject("Radio"); radio1.addProperty(new Property("frequency", new QualityDimension("value", 89.9))); robot3.addAggregatePart(radio1); AbstractObject gps2 = new AbstractObject("GPS"); Property coordinates2 = new Property("Coordinates"); coordinates2.addQualityDimension(new QualityDimension("x", 12.0)); coordinates2.addQualityDimension(new QualityDimension("y", 80.0)); coordinates2.addQualityDimension(new QualityDimension("z", 50.0)); gps2.addProperty(coordinates2); robot3.addAggregatePart(gps2); // Este teste a seguir gera uma falha no JDK11, devido a um bug na linha 160 da classe CodeBuilder // A partir do JDK 9, o método Class.newInstance() foi deprecado, gerando um null ao invés de uma instância da classe //robot.discoveryAffordance(robot3, Arrays.asList(robot2, robot3)); System.out.println("Dynamic Affordance Created ----> OK"); } }
5,873
43.165414
125
java
cst
cst-master/src/test/java/br/unicamp/cst/sensory/ATest.java
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package br.unicamp.cst.sensory; import br.unicamp.cst.core.entities.Codelet; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import br.unicamp.cst.support.TimeStamp; import java.util.concurrent.CopyOnWriteArrayList; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * * @author rgudwin */ public class ATest { public MemoryObject source; public MemoryObject destination; public Codelet cod; public int steps=0; public ATest() { cod = new Codelet() { @Override public void accessMemoryObjects() { } @Override public void proc() { System.out.println("steps: "+steps+" "+TimeStamp.getTimeSinceStart("HH:mm:ss.SSS")); steps++; } @Override public void calculateActivation() { } }; Mind testMind = new Mind(); source = testMind.createMemoryObject("SOURCE"); destination = testMind.createMemoryObject("COMB_FM"); destination.setI(new CopyOnWriteArrayList<Float>()); CopyOnWriteArrayList<String> FMnames = new CopyOnWriteArrayList<>(); testMind.insertCodelet(cod); cod.addInput(source); cod.addOutput(destination); cod.setIsMemoryObserver(true); source.addMemoryObserver(cod); testMind.start(); } @Test public void testATest() { TimeStamp.setStartTime(); ATest test = new ATest(); System.out.println("waiting 2s before calling setI"); try { Thread.sleep(2000);} catch (Exception e) {} System.out.println("calling setI"); test.source.setI((1)); while(TimeStamp.getTimeSinceStart() < 2500) { System.out.println("Testing ... "+test.steps+" "+TimeStamp.getTimeSinceStart("HH:mm:ss.SSS")+" "+TimeStamp.getTimeSinceStart()); } } }
2,162
28.630137
140
java
cst
cst-master/src/test/java/br/unicamp/cst/sensory/SensorBufferCodeletTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation ***********************************************************************************************/ package br.unicamp.cst.sensory; import br.unicamp.cst.core.entities.Memory; import br.unicamp.cst.core.entities.MemoryObject; import br.unicamp.cst.core.entities.Mind; import br.unicamp.cst.support.TimeStamp; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Test for Codelet implementation of SensorBuffers. In order to obtain data observation * to generate the feature maps for each dimension that will be used to compute * salience, a temporal window of data have to be stored. * @author L. L. Rossi (leolellisr) */ public class SensorBufferCodeletTest { public MemoryObject source; public MemoryObject destination; public final void printList(List l) { for (int i=0;i<l.size();i++) { Memory mo = (Memory) l.get(i); System.out.print(mo.getI()+" "); } System.out.print("\n"); } public SensorBufferCodeletTest() { Mind testMind = new Mind(); source = testMind.createMemoryObject("SOURCE"); //source.setI(0); destination = testMind.createMemoryObject("DESTINATION"); destination.setI(new ArrayList<Integer>()); SensorBufferCodelet testSensorBufferCodelet = new SensorBufferCodelet("SOURCE", "DESTINATION", 32); testMind.insertCodelet(testSensorBufferCodelet); testSensorBufferCodelet.addInput(source); testSensorBufferCodelet.addOutput(destination); testSensorBufferCodelet.setIsMemoryObserver(true); source.addMemoryObserver(testSensorBufferCodelet); testMind.start(); //List fulllist = (List)destination.getI(); } @Test public void testSensoryBufferCodelet() { SensorBufferCodeletTest test = new SensorBufferCodeletTest(); for (int i=0;i<64;i++) { System.out.println("Testing ... "+i); long oldtimestamp = test.destination.getTimestamp(); System.out.println("Timestamp before: "+TimeStamp.getStringTimeStamp(oldtimestamp, "dd/MM/yyyy HH:mm:ss.SSS")); test.source.setI(i); long newtimestamp = test.destination.getTimestamp(); while(newtimestamp == oldtimestamp) { newtimestamp = test.destination.getTimestamp(); System.out.println("Timestamp after: "+TimeStamp.getStringTimeStamp(newtimestamp,"dd/MM/yyyy HH:mm:ss.SSS")); } //try{Thread.sleep(300);}catch(Exception e){e.printStackTrace();} System.out.println(" Input: "+test.source.getI()); System.out.print(" Output: "); List fulllist = (List)test.destination.getI(); if (fulllist != null && fulllist.size() > 0) { printList(fulllist); System.out.println(" size: "+((List)(test.destination.getI())).size()+"\n"); MemoryObject first = (MemoryObject)fulllist.get(0); int firsti = (int)(first.getI()); MemoryObject last = (MemoryObject)fulllist.get(fulllist.size()-1); int lasti = (int)(last.getI()); assertEquals(lasti-firsti,fulllist.size()-1); } } } // This class contains tests covering some core Codelet methods // This method is used to generate a new Codelet // SensorBufferCodelet generateSensorBufferCodelet() { // // SensorBufferCodelet testSensorBufferCodelet = new SensorBufferCodelet("test name", "test buffer name", 32) { // // @Override // public void accessMemoryObjects() {} // // // // @Override // public void proc() { // System.out.println("proc method in SensorBufferCodeletTest ran correctly!"); // } // @Override // public void calculateActivation() {} // // // }; // return(testSensorBufferCodelet); // } }
4,589
37.898305
125
java
cst
cst-master/src/test/java/br/unicamp/cst/support/TimeStampTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation * **********************************************************************************************/ package br.unicamp.cst.support; import org.junit.jupiter.api.Test; /** * @author gudwin * */ public class TimeStampTest { @Test public void testTimeStamp() { TimeStamp.setStartTime(); try { Thread.sleep(3358); } catch (Exception e) { e.printStackTrace(); } System.out.println(TimeStamp.getDelaySinceStart()); } }
934
27.333333
98
java
cst
cst-master/src/test/java/br/unicamp/cst/support/ToStringTest.java
/*********************************************************************************************** * Copyright (c) 2012 DCA-FEEC-UNICAMP * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * <p> * Contributors: * K. Raizer, A. L. O. Paraense, E. M. Froes, R. R. Gudwin - initial API and implementation * **********************************************************************************************/ package br.unicamp.cst.support; import java.util.Date; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * * @author rgudwin */ public class ToStringTest { @Test public void testFrom() { Object o = null; String s = ToString.from(o); assertEquals(s,"<NULL>"); long l = 0l; s = ToString.from(l); assertEquals(s,"0"); int i = 0; s = ToString.from(i); assertEquals(s,"0"); float f = 0f; s = ToString.from(f); assertEquals(s,"0.00"); double d = 0d; s = ToString.from(d); assertEquals(s,"0.00"); byte by = 0; s = ToString.from(by); assertEquals(s,"0"); boolean boo = true; s = ToString.from(boo); assertEquals(s,"true"); boo = false; s = ToString.from(boo); assertEquals(s,"false"); long now = System.currentTimeMillis(); Date date = new Date(now); s = ToString.from(date); assertEquals(s,TimeStamp.getStringTimeStamp(now,"dd/MM/yyyy HH:mm:ss.SSS")); o = new Object(); s = ToString.from(o); assertEquals(s,null); } @Test public void testEl() { String s = ToString.el("Test",15); assertEquals(s,"Test[15]"); } }
1,958
29.609375
98
java
Unified-Normalization
Unified-Normalization-master/neural_machine_translation/data_preprocessing/third_party/mosesdecoder/contrib/lmserver/examples/LMClient.java
import java.io.DataInputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.URI; import java.net.URISyntaxException; public class LMClient { private Socket sock; private DataInputStream input; private OutputStreamWriter output; public LMClient(URI u) throws IOException { sock = new Socket(u.getHost(), u.getPort()); System.err.println(sock); input = new DataInputStream(sock.getInputStream()); output = new OutputStreamWriter(sock.getOutputStream(), "UTF8"); } public float wordLogProb(String word, String context) throws IOException { return wordLogProb(word, context.split("\\s+")); } public float wordLogProb(String word, String[] context) throws IOException { StringBuffer sb = new StringBuffer(); sb.append("prob "); sb.append(word); for (int i = context.length-1; i >= 0; --i) { sb.append(' ').append(context[i]); } sb.append("\r\n"); output.write(sb.toString()); output.flush(); byte b1 = input.readByte(); byte b2 = input.readByte(); byte b3 = input.readByte(); byte b4 = input.readByte(); Float f = Float.intBitsToFloat( (((b4 & 0xff) << 24) | ((b3 & 0xff) << 16) | ((b2 & 0xff) << 8) | (b1 & 0xff)) ); input.readByte(); input.readByte(); return f; } public static void main(String[] args) { try { LMClient lm = new LMClient(new URI("lm://csubmit02.umiacs.umd.edu:6666")); System.err.println(lm.wordLogProb("want", "<s> the old man")); System.err.println(lm.wordLogProb("wants", "<s> the old man")); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
1,659
28.642857
115
java
Unified-Normalization
Unified-Normalization-master/neural_machine_translation/data_preprocessing/third_party/mosesdecoder/contrib/server/SampleClient.java
// // Java Sample client for mosesserver (Created by Marwen AZOUZI) // The XML-RPC libraries are available at Apache (http://ws.apache.org/xmlrpc/) // import java.util.HashMap; import java.net.URL; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; public class SampleClient { public static void main(String[] args) { try { // Create an instance of XmlRpcClient XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(new URL("http://localhost:8080/RPC2")); XmlRpcClient client = new XmlRpcClient(); client.setConfig(config); // The XML-RPC data type used by mosesserver is <struct>. In Java, this data type can be represented using HashMap. HashMap<String,String> mosesParams = new HashMap<String,String>(); String textToTranslate = new String("some text to translate ."); mosesParams.put("text", textToTranslate); mosesParams.put("align", "true"); mosesParams.put("report-all-factors", "true"); // The XmlRpcClient.execute method doesn't accept Hashmap (pParams). It's either Object[] or List. Object[] params = new Object[] { null }; params[0] = mosesParams; // Invoke the remote method "translate". The result is an Object, convert it to a HashMap. HashMap result = (HashMap)client.execute("translate", params); // Print the returned results String textTranslation = (String)result.get("text"); System.out.println("Input : "+textToTranslate); System.out.println("Translation : "+textTranslation); if (result.get("align") != null){ Object[] aligns = (Object[])result.get("align"); System.out.println("Phrase alignments : [Source Start:Source End][Target Start]"); for ( Object element : aligns) { HashMap align = (HashMap)element; System.out.println("["+align.get("src-start")+":"+align.get("src-end")+"]["+align.get("tgt-start")+"]"); } } } catch (Exception e) { e.printStackTrace(); } } }
2,020
42
118
java
Unified-Normalization
Unified-Normalization-master/neural_machine_translation/data_preprocessing/third_party/mosesdecoder/contrib/server/Translation-web/src/java/com/hpl/mt/Translate.java
package com.hpl.mt; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.xmlrpc.XmlRpcException; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; /** * * @author ulanov */ public class Translate extends HttpServlet { /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); System.out.println("before" + request.getCharacterEncoding()); request.setCharacterEncoding("UTF-8"); System.out.println("after" + request.getCharacterEncoding()); PrintWriter out = response.getWriter(); try { /* * TODO output your page here. You may use following sample code. */ // Create an instance of XmlRpcClient String textToTranslate = request.getParameter("text"); XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(new URL("http://localhost:9008/RPC2")); XmlRpcClient client = new XmlRpcClient(); client.setConfig(config); // The XML-RPC data type used by mosesserver is <struct>. In Java, this data type can be represented using HashMap. HashMap<String,String> mosesParams = new HashMap<String,String>(); mosesParams.put("text", textToTranslate); mosesParams.put("align", "true"); mosesParams.put("report-all-factors", "true"); // The XmlRpcClient.execute method doesn't accept Hashmap (pParams). It's either Object[] or List. Object[] params = new Object[] { null }; params[0] = mosesParams; // Invoke the remote method "translate". The result is an Object, convert it to a HashMap. HashMap result; try { result = (HashMap)client.execute("translate", params); } catch (XmlRpcException ex) { Logger.getLogger(Translate.class.getName()).log(Level.SEVERE, null, ex); throw new IOException("XML-RPC failed"); } // Print the returned results String textTranslation = (String)result.get("text"); System.out.println("Input : "+textToTranslate); System.out.println("Translation : "+textTranslation); out.write(textTranslation); if (result.get("align") != null){ Object[] aligns = (Object[])result.get("align"); System.out.println("Phrase alignments : [Source Start:Source End][Target Start]"); for ( Object element : aligns) { HashMap align = (HashMap)element; System.out.println("["+align.get("src-start")+":"+align.get("src-end")+"]["+align.get("tgt-start")+"]"); } } } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
5,216
39.130769
136
java
WALA
WALA-master/cast/java/ecj/src/main/java/com/ibm/wala/cast/java/client/ECJJavaSourceAnalysisEngine.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.client; import com.ibm.wala.cast.java.translator.jdt.ecj.ECJClassLoaderFactory; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.util.config.SetOfClasses; public class ECJJavaSourceAnalysisEngine extends JavaSourceAnalysisEngine { @Override protected ClassLoaderFactory getClassLoaderFactory(SetOfClasses exclusions) { return new ECJClassLoaderFactory(exclusions); } }
804
32.541667
79
java
WALA
WALA-master/cast/java/ecj/src/main/java/com/ibm/wala/cast/java/ecj/util/SourceDirCallGraph.java
package com.ibm.wala.cast.java.ecj.util; import com.ibm.wala.cast.ir.ssa.AstIRFactory; import com.ibm.wala.cast.java.client.impl.ZeroOneContainerCFABuilderFactory; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.cast.java.translator.jdt.ecj.ECJClassLoaderFactory; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.SourceDirectoryTreeModule; import com.ibm.wala.classLoader.SourceFileModule; import com.ibm.wala.core.util.warnings.Warnings; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisOptions.ReflectionOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.CallGraphBuilderCancelException; import com.ibm.wala.ipa.callgraph.CallGraphStats; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.properties.WalaProperties; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.io.CommandLine; import java.io.File; import java.io.IOException; import java.util.Properties; import java.util.jar.JarFile; /** * Driver that constructs a call graph for an application specified as a directory of source code. * Example of using the JDT front-end based on ECJ. Useful for getting some code to copy-paste. */ public class SourceDirCallGraph { @FunctionalInterface public interface Processor { void process(CallGraph CG, CallGraphBuilder<?> builder, long time); } /** * Usage: SourceDirCallGraph -sourceDir file_path -mainClass class_name * * <p>If given -mainClass, uses main() method of class_name as entrypoint. Class name should start * with an 'L'. * * <p>Example args: -sourceDir /tmp/srcTest -mainClass LFoo */ public static void main(String[] args) throws ClassHierarchyException, IllegalArgumentException, CallGraphBuilderCancelException, IOException { new SourceDirCallGraph() .doit( args, (cg, builder, time) -> { System.out.println("done"); System.out.println("took " + time + "ms"); System.out.println(CallGraphStats.getStats(cg)); }); } protected ClassLoaderFactory getLoaderFactory(AnalysisScope scope) { return new ECJClassLoaderFactory(scope.getExclusions()); } public void doit(String[] args, Processor processor) throws ClassHierarchyException, IllegalArgumentException, CallGraphBuilderCancelException, IOException { long start = System.currentTimeMillis(); Properties p = CommandLine.parse(args); String sourceDir = p.getProperty("sourceDir"); String mainClass = p.getProperty("mainClass"); AnalysisScope scope = new JavaSourceAnalysisScope(); // add standard libraries to scope String[] stdlibs = WalaProperties.getJ2SEJarFiles(); for (String stdlib : stdlibs) { scope.addToScope(ClassLoaderReference.Primordial, new JarFile(stdlib)); } // add the source directory File root = new File(sourceDir); if (root.isDirectory()) { scope.addToScope(JavaSourceAnalysisScope.SOURCE, new SourceDirectoryTreeModule(root)); } else { String srcFileName = sourceDir.substring(sourceDir.lastIndexOf(File.separator) + 1); assert root.exists() : "couldn't find " + sourceDir; scope.addToScope( JavaSourceAnalysisScope.SOURCE, new SourceFileModule(root, srcFileName, null)); } // build the class hierarchy IClassHierarchy cha = ClassHierarchyFactory.make(scope, getLoaderFactory(scope)); System.out.println(cha.getNumberOfClasses() + " classes"); System.out.println(Warnings.asString()); Warnings.clear(); AnalysisOptions options = new AnalysisOptions(); Iterable<Entrypoint> entrypoints = getEntrypoints(mainClass, cha); options.setEntrypoints(entrypoints); options.getSSAOptions().setDefaultValues(SymbolTable::getDefaultValue); // you can dial down reflection handling if you like options.setReflectionOptions(ReflectionOptions.NONE); IAnalysisCacheView cache = new AnalysisCacheImpl(AstIRFactory.makeDefaultFactory(), options.getSSAOptions()); // CallGraphBuilder builder = new ZeroCFABuilderFactory().make(options, cache, // cha, scope, // false); CallGraphBuilder<?> builder = new ZeroOneContainerCFABuilderFactory().make(options, cache, cha); System.out.println("building call graph..."); CallGraph cg = builder.makeCallGraph(options, null); long end = System.currentTimeMillis(); processor.process(cg, builder, end - start); } protected Iterable<Entrypoint> getEntrypoints(String mainClass, IClassHierarchy cha) { Iterable<Entrypoint> entrypoints = Util.makeMainEntrypoints(JavaSourceAnalysisScope.SOURCE, cha, new String[] {mainClass}); return entrypoints; } }
5,276
41.556452
100
java
WALA
WALA-master/cast/java/ecj/src/main/java/com/ibm/wala/cast/java/translator/jdt/FakeExceptionTypeBinding.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * WALA JDT Frontend is Copyright (c) 2008 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.cast.java.translator.jdt; import com.ibm.wala.util.debug.Assertions; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.dom.IAnnotationBinding; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.IPackageBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; /** * This is a hack to get around the fact that AST.resolveWellKnownTypes() doesn't know about some * implicitly declared exceptions, such as ArithmeticException (implicitly thrown in a division * operation) and NullPointerException (implicitly thrown in a field access). We need to know the * lineage of these types to determine possible catch targets. * * @author evan */ public class FakeExceptionTypeBinding implements ITypeBinding { public static final FakeExceptionTypeBinding arithmetic = new FakeExceptionTypeBinding("Ljava/lang/ArithmeticException;"); public static final FakeExceptionTypeBinding nullPointer = new FakeExceptionTypeBinding("Ljava/lang/NullPointerException;"); public static final FakeExceptionTypeBinding classCast = new FakeExceptionTypeBinding("Ljava/lang/ClassCastException;"); public static final FakeExceptionTypeBinding noClassDef = new FakeExceptionTypeBinding("Ljava/lang/NoClassDefFoundError;"); public static final FakeExceptionTypeBinding initException = new FakeExceptionTypeBinding("Ljava/lang/ExceptionInInitializerError;"); public static final FakeExceptionTypeBinding outOfMemory = new FakeExceptionTypeBinding("Ljava/lang/OutOfMemoryError;"); private final String exceptionBinaryName; private FakeExceptionTypeBinding(String exceptionBinaryName) { this.exceptionBinaryName = exceptionBinaryName; } @Override public boolean isAssignmentCompatible(ITypeBinding variableType) { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean equals(Object o) { if (o instanceof FakeExceptionTypeBinding) return this == o; if (o instanceof ITypeBinding) return ((ITypeBinding) o).getBinaryName().equals(exceptionBinaryName); return false; } @Override public int hashCode() { return exceptionBinaryName.hashCode(); } // --- rest not needed @Override public ITypeBinding createArrayType(int dimension) { Assertions.UNREACHABLE("FakeExceptionTypeBinding createArrayType"); return null; } @Override public String getBinaryName() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding getBound() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding getComponentType() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public IVariableBinding[] getDeclaredFields() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public IMethodBinding[] getDeclaredMethods() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @SuppressWarnings("deprecation") @Override public int getDeclaredModifiers() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return 0; } @Override public ITypeBinding[] getDeclaredTypes() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding getDeclaringClass() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public IMethodBinding getDeclaringMethod() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public int getDimensions() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return 0; } @Override public ITypeBinding getElementType() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding getErasure() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding[] getInterfaces() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public int getModifiers() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return 0; } @Override public String getName() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public IPackageBinding getPackage() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public String getQualifiedName() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding getSuperclass() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding[] getTypeArguments() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding[] getTypeBounds() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding getTypeDeclaration() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding[] getTypeParameters() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public ITypeBinding getWildcard() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public boolean isAnnotation() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isAnonymous() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isArray() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isCapture() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isCastCompatible(ITypeBinding type) { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isClass() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isEnum() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } /** * This overrides a method introduced in recent versions of the {@code ITypeBinding} interface to * handle records. We omit the {@code @Override} annotation to allow building against earlier * versions of {@code org.eclipse.jdt.core}, where {@code ITypeBinding} does not contain this * method. */ public boolean isRecord() { return false; } @Override public boolean isFromSource() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isGenericType() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isInterface() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } // add @Override here once Eclipse Mars is no longer supported public boolean isIntersectionType() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isLocal() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isMember() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isNested() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isNullType() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isParameterizedType() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isPrimitive() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isRawType() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isSubTypeCompatible(ITypeBinding type) { String name = type.getBinaryName(); if (exceptionBinaryName.endsWith("Error;")) { if (name.equals("Ljava/lang/Throwable;") || name.equals("Ljava/lang/Error;") || name.equals(exceptionBinaryName)) { return true; } } else { if (name.equals("Ljava/lang/Throwable;") || name.equals("Ljava/lang/Exception;") || name.equals("Ljava/lang/RuntimeException;") || name.equals(exceptionBinaryName)) { return true; } } return false; } @Override public boolean isTopLevel() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isTypeVariable() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isUpperbound() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isWildcardType() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public IAnnotationBinding[] getAnnotations() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public IJavaElement getJavaElement() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public String getKey() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public int getKind() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return 0; } @Override public boolean isDeprecated() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isEqualTo(IBinding binding) { return this.equals(binding); } @Override public boolean isRecovered() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public boolean isSynthetic() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return false; } @Override public ITypeBinding getGenericTypeOfWildcardType() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } @Override public int getRank() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return 0; } // do not put @Override here, to avoid breaking compilation on Juno @Override public IMethodBinding getFunctionalInterfaceMethod() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } // do not put @Override here, to avoid breaking compilation on Juno @Override public IAnnotationBinding[] getTypeAnnotations() { Assertions.UNREACHABLE("FakeExceptionTypeBinding "); return null; } // do not put @Override here, to avoid breaking compilation on older Eclipse versions public IBinding getDeclaringMember() { // TODO Auto-generated method stub return null; } }
13,132
25.693089
99
java
WALA
WALA-master/cast/java/ecj/src/main/java/com/ibm/wala/cast/java/translator/jdt/JDT2CAstUtils.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * WALA JDT Frontend is Copyright (c) 2008 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.cast.java.translator.jdt; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstSymbol; import com.ibm.wala.cast.tree.impl.CAstOperator; import com.ibm.wala.util.debug.Assertions; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Set; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Assignment.Operator; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.InfixExpression; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.TypeDeclaration; public class JDT2CAstUtils { public static Collection<CAstQualifier> mapModifiersToQualifiers( int modifiers, boolean isInterface, boolean isAnnotation) { Set<CAstQualifier> quals = new LinkedHashSet<>(); if (isInterface) quals.add(CAstQualifier.INTERFACE); if (isAnnotation) quals.add(CAstQualifier.ANNOTATION); if ((modifiers & Modifier.ABSTRACT) != 0) quals.add(CAstQualifier.ABSTRACT); if ((modifiers & Modifier.FINAL) != 0) quals.add(CAstQualifier.FINAL); if ((modifiers & Modifier.NATIVE) != 0) quals.add(CAstQualifier.NATIVE); // if (flags.isPackage()) quals.add(CAstQualifier.PACKAGE); if ((modifiers & Modifier.PRIVATE) != 0) quals.add(CAstQualifier.PRIVATE); if ((modifiers & Modifier.PROTECTED) != 0) quals.add(CAstQualifier.PROTECTED); if ((modifiers & Modifier.PUBLIC) != 0) quals.add(CAstQualifier.PUBLIC); if ((modifiers & Modifier.STATIC) != 0) quals.add(CAstQualifier.STATIC); if ((modifiers & Modifier.STRICTFP) != 0) quals.add(CAstQualifier.STRICTFP); if ((modifiers & Modifier.SYNCHRONIZED) != 0) quals.add(CAstQualifier.SYNCHRONIZED); if ((modifiers & Modifier.TRANSIENT) != 0) quals.add(CAstQualifier.TRANSIENT); if ((modifiers & Modifier.VOLATILE) != 0) quals.add(CAstQualifier.VOLATILE); return quals; } public static CAstOperator mapAssignOperator(Operator op) { if (op == Assignment.Operator.PLUS_ASSIGN) return CAstOperator.OP_ADD; else if (op == Assignment.Operator.BIT_AND_ASSIGN) return CAstOperator.OP_BIT_AND; else if (op == Assignment.Operator.BIT_OR_ASSIGN) return CAstOperator.OP_BIT_OR; else if (op == Assignment.Operator.BIT_XOR_ASSIGN) return CAstOperator.OP_BIT_XOR; else if (op == Assignment.Operator.DIVIDE_ASSIGN) return CAstOperator.OP_DIV; else if (op == Assignment.Operator.REMAINDER_ASSIGN) return CAstOperator.OP_MOD; else if (op == Assignment.Operator.TIMES_ASSIGN) return CAstOperator.OP_MUL; else if (op == Assignment.Operator.LEFT_SHIFT_ASSIGN) return CAstOperator.OP_LSH; else if (op == Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN) return CAstOperator.OP_RSH; else if (op == Assignment.Operator.MINUS_ASSIGN) return CAstOperator.OP_SUB; else if (op == Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN) return CAstOperator.OP_URSH; Assertions.UNREACHABLE("Unknown assignment operator"); return null; } protected static CAstOperator mapBinaryOpcode(InfixExpression.Operator operator) { if (operator == InfixExpression.Operator.PLUS) return CAstOperator.OP_ADD; // separate bitwise and logical AND / OR ? '&' / '|' ? if (operator == InfixExpression.Operator.AND) return CAstOperator.OP_BIT_AND; if (operator == InfixExpression.Operator.OR) return CAstOperator.OP_BIT_OR; if (operator == InfixExpression.Operator.XOR) return CAstOperator.OP_BIT_XOR; // TODO: shouldn't get here (conditional and handled differently); however should separate // bitwise & logical '&' / '|', maybe. if (operator == InfixExpression.Operator.CONDITIONAL_AND) return CAstOperator.OP_REL_AND; if (operator == InfixExpression.Operator.CONDITIONAL_OR) return CAstOperator.OP_REL_OR; if (operator == InfixExpression.Operator.DIVIDE) return CAstOperator.OP_DIV; if (operator == InfixExpression.Operator.EQUALS) return CAstOperator.OP_EQ; if (operator == InfixExpression.Operator.GREATER_EQUALS) return CAstOperator.OP_GE; if (operator == InfixExpression.Operator.GREATER) return CAstOperator.OP_GT; if (operator == InfixExpression.Operator.LESS_EQUALS) return CAstOperator.OP_LE; if (operator == InfixExpression.Operator.LESS) return CAstOperator.OP_LT; if (operator == InfixExpression.Operator.REMAINDER) return CAstOperator.OP_MOD; if (operator == InfixExpression.Operator.TIMES) return CAstOperator.OP_MUL; if (operator == InfixExpression.Operator.NOT_EQUALS) return CAstOperator.OP_NE; if (operator == InfixExpression.Operator.LEFT_SHIFT) return CAstOperator.OP_LSH; if (operator == InfixExpression.Operator.RIGHT_SHIFT_SIGNED) return CAstOperator.OP_RSH; if (operator == InfixExpression.Operator.MINUS) return CAstOperator.OP_SUB; if (operator == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED) return CAstOperator.OP_URSH; Assertions.UNREACHABLE( "Java2CAstTranslator.JavaTranslatingVisitorImpl.mapBinaryOpcode(): unrecognized binary operator."); return null; } /** * Returns true if type is char, byte, short, int, or long. Return false otherwise (including * boolean!) */ public static boolean isLongOrLess(ITypeBinding type) { String t = type.getBinaryName(); return t.equals("C") || t.equals("B") || t.equals("S") || t.equals("I") || t.equals("J"); } /** * If isLongOrLess(type), returns Integer(0). If a float or double, returns Double(0.0) Otherwise * (including boolean), returns CAstSymbol.NULL_DEFAULT_VALUE. */ public static Object defaultValueForType(ITypeBinding type) { if (isLongOrLess(type)) return 0; else if (type.getBinaryName().equals("D") || type.getBinaryName().equals("F")) return 0.0; else return CAstSymbol.NULL_DEFAULT_VALUE; } public static ITypeBinding promoteTypes(ITypeBinding t1, ITypeBinding t2, AST ast) { // JLS 5.6.2 ITypeBinding doble = ast.resolveWellKnownType("double"); if (t1.equals(doble) || t2.equals(doble)) return doble; ITypeBinding flotando = ast.resolveWellKnownType("float"); if (t1.equals(flotando) || t2.equals(flotando)) return flotando; ITypeBinding largo = ast.resolveWellKnownType("long"); if (t1.equals(largo) || t2.equals(largo)) return largo; return ast.resolveWellKnownType("int"); } public static ITypeBinding getDeclaringClassOfNode(ASTNode n) { ASTNode current = n; while (current != null) { if (current instanceof TypeDeclaration) return ((TypeDeclaration) current).resolveBinding(); else if (current instanceof AnonymousClassDeclaration) return ((AnonymousClassDeclaration) current).resolveBinding(); else if (current instanceof EnumDeclaration) return ((EnumDeclaration) current).resolveBinding(); current = current.getParent(); } Assertions.UNREACHABLE("Couldn't find declaring class of node"); return null; } static String anonTypeName(ITypeBinding ct) { String binName = ct.getBinaryName(); String dollarSignNumber = binName.substring(binName.indexOf('$')); return "<anonymous subclass of " + ct.getSuperclass().getBinaryName() + '>' + dollarSignNumber; } /** * If a type variable, return the bound (getTypeVariablesBase()). If a parameterized type, return * the generic type. */ public static ITypeBinding getErasedType(ITypeBinding returnType, AST ast) { if (returnType.isTypeVariable() || returnType.isCapture()) return getTypesVariablesBase(returnType, ast); return returnType .getTypeDeclaration(); // Things like "Collection<? extends Bla>" are parameterized types... } public static ITypeBinding getTypesVariablesBase(ITypeBinding returnType, AST ast) { assert returnType.isTypeVariable() || returnType.isCapture(); if (returnType.getTypeBounds().length > 0) return returnType.getTypeBounds()[0]; // TODO: why is there more than one bound? else return ast.resolveWellKnownType("java.lang.Object"); } public static InfixExpression.Operator mapAssignOperatorToInfixOperator(Assignment.Operator op) { if (op == Assignment.Operator.PLUS_ASSIGN) return InfixExpression.Operator.PLUS; else if (op == Assignment.Operator.BIT_AND_ASSIGN) return InfixExpression.Operator.AND; else if (op == Assignment.Operator.BIT_OR_ASSIGN) return InfixExpression.Operator.OR; else if (op == Assignment.Operator.BIT_XOR_ASSIGN) return InfixExpression.Operator.XOR; else if (op == Assignment.Operator.DIVIDE_ASSIGN) return InfixExpression.Operator.DIVIDE; else if (op == Assignment.Operator.REMAINDER_ASSIGN) return InfixExpression.Operator.REMAINDER; else if (op == Assignment.Operator.TIMES_ASSIGN) return InfixExpression.Operator.TIMES; else if (op == Assignment.Operator.LEFT_SHIFT_ASSIGN) return InfixExpression.Operator.LEFT_SHIFT; else if (op == Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN) return InfixExpression.Operator.RIGHT_SHIFT_SIGNED; else if (op == Assignment.Operator.MINUS_ASSIGN) return InfixExpression.Operator.MINUS; else if (op == Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN) return InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED; Assertions.UNREACHABLE("Unknown assignment operator"); return null; } private static void getMethodInClassOrSuperclass( IMethodBinding met, ITypeBinding klass, boolean superclassonly, HashMap<ITypeBinding, IMethodBinding> overridden) { if (!superclassonly) { for (IMethodBinding ourmet : klass.getDeclaredMethods()) if (met.overrides(ourmet)) { overridden.put( ourmet.getMethodDeclaration().getReturnType(), ourmet.getMethodDeclaration()); break; // there can only be one per class so don't bother looking for more } } for (ITypeBinding iface : klass.getInterfaces()) getMethodInClassOrSuperclass(met, iface, false, overridden); ITypeBinding superclass = klass.getSuperclass(); if (superclass != null) getMethodInClassOrSuperclass(met, superclass, false, overridden); } public static Collection<IMethodBinding> getOverriddenMethod(IMethodBinding met) { HashMap<ITypeBinding, IMethodBinding> overridden = new HashMap<>(); if (met == null) return null; getMethodInClassOrSuperclass(met, met.getDeclaringClass(), true, overridden); if (overridden.size() == 0) return null; return overridden.values(); } public static boolean sameErasedSignatureAndReturnType(IMethodBinding met1, IMethodBinding met2) { if (!met1.getReturnType().getErasure().isEqualTo(met2.getReturnType().getErasure())) return false; ITypeBinding[] params1 = met1.getParameterTypes(); ITypeBinding[] params2 = met2.getParameterTypes(); if (params1.length != params2.length) return false; for (int i = 0; i < params1.length; i++) if (!params1[i].getErasure().isEqualTo(params2[i].getErasure())) return false; return true; } }
13,121
49.275862
107
java
WALA
WALA-master/cast/java/ecj/src/main/java/com/ibm/wala/cast/java/translator/jdt/JDTIdentityMapper.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * WALA JDT Frontend is Copyright (c) 2008 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.cast.java.translator.jdt; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.debug.Assertions; import java.util.Map; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; /** * Class responsible for mapping JDT type system objects representing types, methods and fields to * the corresponding WALA TypeReferences, MethodReferences and FieldReferences. Used during * translation and by clients to help correlate WALA analysis results to the various AST nodes. * * <p>In English: keeps a hashtable of WALA "type references", "field references", etc. which * describe types, fields, etc. Creates these from their JDT equivalents and keeps the hashtable * linking the two representations. * * @author rfuhrer */ public class JDTIdentityMapper { private final Map<String, TypeReference> fTypeMap = HashMapFactory.make(); private final Map<String, FieldReference> fFieldMap = HashMapFactory.make(); private final Map<String, MethodReference> fMethodMap = HashMapFactory.make(); private final ClassLoaderReference fClassLoaderRef; // TAGALONG private final AST fAst; public JDTIdentityMapper(ClassLoaderReference clr, AST ast) { fClassLoaderRef = clr; fAst = ast; } // TYPES /** * Create (or reuse) a TypeReference for the given JDT Type Binding.<br> * This method canonicalizes the TypeReferences */ public TypeReference getTypeRef(ITypeBinding type) { type = JDT2CAstUtils.getErasedType(type, fAst); // GENERICS: erasure... if (!fTypeMap.containsKey(type.getKey())) { TypeName typeName = TypeName.string2TypeName(typeToTypeID(type)); TypeReference ref = TypeReference.findOrCreate(fClassLoaderRef, typeName); fTypeMap.put(type.getKey(), ref); return ref; } return fTypeMap.get(type.getKey()); } /** * Translates the given Polyglot type to a name suitable for use in a DOMO TypeReference (i.e. a * bytecode-compliant type name). */ public String typeToTypeID(ITypeBinding type) { if (type.isPrimitive()) return type.getBinaryName(); else if (type.isArray()) // arrays' binary names in JDT are like "[Ljava.lang.String;" return type.getBinaryName().replace('.', '/').replace(";", ""); else if (type.isLocal() || type.isAnonymous()) return anonLocalTypeToTypeID(type); else if (type.isClass() || type.isEnum() || type.isInterface()) // in polyglot interfaces are classes too. not in JDT // class binary names in JDT are like "java.lang.String" return 'L' + type.getBinaryName().replace('.', '/'); // TODO: else if (type.isTypeVariable()) { return typeToTypeID(JDT2CAstUtils.getTypesVariablesBase(type, fAst)); } Assertions.UNREACHABLE( "typeToTypeID() encountered the type " + type + " that is neither primitive, array, nor class!"); return null; } public String anonLocalTypeToTypeID(ITypeBinding type) { String outerTypeID = typeToTypeID(type.getDeclaringClass()); String metSelectorName; IMethodBinding metBinding = type.getDeclaringMethod(); if (metBinding == null) // anonymous class declared in initializer or static initializer (rare case...) metSelectorName = "<init>"; else metSelectorName = getMethodRef(metBinding).getSelector().toString(); String shortName = type.isAnonymous() ? JDT2CAstUtils.anonTypeName(type) : type.getName(); return outerTypeID + '/' + metSelectorName + '/' + shortName; } // FIELDS public FieldReference getFieldRef(IVariableBinding field) { if (!fFieldMap.containsKey(field.getKey())) { // create one ITypeBinding targetType = field.getDeclaringClass(); TypeReference targetTypeRef = TypeReference.findOrCreate(fClassLoaderRef, typeToTypeID(targetType)); ITypeBinding fieldType = field.getType(); TypeReference fieldTypeRef = TypeReference.findOrCreate(fClassLoaderRef, typeToTypeID(fieldType)); Atom fieldName = Atom.findOrCreateUnicodeAtom(field.getName()); FieldReference ref = FieldReference.findOrCreate(targetTypeRef, fieldName, fieldTypeRef); fFieldMap.put(field.getKey(), ref); return ref; } return fFieldMap.get(field.getKey()); } public MethodReference fakeMethodRefNoArgs( String key, String typeID, String metName, String returnTypeID) { if (!fMethodMap.containsKey(key)) { // create one TypeName ownerType = TypeName.string2TypeName(typeID); TypeReference ownerTypeRef = TypeReference.findOrCreate(fClassLoaderRef, ownerType); // FAKE SELECTOR Atom name = Atom.findOrCreateUnicodeAtom(metName); TypeName[] argTypeNames = null; TypeName retTypeName = TypeName.string2TypeName(returnTypeID); Descriptor desc = Descriptor.findOrCreate(argTypeNames, retTypeName); Selector selector = new Selector(name, desc); MethodReference ref = MethodReference.findOrCreate(ownerTypeRef, selector); fMethodMap.put(key, ref); return ref; } return fMethodMap.get(key); } // METHODS public MethodReference getMethodRef(IMethodBinding met) { if (!fMethodMap.containsKey(met.getKey())) { // create one TypeName ownerType = TypeName.string2TypeName(typeToTypeID(met.getDeclaringClass())); TypeReference ownerTypeRef = TypeReference.findOrCreate(fClassLoaderRef, ownerType); MethodReference ref = MethodReference.findOrCreate(ownerTypeRef, selectorForMethod(met)); fMethodMap.put(met.getKey(), ref); return ref; } return fMethodMap.get(met.getKey()); } private Selector selectorForMethod(IMethodBinding met) { // TODO: have to handle default constructors? // TODO: generics... Atom name = met.isConstructor() ? MethodReference.initAtom : Atom.findOrCreateUnicodeAtom(met.getName()); TypeName[] argTypeNames = null; ITypeBinding[] formalTypes = met.getParameterTypes(); int length = formalTypes.length; // ENUMS: hidden name and ID in constructor if (met.isConstructor() && met.getDeclaringClass().isEnum()) length += 2; // Descriptor prefers null to an empty array if (length > 0) { argTypeNames = new TypeName[length]; int i = 0; if (met.isConstructor() && met.getDeclaringClass().isEnum()) { argTypeNames[0] = TypeName.string2TypeName(typeToTypeID(fAst.resolveWellKnownType("java.lang.String"))); argTypeNames[1] = TypeName.string2TypeName(typeToTypeID(fAst.resolveWellKnownType("int"))); i = 2; } for (ITypeBinding argType : formalTypes) argTypeNames[i++] = TypeName.string2TypeName(typeToTypeID(argType)); } TypeName retTypeName = TypeName.string2TypeName(typeToTypeID(met.getReturnType())); Descriptor desc = Descriptor.findOrCreate(argTypeNames, retTypeName); return new Selector(name, desc); } }
9,329
38.871795
99
java
WALA
WALA-master/cast/java/ecj/src/main/java/com/ibm/wala/cast/java/translator/jdt/JDTJava2CAstTranslator.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * WALA JDT Frontend is Copyright (c) 2008 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.cast.java.translator.jdt; import com.ibm.wala.analysis.typeInference.JavaPrimitiveType; import com.ibm.wala.cast.ir.translator.AstTranslator.InternalCAstSymbol; import com.ibm.wala.cast.ir.translator.TranslatorToCAst; import com.ibm.wala.cast.ir.translator.TranslatorToCAst.DoLoopTranslator; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl; import com.ibm.wala.cast.java.loader.Util; import com.ibm.wala.cast.java.translator.JavaProcedureEntity; import com.ibm.wala.cast.tree.CAst; import com.ibm.wala.cast.tree.CAstAnnotation; import com.ibm.wala.cast.tree.CAstControlFlowMap; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstNodeTypeMap; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.cast.tree.impl.CAstControlFlowRecorder; import com.ibm.wala.cast.tree.impl.CAstImpl; import com.ibm.wala.cast.tree.impl.CAstNodeTypeMapRecorder; import com.ibm.wala.cast.tree.impl.CAstOperator; import com.ibm.wala.cast.tree.impl.CAstSourcePositionRecorder; import com.ibm.wala.cast.tree.impl.CAstSymbolImpl; import com.ibm.wala.cast.util.CAstPrinter; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.collections.EmptyIterator; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.debug.Assertions; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.jdt.core.dom.ArrayAccess; import org.eclipse.jdt.core.dom.ArrayCreation; import org.eclipse.jdt.core.dom.ArrayInitializer; import org.eclipse.jdt.core.dom.AssertStatement; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.BooleanLiteral; import org.eclipse.jdt.core.dom.BreakStatement; import org.eclipse.jdt.core.dom.CastExpression; import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.CharacterLiteral; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ConditionalExpression; import org.eclipse.jdt.core.dom.ConstructorInvocation; import org.eclipse.jdt.core.dom.ContinueStatement; import org.eclipse.jdt.core.dom.DoStatement; import org.eclipse.jdt.core.dom.EmptyStatement; import org.eclipse.jdt.core.dom.EnhancedForStatement; import org.eclipse.jdt.core.dom.EnumConstantDeclaration; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.ForStatement; import org.eclipse.jdt.core.dom.IAnnotationBinding; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMemberValuePairBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.InfixExpression; import org.eclipse.jdt.core.dom.Initializer; import org.eclipse.jdt.core.dom.InstanceofExpression; import org.eclipse.jdt.core.dom.LabeledStatement; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.NullLiteral; import org.eclipse.jdt.core.dom.NumberLiteral; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.ParenthesizedExpression; import org.eclipse.jdt.core.dom.PostfixExpression; import org.eclipse.jdt.core.dom.PrefixExpression; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Statement; import org.eclipse.jdt.core.dom.StringLiteral; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; import org.eclipse.jdt.core.dom.SuperFieldAccess; import org.eclipse.jdt.core.dom.SuperMethodInvocation; import org.eclipse.jdt.core.dom.SwitchCase; import org.eclipse.jdt.core.dom.SwitchStatement; import org.eclipse.jdt.core.dom.SynchronizedStatement; import org.eclipse.jdt.core.dom.ThisExpression; import org.eclipse.jdt.core.dom.ThrowStatement; import org.eclipse.jdt.core.dom.TryStatement; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.TypeDeclarationStatement; import org.eclipse.jdt.core.dom.TypeLiteral; import org.eclipse.jdt.core.dom.UnionType; import org.eclipse.jdt.core.dom.VariableDeclarationExpression; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.VariableDeclarationStatement; import org.eclipse.jdt.core.dom.WhileStatement; // TOTEST: // "1/0" surrounded by catch ArithmeticException & RunTimeException (TryCatchContext.getCatchTypes" // another subtype of ArithmeticException surrounded by catch ArithmeticException // binary ops with all kinds of type conversions // simplenames: fields of this, fields of an enclosing class, fields of an enclosing method, static // fields, fully qualified fields w/ package stuff // exceptional CFG edges, somehow. call nodes, new nodes, division by zero in binary ops, null // pointer in field accesses, etc. // implicit constructors // FIXME 1.4: thing about / ask agout TAGALONG (JDT stuff tagging along in memory cos we keep it). // FIXME 1.4: find LEFTOUT and find out why polyglot has extra code / infrastructure, if it's used // and what for, etc. // Java 1.6: // * type parameters/generics: see getArgumentTypes in ProcedureEntity$anon. also anywhere we use // ITypeBinding.equals() may be affected // see anywhere in code labeled GENERICS for present "treat as raw types"/"pretend it's 1.4 and // casts" solution. // * boxing (YUCK). see resolveBoxing() // * enums (probably in simplename or something. but using resolveConstantExpressionValue() // possible) public abstract class JDTJava2CAstTranslator<T extends Position> { protected boolean dump = false; protected final CAst fFactory = new CAstImpl(); // /////////////////////////////////////////// // / HANDLINGS OF VARIOUS THINGS // // /////////////////////////////////////////// protected final AST ast; // TAGALONG protected final JDTIdentityMapper fIdentityMapper; // TAGALONG protected final JDTTypeDictionary fTypeDict; protected final JavaSourceLoaderImpl fSourceLoader; protected final ITypeBinding fDivByZeroExcType; protected final ITypeBinding fNullPointerExcType; protected final ITypeBinding fClassCastExcType; protected final ITypeBinding fRuntimeExcType; protected final ITypeBinding NoClassDefFoundError; protected final ITypeBinding ExceptionInInitializerError; protected final ITypeBinding OutOfMemoryError; protected final DoLoopTranslator doLoopTranslator; protected final String fullPath; protected final CompilationUnit cu; // // COMPILATION UNITS & TYPES // public JDTJava2CAstTranslator( JavaSourceLoaderImpl sourceLoader, CompilationUnit astRoot, String fullPath, boolean replicateForDoLoops) { this(sourceLoader, astRoot, fullPath, replicateForDoLoops, false); } public JDTJava2CAstTranslator( JavaSourceLoaderImpl sourceLoader, CompilationUnit astRoot, String fullPath, boolean replicateForDoLoops, boolean dump) { fDivByZeroExcType = FakeExceptionTypeBinding.arithmetic; fNullPointerExcType = FakeExceptionTypeBinding.nullPointer; fClassCastExcType = FakeExceptionTypeBinding.classCast; NoClassDefFoundError = FakeExceptionTypeBinding.noClassDef; ExceptionInInitializerError = FakeExceptionTypeBinding.initException; OutOfMemoryError = FakeExceptionTypeBinding.outOfMemory; this.fSourceLoader = sourceLoader; this.cu = astRoot; this.fullPath = fullPath; this.ast = astRoot.getAST(); this.doLoopTranslator = new DoLoopTranslator(replicateForDoLoops, fFactory); this.dump = dump; // FIXME: we might need one AST (-> "Object" class) for all files. fIdentityMapper = new JDTIdentityMapper(fSourceLoader.getReference(), ast); fTypeDict = new JDTTypeDictionary(ast, fIdentityMapper); fRuntimeExcType = ast.resolveWellKnownType("java.lang.RuntimeException"); assert fRuntimeExcType != null; } public CAstEntity translateToCAst() { List<CAstEntity> declEntities = new ArrayList<>(); for (AbstractTypeDeclaration decl : (Iterable<AbstractTypeDeclaration>) cu.types()) { // can be of type AnnotationTypeDeclaration, EnumDeclaration, TypeDeclaration declEntities.add(visit(decl, new RootContext())); } if (dump) { for (CAstEntity d : declEntities) { CAstPrinter.printTo(d, new PrintWriter(System.err)); } } return new CompilationUnitEntity(cu.getPackage(), declEntities); } // // TYPES // protected final class ClassEntity implements CAstEntity { // TAGALONG (not static, will keep reference to ast, fIdentityMapper, etc) @Override public Position getPosition(int arg) { return null; } private final String fName; private final Collection<CAstQualifier> fQuals; private final Collection<CAstEntity> fEntities; private final ITypeBinding fJdtType; // TAGALONG private final T fSourcePosition; private final T fNamePos; public ClassEntity( ITypeBinding jdtType, String name, Collection<CAstQualifier> quals, Collection<CAstEntity> entities, T pos, T namePos) { fNamePos = namePos; fName = name; fQuals = quals; fEntities = entities; fJdtType = jdtType; fSourcePosition = pos; } @Override public Collection<CAstAnnotation> getAnnotations() { // TODO Auto-generated method stub return null; } @Override public int getKind() { return TYPE_ENTITY; } @Override public String getName() { return fName; // unqualified? } @Override public String getSignature() { return 'L' + fName.replace('.', '/') + ';'; } @Override public String[] getArgumentNames() { return new String[0]; } @Override public CAstNode[] getArgumentDefaults() { return new CAstNode[0]; } @Override public int getArgumentCount() { return 0; } @Override public CAstNode getAST() { // This entity has no AST nodes, really. return null; } @Override public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() { return Collections.singletonMap(null, fEntities); } @Override public Iterator<CAstEntity> getScopedEntities(CAstNode construct) { Assertions.UNREACHABLE( "Non-AST-bearing entity (ClassEntity) asked for scoped entities related to a given AST node"); return null; } @Override public CAstControlFlowMap getControlFlow() { // This entity has no AST nodes, really. return null; } @Override public CAstSourcePositionMap getSourceMap() { // This entity has no AST nodes, really. return null; } @Override public CAstSourcePositionMap.Position getPosition() { return fSourcePosition; } @Override public CAstNodeTypeMap getNodeTypeMap() { // This entity has no AST nodes, really. return new CAstNodeTypeMap() { @Override public CAstType getNodeType(CAstNode node) { throw new UnsupportedOperationException(); } @Override public Collection<CAstNode> getMappedNodes() { throw new UnsupportedOperationException(); } }; } @Override public Collection<CAstQualifier> getQualifiers() { return fQuals; } @Override public CAstType getType() { // return new JdtJavaType(fCT, getTypeDict(), fTypeSystem); return fTypeDict.new JdtJavaType(fJdtType); } @Override public Position getNamePosition() { return fNamePos; } } private static boolean isInterface(AbstractTypeDeclaration decl) { return decl instanceof AnnotationTypeDeclaration || (decl instanceof TypeDeclaration && ((TypeDeclaration) decl).isInterface()); } private CAstEntity visitTypeDecl(AbstractTypeDeclaration n, WalkContext context) { return createClassDeclaration( n, n.bodyDeclarations(), null, n.resolveBinding(), n.getName().getIdentifier(), n.getModifiers(), isInterface(n), n instanceof AnnotationTypeDeclaration, context, makePosition(n.getName())); } /** @param name Used in creating default constructor, and passed into new ClassEntity() */ private CAstEntity createClassDeclaration( ASTNode n, List<BodyDeclaration> bodyDecls, List<EnumConstantDeclaration> enumConstants, ITypeBinding typeBinding, String name, int modifiers, boolean isInterface, boolean isAnnotation, WalkContext context, T namePos) { final List<CAstEntity> memberEntities = new ArrayList<>(); // find and collect all initializers (type Initializer) and field initializers (type // VariableDeclarationFragment). // instance initializer code will be inserted into each constructors. // all static initializer code will be grouped together in its own entity. ArrayList<ASTNode> inits = new ArrayList<>(); ArrayList<ASTNode> staticInits = new ArrayList<>(); if (enumConstants != null) { // always (implicitly) static,final (actually, no modifiers allowed) staticInits.addAll(enumConstants); } for (BodyDeclaration decl : bodyDecls) { if (decl instanceof Initializer) { Initializer initializer = (Initializer) decl; boolean isStatic = ((initializer.getModifiers() & Modifier.STATIC) != 0); (isStatic ? staticInits : inits).add(initializer); } else if (decl instanceof FieldDeclaration) { FieldDeclaration fd = (FieldDeclaration) decl; for (VariableDeclarationFragment frag : (Iterable<VariableDeclarationFragment>) fd.fragments()) { if (frag.getInitializer() != null) { boolean isStatic = ((fd.getModifiers() & Modifier.STATIC) != 0); (isStatic ? staticInits : inits).add(frag); } } } } // process entities. initializers will be folded in here. if (enumConstants != null) { for (EnumConstantDeclaration decl : enumConstants) { memberEntities.add(visit(decl)); } } for (BodyDeclaration decl : bodyDecls) { if (decl instanceof FieldDeclaration) { FieldDeclaration fieldDecl = (FieldDeclaration) decl; Collection<CAstQualifier> quals = JDT2CAstUtils.mapModifiersToQualifiers(fieldDecl.getModifiers(), false, false); for (VariableDeclarationFragment fieldFrag : (Iterable<VariableDeclarationFragment>) fieldDecl.fragments()) { IVariableBinding fieldBinding = fieldFrag.resolveBinding(); memberEntities.add( new FieldEntity( fieldFrag.getName().getIdentifier(), fieldBinding.getType(), quals, makePosition( fieldFrag.getStartPosition(), fieldFrag.getStartPosition() + fieldFrag.getLength()), handleAnnotations(fieldBinding), makePosition(fieldFrag.getName()))); } } else if (decl instanceof Initializer) { // Initializers are inserted into constructors when making constructors. } else if (decl instanceof MethodDeclaration) { MethodDeclaration metDecl = (MethodDeclaration) decl; if (typeBinding.isEnum() && metDecl.isConstructor()) memberEntities.add( createEnumConstructorWithParameters( metDecl.resolveBinding(), metDecl, context, inits, metDecl)); else { memberEntities.add(visit(metDecl, typeBinding, context, inits)); // /////////////// Java 1.5 "overridden with subtype" thing (covariant return type) // /////////// Collection<IMethodBinding> overriddenMets = JDT2CAstUtils.getOverriddenMethod(metDecl.resolveBinding()); if (overriddenMets != null) { for (IMethodBinding overridden : overriddenMets) if (!JDT2CAstUtils.sameErasedSignatureAndReturnType( metDecl.resolveBinding(), overridden)) memberEntities.add( makeSyntheticCovariantRedirect( metDecl, metDecl.resolveBinding(), overridden, context)); } } } else if (decl instanceof AbstractTypeDeclaration) { memberEntities.add(visit((AbstractTypeDeclaration) decl, context)); } else if (decl instanceof AnnotationTypeMemberDeclaration) { // TODO: need to decide what to do with these } else { Assertions.UNREACHABLE("BodyDeclaration not Field, Initializer, or Method"); } } // add default constructor(s) if necessary // most default constructors have no parameters; however, those created by anonymous classes // will have parameters // (they just call super with those parameters) for (IMethodBinding met : typeBinding.getDeclaredMethods()) { if (met.isDefaultConstructor()) { if (typeBinding.isEnum()) memberEntities.add(createEnumConstructorWithParameters(met, n, context, inits, null)); else if (met.getParameterTypes().length > 0) memberEntities.add(createDefaultConstructorWithParameters(met, n, context, inits)); else memberEntities.add(createDefaultConstructor(typeBinding, context, inits, n)); } } if (typeBinding.isEnum() && !typeBinding.isAnonymous()) doEnumHiddenEntities(typeBinding, memberEntities, context); // collect static inits if (!staticInits.isEmpty()) { Map<CAstNode, CAstEntity> childEntities = HashMapFactory.make(); final MethodContext newContext = new MethodContext(context, childEntities); // childEntities is the same one as in the ProcedureEntity. later visit(New), etc. may add to // this. List<CAstNode> bodyNodes = new ArrayList<>(staticInits.size()); for (ASTNode staticInit : staticInits) bodyNodes.add(visitFieldInitNode(staticInit, newContext)); CAstNode staticInitAst = makeNode(newContext, fFactory, n, CAstNode.BLOCK_STMT, bodyNodes); memberEntities.add( new ProcedureEntity(staticInitAst, typeBinding, childEntities, newContext, null)); } Collection<CAstQualifier> quals = JDT2CAstUtils.mapModifiersToQualifiers(modifiers, isInterface, isAnnotation); return new ClassEntity(typeBinding, name, quals, memberEntities, makePosition(n), namePos); } private CAstEntity visit(AnonymousClassDeclaration n, WalkContext context) { return createClassDeclaration( n, n.bodyDeclarations(), null, n.resolveBinding(), JDT2CAstUtils.anonTypeName(n.resolveBinding()), 0 /* no modifiers */, false, false, context, null); } private CAstNode visit(TypeDeclarationStatement n, WalkContext context) { // TODO 1.6: enums of course... AbstractTypeDeclaration decl = n.getDeclaration(); assert decl instanceof TypeDeclaration : "Local enum declaration not yet supported"; CAstEntity classEntity = visitTypeDecl(decl, context); // these statements don't actually do anything, just define a type final CAstNode lcdNode = makeNode(context, fFactory, n, CAstNode.EMPTY); // so define it! context.addScopedEntity(lcdNode, classEntity); return lcdNode; } // //////////////////////////////// // METHODS // //////////////////////////////// /** * @param n for positioning. * <p>Make a constructor with parameters that calls super(...) with parameters. Used for * anonymous classes with arguments to a constructor, like new Foo(arg1,arg2) { } */ private CAstEntity createDefaultConstructorWithParameters( IMethodBinding ctor, ASTNode n, WalkContext oldContext, ArrayList<ASTNode> inits) { // PART I: find super ctor to call ITypeBinding newType = ctor.getDeclaringClass(); ITypeBinding superType = newType.getSuperclass(); IMethodBinding superCtor = null; for (IMethodBinding m : superType.getDeclaredMethods()) if (m.isConstructor() && Arrays.equals(m.getParameterTypes(), ctor.getParameterTypes())) superCtor = m; assert superCtor != null : "couldn't find constructor for anonymous class"; // PART II: make ctor with simply "super(a,b,c...)" final Map<CAstNode, CAstEntity> memberEntities = new LinkedHashMap<>(); final MethodContext context = new MethodContext(oldContext, memberEntities); MethodDeclaration fakeCtor = ast.newMethodDeclaration(); fakeCtor.setConstructor(true); fakeCtor.setSourceRange(n.getStartPosition(), n.getLength()); fakeCtor.setBody(ast.newBlock()); // PART IIa: make a fake JDT constructor method with the proper number of args // Make fake args that will be passed String[] fakeArguments = new String[superCtor.getParameterTypes().length + 1]; ArrayList<CAstType> paramTypes = new ArrayList<>(superCtor.getParameterTypes().length); // TODO: change to invalid name and don't use Arrays.setAll(fakeArguments, i -> (i == 0) ? "this" : ("argument" + i)); // singlevariabledeclaration below for (int i = 1; i < fakeArguments.length; i++) { // the name SingleVariableDeclaration svd = ast.newSingleVariableDeclaration(); svd.setName(ast.newSimpleName(fakeArguments[i])); fakeCtor.parameters().add(svd); // the type paramTypes.add(fTypeDict.getCAstTypeFor(ctor.getParameterTypes()[i - 1])); } // PART IIb: create the statements in the constructor // one super() call plus the inits List<CAstNode> bodyNodes = new ArrayList<>(inits.size() + 1); // make super(...) call // this, call ref, args List<CAstNode> children = new ArrayList<>(fakeArguments.length + 1); children.add(makeNode(context, fFactory, n, CAstNode.SUPER)); CallSiteReference callSiteRef = CallSiteReference.make( 0, fIdentityMapper.getMethodRef(superCtor), IInvokeInstruction.Dispatch.SPECIAL); children.add(fFactory.makeConstant(callSiteRef)); for (int i = 1; i < fakeArguments.length; i++) { CAstNode argName = fFactory.makeConstant(fakeArguments[i]); CAstNode argType = fFactory.makeConstant(paramTypes.get(i - 1)); children.add(makeNode(context, fFactory, n, CAstNode.VAR, argName, argType)); } bodyNodes.add(makeNode(context, fFactory, n, CAstNode.CALL, children)); // QUESTION: no handleExceptions? for (ASTNode init : inits) bodyNodes.add(visitFieldInitNode(init, context)); // finally, make the procedure entity CAstNode ast = makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, bodyNodes); return new ProcedureEntity( ast, fakeCtor, newType, memberEntities, context, paramTypes, null, null); } private CAstEntity createDefaultConstructor( ITypeBinding classBinding, WalkContext oldContext, ArrayList<ASTNode> inits, ASTNode positioningNode) { MethodDeclaration fakeCtor = ast.newMethodDeclaration(); fakeCtor.setConstructor(true); // fakeCtor.setName(ast.newSimpleName(className)); will crash on anonymous types... fakeCtor.setSourceRange(positioningNode.getStartPosition(), positioningNode.getLength()); fakeCtor.setBody(ast.newBlock()); return visit(fakeCtor, classBinding, oldContext, inits); } private static IMethodBinding findDefaultCtor(ITypeBinding superClass) { for (IMethodBinding met : superClass.getDeclaredMethods()) { if (met.isConstructor() && met.getParameterTypes().length == 0) return met; } Assertions.UNREACHABLE("Couldn't find default ctor"); return null; } /** * Setup constructor body. Here we add the initializer code (both initalizer blocks and * initializers in field declarations). We may also need to add an implicit super() call. * * @param classBinding Used so we can use this with fake MethodDeclaration nodes, as in the case * of creating a default constructor. */ private CAstNode createConstructorBody( MethodDeclaration n, ITypeBinding classBinding, WalkContext context, ArrayList<ASTNode> inits) { // three possibilites: has super(), has this(), has neither. Statement firstStatement = null; if (!n.getBody().statements().isEmpty()) firstStatement = (Statement) n.getBody().statements().get(0); if (firstStatement instanceof SuperConstructorInvocation) { // Split at call to super: // super(); // field initializer code // remainder of ctor body ArrayList<CAstNode> origStatements = createBlock(n.getBody(), context); List<CAstNode> bodyNodes = new ArrayList<>(inits.size() + origStatements.size()); bodyNodes.add(origStatements.get(0)); for (ASTNode init : inits) bodyNodes.add( visitFieldInitNode( init, context)); // visit each in this constructor's context, ensuring // proper handling of exceptions (we can't just reuse the // CAstNodes) for (int i = 1; i < origStatements.size(); i++) bodyNodes.add(origStatements.get(i)); return makeNode( context, fFactory, n.getBody(), CAstNode.BLOCK_STMT, bodyNodes); // QUESTION: why no LOCAL_SCOPE? // that's the way it is in // polyglot. } else if (firstStatement instanceof ConstructorInvocation) { return visitNode( n.getBody(), context); // has this(...) call; initializers will be set somewhere else. } else { // add explicit call to default super() // QUESTION their todo: following superClass lookup of default ctor won't work if we // process Object in source... ITypeBinding superType = classBinding.getSuperclass(); // find default constructor. IT is an error to have a constructor // without super() when the default constructor of the superclass does not exist. IMethodBinding defaultSuperCtor = findDefaultCtor(superType); CallSiteReference callSiteRef = CallSiteReference.make( 0, fIdentityMapper.getMethodRef(defaultSuperCtor), IInvokeInstruction.Dispatch.SPECIAL); // QUESTION: why isn't first arg this like in visit(ConstructorInvocation) ? // why don't we handle exceptions like in visit(ConstructorInvocation) ? (these two things are // same in polyglot // implementation) CAstNode superCall = makeNode( context, fFactory, n.getBody(), CAstNode.CALL, makeNode(context, fFactory, n.getBody(), CAstNode.SUPER), fFactory.makeConstant(callSiteRef)); Object mapper = new Object(); // dummy used for mapping this node in CFG handleThrowsFromCall(defaultSuperCtor, mapper, context); context.cfg().map(mapper, superCall); ArrayList<CAstNode> origStatements = createBlock(n.getBody(), context); List<CAstNode> bodyNodes = new ArrayList<>(inits.size() + origStatements.size() + 1); // superCall, inits, ctor body bodyNodes.add(superCall); for (ASTNode init : inits) bodyNodes.add(visitFieldInitNode(init, context)); bodyNodes.addAll(origStatements); return makeNode(context, fFactory, n.getBody(), CAstNode.BLOCK_STMT, bodyNodes); } } /** * Make a "fake" function (it doesn't exist in source code but it does in bytecode) for covariant * return types. * * @param overriding Declaration of the overriding method. * @param overridden Binding of the overridden method, in a a superclass or implemented interface. */ private CAstEntity makeSyntheticCovariantRedirect( MethodDeclaration overriding, IMethodBinding overridingBinding, IMethodBinding overridden, WalkContext oldContext) { // SuperClass foo(A, B, C...) // SubClass foo(A,B,C...) // // add a method exactly like overridden that calls overriding final Map<CAstNode, CAstEntity> memberEntities = new LinkedHashMap<>(); final MethodContext context = new MethodContext(oldContext, memberEntities); CAstNode calltarget; if ((overridingBinding.getModifiers() & Modifier.STATIC) == 0) calltarget = makeNode(context, fFactory, null, CAstNode.SUPER); else calltarget = makeNode(context, fFactory, null, CAstNode.VOID); ITypeBinding paramTypes[] = overridden.getParameterTypes(); ArrayList<CAstNode> arguments = new ArrayList<>(); int i = 0; for (SingleVariableDeclaration svd : (Iterable<SingleVariableDeclaration>) overriding.parameters()) { CAstNode varNode = makeNode( context, fFactory, null, CAstNode.VAR, fFactory.makeConstant(svd.getName().getIdentifier())); ITypeBinding fromType = JDT2CAstUtils.getErasedType(paramTypes[i], ast); ITypeBinding toType = JDT2CAstUtils.getErasedType(overridingBinding.getParameterTypes()[i], ast); if (fromType.equals(toType)) { arguments.add(varNode); } else { arguments.add(createCast(null, varNode, fromType, toType, context)); } i++; } CAstNode callnode = createMethodInvocation(null, overridingBinding, calltarget, arguments, context); CAstNode mdast = makeNode( context, fFactory, null, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, null, CAstNode.BLOCK_STMT, makeNode(context, fFactory, null, CAstNode.RETURN, callnode))); // make parameters to new synthetic method // use RETURN TYPE of overridden, everything else from overriding (including parameter names) ArrayList<CAstType> paramCAstTypes = new ArrayList<>(overridden.getParameterTypes().length); for (ITypeBinding paramType : overridden.getParameterTypes()) paramCAstTypes.add(fTypeDict.getCAstTypeFor(paramType)); return new ProcedureEntity( mdast, overriding, overridingBinding.getDeclaringClass(), memberEntities, context, paramCAstTypes, overridden.getReturnType(), null); } /** * @param inits Instance intializers & field initializers. Only used if method is a constructor, * in which case the initializers will be inserted in. */ private CAstEntity visit( MethodDeclaration n, ITypeBinding classBinding, WalkContext oldContext, ArrayList<ASTNode> inits) { // pass in memberEntities to the context, later visit(New) etc. may add classes final Map<CAstNode, CAstEntity> memberEntities = new LinkedHashMap<>(); final MethodContext context = new MethodContext(oldContext, memberEntities); // LEFTOUT: in polyglot there is a // class context in between method and // root CAstNode mdast; if (n.isConstructor()) mdast = createConstructorBody(n, classBinding, context, inits); else if ((n.getModifiers() & Modifier.ABSTRACT) != 0) // abstract mdast = null; else if (n.getBody() == null || n.getBody().statements().size() == 0) // empty mdast = makeNode(context, fFactory, n, CAstNode.RETURN); else mdast = visitNode(n.getBody(), context); // Polyglot comment: Presumably the MethodContext's parent is a ClassContext, // and he has the list of initializers. Hopefully the following // will glue that stuff in the right place in any constructor body. if (context.getNameDecls() != null && !context.getNameDecls().isEmpty()) { // new first statement will be a block declaring all names. mdast = fFactory.makeNode( CAstNode.BLOCK_STMT, context.getNameDecls().size() == 1 ? context.getNameDecls().iterator().next() : fFactory.makeNode(CAstNode.BLOCK_STMT, context.getNameDecls()), mdast); } Set<CAstAnnotation> annotations = null; if (n.resolveBinding() != null) { annotations = handleAnnotations(n.resolveBinding()); } return new ProcedureEntity(mdast, n, classBinding, memberEntities, context, annotations); } private Set<CAstAnnotation> handleAnnotations(IBinding binding) { IAnnotationBinding[] annotations = binding.getAnnotations(); if (annotations == null || annotations.length == 0) { return null; } Set<CAstAnnotation> castAnnotations = HashSetFactory.make(); for (IAnnotationBinding annotation : annotations) { ITypeBinding annotationTypeBinding = annotation.getAnnotationType(); final CAstType annotationType = fTypeDict.getCAstTypeFor(annotationTypeBinding); final Map<String, Object> args = HashMapFactory.make(); for (IMemberValuePairBinding mvpb : annotation.getAllMemberValuePairs()) { String name = mvpb.getName(); Object value = mvpb.getValue(); args.put(name, value); } castAnnotations.add( new CAstAnnotation() { @Override public CAstType getType() { return annotationType; } @Override public Map<String, Object> getArguments() { return args; } @Override public String toString() { return annotationType.getName() + args; } }); } return castAnnotations; } protected final class ProcedureEntity implements JavaProcedureEntity { // TAGALONG (make static, access ast) // From Code Body Entity private final Map<CAstNode, Collection<CAstEntity>> fEntities; @Override public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() { return Collections.unmodifiableMap(fEntities); } @Override public Iterator<CAstEntity> getScopedEntities(CAstNode construct) { if (fEntities.containsKey(construct)) { return fEntities.get(construct).iterator(); } else { return EmptyIterator.instance(); } } @Override public String getSignature() { return Util.methodEntityToSelector(this).toString(); } private final CAstNode fAst; MethodDeclaration fDecl; // TAGALONG serious tagalong... private final String[] fParameterNames; // INCLUDING this private final ArrayList<CAstType> fParameterTypes; private final MethodContext fContext; // possibly TAGALONG, maybe not private final ITypeBinding fType; // TAGALONG private final ITypeBinding fReturnType; private final int fModifiers; private final Set<CAstAnnotation> annotations; // can be method, constructor, "fake" default constructor, or null decl = static initializer /** For a static initializer, pass a null decl. */ // FIXME: get rid of decl and pass in everything instead of having to do two different things // with parameters // regular case private ProcedureEntity( CAstNode mdast, MethodDeclaration decl, ITypeBinding type, Map<CAstNode, CAstEntity> entities, MethodContext context, Set<CAstAnnotation> annotations) { this(mdast, decl, type, entities, context, null, null, decl.getModifiers(), annotations); } // static init private ProcedureEntity( CAstNode mdast, ITypeBinding type, Map<CAstNode, CAstEntity> entities, MethodContext context, Set<CAstAnnotation> annotations) { this(mdast, null, type, entities, context, null, null, 0, annotations); } private ProcedureEntity( CAstNode mdast, MethodDeclaration decl, ITypeBinding type, Map<CAstNode, CAstEntity> entities, MethodContext context, ArrayList<CAstType> parameterTypes, ITypeBinding returnType, Set<CAstAnnotation> annotations) { this( mdast, decl, type, entities, context, parameterTypes, returnType, decl.getModifiers(), annotations); } private ProcedureEntity( CAstNode mdast, MethodDeclaration decl, ITypeBinding type, Map<CAstNode, CAstEntity> entities, MethodContext context, ArrayList<CAstType> parameterTypes, ITypeBinding returnType, int modifiers, Set<CAstAnnotation> annotations) { // TypeSystem system, CodeInstance pd, String[] argumentNames, // } // Map<CAstNode, CAstEntity> entities, MethodContext mc) { fDecl = decl; fAst = mdast; // "procedure decl ast" fContext = context; fType = type; fReturnType = returnType; fModifiers = modifiers; this.annotations = annotations; // from CodeBodyEntity fEntities = new LinkedHashMap<>(); for (Map.Entry<CAstNode, CAstEntity> entry : entities.entrySet()) { fEntities.put(entry.getKey(), Collections.singleton(entry.getValue())); } if (fDecl != null) { int i = 0; // index to start filling up with real params if ((fModifiers & Modifier.STATIC) != 0) { fParameterNames = new String[fDecl.parameters().size()]; i = 0; } else { fParameterNames = new String[fDecl.parameters().size() + 1]; fParameterNames[0] = "this"; i = 1; } if (parameterTypes == null) { fParameterTypes = new ArrayList<>(fDecl.parameters().size()); for (SingleVariableDeclaration p : (Iterable<SingleVariableDeclaration>) fDecl.parameters()) { fParameterNames[i++] = p.getName().getIdentifier(); fParameterTypes.add(fTypeDict.getCAstTypeFor(p.resolveBinding().getType())); } } else { // currently this is only used in making a default constructor with arguments (anonymous // classes). // this is because we cannot synthesize bindings. fParameterTypes = parameterTypes; for (SingleVariableDeclaration p : (Iterable<SingleVariableDeclaration>) fDecl.parameters()) { fParameterNames[i++] = p.getName().getIdentifier(); } } } else { fParameterNames = new String[0]; fParameterTypes = new ArrayList<>(0); // static initializer } } @Override public Collection<CAstAnnotation> getAnnotations() { return annotations; } @Override public String toString() { return fDecl == null ? "<clinit>" : fDecl.toString(); } @Override public int getKind() { return CAstEntity.FUNCTION_ENTITY; } @Override public String getName() { if (fDecl == null) return MethodReference.clinitName.toString(); else if (fDecl.isConstructor()) return MethodReference.initAtom.toString(); else return fDecl.getName().getIdentifier(); } /** INCLUDING first parameter 'this' (for non-static methods) */ @Override public String[] getArgumentNames() { return fParameterNames; } @Override public CAstNode[] getArgumentDefaults() { return new CAstNode[0]; } /** INCLUDING first parameter 'this' (for non-static methods) */ @Override public int getArgumentCount() { return fParameterNames.length; } @Override public CAstNode getAST() { return fAst; } @Override public CAstControlFlowMap getControlFlow() { return fContext.cfg(); } @Override public CAstSourcePositionMap getSourceMap() { return fContext.pos(); } @Override public CAstSourcePositionMap.Position getPosition() { return fDecl == null ? getSourceMap().getPosition(fAst) : makePosition(fDecl); } @Override public CAstNodeTypeMap getNodeTypeMap() { return fContext.getNodeTypeMap(); } @Override public Collection<CAstQualifier> getQualifiers() { if (fDecl == null) return JDT2CAstUtils.mapModifiersToQualifiers(Modifier.STATIC, false, false); // static init else return JDT2CAstUtils.mapModifiersToQualifiers(fModifiers, false, false); } @Override public CAstType getType() { return new CAstType.Method() { private Collection<CAstType> fExceptionTypes = null; @Override public boolean isStatic() { return getQualifiers().contains(CAstQualifier.STATIC); } @Override public CAstType getReturnType() { if (fReturnType != null) return fTypeDict.getCAstTypeFor(fReturnType); @SuppressWarnings("deprecation") Type type = fDecl == null ? null : (ast.apiLevel() == 2 ? fDecl.getReturnType() : fDecl.getReturnType2()); if (type == null) return fTypeDict.getCAstTypeFor(ast.resolveWellKnownType("void")); else return fTypeDict.getCAstTypeFor(type.resolveBinding()); } /** NOT INCLUDING first parameter 'this' (for non-static methods) */ @Override public List<CAstType> getArgumentTypes() { return fParameterTypes; } /** NOT INCLUDING first parameter 'this' (for non-static methods) */ @Override public int getArgumentCount() { return fDecl == null ? 0 : fParameterTypes.size(); } @Override public String getName() { Assertions.UNREACHABLE("CAstType.FunctionImpl#getName() called???"); return "?"; } @Override public Collection<CAstType> getSupertypes() { Assertions.UNREACHABLE("CAstType.FunctionImpl#getSupertypes() called???"); return null; } @Override public Collection<CAstType> /* <CAstType> */ getExceptionTypes() { if (fExceptionTypes == null) { fExceptionTypes = new LinkedHashSet<>(); if (fDecl != null) for (SimpleType exception : (Iterable<SimpleType>) fDecl.thrownExceptionTypes()) fExceptionTypes.add(fTypeDict.getCAstTypeFor(exception.resolveBinding())); } return fExceptionTypes; } @Override public CAstType getDeclaringType() { return fTypeDict.getCAstTypeFor(fType); } }; } @Override public Position getPosition(int arg) { // TODO Auto-generated method stub SingleVariableDeclaration p = (SingleVariableDeclaration) fDecl.parameters().get(arg); return makePosition(p); } @Override public Position getNamePosition() { if (fDecl == null || fDecl.getName() == null) { return null; } else { return makePosition(fDecl.getName()); } } } // //////////////////////////////////// // FIELDS //////////////////////////// // //////////////////////////////////// // FIELDS ADDED DIRECTLY IN visit(TypeDeclaration,WalkContext) private CAstNode visitFieldInitNode(ASTNode node, WalkContext context) { // there are gathered by createClassDeclaration and can only be of two types: if (node instanceof Initializer) { return visitNode(((Initializer) node).getBody(), context); } else if (node instanceof VariableDeclarationFragment) { VariableDeclarationFragment f = (VariableDeclarationFragment) node; // this is guaranteed to have an initializer // Generate CAST node for the initializer (init()) // Type targetType = f.memberInstance().container(); // Type fieldType = f.type().type(); FieldReference fieldRef = fIdentityMapper.getFieldRef(f.resolveBinding()); // We use null to indicate an OBJECT_REF to a static field, as the // FieldReference doesn't // hold enough info to determine this. In this case, (unlike field ref) // we don't have a // target expr to evaluate. boolean isStatic = ((f.resolveBinding().getModifiers() & Modifier.STATIC) != 0); CAstNode thisNode = isStatic ? makeNode(context, fFactory, null, CAstNode.VOID) : makeNode(context, fFactory, f, CAstNode.THIS); CAstNode lhsNode = makeNode( context, fFactory, f, CAstNode.OBJECT_REF, thisNode, fFactory.makeConstant(fieldRef)); Expression init = f.getInitializer(); CAstNode rhsNode = visitNode(init, context); CAstNode assNode = makeNode(context, fFactory, f, CAstNode.ASSIGN, lhsNode, rhsNode); return assNode; // their naming, not mine } else if (node instanceof EnumConstantDeclaration) { return createEnumConstantDeclarationInit((EnumConstantDeclaration) node, context); } else { Assertions.UNREACHABLE("invalid init node gathered by createClassDeclaration"); return null; } } protected final class FieldEntity implements CAstEntity { private final ITypeBinding type; private final String name; private final Collection<CAstQualifier> quals; private final T position; private final T namePos; private final Set<CAstAnnotation> annotations; private FieldEntity( String name, ITypeBinding type, Collection<CAstQualifier> quals, T position, Set<CAstAnnotation> annotations, T namePos) { super(); this.type = type; this.quals = quals; this.name = name; this.namePos = namePos; this.position = position; this.annotations = annotations; } @Override public Collection<CAstAnnotation> getAnnotations() { return annotations; } @Override public int getKind() { return CAstEntity.FIELD_ENTITY; } @Override public String getName() { return name; } @Override public String getSignature() { return name + fIdentityMapper.typeToTypeID(type); } @Override public String[] getArgumentNames() { return new String[0]; } @Override public CAstNode[] getArgumentDefaults() { return new CAstNode[0]; } @Override public int getArgumentCount() { return 0; } @Override public Iterator<CAstEntity> getScopedEntities(CAstNode construct) { return EmptyIterator.instance(); } @Override public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() { return Collections.emptyMap(); } @Override public CAstNode getAST() { // No AST for a field decl; initializers folded into // constructor processing... return null; } @Override public CAstControlFlowMap getControlFlow() { // No AST for a field decl; initializers folded into // constructor processing... return null; } @Override public CAstSourcePositionMap getSourceMap() { // No AST for a field decl; initializers folded into // constructor processing... return null; } @Override public CAstSourcePositionMap.Position getPosition() { return position; } @Override public CAstNodeTypeMap getNodeTypeMap() { // No AST for a field decl; initializers folded into // constructor processing... return null; } @Override public Collection<CAstQualifier> getQualifiers() { return quals; } @Override public CAstType getType() { return fTypeDict.getCAstTypeFor(type); } @Override public Position getPosition(int arg) { return namePos; } @Override public Position getNamePosition() { // TODO Auto-generated method stub return null; } } // ///////////////////////////////////// // / NODES ///////////////////////////// // ///////////////////////////////////// /** * Visit all the statements in the block and return an arraylist of the statements. Some * statements (VariableDeclarationStatements) may expand to more than one CAstNode. */ private ArrayList<CAstNode> createBlock(Block n, WalkContext context) { ArrayList<CAstNode> stmtNodes = new ArrayList<>(); for (ASTNode s : (Iterable<ASTNode>) n.statements()) visitNodeOrNodes(s, context, stmtNodes); return stmtNodes; } private CAstNode visit(Block n, WalkContext context) { ArrayList<CAstNode> stmtNodes = createBlock(n, context); return makeNode( context, fFactory, n, CAstNode.LOCAL_SCOPE, makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, stmtNodes)); } private CAstNode visit(VariableDeclarationFragment n, WalkContext context) { int modifiers; if (n.getParent() instanceof VariableDeclarationStatement) modifiers = ((VariableDeclarationStatement) n.getParent()).getModifiers(); else if (n.getParent() instanceof VariableDeclarationExpression) modifiers = ((VariableDeclarationExpression) n.getParent()).getModifiers(); else modifiers = ((FieldDeclaration) n.getParent()).getModifiers(); boolean isFinal = (modifiers & Modifier.FINAL) != 0; assert n.resolveBinding() != null : n; ITypeBinding type = n.resolveBinding().getType(); Expression init = n.getInitializer(); CAstNode initNode; String t = type.getBinaryName(); if (init == null) { if (JDT2CAstUtils.isLongOrLess(type)) // doesn't include boolean initNode = fFactory.makeConstant(0); else if (t.equals("D") || t.equals("F")) initNode = fFactory.makeConstant(0.0); else initNode = fFactory.makeConstant(null); } else initNode = visitNode(init, context); Object defaultValue = JDT2CAstUtils.defaultValueForType(type); return makeNode( context, fFactory, n, CAstNode.DECL_STMT, fFactory.makeConstant( new CAstSymbolImpl( n.getName().getIdentifier(), fTypeDict.getCAstTypeFor(type), isFinal, defaultValue)), initNode); } /* * One VariableDeclarationStatement represents more than one CAstNode statement. */ private ArrayList<CAstNode> visit(VariableDeclarationStatement n, WalkContext context) { ArrayList<CAstNode> result = new ArrayList<>(); for (VariableDeclarationFragment o : (Iterable<VariableDeclarationFragment>) n.fragments()) result.add(visit(o, context)); return result; } private CAstNode visit(VariableDeclarationExpression n, WalkContext context) { ArrayList<CAstNode> result = new ArrayList<>(); for (VariableDeclarationFragment o : (Iterable<VariableDeclarationFragment>) n.fragments()) result.add(visit(o, context)); return fFactory.makeNode(CAstNode.BLOCK_EXPR, result); } private CAstNode visit(ArrayInitializer n, WalkContext context) { ITypeBinding type = n.resolveTypeBinding(); assert type != null : "Could not determine type of ArrayInitializer"; TypeReference newTypeRef = fIdentityMapper.getTypeRef(type); List<CAstNode> eltNodes = new ArrayList<>(n.expressions().size() + 1); eltNodes.add( makeNode( context, fFactory, n, CAstNode.NEW, fFactory.makeConstant(newTypeRef), fFactory.makeConstant(n.expressions().size()))); for (Expression element : (Iterable<Expression>) n.expressions()) { final CAstNode visited = visitNode(element, context); assert visited != null : element.toString(); eltNodes.add(visited); } return makeNode(context, fFactory, n, CAstNode.ARRAY_LITERAL, eltNodes); } private CAstNode visit(ClassInstanceCreation n, WalkContext context) { return createClassInstanceCreation( n, n.arguments(), n.resolveConstructorBinding(), n.getExpression(), n.getAnonymousClassDeclaration(), context); } private CAstNode createClassInstanceCreation( ASTNode nn, List<?> arguments, IMethodBinding ctorBinding, Expression qual, AnonymousClassDeclaration anonDecl, WalkContext context) { // a new instruction is actually two things: a NEW object and a CALL to a constructor CAstNode newNode; CAstNode callNode; final String tmpName = "ctor temp"; // this name is an illegal Java identifier. this var will hold the new object so we can call the // constructor on it // GENERICS getMethodDeclaration() ctorBinding = ctorBinding.getMethodDeclaration(); // unlike polyglot, this will // point to a default // constructor in the anon class MethodReference ctorRef = fIdentityMapper.getMethodRef(ctorBinding); // ////////////// PART I: make the NEW expression // /////////////////////////////////////////////////////// ITypeBinding newType = ctorBinding.getDeclaringClass(); TypeReference newTypeRef = fIdentityMapper.getTypeRef(newType); // new nodes with an explicit enclosing argument, e.g. "outer.new Inner()". They are mostly // treated the same, except // in JavaCAst2IRTranslator.doNewObject CAstNode qualNode = null; if (qual == null && newType.getDeclaringClass() != null && ((newType.getModifiers() & Modifier.STATIC) == 0) && !newType.isLocal()) { // "new X()" expanded into "new this.X()" or "new MyClass.this.X" // check isLocal because anonymous classes and local classes are not included. ITypeBinding plainThisType = JDT2CAstUtils.getDeclaringClassOfNode(nn); // type of "this" ITypeBinding implicitThisType = findClosestEnclosingClassSubclassOf( plainThisType, newType.getDeclaringClass(), ((newType.getModifiers() & Modifier.PRIVATE) != 0)); if (implicitThisType.isEqualTo(plainThisType)) qualNode = makeNode(context, fFactory, nn, CAstNode.THIS); // "new this.X()" else qualNode = makeNode( context, fFactory, nn, CAstNode.THIS, fFactory.makeConstant( fIdentityMapper.getTypeRef(implicitThisType))); // "new Bla.this.X()" } else if (qual != null) qualNode = visitNode(qual, context); if (qualNode != null) newNode = makeNode( context, fFactory, nn, CAstNode.NEW_ENCLOSING, fFactory.makeConstant(newTypeRef), qualNode); else newNode = makeNode(context, fFactory, nn, CAstNode.NEW, fFactory.makeConstant(newTypeRef)); ITypeBinding[] newExceptions = new ITypeBinding[] {NoClassDefFoundError, ExceptionInInitializerError, OutOfMemoryError}; context.cfg().map(newNode, newNode); for (ITypeBinding exp : newExceptions) { for (Pair<ITypeBinding, Object> catchTarget : context.getCatchTargets(exp)) { context.cfg().add(newNode, catchTarget.snd, catchTarget.fst); } } // ANONYMOUS CLASSES // ctor already points to right place, so should type ref, so all we have to do is make the // entity if (anonDecl != null) context.addScopedEntity(newNode, visit(anonDecl, context)); // ////////////// PART II: make the CALL expression // /////////////////////////////////////////////////////// // setup args & handle exceptions List<CAstNode> argNodes = new ArrayList<>(arguments.size() + 2); // arg 0: this argNodes.add( makeNode( context, fFactory, nn, CAstNode.VAR, fFactory.makeConstant(tmpName), fFactory.makeConstant(fTypeDict.getCAstTypeFor(newType)))); // contains output from newNode (see part III) // arg 1: call site ref (WHY?) int dummyPC = 0; // Just want to wrap the kind of call; the "rear end" won't care about anything else CallSiteReference callSiteRef = CallSiteReference.make(dummyPC, ctorRef, IInvokeInstruction.Dispatch.SPECIAL); argNodes.add(fFactory.makeConstant(callSiteRef)); // rest of args for (Object arg : arguments) { argNodes.add( (arg instanceof CAstNode) ? ((CAstNode) arg) : visitNode((Expression) arg, context)); } callNode = makeNode(context, fFactory, nn, CAstNode.CALL, argNodes); context.cfg().map(nn, callNode); handleThrowsFromCall(ctorBinding, nn, context); // PART III: make a node with both NEW and CALL // Make a LOCAL_SCOPE with a BLOCK_EXPR node child which does three things: // 1) declare a temporary variable and assign the new object to it (LOCAL_SCOPE is needed to // chain this new variable // to this block) // 2) CALL the constructor on the new variable // 3) access this temporary variable. Since the value of the block is the last thing in the // block, the resultant // value will be the variable return makeNode( context, fFactory, nn, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, nn, CAstNode.BLOCK_EXPR, makeNode( context, fFactory, nn, CAstNode.DECL_STMT, fFactory.makeConstant( new InternalCAstSymbol(tmpName, fTypeDict.getCAstTypeFor(newType), true)), newNode), callNode, makeNode(context, fFactory, nn, CAstNode.VAR, fFactory.makeConstant(tmpName)))); } /** * @param mappedAstNode An AST node or object mapped in the CFG: we will call context.cfg().add() * on it. Caller must worry about mapping it with context.cfg().map(). */ private void handleThrowsFromCall(IMethodBinding met, Object mappedAstNode, WalkContext context) { ITypeBinding[] throwTypes = met.getExceptionTypes(); for (ITypeBinding thrownType : throwTypes) { Collection<Pair<ITypeBinding, Object>> catchTargets = context.getCatchTargets(thrownType); for (Pair<ITypeBinding, Object> catchTarget : catchTargets) context.cfg().add(mappedAstNode, catchTarget.snd, catchTarget.fst); } // can also throw runtime exception for (Pair<ITypeBinding, Object> catchTarget : context.getCatchTargets(fRuntimeExcType)) context.cfg().add(mappedAstNode, catchTarget.snd, catchTarget.fst); } private CAstNode visit(ExpressionStatement n, WalkContext context) { return visitNode(n.getExpression(), context); } private CAstNode visit(SuperMethodInvocation n, WalkContext context) { CAstNode target; if (n.getQualifier() == null) target = makeNode(context, fFactory, n, CAstNode.SUPER); else { TypeReference owningTypeRef = fIdentityMapper.getTypeRef(n.getQualifier().resolveTypeBinding()); target = makeNode(context, fFactory, n, CAstNode.SUPER, fFactory.makeConstant(owningTypeRef)); } // GENERICS getMethodDeclaration() return createMethodInvocation( n, n.resolveMethodBinding().getMethodDeclaration(), target, n.arguments(), context); } // FIXME: implicit this private CAstNode visit(MethodInvocation n, WalkContext context) { // GENERICS getMethodDeclaration() IMethodBinding binding = n.resolveMethodBinding().getMethodDeclaration(); if ((binding.getModifiers() & Modifier.STATIC) != 0) { CAstNode target; // JLS says: evaluate qualifier & throw away unless of course it's just a class name (or // null), // in which case we replace the EMPTY with a VOID // of course, "this" has no side effects either. target = visitNode(n.getExpression(), context); if (target.getKind() == CAstNode.EMPTY || target.getKind() == CAstNode.THIS) return createMethodInvocation( n, binding, makeNode(context, fFactory, null, CAstNode.VOID), n.arguments(), context); else return makeNode( context, fFactory, n, CAstNode.BLOCK_EXPR, target, createMethodInvocation( n, binding, makeNode(context, fFactory, null, CAstNode.VOID), n.arguments(), context)); // target is evaluated but thrown away, and only result of method invocation is kept } else { CAstNode target; if (n.getExpression() != null) { target = visitNode(n.getExpression(), context); } else { ITypeBinding typeOfThis = JDT2CAstUtils.getDeclaringClassOfNode(n); boolean methodIsPrivate = (binding.getModifiers() & Modifier.PRIVATE) != 0; // how could it be in the subtype and private? this only happens the supertype is also an // enclosing type. in that case the variable refers to the field in the enclosing instance. // NOTE: method may be defined in MyClass's superclass, but we still want to expand // this into MyClass, so we have to find the enclosing class which defines this function. ITypeBinding implicitThisClass = findClosestEnclosingClassSubclassOf( typeOfThis, binding.getDeclaringClass(), methodIsPrivate); if (typeOfThis.isEqualTo(implicitThisClass)) // "foo = 5" -> "this.foo = 5": expand into THIS + class target = makeNode(context, fFactory, n, CAstNode.THIS); else // "foo = 5" -> "MyClass.this.foo = 5" -- inner class: expand into THIS + class target = makeNode( context, fFactory, n, CAstNode.THIS, fFactory.makeConstant(fIdentityMapper.getTypeRef(implicitThisClass))); // NOTE: method may be defined in MyClass's superclass, but we still want to expand // this into MyClass, so we have to find the enclosing class which defines this function. } CAstNode node = createMethodInvocation(n, binding, target, n.arguments(), context); // TODO: maybe not exactly right... what if it's a capture? we may have to cast it down a // little bit. if (binding.getReturnType().isTypeVariable()) { // GENERICS: add a cast ITypeBinding realtype = JDT2CAstUtils.getErasedType(n.resolveMethodBinding().getReturnType(), ast); ITypeBinding fromtype = JDT2CAstUtils.getTypesVariablesBase(binding.getReturnType(), ast); if (!realtype.isEqualTo(fromtype)) return createCast(n, node, fromtype, realtype, context); } return node; } } private CAstNode createMethodInvocation( ASTNode pos, IMethodBinding methodBinding, CAstNode target, List<?> arguments, WalkContext context) { // MethodMethodInstance methodInstance = n.methodInstance(); boolean isStatic = (methodBinding.getModifiers() & Modifier.STATIC) != 0; ITypeBinding methodOwner = methodBinding.getDeclaringClass(); if (!(methodOwner.isInterface() || methodOwner.isClass() || methodOwner.isEnum())) { assert false : "owner " + methodOwner + " of " + methodBinding + " is not a class"; } // POPULATE PARAMETERS // this (or void for static), method reference, rest of args int nFormals = methodBinding.getParameterTypes().length; List<CAstNode> children = new ArrayList<>(2 + nFormals); // this (or void for static) assert target != null : "no receiver for " + methodBinding; children.add(target); // method reference // unlike polyglot, expression will never be super here. this is handled in // SuperMethodInvocation. IInvokeInstruction.IDispatch dispatchType; if (isStatic) dispatchType = IInvokeInstruction.Dispatch.STATIC; else if (methodOwner.isInterface()) dispatchType = IInvokeInstruction.Dispatch.INTERFACE; else if ((methodBinding.getModifiers() & Modifier.PRIVATE) != 0 || target.getKind() == CAstNode.SUPER) // only one possibility, not a virtual call (I guess?) dispatchType = IInvokeInstruction.Dispatch.SPECIAL; else dispatchType = IInvokeInstruction.Dispatch.VIRTUAL; // pass 0 for dummyPC: Just want to wrap the kind of call; the "rear end" won't care about // anything else... CallSiteReference callSiteRef = CallSiteReference.make(0, fIdentityMapper.getMethodRef(methodBinding), dispatchType); children.add(fFactory.makeConstant(callSiteRef)); populateArguments(children, methodBinding, arguments, context); Object fakeCfgMap = new Object(); handleThrowsFromCall(methodBinding, fakeCfgMap, context); CAstNode result = makeNode(context, fFactory, pos, CAstNode.CALL, children); context.cfg().map(fakeCfgMap, result); return result; } /** * Populate children, starting at index 2, for the invocation of methodBinding. If varargs are * used this function will collapse the proper arguments into an array. * * <p>If the number of actuals equals the number of formals and the function is varargs, we have * to check the type of the last argument to see if we should "box" it in an array. If the * arguments[arguments.length-1] is not an Expression, we cannot get the type, so we do not box * it. (Making covariant varargs functions require this behavior) */ private void populateArguments( List<CAstNode> children, IMethodBinding methodBinding, List<? /* CAstNode or Expression */> arguments, WalkContext context) { int nFormals = methodBinding.getParameterTypes().length; assert children.size() == 2; int nActuals = arguments.size(); ITypeBinding lastArgType = null; if (nActuals > 0 && arguments.get(nActuals - 1) instanceof Expression) lastArgType = ((Expression) arguments.get(nActuals - 1)).resolveTypeBinding(); // if the # of actuals equals the # of formals, AND the function is varargs, we have to check // to see if the lastArgType is subtype compatible with the type of last parameter (which will // be an array). // If it is, we pass this array in directly. Otherwise this it is wrapped in an array init. // Example: 'void foo(int... x)' can be run via 'foo(5)' or 'foo(new int[] { 5, 6 })' -- both // have one argument so we must check // the type if (nActuals == nFormals && (!methodBinding.isVarargs() || lastArgType == null || lastArgType.isSubTypeCompatible(methodBinding.getParameterTypes()[nFormals - 1]))) { for (Object arg : arguments) children.add( (arg instanceof CAstNode) ? ((CAstNode) arg) : visitNode((Expression) arg, context)); } else { assert nActuals >= (nFormals - 1) && methodBinding.isVarargs() : "Invalid number of parameters for constructor call"; for (int i = 0; i < nFormals - 1; i++) { Object arg = arguments.get(i); children.add( (arg instanceof CAstNode) ? ((CAstNode) arg) : visitNode((Expression) arg, context)); } final int numSubargs = nActuals - nFormals + 2; List<CAstNode> subargs = new ArrayList<>(numSubargs); // nodes for args and one extra for NEW expression TypeReference newTypeRef = fIdentityMapper.getTypeRef(methodBinding.getParameterTypes()[nFormals - 1]); subargs.add( makeNode( context, fFactory, null, CAstNode.NEW, fFactory.makeConstant(newTypeRef), fFactory.makeConstant(numSubargs - 1))); for (int j = 1; j < numSubargs; j++) { Object arg = arguments.get(j + nFormals - 2); subargs.add( (arg instanceof CAstNode) ? ((CAstNode) arg) : visitNode((Expression) arg, context)); } children.add(makeNode(context, fFactory, (ASTNode) null, CAstNode.ARRAY_LITERAL, subargs)); } } private CAstNode visit(ReturnStatement r, WalkContext context) { Expression retExpr = r.getExpression(); if (retExpr == null) return makeNode(context, fFactory, r, CAstNode.RETURN); else return makeNode(context, fFactory, r, CAstNode.RETURN, visitNode(retExpr, context)); } private CAstNode visit(Assignment n, WalkContext context) { if (n.getOperator() == Assignment.Operator.ASSIGN) return makeNode( context, fFactory, n, CAstNode.ASSIGN, visitNode(n.getLeftHandSide(), new AssignmentContext(context)), visitNode(n.getRightHandSide(), context)); else { CAstNode left = visitNode(n.getLeftHandSide(), context); // GENERICs lvalue for pre op hack if (left.getKind() == CAstNode.CAST) { return doFunkyGenericAssignPreOpHack(n, context); } // +=, %=, &=, etc. CAstNode result = makeNode( context, fFactory, n, CAstNode.ASSIGN_PRE_OP, left, visitNode(n.getRightHandSide(), context), JDT2CAstUtils.mapAssignOperator(n.getOperator())); // integer division by zero if (JDT2CAstUtils.isLongOrLess(n.resolveTypeBinding()) && (n.getOperator() == Assignment.Operator.DIVIDE_ASSIGN || n.getOperator() == Assignment.Operator.REMAINDER_ASSIGN)) { Collection<Pair<ITypeBinding, Object>> excTargets = context.getCatchTargets(fDivByZeroExcType); if (!excTargets.isEmpty()) { for (Pair<ITypeBinding, Object> catchPair : excTargets) context.cfg().add(result, catchPair.snd, fDivByZeroExcType); } else { context.cfg().add(result, CAstControlFlowMap.EXCEPTION_TO_EXIT, fDivByZeroExcType); } } return result; } } /** * Consider the case: * * <pre> * String real_oneheyya = (((returnObjectWithSideEffects().y))+=&quot;hey&quot;)+&quot;ya&quot; * </pre> * * where field 'y' is parameterized to type string. then += is not defined for type 'object'. This * function is a hack that expands the code into an assignment and binary operation. */ private CAstNode doFunkyGenericAssignPreOpHack(Assignment assign, WalkContext context) { Expression left = assign.getLeftHandSide(); Expression right = assign.getRightHandSide(); // consider the case: // String real_oneheyya = (((returnObjectWithSideEffects().y))+="hey")+"ya"; // this is going to // be a MAJOR pain... // where field 'y' is parameterized to type string. then += is not defined for type 'object'. we // want to transform // it kind of like this, except we have to define temp. // String real_oneheyya = (String)((temp=cg2WithSideEffects()).y = (String)temp.y + "hey")+"ya"; // ---------------------------------------------------------------- // // we are responsible for underlined portion // CAST(LOCAL SCOPE(BLOCK EXPR(DECL STMT(temp, // left.target),ASSIGN(OBJECT_REF(temp,y),BINARY_EXPR(CAST(OBJECT_REF(Temp,y)),RIGHT))))) // yeah, I know, it's cheating, LOCAL SCOPE / DECL STMT inside an expression ... will it work? while (left instanceof ParenthesizedExpression) left = ((ParenthesizedExpression) left).getExpression(); assert left instanceof FieldAccess : "Cast in assign pre-op but no field access?!"; FieldAccess field = (FieldAccess) left; InfixExpression.Operator infixop = JDT2CAstUtils.mapAssignOperatorToInfixOperator(assign.getOperator()); // DECL_STMT: temp = ...; final String tmpName = "temp generic preop hack"; // illegal Java identifier CAstNode exprNode = visitNode(field.getExpression(), context); CAstNode tmpDeclNode = makeNode( context, fFactory, left, CAstNode.DECL_STMT, fFactory.makeConstant( new InternalCAstSymbol( tmpName, fTypeDict.getCAstTypeFor(field.getExpression().resolveTypeBinding()), true)), exprNode); // need two object refndoes "temp.y" CAstNode obref1 = createFieldAccess( makeNode( context, fFactory, left, CAstNode.VAR, fFactory.makeConstant(tmpName), fFactory.makeConstant( fTypeDict.getCAstTypeFor(field.resolveFieldBinding().getType()))), field.getName().getIdentifier(), field.resolveFieldBinding(), left, new AssignmentContext(context)); CAstNode obref2 = createFieldAccess( makeNode( context, fFactory, left, CAstNode.VAR, fFactory.makeConstant(tmpName), fFactory.makeConstant( fTypeDict.getCAstTypeFor(field.resolveFieldBinding().getType()))), field.getName().getIdentifier(), field.resolveFieldBinding(), left, context); ITypeBinding realtype = JDT2CAstUtils.getErasedType(field.resolveFieldBinding().getType(), ast); ITypeBinding fromtype = JDT2CAstUtils.getTypesVariablesBase( field.resolveFieldBinding().getVariableDeclaration().getType(), ast); CAstNode castedObref = obref2; // createCast(left, obref2, fromtype, realtype, context); // put it all together // CAST(LOCAL SCOPE(BLOCK EXPR(DECL STMT(temp, // left.target),ASSIGN(OBJECT_REF(temp,y),BINARY_EXPR(CAST(OBJECT_REF(Temp,y)),RIGHT))))) CAstNode result = makeNode( context, fFactory, assign, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, assign, CAstNode.BLOCK_EXPR, tmpDeclNode, makeNode( context, fFactory, assign, CAstNode.ASSIGN, obref1, createInfixExpression( infixop, realtype, left.getStartPosition(), left.getLength(), castedObref, right, context)))); return createCast(assign, result, fromtype, realtype, context); } private CAstNode visit(ParenthesizedExpression n, WalkContext context) { return visitNode(n.getExpression(), context); } private CAstNode visit(BooleanLiteral n) { return fFactory.makeConstant(n.booleanValue()); } private CAstNode visit(CharacterLiteral n) { return fFactory.makeConstant(n.charValue()); } private CAstNode visit() { return fFactory.makeConstant(null); } private CAstNode visit(StringLiteral n, WalkContext context) { CAstNode str = fFactory.makeConstant(n.getLiteralValue()); setPos(context, str, n); return str; } private CAstNode visit(TypeLiteral n, WalkContext context) { String typeName = fIdentityMapper.typeToTypeID(n.resolveTypeBinding()); return makeNode( context, fFactory, n, CAstNode.TYPE_LITERAL_EXPR, fFactory.makeConstant(typeName)); } private CAstNode visit(NumberLiteral n, WalkContext context) { CAstNode str = fFactory.makeConstant(n.resolveConstantExpressionValue()); setPos(context, str, n); return str; } /** SimpleName can be a field access, local, or class name (do nothing case) */ private CAstNode visit(SimpleName n, WalkContext context) { // class name, handled above in either method invocation, qualified name, or qualified this if (n.resolveBinding() instanceof ITypeBinding) return makeNode(context, fFactory, null, CAstNode.EMPTY); assert n.resolveBinding() instanceof IVariableBinding : "SimpleName's binding, " + n.resolveBinding() + ", is not a variable or a type binding!"; IVariableBinding binding = (IVariableBinding) n.resolveBinding(); binding = binding.getVariableDeclaration(); // ignore weird generic stuff // TODO: enum constants if (binding.isField()) { // enum constants ... // implicit field access -- implicit this or class CAstNode targetNode; if ((binding.getModifiers() & Modifier.STATIC) != 0) { // "foo = 5" -> "MyClass.foo = 5" or "SomeEnclosingClass.foo" = 5 targetNode = makeNode( context, fFactory, null, CAstNode.EMPTY); // we will get type from binding. no side // effects in evaluating a class name, so NOP // here. } else { ITypeBinding typeOfThis = JDT2CAstUtils.getDeclaringClassOfNode(n); boolean fieldIsPrivate = (binding.getModifiers() & Modifier.PRIVATE) != 0; // how could it be in the subtype and private? this only happens the supertype is also an // enclosing type. in that case the variable refers to the field in the enclosing instance. // NOTE: method may be defined in MyClass's superclass, but we still want to expand // this into MyClass, so we have to find the enclosing class which defines this function. ITypeBinding implicitThisClass = findClosestEnclosingClassSubclassOf( typeOfThis, binding.getDeclaringClass(), fieldIsPrivate); if (typeOfThis.isEqualTo(implicitThisClass)) // "foo = 5" -> "this.foo = 5": expand into THIS + class targetNode = makeNode(context, fFactory, n, CAstNode.THIS); else // "foo = 5" -> "MyClass.this.foo = 5" -- inner class: expand into THIS + class targetNode = makeNode( context, fFactory, n, CAstNode.THIS, fFactory.makeConstant(fIdentityMapper.getTypeRef(implicitThisClass))); // NOTE: method may be defined in MyClass's superclass, but we still want to expand // this into MyClass, so we have to find the enclosing class which defines this function. // fFactory.makeConstant(owningTypeRef)); } return createFieldAccess(targetNode, n.getIdentifier(), binding, n, context); } else { // local CAstType t = fTypeDict.getCAstTypeFor(((IVariableBinding) n.resolveBinding()).getType()); return makeNode( context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(n.getIdentifier()), fFactory.makeConstant(t)); } } /** * Sees if a field defined in owningTypeRef is contained & accessible to a type of typeOfThis. * That is, if owningTypeRef == typeOfThis or typeOfThis is a subtype and isPrivate is false. If * this is not that case, looks in the enclosing class of typeOfThis and tries again, and its * enclosing class, ... * * <p>Essentially if we have a field/method referenced only by name and we know its type * (owningTypeRef), this function will return owningTypeRef or the subtype that the field is * accessed thru, for expanding "f = 5" into "TheClass.this.f = 5". */ private static ITypeBinding findClosestEnclosingClassSubclassOf( ITypeBinding typeOfThis, ITypeBinding owningType, boolean isPrivate) { // GENERICS // if (owningType.isParameterizedType()) // owningType = owningType.getTypeDeclaration(); // if (typeOfThis.isParameterizedType()) // typeOfThis = typeOfThis.getTypeDeclaration(); // // typeOfThis.getTypeDeclaration() owningType = owningType.getErasure(); ITypeBinding current = typeOfThis; while (current != null) { current = current.getErasure(); // Walk the hierarchy rather than using isSubTypeCompatible to handle // generics -- we need to perform erasure of super types boolean isInSubtype = false; // current.isSubTypeCompatible(owningType); ITypeBinding supertp = current; while (supertp != null) { supertp = supertp.getErasure(); // Use isSubTypeCompatible even though we are manually walking type hierarchy -- // that way interfaces are handled without us having to do it manually. if (supertp.isSubTypeCompatible(owningType)) { isInSubtype = true; break; } supertp = supertp.getSuperclass(); } // how could it be in the subtype and private? this only happens the supertype is also an // enclosing type. in that case the variable refers to the field in the enclosing instance. if (current.isEqualTo(owningType) || (isInSubtype && !isPrivate)) return current; current = current.getDeclaringClass(); } Assertions.UNREACHABLE( "Couldn't find field in class or enclosing class or superclasses of these"); return null; } /** * Process a field access. Semantics differ for static and instance fields. Fields can throw null * pointer exceptions so we must connect proper exceptional edges in the CFG. */ private CAstNode visit(FieldAccess n, WalkContext context) { CAstNode targetNode = visitNode(n.getExpression(), context); return createFieldAccess( targetNode, n.getName().getIdentifier(), n.resolveFieldBinding(), n, context); } /** * Used by visit(FieldAccess) and visit(SimpleName) -- implicit "this" / static field access. * things from 'this' cannot throw an exception. maybe handle this in here as a special case? i * don't know... or check if targetNode is THIS, that should even work for this.x = 5 and (this).x * = 5 * * @param targetNode Used to evaluate the field access. In the case of static field accesses, this * is included in the first part of a block -- thus it is evaluated for any side effects but * thrown away. * @param fieldName Name of the field. * @param positioningNode Used only for making a JdtPosition. */ private CAstNode createFieldAccess( CAstNode targetNode, String fieldName, IVariableBinding possiblyParameterizedBinding, ASTNode positioningNode, WalkContext context) { IVariableBinding fieldBinding = possiblyParameterizedBinding.getVariableDeclaration(); ITypeBinding targetType = fieldBinding.getDeclaringClass(); if (targetType == null) { // array assert fieldName.equals("length") : "null targetType but not aray length access"; return makeNode(context, fFactory, positioningNode, CAstNode.ARRAY_LENGTH, targetNode); } assert fieldBinding.isField() : "Field binding is not a field?!"; // we can probably safely delete this // check // translate JDT field ref to WALA field ref FieldReference fieldRef = fIdentityMapper.getFieldRef(fieldBinding); if ((fieldBinding.getModifiers() & Modifier.STATIC) != 0) { // JLS says: evaluate the target of the field ref and throw it away. // Hence the following block expr, whose 2 children are the target // evaluation // followed by the OBJECT_REF with a null target child (which the // "back-end" // CAst -> IR translator interprets as a static ref). // TODO: enum constants // don't worry about generics (can't declare static fields with type variables) if (fieldBinding.getConstantValue() != null) { return makeNode( context, fFactory, positioningNode, CAstNode.BLOCK_EXPR, targetNode, fFactory.makeConstant(fieldBinding.getConstantValue())); } else { return makeNode( context, fFactory, positioningNode, CAstNode.BLOCK_EXPR, targetNode, makeNode( context, fFactory, positioningNode, CAstNode.OBJECT_REF, makeNode(context, fFactory, null, CAstNode.VOID), fFactory.makeConstant(fieldRef))); } } else { CAstNode refNode = makeNode( context, fFactory, positioningNode, CAstNode.OBJECT_REF, targetNode, fFactory.makeConstant(fieldRef)); if (targetNode.getKind() != CAstNode.THIS) { // this.x will never throw a null pointer exception, because this // can never be null Collection<Pair<ITypeBinding, Object>> excTargets = context.getCatchTargets(fNullPointerExcType); if (!excTargets.isEmpty()) { // connect NPE exception edge to relevant catch targets // (presumably only one) for (Pair<ITypeBinding, Object> catchPair : excTargets) { context.cfg().add(refNode, catchPair.snd, fNullPointerExcType); } } else { // connect exception edge to exit context.cfg().add(refNode, CAstControlFlowMap.EXCEPTION_TO_EXIT, fNullPointerExcType); } context.cfg().map(refNode, refNode); } if (fieldBinding.getConstantValue() != null) { // don't have to worry about generics, a constant of generic type can only be null return makeNode( context, fFactory, positioningNode, CAstNode.BLOCK_EXPR, refNode, // evaluating 'refNode' can have side effects, so we must still evaluate it! fFactory.makeConstant(fieldBinding.getConstantValue())); } else { if (fieldBinding.getType().isTypeVariable() && !context.needLValue()) { // GENERICS: add a cast ITypeBinding realtype = JDT2CAstUtils.getErasedType(possiblyParameterizedBinding.getType(), ast); ITypeBinding fromtype = JDT2CAstUtils.getTypesVariablesBase(fieldBinding.getType(), ast); if (!realtype.isEqualTo(fromtype)) return createCast(positioningNode, refNode, fromtype, realtype, context); } return refNode; } } } private CAstNode visit(ThisExpression n, WalkContext context) { if (n.getQualifier() != null) { ITypeBinding owningType = n.getQualifier().resolveTypeBinding(); TypeReference owningTypeRef = fIdentityMapper.getTypeRef(owningType); return makeNode(context, fFactory, n, CAstNode.THIS, fFactory.makeConstant(owningTypeRef)); } else return makeNode(context, fFactory, n, CAstNode.THIS); } /** * QualifiedNames may be: 1) static of non-static field accesses -- we handle this case here 2) * type names used in the context of: a) field access (QualifiedName) b) method invocation c) * qualifier of "this" in these cases we get the binding info in each of these three functions and * use them there, thus we return an EMPTY (no-op) here. 3) package names used in the context of a * QualifiedName class we return a EMPTY (no-op) here. */ private CAstNode visit(QualifiedName n, WalkContext context) { // "package.Class" is a QualifiedName, but also is "Class.staticField" // only handle if it's a "Class.staticField" ("Field" in polyglot AST) if (n.resolveBinding() instanceof IVariableBinding) { IVariableBinding binding = (IVariableBinding) n.resolveBinding(); assert binding.isField() : "Non-field variable QualifiedName!"; // if field access is static, visitNode(n.getQualifier()) will come back here // and we will return an EMPTY node return createFieldAccess( visitNode(n.getQualifier(), context), n.getName().getIdentifier(), binding, n, context); } else return makeNode(context, fFactory, null, CAstNode.EMPTY); // type name, handled in surrounding context } private CAstNode visit(InfixExpression n, WalkContext context) { Expression left = n.getLeftOperand(); ITypeBinding leftType = left.resolveTypeBinding(); int leftStartPosition = left.getStartPosition(); CAstNode leftNode = visitNode(left, context); int leftLength = n.getLeftOperand().getLength(); CAstNode result = createInfixExpression( n.getOperator(), leftType, leftStartPosition, leftLength, leftNode, n.getRightOperand(), context); if (n.hasExtendedOperands()) { // keep on adding operands on the right side leftLength = n.getRightOperand().getStartPosition() + n.getRightOperand().getLength() - leftStartPosition; for (Expression operand : (Iterable<Expression>) n.extendedOperands()) { result = createInfixExpression( n.getOperator(), leftType, leftStartPosition, leftLength, result, operand, context); if (leftType.isPrimitive() && operand.resolveTypeBinding().isPrimitive()) leftType = JDT2CAstUtils.promoteTypes( leftType, operand.resolveTypeBinding(), ast); // TODO: boxing else leftType = operand.resolveTypeBinding(); // leftStartPosition doesn't change, beginning is always the first operand leftLength = operand.getStartPosition() + operand.getLength() - leftStartPosition; } } return result; } private CAstNode createInfixExpression( InfixExpression.Operator op, ITypeBinding leftType, int leftStartPosition, int leftLength, CAstNode leftNode, Expression right, WalkContext context) { CAstNode rightNode = visitNode(right, context); int start = leftStartPosition; int end = right.getStartPosition() + right.getLength(); T pos = makePosition(start, end); T leftPos = makePosition(leftStartPosition, leftStartPosition + leftLength); T rightPos = makePosition(right.getStartPosition(), right.getStartPosition() + right.getLength()); if (op == InfixExpression.Operator.CONDITIONAL_AND) { return makeNode( context, fFactory, pos, CAstNode.IF_EXPR, leftNode, rightNode, fFactory.makeConstant(false)); } else if (op == InfixExpression.Operator.CONDITIONAL_OR) { return makeNode( context, fFactory, pos, CAstNode.IF_EXPR, leftNode, fFactory.makeConstant(true), rightNode); } else { ITypeBinding rightType = right.resolveTypeBinding(); if (leftType.isPrimitive() && rightType.isPrimitive()) { // TODO: boxing ITypeBinding result = JDT2CAstUtils.promoteTypes(leftType, rightType, ast); // cast to proper type if (!result.isEqualTo(leftType)) leftNode = makeNode( context, fFactory, leftPos, CAstNode.CAST, fFactory.makeConstant(fTypeDict.getCAstTypeFor(result)), leftNode, fFactory.makeConstant(fTypeDict.getCAstTypeFor(leftType))); if (!result.isEqualTo(rightType)) rightNode = makeNode( context, fFactory, rightPos, CAstNode.CAST, fFactory.makeConstant(fTypeDict.getCAstTypeFor(result)), rightNode, fFactory.makeConstant(fTypeDict.getCAstTypeFor(rightType))); CAstNode opNode = makeNode( context, fFactory, pos, CAstNode.BINARY_EXPR, JDT2CAstUtils.mapBinaryOpcode(op), leftNode, rightNode); // divide by zero exception implicitly thrown if (JDT2CAstUtils.isLongOrLess(leftType) && JDT2CAstUtils.isLongOrLess(rightType) && (JDT2CAstUtils.mapBinaryOpcode(op) == CAstOperator.OP_DIV || JDT2CAstUtils.mapBinaryOpcode(op) == CAstOperator.OP_MOD)) { Collection<Pair<ITypeBinding, Object>> excTargets = context.getCatchTargets(fDivByZeroExcType); if (!excTargets.isEmpty()) { for (Pair<ITypeBinding, Object> catchPair : excTargets) { context.cfg().add(op, catchPair.snd, fDivByZeroExcType); } } else { context.cfg().add(op, CAstControlFlowMap.EXCEPTION_TO_EXIT, fDivByZeroExcType); } } return opNode; } else { return makeNode( context, fFactory, pos, CAstNode.BINARY_EXPR, JDT2CAstUtils.mapBinaryOpcode(op), leftNode, rightNode); } } } private CAstNode visit(ConstructorInvocation n, WalkContext context) { // GENERICS getMethodDeclaration() return createConstructorInvocation( n.resolveConstructorBinding().getMethodDeclaration(), n.arguments(), n, context, false); } private CAstNode visit(SuperConstructorInvocation n, WalkContext context) { // FIXME: use expression?! polyglot doesn't handle it and it seems to be a very rare case. // class E { class X {} } // class Y extends E.X { Y(E e) { e.super(); } } // GENERICS getMethodDeclaration() return createConstructorInvocation( n.resolveConstructorBinding().getMethodDeclaration(), n.arguments(), n, context, true); } private CAstNode visit(SuperFieldAccess n, WalkContext context) { CAstNode targetNode; if (n.getQualifier() == null) targetNode = makeNode(context, fFactory, n, CAstNode.SUPER); else { TypeReference owningTypeRef = fIdentityMapper.getTypeRef(n.getQualifier().resolveTypeBinding()); targetNode = makeNode(context, fFactory, n, CAstNode.SUPER, fFactory.makeConstant(owningTypeRef)); } return createFieldAccess( targetNode, n.getName().getIdentifier(), n.resolveFieldBinding(), n, context); } /** callerNode: used for positioning and also in CFG (handleThrowsFrom Call) */ private CAstNode createConstructorInvocation( IMethodBinding ctorBinding, List<Expression> arguments, ASTNode callerNode, WalkContext context, boolean isSuper) { ITypeBinding ctorType = ctorBinding.getDeclaringClass(); assert ctorType.isClass(); // dummy PC = 0 -- Just want to wrap the kind of call; the "rear end" // won't care about anything else... CallSiteReference callSiteRef = CallSiteReference.make( 0, fIdentityMapper.getMethodRef(ctorBinding), IInvokeInstruction.Dispatch.SPECIAL); int nFormals = ctorBinding.getParameterTypes().length; List<CAstNode> children = new ArrayList<>(2 + nFormals); // this, call site ref, args CAstNode targetNode = makeNode(context, fFactory, callerNode, isSuper ? CAstNode.SUPER : CAstNode.THIS); children.add(targetNode); children.add(fFactory.makeConstant(callSiteRef)); populateArguments(children, ctorBinding, arguments, context); handleThrowsFromCall(ctorBinding, callerNode, context); CAstNode result = makeNode(context, fFactory, callerNode, CAstNode.CALL, children); context.cfg().map(context, result); return result; } private CAstNode visit(IfStatement n, WalkContext context) { return makeNode( context, fFactory, n, CAstNode.IF_STMT, visitNode(n.getExpression(), context), visitNode(n.getThenStatement(), context), visitNode(n.getElseStatement(), context)); } private CAstNode visit(InstanceofExpression n, WalkContext context) { return makeNode( context, fFactory, n, CAstNode.INSTANCEOF, fFactory.makeConstant(fTypeDict.getCAstTypeFor(n.getRightOperand().resolveBinding())), visitNode(n.getLeftOperand(), context)); } private CAstNode visit(CastExpression n, WalkContext context) { Expression arg = n.getExpression(); ITypeBinding castedFrom = arg.resolveTypeBinding(); ITypeBinding castedTo = n.getType().resolveBinding(); return createCast(n, visitNode(arg, context), castedFrom, castedTo, context); } private CAstNode createCast( ASTNode pos, CAstNode argNode, ITypeBinding castedFrom, ITypeBinding castedTo, WalkContext context) { Object cfgMapDummy = new Object(); // safer as 'pos' may be used for another purpose (i.e., this could be an // implicit cast) // null can go into anything (e.g. in "((Foobar) null)" null can be assumed to be of type Foobar // already) if (castedFrom.isNullType()) castedFrom = castedTo; CAstNode ast = makeNode( context, fFactory, pos, CAstNode.CAST, fFactory.makeConstant(fTypeDict.getCAstTypeFor(castedTo)), argNode, fFactory.makeConstant(fTypeDict.getCAstTypeFor(castedFrom))); Collection<Pair<ITypeBinding, Object>> excTargets = context.getCatchTargets(fClassCastExcType); if (!excTargets.isEmpty()) { // connect ClassCastException exception edge to relevant catch targets // (presumably only one) for (Pair<ITypeBinding, Object> catchPair : excTargets) { context.cfg().add(cfgMapDummy, catchPair.snd, fClassCastExcType); } } else { // connect exception edge to exit context.cfg().add(cfgMapDummy, CAstControlFlowMap.EXCEPTION_TO_EXIT, fClassCastExcType); } context.cfg().map(cfgMapDummy, ast); return ast; } private int ceCounter = 0; private CAstNode visit(ConditionalExpression n, WalkContext context) { String var = "ceTemporary" + ceCounter++; CAstNode declNode = makeNode( context, fFactory, n, CAstNode.DECL_STMT, fFactory.makeConstant( new InternalCAstSymbol( var, fTypeDict.getCAstTypeFor(n.getThenExpression().resolveTypeBinding()), true))); context.addNameDecl(declNode); return makeNode( context, fFactory, n, CAstNode.BLOCK_EXPR, makeNode( context, fFactory, n, CAstNode.IF_STMT, visitNode(n.getExpression(), context), makeNode( context, fFactory, n, CAstNode.ASSIGN, makeNode(context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(var)), visitNode(n.getThenExpression(), context)), makeNode( context, fFactory, n, CAstNode.ASSIGN, makeNode(context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(var)), visitNode(n.getElseExpression(), context))), makeNode(context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(var))); } private CAstNode visit(PostfixExpression n, WalkContext context) { CAstOperator op = (n.getOperator() == PostfixExpression.Operator.DECREMENT) ? CAstOperator.OP_SUB : CAstOperator.OP_ADD; return makeNode( context, fFactory, n, CAstNode.ASSIGN_POST_OP, visitNode(n.getOperand(), context), fFactory.makeConstant(1), op); } private CAstNode visit(PrefixExpression n, WalkContext context) { PrefixExpression.Operator op = n.getOperator(); if (op == PrefixExpression.Operator.DECREMENT || op == PrefixExpression.Operator.INCREMENT) { CAstOperator castOp = (n.getOperator() == PrefixExpression.Operator.DECREMENT) ? CAstOperator.OP_SUB : CAstOperator.OP_ADD; return makeNode( context, fFactory, n, CAstNode.ASSIGN_PRE_OP, visitNode(n.getOperand(), context), fFactory.makeConstant(1), castOp); } else if (op == PrefixExpression.Operator.PLUS) { return visitNode(n.getOperand(), context); // drop useless unary plus operator } else if (op == PrefixExpression.Operator.MINUS) { CAstNode zero; ITypeBinding type = n.getOperand().resolveTypeBinding(); switch (type.getBinaryName()) { case "C": zero = fFactory.makeConstant((char) 0); break; case "B": zero = fFactory.makeConstant((byte) 0); break; case "S": zero = fFactory.makeConstant((short) 0); break; case "I": zero = fFactory.makeConstant(0); break; case "J": zero = fFactory.makeConstant(0L); break; case "F": zero = fFactory.makeConstant(0.0); break; case "D": zero = fFactory.makeConstant(0.0D); break; default: zero = null; assert false : "unexpected type " + type.getBinaryName(); break; } return makeNode( context, fFactory, n, CAstNode.BINARY_EXPR, CAstOperator.OP_SUB, zero, visitNode(n.getOperand(), context)); } else { // ! and ~ CAstOperator castOp = (n.getOperator() == PrefixExpression.Operator.NOT) ? CAstOperator.OP_NOT : CAstOperator.OP_BITNOT; return makeNode( context, fFactory, n, CAstNode.UNARY_EXPR, castOp, visitNode(n.getOperand(), context)); } } private CAstNode visit(EmptyStatement n, WalkContext context) { CAstNode result = makeNode(context, fFactory, n, CAstNode.EMPTY); context .cfg() .map(n, result); // why is this necessary? for break / continue targets? (they use an empty // statement) return result; } private CAstNode visit(AssertStatement n, WalkContext context) { return makeNode(context, fFactory, n, CAstNode.ASSERT, visitNode(n.getExpression(), context)); } // //////////////// // LOOPS -- special handling of for and continue // //////////////// private CAstNode visit(LabeledStatement n, WalkContext context) { // find the first non-block statement ant set-up the label map (useful for breaking many fors) ASTNode stmt = n.getBody(); while (stmt instanceof Block) stmt = (ASTNode) ((Block) stmt).statements().iterator().next(); if (n.getParent() != null) // if not a synthetic node from a break/continue -- don't pollute namespace with label, we get // it thru the context context.getLabelMap().put(stmt, n.getLabel().getIdentifier()); CAstNode result; if (!(n.getBody() instanceof EmptyStatement)) { ASTNode breakTarget = makeBreakOrContinueTarget(n, n.getLabel().getIdentifier()); CAstNode breakNode = visitNode(breakTarget, context); WalkContext child = new BreakContext(context, n.getLabel().getIdentifier(), breakTarget); result = makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, makeNode( context, fFactory, n, CAstNode.LABEL_STMT, fFactory.makeConstant(n.getLabel().getIdentifier()), visitNode(n.getBody(), child)), breakNode); } else { result = makeNode( context, fFactory, n, CAstNode.LABEL_STMT, fFactory.makeConstant(n.getLabel().getIdentifier()), visitNode(n.getBody(), context)); } context.cfg().map(n, result); if (n.getParent() != null) // if not a synthetic node from a break/continue -- don't pollute namespace with label, we get // it thru the context context.getLabelMap().remove(stmt); return result; } /** Make a fake labeled node with no body, as an anchor to go to */ private ASTNode makeBreakOrContinueTarget(ASTNode loop, String name) { LabeledStatement labeled = ast.newLabeledStatement(); labeled.setBody(ast.newEmptyStatement()); labeled.setSourceRange(loop.getStartPosition(), loop.getLength()); labeled.setLabel( ast.newSimpleName(name)); // we don't have to worry about namespace conflicts as it is only // definedwithin return labeled; } private CAstNode visit(BreakStatement n, WalkContext context) { String label = n.getLabel() == null ? null : n.getLabel().getIdentifier(); ASTNode target = context.getBreakFor(label); assert target != null; CAstNode result = makeNode(context, fFactory, n, CAstNode.GOTO); context.cfg().map(n, result); context.cfg().add(n, target, null); return result; } private CAstNode visit(ContinueStatement n, WalkContext context) { String label = n.getLabel() == null ? null : n.getLabel().getIdentifier(); ASTNode target = context.getContinueFor(label); assert target != null; CAstNode result = makeNode(context, fFactory, n, CAstNode.GOTO); context.cfg().map(n, result); context.cfg().add(n, target, null); return result; } private CAstNode visit(WhileStatement n, WalkContext context) { Expression cond = n.getExpression(); Statement body = n.getBody(); ASTNode breakTarget = makeBreakOrContinueTarget(n, "breakLabel" + n.getStartPosition()); CAstNode breakNode = visitNode(breakTarget, context); ASTNode continueTarget = makeBreakOrContinueTarget(n, "continueLabel" + n.getStartPosition()); CAstNode continueNode = visitNode(continueTarget, context); String loopLabel = context.getLabelMap().get(n); LoopContext lc = new LoopContext(context, loopLabel, breakTarget, continueTarget); /* * The following loop is created sligtly differently than in jscore. It doesn't have a specific target for continue. */ return makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, makeNode( context, fFactory, n, CAstNode.LOOP, visitNode(cond, context), makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, visitNode(body, lc), continueNode)), breakNode); } private CAstNode getSwitchCaseConstant(SwitchCase n, WalkContext context) { // TODO: enums Expression expr = n.getExpression(); Object constant = (expr == null) ? Integer.valueOf(0) : expr.resolveConstantExpressionValue(); // default case label of // "0" (what polyglot // does). we also set // SWITCH_DEFAULT // somewhere else // polyglot converts all labels to longs. why? who knows... if (constant instanceof Character) constant = (long) ((Character) constant).charValue(); else if (constant instanceof Byte) constant = ((Byte) constant).longValue(); else if (constant instanceof Integer) constant = ((Integer) constant).longValue(); else if (constant instanceof Short) constant = ((Short) constant).longValue(); if (constant != null) { return fFactory.makeConstant(constant); } else if (expr instanceof SimpleName) { // enum constant return visit((SimpleName) expr, context); } else { Assertions.UNREACHABLE("null constant for non-enum switch case!"); return null; } } private CAstNode visit(SwitchCase n, WalkContext context) { CAstNode label = makeNode( context, fFactory, n, CAstNode.LABEL_STMT, getSwitchCaseConstant(n, context), makeNode(context, fFactory, n, CAstNode.EMPTY)); context.cfg().map(n, label); return label; } private CAstNode visit(SwitchStatement n, WalkContext context) { ASTNode breakTarget = makeBreakOrContinueTarget(n, "breakLabel" + n.getStartPosition()); CAstNode breakAst = visitNode(breakTarget, context); String loopLabel = context.getLabelMap().get(n); // set by labeled statement (if there is one before this // switch statement) WalkContext childContext = new BreakContext(context, loopLabel, breakTarget); Expression cond = n.getExpression(); List<Statement> cases = n.statements(); // First compute the control flow edges for the various case labels for (Statement se : cases) { if (se instanceof SwitchCase) { SwitchCase c = (SwitchCase) se; if (c.isDefault()) context.cfg().add(n, c, CAstControlFlowMap.SWITCH_DEFAULT); else context.cfg().add(n, c, getSwitchCaseConstant(c, context)); // if we don't do this, we may not get a constant but a // block expression or something else } } ArrayList<CAstNode> caseNodes = new ArrayList<>(); // polyglot bundles all statements in between two statements into a block. // this is temporary place to hold current bundle of nodes. ArrayList<CAstNode> currentBlock = new ArrayList<>(); // Now produce the CAst representation for each case for (Statement s : cases) { if (s instanceof SwitchCase) { if (!currentBlock.isEmpty()) { // bundle up statements before this case List<CAstNode> stmtNodes = new ArrayList<>(currentBlock); // make position from start of first statement to end of last statement T positionOfAll = makePosition( childContext.pos().getPosition(stmtNodes.get(0)).getFirstOffset(), childContext .pos() .getPosition(stmtNodes.get(stmtNodes.size() - 1)) .getLastOffset()); caseNodes.add( makeNode(childContext, fFactory, positionOfAll, CAstNode.BLOCK_STMT, stmtNodes)); currentBlock.clear(); } caseNodes.add(visitNode(s, childContext)); } else { visitNodeOrNodes(s, childContext, currentBlock); } } if (!currentBlock.isEmpty()) { // bundle up statements before this case List<CAstNode> stmtNodes = new ArrayList<>(currentBlock); // make position from start of first statement to end of last statement T positionOfAll = makePosition( childContext.pos().getPosition(stmtNodes.get(0)).getFirstOffset(), childContext.pos().getPosition(stmtNodes.get(stmtNodes.size() - 1)).getLastOffset()); caseNodes.add( makeNode(childContext, fFactory, positionOfAll, CAstNode.BLOCK_STMT, stmtNodes)); } // Now produce the switch stmt itself CAstNode switchAst = makeNode( context, fFactory, n, CAstNode.SWITCH, visitNode(cond, context), makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, caseNodes)); context.cfg().map(n, switchAst); // Finally, wrap the entire switch in a block so that we have a // well-defined place to 'break' to. return makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, switchAst, breakAst); } private CAstNode visit(DoStatement n, WalkContext context) { String loopLabel = context.getLabelMap().get(n); // set by visit(LabeledStatement) String token = loopLabel == null ? "at_" + n.getStartPosition() : loopLabel; ASTNode breakTarget = makeBreakOrContinueTarget(n, "breakLabel_" + token); CAstNode breakNode = visitNode(breakTarget, context); ASTNode continueTarget = makeBreakOrContinueTarget(n, "continueLabel_" + token); CAstNode continueNode = visitNode(continueTarget, context); CAstNode loopTest = visitNode(n.getExpression(), context); WalkContext loopContext = new LoopContext(context, loopLabel, breakTarget, continueTarget); CAstNode loopBody = visitNode(n.getBody(), loopContext); CAstNode madeNode = doLoopTranslator.translateDoLoop(loopTest, loopBody, continueNode, breakNode, context); context.pos().setPosition(madeNode, makePosition(n)); return madeNode; } /** * Expands the form: for ( [final] Type var: iterable ) { ... } Into something equivalent to: for * ( Iterator iter = iterable.iter(); iter.hasNext(); ) { [final] Type var = (Type) iter.next(); * ... } Or, in the case of an array: for ( int idx = 0; i &lt; iterable.length; i++ ) { [final] * Type var = iterable[idx]; ... } Except that the expression "iterable" is only evaluate once (or * is it?) */ private CAstNode visit(EnhancedForStatement n, WalkContext context) { if (n.getExpression().resolveTypeBinding().isArray()) return makeArrayEnhancedForLoop(n, context); else return makeIteratorEnhancedForLoop(n, context); } private CAstNode makeIteratorEnhancedForLoop(EnhancedForStatement n, WalkContext context) { // case 1: iterator CAstNode exprNode = visitNode(n.getExpression(), context); SingleVariableDeclaration svd = n.getParameter(); Statement body = n.getBody(); // expand into: // typical for loop: // { [inits]; while (cond) { [body]; [label continueTarget]; iters } [label breakTarget] // BLOCK(BLOCK(init1,init2,...),LOOP(cond,BLOCK(bodyblock,continuetarget,BLOCK(iter1,iter2,...))),breaktarget // in our case: // the only init is "Iterator iter = iterable.iter()" // cond is "iter.hasNext()" // bodyblock should be prepended with "[final] Type var = iter.next()" (put in the block that // body belongs to) // iter is null // continuetarget and breaktarget are the same as in a regular for loop // BLOCK(iterassign,LOOP(cond,BLOCK(paramassign,bodyblock,continuetarget)),breaktarget) final String tmpName = "iter tmp"; // this is an illegal Java identifier, we will use this variable to hold the // "invisible" // iterator /*-------- make "iter = iterator.iter()" ---------*/ // make a fake method ref MethodReference iterMethodRef = fIdentityMapper.fakeMethodRefNoArgs( "Ljava/lang/Iterable;.iterator()Ljava/util/Iterator<TT;>;", "Ljava/lang/Iterable", "iterator", "Ljava/util/Iterator"); CAstNode iterCallSiteRef = fFactory.makeConstant( CallSiteReference.make(0, iterMethodRef, IInvokeInstruction.Dispatch.INTERFACE)); // Iterable.iter() throws no exceptions. CAstNode iterCallNode = makeNode(context, fFactory, n, CAstNode.CALL, exprNode, iterCallSiteRef); // handle runtimeexception Object o1 = new Object(); // dummy object used for mapping / exceptions for (Pair<ITypeBinding, Object> catchTarget : context.getCatchTargets(fRuntimeExcType)) context.cfg().add(o1, catchTarget.snd, catchTarget.fst); context .cfg() .map(o1, iterCallNode); // TODO: this might not work, lots of calls in this one statement. CAstNode iterAssignNode = makeNode( context, fFactory, n, CAstNode.DECL_STMT, fFactory.makeConstant( new InternalCAstSymbol( tmpName, fTypeDict.getCAstTypeFor(ast.resolveWellKnownType("int")), true)), iterCallNode); // MATCHUP: wrap in a block iterAssignNode = makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, iterAssignNode); // TODO: TOTEST: using this and Iterable.hasNext() explicitly in same file. /*---------- cond: iter.hasNext(); -----------*/ MethodReference hasNextMethodRef = fIdentityMapper.fakeMethodRefNoArgs( "Ljava/util/Iterator;.hasNext()Z", "Ljava/util/Iterator", "hasNext", "Z"); CAstNode iterVar = makeNode(context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(tmpName)); CAstNode hasNextCallSiteRef = fFactory.makeConstant( CallSiteReference.make(0, hasNextMethodRef, IInvokeInstruction.Dispatch.INTERFACE)); // throws no exceptions. CAstNode hasNextCallNode = makeNode(context, fFactory, n, CAstNode.CALL, iterVar, hasNextCallSiteRef); // handle runtimeexception Object o2 = new Object(); // dummy object used for mapping / exceptions for (Pair<ITypeBinding, Object> catchTarget : context.getCatchTargets(fRuntimeExcType)) context.cfg().add(o2, catchTarget.snd, catchTarget.fst); context .cfg() .map( o2, hasNextCallNode); // TODO: this might not work, lots of calls in this one statement. /*---------- paramassign: var = (Type) iter.next() ---------*/ MethodReference nextMethodRef = fIdentityMapper.fakeMethodRefNoArgs( "Ljava/util/Iterator;.next()TE;", "Ljava/util/Iterator", "next", "Ljava/lang/Object"); CAstNode nextCallSiteRef = fFactory.makeConstant( CallSiteReference.make(0, nextMethodRef, IInvokeInstruction.Dispatch.INTERFACE)); // throws no exceptions. CAstNode iterVar2 = makeNode(context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(tmpName)); CAstNode nextCallNode = makeNode(context, fFactory, n, CAstNode.CALL, iterVar2, nextCallSiteRef); for (Pair<ITypeBinding, Object> catchTarget : context.getCatchTargets(fRuntimeExcType)) context.cfg().add(svd, catchTarget.snd, catchTarget.fst); context.cfg().map(svd, nextCallNode); // TODO: another cfg edge associated with svd! is this okay? prolly not... associate it with the // cast, somehow... CAstNode castedNode = createCast( svd, nextCallNode, ast.resolveWellKnownType("java.lang.Object"), svd.resolveBinding().getType(), context); Object defaultValue = JDT2CAstUtils.defaultValueForType(svd.resolveBinding().getType()); CAstNode nextAssignNode = makeNode( context, fFactory, n, CAstNode.DECL_STMT, fFactory.makeConstant( new CAstSymbolImpl( svd.getName().getIdentifier(), fTypeDict.getCAstTypeFor(svd.resolveBinding().getType()), (svd.getModifiers() & Modifier.FINAL) != 0, defaultValue)), castedNode); /*----------- put it all together ----------*/ ASTNode breakTarget = makeBreakOrContinueTarget(n, "breakLabel" + n.getStartPosition()); ASTNode continueTarget = makeBreakOrContinueTarget(n, "continueLabel" + n.getStartPosition()); String loopLabel = context.getLabelMap().get(n); WalkContext loopContext = new LoopContext(context, loopLabel, breakTarget, continueTarget); // LOCAL_SCOPE(BLOCK(iterassign,LOOP(cond,BLOCK(BLOCK(paramassign,bodyblock),continuetarget,BLOCK())),breaktarget)) return makeNode( context, fFactory, n, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, iterAssignNode, makeNode( context, fFactory, n, CAstNode.LOOP, hasNextCallNode, makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, makeNode( context, fFactory, n, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, nextAssignNode, visitNode(body, loopContext))), visitNode(continueTarget, context), makeNode(context, fFactory, n, CAstNode.BLOCK_STMT))), visitNode(breakTarget, context))); } private CAstNode makeArrayEnhancedForLoop(EnhancedForStatement n, WalkContext context) { // ********* BEFORE: // for ( String x: doSomething() ) { ... } // ********* AFTER: // { // String tmparray[] = doSomething(); // for ( int tmpindex = 0; i < tmparray.length; tmpindex++ ) { // String x = tmparray[tmpindex]; // ... // } // } // simplest: // LOCAL_SCOPE(BLOCK(arrayDecl,indexDecl,LOOP(cond,BLOCK(nextAssign,bodyblock,continuetarget,iter)),breaktarget)) // match up exactly: // LOCAL_SCOPE(BLOCK(arrayDecl,LOCAL_SCOPE(BLOCK(BLOCK(indexDecl),LOOP(cond,BLOCK(LOCAL_SCOPE(BLOCK(nextAssign,bodyblock)),continuetarget,BLOCK(iter))),breaktarget)))) /*------ arrayDecl --------- String tmparray[] = doSomething() ------*/ final String tmpArrayName = "for temp array"; // illegal java identifier CAstNode exprNode = visitNode(n.getExpression(), context); CAstNode arrayDeclNode = makeNode( context, fFactory, n, CAstNode.DECL_STMT, fFactory.makeConstant( new InternalCAstSymbol( tmpArrayName, fTypeDict.getCAstTypeFor(n.getExpression().resolveTypeBinding()), true)), exprNode); /*------ indexDecl --------- int tmpindex = 0 ------*/ final String tmpIndexName = "for temp index"; CAstNode indexDeclNode = makeNode( context, fFactory, n, CAstNode.DECL_STMT, fFactory.makeConstant( new InternalCAstSymbol( tmpIndexName, fTypeDict.getCAstTypeFor(ast.resolveWellKnownType("int")), true)), fFactory.makeConstant(Integer.valueOf(0))); /*------ cond ------------- tmpindex < tmparray.length ------*/ CAstNode tmpArrayLengthNode = makeNode( context, fFactory, n, CAstNode.ARRAY_LENGTH, makeNode( context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(tmpArrayName), fFactory.makeConstant( fTypeDict.getCAstTypeFor(n.getExpression().resolveTypeBinding())))); CAstNode condNode = makeNode( context, fFactory, n, CAstNode.BINARY_EXPR, CAstOperator.OP_LT, makeNode( context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(tmpIndexName), fFactory.makeConstant(JavaPrimitiveType.INT)), tmpArrayLengthNode); /*------ tmpIndexInc -------- tmpindex++ ------*/ CAstNode tmpArrayIncNode = makeNode( context, fFactory, n, CAstNode.ASSIGN_POST_OP, makeNode(context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(tmpIndexName)), fFactory.makeConstant(1), CAstOperator.OP_ADD); /*------ tmpArrayAccess ----- String x = tmparray[tmpindex] ------*/ CAstNode tmpArrayAccessNode = makeNode( context, fFactory, n, CAstNode.ARRAY_REF, makeNode(context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(tmpArrayName)), fFactory.makeConstant( fIdentityMapper.getTypeRef( n.getExpression().resolveTypeBinding().getComponentType())), makeNode(context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(tmpIndexName))); SingleVariableDeclaration svd = n.getParameter(); Object defaultValue = JDT2CAstUtils.defaultValueForType(svd.resolveBinding().getType()); CAstNode nextAssignNode = makeNode( context, fFactory, n, CAstNode.DECL_STMT, fFactory.makeConstant( new CAstSymbolImpl( svd.getName().getIdentifier(), fTypeDict.getCAstTypeFor( n.getExpression().resolveTypeBinding().getComponentType()), (svd.getModifiers() & Modifier.FINAL) != 0, defaultValue)), tmpArrayAccessNode); // LOCAL_SCOPE(BLOCK(arrayDecl,LOCAL_SCOPE(BLOCK(BLOCK(indexDecl),LOOP(cond,BLOCK(LOCAL_SCOPE(BLOCK(nextAssign,bodyblock)),continuetarget,BLOCK(iter))),breaktarget)))) // more complicated than it has to be, but it matches up exactly with the Java expansion above. ASTNode breakTarget = makeBreakOrContinueTarget(n, "breakLabel" + n.getStartPosition()); ASTNode continueTarget = makeBreakOrContinueTarget(n, "continueLabel" + n.getStartPosition()); String loopLabel = context.getLabelMap().get(n); WalkContext loopContext = new LoopContext(context, loopLabel, breakTarget, continueTarget); return makeNode( context, fFactory, n, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, arrayDeclNode, makeNode( context, fFactory, n, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, indexDeclNode), makeNode( context, fFactory, n, CAstNode.LOOP, condNode, makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, makeNode( context, fFactory, n, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, nextAssignNode, visitNode(n.getBody(), loopContext))), visitNode(continueTarget, context), makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, tmpArrayIncNode))), visitNode(breakTarget, context))))); } private CAstNode visit(ForStatement n, WalkContext context) { ASTNode breakTarget = makeBreakOrContinueTarget(n, "breakLabel" + n.getStartPosition()); ASTNode continueTarget = makeBreakOrContinueTarget(n, "continueLabel" + n.getStartPosition()); String loopLabel = context.getLabelMap().get(n); WalkContext loopContext = new LoopContext(context, loopLabel, breakTarget, continueTarget); ArrayList<CAstNode> inits = new ArrayList<>(); for (int i = 0; i < n.initializers().size(); i++) { ASTNode init = (ASTNode) n.initializers().get(i); if (init instanceof VariableDeclarationExpression) { for (ASTNode o : (Iterable<ASTNode>) ((VariableDeclarationExpression) init).fragments()) inits.add(visitNode(o, context)); } else inits.add(visitNode(init, context)); } List<CAstNode> iters = new ArrayList<>(n.updaters().size()); for (Object updater : n.updaters()) iters.add(visitNode((ASTNode) updater, context)); CAstNode initsBlock = makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, inits); CAstNode itersBlock = makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, iters); // { [inits]; while (cond) { [body]; [label continueTarget]; iters } [label breakTarget] return makeNode( context, fFactory, n, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, initsBlock, makeNode( context, fFactory, n, CAstNode.LOOP, visitNode(n.getExpression(), context), makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, visitNode(n.getBody(), loopContext), visitNode(continueTarget, context), itersBlock)), visitNode(breakTarget, context))); } private CAstNode visit(TryStatement n, WalkContext context) { List<CatchClause> catchBlocks = n.catchClauses(); Block finallyBlock = n.getFinally(); Block tryBlock = n.getBody(); List<?> resources = n.resources(); // try/resources if (resources != null && !resources.isEmpty()) { CAstNode[] body = new CAstNode[resources.size()]; for (int i = 0; i < resources.size(); i++) { body[i] = visitNode((ASTNode) resources.get(i), context); } List<CAstNode> fb = new ArrayList<>(); for (Object x : resources) { if (x instanceof VariableDeclarationExpression) { for (Object y : ((VariableDeclarationExpression) x).fragments()) { if (y instanceof VariableDeclarationFragment) { ITypeBinding object = ast.resolveWellKnownType("java.lang.Object"); IMethodBinding m = null; ITypeBinding me = ((VariableDeclarationFragment) y).resolveBinding().getType(); outer: while (!object.equals(me)) { for (IMethodBinding ourmet : me.getDeclaredMethods()) if (ourmet.getName().equals("close")) { m = ourmet; break outer; // there can only be one per class so don't bother looking for more } me = me.getSuperclass(); } CAstNode target = fFactory.makeNode( CAstNode.VAR, fFactory.makeConstant( ((VariableDeclarationFragment) y).resolveBinding().getName())); fb.add(createMethodInvocation(n, m, target, Collections.emptyList(), context)); } } } } return makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, fFactory.makeNode(CAstNode.BLOCK_STMT, body), makeNode( context, fFactory, n, CAstNode.UNWIND, visitNode(tryBlock, context), fFactory.makeNode(CAstNode.BLOCK_STMT, fb))); // try/finally } else if (catchBlocks.isEmpty()) { return makeNode( context, fFactory, n, CAstNode.UNWIND, visitNode(tryBlock, context), visitNode(finallyBlock, context)); // try/catch/[finally] } else { TryCatchContext tc = new TryCatchContext(context, n); CAstNode tryNode = visitNode(tryBlock, tc); for (CatchClause catchClause : catchBlocks) { tryNode = makeNode(context, fFactory, n, CAstNode.TRY, tryNode, visitNode(catchClause, context)); } // try/catch if (finallyBlock == null) { return tryNode; // try/catch/finally } else { return makeNode( context, fFactory, n, CAstNode.UNWIND, tryNode, visitNode(finallyBlock, context)); } } } private CAstNode visit(CatchClause n, WalkContext context) { Block body = n.getBody(); SingleVariableDeclaration formal = n.getException(); CAstNode excDecl = makeNode( context, fFactory, n, CAstNode.CATCH, fFactory.makeConstant(formal.getName().getIdentifier()), visitNode(body, context)); CAstNode declStmt = makeNode( context, fFactory, n, CAstNode.DECL_STMT, fFactory.makeConstant( new CAstSymbolImpl( formal.getName().getIdentifier(), fTypeDict.getCAstTypeFor(formal.getName().resolveTypeBinding()), true))); CAstNode localScope = makeNode( context, fFactory, n, CAstNode.LOCAL_SCOPE, makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, declStmt, excDecl)); context.cfg().map(n, excDecl); CAstType type = n.getException().getType() instanceof UnionType ? fTypeDict.getCAstTypeForUnion((UnionType) n.getException().getType()) : fTypeDict.getCAstTypeFor(n.getException().resolveBinding().getType()); context.getNodeTypeMap().add(excDecl, type); return localScope; } private CAstNode visit(ThrowStatement n, WalkContext context) { CAstNode result = makeNode(context, fFactory, n, CAstNode.THROW, visitNode(n.getExpression(), context)); ITypeBinding label = n.getExpression().resolveTypeBinding(); context.cfg().map(n, result); Collection<Pair<ITypeBinding, Object>> catchNodes = context.getCatchTargets(label); for (Pair<ITypeBinding, Object> catchNode : catchNodes) { context.cfg().add(n, catchNode.snd, catchNode.fst); } return result; } private void hookUpNPETargets(ASTNode n, WalkContext wc) { Collection<Pair<ITypeBinding, Object>> excTargets = wc.getCatchTargets(fNullPointerExcType); if (!excTargets.isEmpty()) { // connect NPE exception edge to relevant catch targets // (presumably only one) for (Pair<ITypeBinding, Object> catchPair : excTargets) { wc.cfg().add(n, catchPair.snd, fNullPointerExcType); } } else { // connect exception edge to exit wc.cfg().add(n, CAstControlFlowMap.EXCEPTION_TO_EXIT, fNullPointerExcType); } } // // ARRAYS // private CAstNode visit(ArrayAccess n, WalkContext context) { TypeReference eltTypeRef = fIdentityMapper.getTypeRef(n.resolveTypeBinding()); CAstNode cast = makeNode( context, fFactory, n, CAstNode.ARRAY_REF, visitNode(n.getArray(), context), fFactory.makeConstant(eltTypeRef), visitNode(n.getIndex(), context)); hookUpNPETargets(n, context); context.cfg().map(n, cast); return cast; } // FIXME: inner classes here, probably too... private CAstNode visit(ArrayCreation n, WalkContext context) { ITypeBinding newType = n.resolveTypeBinding(); ArrayInitializer ai = n.getInitializer(); assert newType.isArray(); if (ai != null) { return visitNode(ai, context); } else { TypeReference arrayTypeRef = fIdentityMapper.getTypeRef(newType); List<Expression> dims = n.dimensions(); List<CAstNode> args = new ArrayList<>(dims.size() + 1); args.add(fFactory.makeConstant(arrayTypeRef)); for (Expression dimExpr : dims) { args.add(visitNode(dimExpr, context)); } return makeNode(context, fFactory, n, CAstNode.NEW, args); } } private CAstNode visit(SynchronizedStatement n, WalkContext context) { CAstNode exprNode = visitNode(n.getExpression(), context); String exprName = fFactory.makeUnique(); CAstNode declStmt = makeNode( context, fFactory, n, CAstNode.DECL_STMT, fFactory.makeConstant( new CAstSymbolImpl( exprName, fTypeDict.getCAstTypeFor(n.getExpression().resolveTypeBinding()), true)), exprNode); CAstNode monitorEnterNode = makeNode( context, fFactory, n, CAstNode.MONITOR_ENTER, makeNode(context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(exprName))); context.cfg().map(monitorEnterNode, monitorEnterNode); for (Pair<ITypeBinding, Object> catchTarget : context.getCatchTargets(fNullPointerExcType)) context.cfg().add(monitorEnterNode, catchTarget.snd, catchTarget.fst); CAstNode bodyNodes = visitNode(n.getBody(), context); CAstNode monitorExitNode = makeNode( context, fFactory, n, CAstNode.MONITOR_EXIT, makeNode(context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(exprName))); context.cfg().map(monitorExitNode, monitorExitNode); for (Pair<ITypeBinding, Object> catchTarget : context.getCatchTargets(fNullPointerExcType)) context.cfg().add(monitorExitNode, catchTarget.snd, catchTarget.fst); CAstNode bigBody = makeNode( context, fFactory, n, CAstNode.BLOCK_STMT, monitorEnterNode, makeNode(context, fFactory, n, CAstNode.UNWIND, bodyNodes, monitorExitNode)); return makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, declStmt, bigBody); } // /////////////////////////////////////////// // / THE GIANT SWITCH STATEMENT ( BORING ) /// // /////////////////////////////////////////// /** Giant switch statement. */ private CAstEntity visit(AbstractTypeDeclaration n, WalkContext context) { // handling of compilationunit in translate() if (n instanceof TypeDeclaration) { return visitTypeDecl(n, context); } else if (n instanceof EnumDeclaration) { return visit((EnumDeclaration) n, context); } else if (n instanceof AnnotationTypeDeclaration) { return visitTypeDecl(n, context); } else { Assertions.UNREACHABLE("Unhandled type declaration type"); return null; } } /** Giant switch statement, part deux */ private CAstNode visitNode(ASTNode n, WalkContext context) { if (n == null) return makeNode(context, fFactory, null, CAstNode.EMPTY); if (n instanceof ArrayAccess) { return visit((ArrayAccess) n, context); } else if (n instanceof ArrayCreation) { return visit((ArrayCreation) n, context); } else if (n instanceof ArrayInitializer) { return visit((ArrayInitializer) n, context); } else if (n instanceof AssertStatement) { return visit((AssertStatement) n, context); } else if (n instanceof Assignment) { return visit((Assignment) n, context); } else if (n instanceof Block) { return visit((Block) n, context); } else if (n instanceof BooleanLiteral) { return visit((BooleanLiteral) n); } else if (n instanceof BreakStatement) { return visit((BreakStatement) n, context); } else if (n instanceof CastExpression) { return visit((CastExpression) n, context); } else if (n instanceof CatchClause) { return visit((CatchClause) n, context); } else if (n instanceof CharacterLiteral) { return visit((CharacterLiteral) n); } else if (n instanceof ClassInstanceCreation) { return visit((ClassInstanceCreation) n, context); } else if (n instanceof ConditionalExpression) { return visit((ConditionalExpression) n, context); } else if (n instanceof ConstructorInvocation) { return visit((ConstructorInvocation) n, context); } else if (n instanceof ContinueStatement) { return visit((ContinueStatement) n, context); } else if (n instanceof DoStatement) { return visit((DoStatement) n, context); } else if (n instanceof EmptyStatement) { return visit((EmptyStatement) n, context); } else if (n instanceof EnhancedForStatement) { return visit((EnhancedForStatement) n, context); } else if (n instanceof ExpressionStatement) { return visit((ExpressionStatement) n, context); } else if (n instanceof FieldAccess) { return visit((FieldAccess) n, context); } else if (n instanceof ForStatement) { return visit((ForStatement) n, context); } else if (n instanceof IfStatement) { return visit((IfStatement) n, context); } else if (n instanceof InfixExpression) { return visit((InfixExpression) n, context); } else if (n instanceof InstanceofExpression) { return visit((InstanceofExpression) n, context); } else if (n instanceof LabeledStatement) { return visit((LabeledStatement) n, context); } else if (n instanceof MethodInvocation) { return visit((MethodInvocation) n, context); } else if (n instanceof NumberLiteral) { return visit((NumberLiteral) n, context); } else if (n instanceof NullLiteral) { return visit(); } else if (n instanceof ParenthesizedExpression) { return visit((ParenthesizedExpression) n, context); } else if (n instanceof PostfixExpression) { return visit((PostfixExpression) n, context); } else if (n instanceof PrefixExpression) { return visit((PrefixExpression) n, context); } else if (n instanceof QualifiedName) { return visit((QualifiedName) n, context); } else if (n instanceof ReturnStatement) { return visit((ReturnStatement) n, context); } else if (n instanceof SimpleName) { return visit((SimpleName) n, context); } else if (n instanceof StringLiteral) { return visit((StringLiteral) n, context); } else if (n instanceof SuperConstructorInvocation) { return visit((SuperConstructorInvocation) n, context); } else if (n instanceof SuperFieldAccess) { return visit((SuperFieldAccess) n, context); } else if (n instanceof SuperMethodInvocation) { return visit((SuperMethodInvocation) n, context); } else if (n instanceof SynchronizedStatement) { return visit((SynchronizedStatement) n, context); } else if (n instanceof SwitchStatement) { return visit((SwitchStatement) n, context); } else if (n instanceof SwitchCase) { return visit((SwitchCase) n, context); } else if (n instanceof ThisExpression) { return visit((ThisExpression) n, context); } else if (n instanceof TypeLiteral) { return visit((TypeLiteral) n, context); } else if (n instanceof ThrowStatement) { return visit((ThrowStatement) n, context); } else if (n instanceof TryStatement) { return visit((TryStatement) n, context); } else if (n instanceof TypeDeclarationStatement) { return visit((TypeDeclarationStatement) n, context); } else if (n instanceof VariableDeclarationExpression) { return visit((VariableDeclarationExpression) n, context); } else if (n instanceof VariableDeclarationFragment) { return visit((VariableDeclarationFragment) n, context); } else if (n instanceof WhileStatement) { return visit((WhileStatement) n, context); } // VariableDeclarationStatement handled as special case (returns multiple statements) Assertions.UNREACHABLE("Unhandled JDT node type " + n.getClass().getCanonicalName()); return null; } private void visitNodeOrNodes(ASTNode n, WalkContext context, Collection<CAstNode> coll) { if (n instanceof VariableDeclarationStatement) coll.addAll(visit((VariableDeclarationStatement) n, context)); else coll.add(visitNode(n, context)); } // ///////////////////////////////////////// // SPECIALIZED CASTENTITYs AND CASTNODEs // // ///////////////////////////////////////// protected static final class CompilationUnitEntity implements CAstEntity { private final String fName; private final Collection<CAstEntity> fTopLevelDecls; public CompilationUnitEntity( PackageDeclaration packageDeclaration, List<CAstEntity> topLevelDecls) { fName = (packageDeclaration == null) ? "" : packageDeclaration.getName().getFullyQualifiedName().replace('.', '/'); fTopLevelDecls = topLevelDecls; } @Override public Collection<CAstAnnotation> getAnnotations() { return null; } @Override public int getKind() { return FILE_ENTITY; } @Override public String getName() { return fName; } @Override public String getSignature() { Assertions.UNREACHABLE(); return null; } @Override public String[] getArgumentNames() { return new String[0]; } @Override public CAstNode[] getArgumentDefaults() { return new CAstNode[0]; } @Override public int getArgumentCount() { return 0; } @Override public Map<CAstNode, Collection<CAstEntity>> getAllScopedEntities() { return Collections.singletonMap(null, fTopLevelDecls); } @Override public Iterator<CAstEntity> getScopedEntities(CAstNode construct) { Assertions.UNREACHABLE( "CompilationUnitEntity asked for AST-related entities, but it has no AST."); return null; } @Override public CAstNode getAST() { return null; } @Override public CAstControlFlowMap getControlFlow() { Assertions.UNREACHABLE("CompilationUnitEntity.getControlFlow()"); return null; } @Override public CAstSourcePositionMap getSourceMap() { Assertions.UNREACHABLE("CompilationUnitEntity.getSourceMap()"); return null; } @Override public CAstSourcePositionMap.Position getPosition() { return null; } @Override public CAstNodeTypeMap getNodeTypeMap() { Assertions.UNREACHABLE("CompilationUnitEntity.getNodeTypeMap()"); return null; } @Override public Collection<CAstQualifier> getQualifiers() { return Collections.emptyList(); } @Override public CAstType getType() { Assertions.UNREACHABLE("CompilationUnitEntity.getType()"); return null; } @Override public Position getPosition(int arg) { return null; } @Override public Position getNamePosition() { return null; } } // ///////////////////////////// // WALK CONTEXTS // WHY???? // //////////////////////////////// /** * Contains things needed by in the visit() of some nodes to process the nodes. For example, pos() * contains the source position mapping which each node registers */ public interface WalkContext extends TranslatorToCAst.WalkContext<WalkContext, ASTNode> { Collection<Pair<ITypeBinding, Object>> getCatchTargets(ITypeBinding type); Map<ASTNode, String> getLabelMap(); boolean needLValue(); } /** * Default context functions. When one context doesn't handle something, it the next one up does. * For example, there is only one source pos. mapping per MethodContext, so loop contexts delegate * it up. */ public static class DelegatingContext extends TranslatorToCAst.DelegatingContext<WalkContext, ASTNode> implements WalkContext { public DelegatingContext(WalkContext parent) { super(parent); } @Override public Collection<Pair<ITypeBinding, Object>> getCatchTargets(ITypeBinding type) { return parent.getCatchTargets(type); } @Override public Map<ASTNode, String> getLabelMap() { return parent.getLabelMap(); } @Override public boolean needLValue() { return parent.needLValue(); } } /* * Root context. Doesn't do anything. */ public static class RootContext extends TranslatorToCAst.RootContext<WalkContext, ASTNode> implements WalkContext { @Override public Collection<Pair<ITypeBinding, Object>> getCatchTargets(ITypeBinding type) { Assertions.UNREACHABLE("RootContext.getCatchTargets()"); return null; } @Override public Map<ASTNode, String> getLabelMap() { Assertions.UNREACHABLE("RootContext.getLabelMap()"); return null; } @Override public boolean needLValue() { Assertions.UNREACHABLE("Rootcontext.needLValue()"); return false; } } private static class AssignmentContext extends DelegatingContext { protected AssignmentContext(WalkContext parent) { super(parent); } @Override public boolean needLValue() { return true; } } private static class TryCatchContext extends DelegatingContext { Collection<Pair<ITypeBinding, Object>> fCatchNodes = new ArrayList<>(); TryCatchContext(WalkContext parent, TryStatement tryNode) { super(parent); for (CatchClause c : (Iterable<CatchClause>) tryNode.catchClauses()) { Pair<ITypeBinding, Object> p = Pair.make(c.getException().resolveBinding().getType(), (Object) c); fCatchNodes.add(p); } } @Override public Collection<Pair<ITypeBinding, Object>> getCatchTargets(ITypeBinding label) { // Look for all matching targets for this thrown type: // if supertpe match, then return only matches at this catch // if subtype match, then matches here and parent matches Collection<Pair<ITypeBinding, Object>> catchNodes = new ArrayList<>(); for (Pair<ITypeBinding, Object> p : fCatchNodes) { ITypeBinding catchType = p.fst; // catchType here should NEVER be FakeExceptionTypeBinary, because these can only be thrown // (not caught) by // "1/0", implicit null pointer exceptions, etc. assert !(catchNodes instanceof FakeExceptionTypeBinding) : "catchNodes instanceof FakeExceptionTypeBinary!"; if (label.isSubTypeCompatible(catchType) || label.isEqualTo(catchType)) { catchNodes.add(p); return catchNodes; // _might_ get caught } else if (catchType.isSubTypeCompatible(label)) { catchNodes.add(p); continue; } } catchNodes.addAll(parent.getCatchTargets(label)); return catchNodes; } } private static class BreakContext extends DelegatingContext { protected final String label; private final ASTNode breakTo; BreakContext(WalkContext parent, String label, ASTNode breakTo) { super(parent); this.label = label; this.breakTo = breakTo; } @Override public ASTNode getBreakFor(String label) { return (label == null || label.equals(this.label)) ? breakTo : super.getBreakFor(label); } } private static class LoopContext extends BreakContext { private final ASTNode continueTo; protected LoopContext(WalkContext parent, String label, ASTNode breakTo, ASTNode continueTo) { super(parent, label, breakTo); this.continueTo = continueTo; } @Override public ASTNode getContinueFor(String label) { return (label == null || label.equals(this.label)) ? continueTo : super.getContinueFor(label); } } public class MethodContext extends DelegatingContext { private final Map<CAstNode, CAstEntity> fEntities; private final Map<ASTNode, String> labelMap = HashMapFactory.make(2); public MethodContext(WalkContext parent, Map<CAstNode, CAstEntity> entities) { // constructor did take: pd.procedureInstance(), memberEntities, context super(parent); fEntities = entities; } private final List<CAstNode> initializers = new ArrayList<>(); @Override public void addNameDecl(CAstNode v) { initializers.add(v); } @Override public List<CAstNode> getNameDecls() { return initializers; } @Override public Map<ASTNode, String> getLabelMap() { return labelMap; // labels are kept within a method. } final CAstSourcePositionRecorder fSourceMap = new CAstSourcePositionRecorder(); final CAstControlFlowRecorder fCFG = new CAstControlFlowRecorder(fSourceMap); final CAstNodeTypeMapRecorder fNodeTypeMap = new CAstNodeTypeMapRecorder(); @Override public CAstControlFlowRecorder cfg() { return fCFG; } @Override public void addScopedEntity(CAstNode node, CAstEntity entity) { fEntities.put(node, entity); } @Override public CAstSourcePositionRecorder pos() { return fSourceMap; } @Override public CAstNodeTypeMapRecorder getNodeTypeMap() { return fNodeTypeMap; } @Override public Collection<Pair<ITypeBinding, Object>> getCatchTargets(ITypeBinding label) { // TAGALONG (need fRuntimeExcType) // Why do we seemingly catch a RuntimeException in every method? this won't catch the // RuntimeException above where // it is supposed to be caught? Collection<Pair<ITypeBinding, Object>> result = Collections.singleton( Pair.<ITypeBinding, Object>make( fRuntimeExcType, CAstControlFlowMap.EXCEPTION_TO_EXIT)); return result; } @Override public boolean needLValue() { return false; } } // //////////////////////////////////// // MAKE NODE VARIATIONS & POSITIONS (BORING) // maybe moved to different file. // makeNode() simply calls Ast.makeNode() and sets the position for the node // //////////////////////////////////// protected CAstNode makeNode(WalkContext wc, CAst Ast, ASTNode n, int kind) { CAstNode cn = Ast.makeNode(kind); setPos(wc, cn, n); return cn; } protected CAstNode makeNode(WalkContext wc, CAst Ast, ASTNode n, int kind, List<CAstNode> c) { CAstNode cn = Ast.makeNode(kind, c); setPos(wc, cn, n); return cn; } protected CAstNode makeNode(WalkContext wc, CAst Ast, T pos, int kind, List<CAstNode> c) { CAstNode cn = Ast.makeNode(kind, c); wc.pos().setPosition(cn, pos); return cn; } protected CAstNode makeNode( WalkContext wc, CAst Ast, ASTNode n, int kind, CAstNode c1, CAstNode c2) { CAstNode cn = Ast.makeNode(kind, c1, c2); setPos(wc, cn, n); return cn; } protected CAstNode makeNode(WalkContext wc, CAst Ast, ASTNode n, int kind, CAstNode c) { CAstNode cn = Ast.makeNode(kind, c); setPos(wc, cn, n); return cn; } protected CAstNode makeNode( WalkContext wc, CAst Ast, ASTNode n, int kind, CAstNode c1, CAstNode c2, CAstNode c3) { CAstNode cn = Ast.makeNode(kind, c1, c2, c3); setPos(wc, cn, n); return cn; } protected CAstNode makeNode( WalkContext wc, CAst Ast, ASTNode n, int kind, CAstNode c1, CAstNode c2, CAstNode c3, CAstNode c4) { CAstNode cn = Ast.makeNode(kind, c1, c2, c3, c4); setPos(wc, cn, n); return cn; } protected CAstNode makeNode( WalkContext wc, CAst Ast, T pos, int kind, CAstNode c1, CAstNode c2, CAstNode c3) { CAstNode cn = Ast.makeNode(kind, c1, c2, c3); wc.pos().setPosition(cn, pos); return cn; } protected void setPos(WalkContext wc, CAstNode cn, ASTNode jdtNode) { if (jdtNode != null) wc.pos().setPosition(cn, makePosition(jdtNode)); } public T makePosition(ASTNode n) { return makePosition(n.getStartPosition(), n.getStartPosition() + n.getLength()); } public abstract T makePosition(int start, int end); // ///////////////////////////////////////////////////////////////// // // ENUM TRANSFORMATION ////////////////////////////////////////// // ///////////////////////////////////////////////////////////////// private static final ArrayList<CAstQualifier> enumQuals = new ArrayList<>(3); static { enumQuals.add(CAstQualifier.PUBLIC); enumQuals.add(CAstQualifier.STATIC); enumQuals.add(CAstQualifier.FINAL); } /** Only called from createClassDeclaration. */ private CAstEntity visit(EnumConstantDeclaration decl) { return new FieldEntity( decl.getName().getIdentifier(), decl.resolveVariable().getType(), enumQuals, makePosition(decl.getStartPosition(), decl.getStartPosition() + decl.getLength()), null, makePosition(decl.getName())); } /** Called only from visitFieldInitNode(node,context) */ private CAstNode createEnumConstantDeclarationInit( EnumConstantDeclaration node, WalkContext context) { String hiddenVariableName = (String) node.getProperty("com.ibm.wala.cast.java.translator.jdt.fakeValuesDeclName"); if (hiddenVariableName == null) { FieldReference fieldRef = fIdentityMapper.getFieldRef(node.resolveVariable()); // We use null to indicate an OBJECT_REF to a static field CAstNode lhsNode = makeNode( context, fFactory, node, CAstNode.OBJECT_REF, makeNode(context, fFactory, null, CAstNode.VOID), fFactory.makeConstant(fieldRef)); // CONSTRUCT ARGUMENTS & "new MyEnum(...)" statement ArrayList<Object> arguments = new ArrayList<>(); arguments.add(fFactory.makeConstant(node.getName().getIdentifier())); // name of constant arguments.add(fFactory.makeConstant(node.resolveVariable().getVariableId())); // id arguments.addAll(node.arguments()); CAstNode rhsNode = createClassInstanceCreation( node, arguments, node.resolveConstructorBinding(), null, node.getAnonymousClassDeclaration(), context); CAstNode assNode = makeNode(context, fFactory, node, CAstNode.ASSIGN, lhsNode, rhsNode); return assNode; // their naming, not mine } else { // String[] x = (new Direction[] { // NORTH, EAST, SOUTH, WEST, $VALUES, $VALUES$ // }); return null; } } private CAstEntity createEnumValueOfMethod(ITypeBinding enumType, WalkContext oldContext) { IMethodBinding met = null, superMet = null; // find our valueOf(String) for (IMethodBinding m : enumType.getDeclaredMethods()) if (m.getName().equals("valueOf") && m.getParameterTypes().length == 1 && m.getParameterTypes()[0].isEqualTo(ast.resolveWellKnownType("java.lang.String"))) met = m; // find Enum.valueOf(Class, String) for (IMethodBinding m : enumType.getSuperclass().getTypeDeclaration().getDeclaredMethods()) if (m.getName().equals("valueOf") && m.getParameterTypes().length == 2) superMet = m; assert met != null && superMet != null : "Couldn't find enum values() function in JDT bindings!"; Map<CAstNode, CAstEntity> memberEntities = new LinkedHashMap<>(); final MethodContext context = new MethodContext(oldContext, memberEntities); MethodDeclaration fakeMet = ast.newMethodDeclaration(); fakeMet.setName(ast.newSimpleName("valueOf")); fakeMet.setSourceRange(-1, 0); fakeMet.setBody(ast.newBlock()); SingleVariableDeclaration stringS = ast.newSingleVariableDeclaration(); stringS.setName(ast.newSimpleName("s")); fakeMet.parameters().add(stringS); // TODO: probably uses reflection so isn't very useful for analyses. Is there something more // useful we could put in here? // return (MyEnum)Enum.valueOf(MyEnum.class, s); // cast(call(type_literal, var))) CAstNode typeLit = makeNode( context, fFactory, fakeMet, CAstNode.TYPE_LITERAL_EXPR, fFactory.makeConstant(fIdentityMapper.typeToTypeID(enumType))); CAstNode stringSvar = makeNode( context, fFactory, fakeMet, CAstNode.VAR, fFactory.makeConstant("s"), fFactory.makeConstant( fTypeDict.getCAstTypeFor(ast.resolveWellKnownType("java.lang.String")))); ArrayList<Object> args = new ArrayList<>(); args.add(typeLit); args.add(stringSvar); CAstNode call = createMethodInvocation( fakeMet, superMet, makeNode(context, fFactory, fakeMet, CAstNode.VOID), args, context); CAstNode cast = createCast(fakeMet, call, enumType, superMet.getReturnType(), context); CAstNode bodyNode = makeNode( context, fFactory, fakeMet, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, fakeMet, CAstNode.BLOCK_STMT, makeNode(context, fFactory, fakeMet, CAstNode.RETURN, cast))); ArrayList<CAstType> paramTypes = new ArrayList<>(1); paramTypes.add(fTypeDict.getCAstTypeFor(ast.resolveWellKnownType("java.lang.String"))); return new ProcedureEntity( bodyNode, fakeMet, enumType, memberEntities, context, paramTypes, enumType, met.getModifiers(), handleAnnotations(met)); } private CAstEntity createEnumValuesMethod( ITypeBinding enumType, ArrayList<IVariableBinding> constants, WalkContext oldContext) { IMethodBinding met = null; for (IMethodBinding m : enumType.getDeclaredMethods()) if (m.getName().equals("values") && m.getParameterTypes().length == 0) met = m; assert met != null : "Couldn't find enum values() function in JDT bindings!"; Map<CAstNode, CAstEntity> memberEntities = new LinkedHashMap<>(); final MethodContext context = new MethodContext(oldContext, memberEntities); MethodDeclaration fakeMet = ast.newMethodDeclaration(); fakeMet.setName(ast.newSimpleName("values")); fakeMet.setSourceRange(-1, 0); fakeMet.setBody(ast.newBlock()); // make enum constant values array: new MyEnum() { MYENUMCST1, MYENUMCST2, ... } List<CAstNode> eltNodes = new ArrayList<>(constants.size() + 1); TypeReference arrayTypeRef = fIdentityMapper.getTypeRef(enumType.createArrayType(1)); eltNodes.add( makeNode( context, fFactory, fakeMet, CAstNode.NEW, fFactory.makeConstant(arrayTypeRef), fFactory.makeConstant(constants.size()))); for (IVariableBinding cst : constants) eltNodes.add( createFieldAccess( makeNode(context, fFactory, fakeMet, CAstNode.VOID), cst.getName(), cst, fakeMet, context)); CAstNode bodyNode = makeNode( context, fFactory, fakeMet, CAstNode.LOCAL_SCOPE, makeNode( context, fFactory, fakeMet, CAstNode.BLOCK_STMT, makeNode( context, fFactory, fakeMet, CAstNode.RETURN, makeNode(context, fFactory, fakeMet, CAstNode.ARRAY_LITERAL, eltNodes)))); ArrayList<CAstType> paramTypes = new ArrayList<>(0); return new ProcedureEntity( bodyNode, fakeMet, enumType, memberEntities, context, paramTypes, enumType.createArrayType(1), met.getModifiers(), handleAnnotations(enumType)); } private void doEnumHiddenEntities( ITypeBinding typeBinding, List<CAstEntity> memberEntities, WalkContext context) { // PART I: create a $VALUES field // collect constants // ArrayList<String> constants = new ArrayList<String>(); // for ( ASTNode n: staticInits ) // if ( n instanceof EnumConstantDeclaration ) // constants.add(((EnumConstantDeclaration)n).getName().getIdentifier()); // figure out a suitable untaken name // String hiddenFieldName = "hidden values field"; // illegal name // // public static final MyEnum[] $VALUES; // memberEntities.add(new FieldEntity(hiddenFieldName, // typeBinding.createArrayType(1), enumQuals, // makePosition(-1,-1))); // // EnumConstantDeclaration fakeValuesDecl = ast.newEnumConstantDeclaration(); // // pass along values that we will use in createEnumConstantDeclarationInit() in creating // static initializer // fakeValuesDecl.setProperty("com.ibm.wala.cast.java.translator.jdt.fakeValuesDeclName", // hiddenFieldName); // fakeValuesDecl.setProperty("com.ibm.wala.cast.java.translator.jdt.fakeValuesDeclConstants", // constants); // staticInits.add(fakeValuesDecl); ArrayList<IVariableBinding> constants = new ArrayList<>(); for (IVariableBinding var : typeBinding.getDeclaredFields()) if (var.isEnumConstant()) constants.add(var); // constants are unsorted by default constants.sort(Comparator.comparingInt(IVariableBinding::getVariableId)); // PART II: create values() memberEntities.add(createEnumValuesMethod(typeBinding, constants, context)); // PART III: create valueOf() memberEntities.add(createEnumValueOfMethod(typeBinding, context)); } private CAstEntity visit(EnumDeclaration n, WalkContext context) { // JDT contains correct type info / class / subclass info for the enum return createClassDeclaration( n, n.bodyDeclarations(), n.enumConstants(), n.resolveBinding(), n.getName().getIdentifier(), n.resolveBinding().getModifiers(), false, false, context, makePosition(n.getName())); } /** @param n for positioning. */ private CAstEntity createEnumConstructorWithParameters( IMethodBinding ctor, ASTNode n, WalkContext oldContext, ArrayList<ASTNode> inits, MethodDeclaration nonDefaultCtor) { // PART I: find super ctor to call ITypeBinding newType = ctor.getDeclaringClass(); ITypeBinding javalangenumType = newType.getSuperclass(); IMethodBinding superCtor = null; if (newType.isEnum()) { for (IMethodBinding met : javalangenumType.getDeclaredMethods()) if (met.isConstructor()) { superCtor = met; break; } } assert superCtor != null : "enum"; // PART II: make ctor with simply "super(a,b,c...)" // TODO: extra CAstNodes final Map<CAstNode, CAstEntity> memberEntities = new LinkedHashMap<>(); final MethodContext context = new MethodContext(oldContext, memberEntities); MethodDeclaration fakeCtor = ast.newMethodDeclaration(); fakeCtor.setConstructor(true); fakeCtor.setSourceRange(n.getStartPosition(), n.getLength()); fakeCtor.setBody(ast.newBlock()); // PART IIa: make a fake JDT constructor method with the proper number of args // Make fake args that will be passed String[] fakeArguments = new String[3 + ctor.getParameterTypes().length]; if (nonDefaultCtor == null) { for (int i = 3; i < fakeArguments.length; i++) fakeArguments[i] = "__wala_jdtcast_argument" + i; // this is in the case of an anonymous class with parameters, eg NORTH in // the following example: public enum A { NORTH("south") { ...} A(String // s){} } } else { for (int i = 3; i < fakeArguments.length; i++) fakeArguments[i] = ((SingleVariableDeclaration) nonDefaultCtor.parameters().get(i - 3)) .getName() .getIdentifier(); } ArrayList<CAstType> paramTypes = new ArrayList<>(superCtor.getParameterTypes().length); fakeArguments[0] = "this"; fakeArguments[1] = "__wala_jdtcast_argument1"; // TODO FIXME: change to invalid name in the case that // nonDefaultCtor != null fakeArguments[2] = "__wala_jdtcast_argument2"; // otherwise there will be conflicts if we name our variable // __wala_jdtcast_argument1!!! for (int i = 1; i < fakeArguments.length; i++) { // the name SingleVariableDeclaration svd = ast.newSingleVariableDeclaration(); svd.setName(ast.newSimpleName(fakeArguments[i])); fakeCtor.parameters().add(svd); // the type switch (i) { case 1: paramTypes.add(fTypeDict.getCAstTypeFor(ast.resolveWellKnownType("java.lang.String"))); break; case 2: paramTypes.add(fTypeDict.getCAstTypeFor(ast.resolveWellKnownType("int"))); break; default: paramTypes.add(fTypeDict.getCAstTypeFor(ctor.getParameterTypes()[i - 3])); break; } } // PART IIb: create the statements in the constructor // one super() call plus the inits List<CAstNode> bodyNodes; if (nonDefaultCtor == null) bodyNodes = new ArrayList<>(inits.size() + 1); else bodyNodes = new ArrayList<>(inits.size() + 2); // make super(...) call // this, call ref, args List<CAstNode> children; if (ctor.isDefaultConstructor()) children = new ArrayList<>( 4 + ctor.getParameterTypes() .length); // anonymous class' implicit constructors call constructors with // more than standard two enum args else children = new ArrayList<>(4); // explicit constructor children.add(makeNode(context, fFactory, n, CAstNode.SUPER)); CallSiteReference callSiteRef = CallSiteReference.make( 0, fIdentityMapper.getMethodRef(superCtor), IInvokeInstruction.Dispatch.SPECIAL); children.add(fFactory.makeConstant(callSiteRef)); children.add( makeNode( context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(fakeArguments[1]), fFactory.makeConstant(paramTypes.get(0)))); children.add( makeNode( context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(fakeArguments[2]), fFactory.makeConstant(paramTypes.get(1)))); if (ctor.isDefaultConstructor()) for (int i = 0; i < ctor.getParameterTypes().length; i++) children.add( makeNode( context, fFactory, n, CAstNode.VAR, fFactory.makeConstant(fakeArguments[i + 3]), fFactory.makeConstant(paramTypes.get(i + 2)))); bodyNodes.add(makeNode(context, fFactory, n, CAstNode.CALL, children)); // QUESTION: no handleExceptions? for (ASTNode init : inits) bodyNodes.add(visitFieldInitNode(init, context)); if (nonDefaultCtor != null) bodyNodes.add(visitNode(nonDefaultCtor.getBody(), context)); // finally, make the procedure entity CAstNode ast = makeNode(context, fFactory, n, CAstNode.BLOCK_STMT, bodyNodes); return new ProcedureEntity( ast, fakeCtor, newType, memberEntities, context, paramTypes, null, handleAnnotations(ctor)); } }
173,935
35.757396
171
java
WALA
WALA-master/cast/java/ecj/src/main/java/com/ibm/wala/cast/java/translator/jdt/JDTTypeDictionary.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * WALA JDT Frontend is Copyright (c) 2008 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.cast.java.translator.jdt; import com.ibm.wala.cast.java.types.JavaPrimitiveTypeMap; import com.ibm.wala.cast.java.types.JavaType; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.cast.tree.CAstType.Union; import com.ibm.wala.cast.tree.impl.CAstTypeDictionaryImpl; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.UnionType; public class JDTTypeDictionary extends CAstTypeDictionaryImpl<ITypeBinding> { // TODO: better way of getting type "ObjecT" that doesn't require us to keep AST? although this is // similar to // polyglot. protected final AST fAst; // TAGALONG protected final JDTIdentityMapper fIdentityMapper; // TAGALONG /** @param ast Needed to get root type "java.lang.Object" */ public JDTTypeDictionary(AST ast, JDTIdentityMapper identityMapper) { fAst = ast; fIdentityMapper = identityMapper; } public CAstType getCAstTypeForUnion(UnionType astType) { List<?> types = astType.types(); Set<CAstType> elts = HashSetFactory.make(); types.forEach((type) -> elts.add(getCAstTypeFor(((Type) type).resolveBinding()))); return new JdtUnionType(elts); } @Override public CAstType getCAstTypeFor(Object astType) { ITypeBinding jdtType = JDT2CAstUtils.getErasedType((ITypeBinding) astType, fAst); CAstType type = super.getCAstTypeFor(astType); // check cache first // Handle the case where we haven't seen an AST decl for some type before // processing a reference. This can certainly happen with classes in byte- // code libraries, for which we never see an AST decl. // In this case, just create a new type and return that. if (type == null) { if (jdtType.isClass() || jdtType.isEnum() || jdtType.isInterface()) // in JDT interfaces are not classes type = new JdtJavaType(jdtType); else if (jdtType.isPrimitive()) { type = JavaPrimitiveTypeMap.lookupType(jdtType.getName()); } else if (jdtType.isArray()) { type = new JdtJavaArrayType(jdtType); } else Assertions.UNREACHABLE( "getCAstTypeFor() passed type that is not primitive, array, or class?"); super.map((ITypeBinding) astType, type); // put in cache } return type; } private final class JdtJavaArrayType implements CAstType.Array { private final ITypeBinding fEltJdtType; private final CAstType fEltCAstType; private JdtJavaArrayType(ITypeBinding arrayType) { super(); fEltJdtType = arrayType.getComponentType(); fEltCAstType = getCAstTypeFor(fEltJdtType); } @Override public int getNumDimensions() { return 1; // always 1 for Java } @Override public CAstType getElementType() { return fEltCAstType; } @Override public String getName() { return '[' + fEltCAstType.getName(); } @Override public Collection<CAstType> getSupertypes() { if (fEltJdtType.isPrimitive()) return Collections.singleton(getCAstTypeFor(fAst.resolveWellKnownType("java.lang.Object"))); // TODO: there is no '.isReference()' as in Polyglot: is this right? enum? I think if it's // another array it will // just ignore it // TEST DOUBLE ARRAYS! and maybe ask someone? assert fEltJdtType.isArray() || fEltJdtType.isClass() : "Non-primitive, non-reference array element type!"; Collection<CAstType> supers = new ArrayList<>(); for (ITypeBinding type : fEltJdtType.getInterfaces()) { supers.add(getCAstTypeFor(type)); } if (fEltJdtType.getSuperclass() != null) supers.add(getCAstTypeFor(fEltJdtType.getSuperclass())); return supers; } } public final class JdtJavaType implements JavaType { private final ITypeBinding fType; private Collection<CAstType> fSuperTypes = null; @Override public String toString() { return super.toString() + ':' + getName(); } public JdtJavaType(ITypeBinding type) { super(); fType = type; } @Override public String getName() { return fIdentityMapper.getTypeRef(fType).getName().toString(); } @Override public Collection<CAstType> getSupertypes() { if (fSuperTypes == null) { buildSuperTypes(); } return fSuperTypes; } private void buildSuperTypes() { // TODO this is a source entity, but it might actually be the root type // (Object), so assume # intfs + 1 ITypeBinding superType = (fType.getSuperclass() == null) ? fAst.resolveWellKnownType("java.lang.Object") : fType.getSuperclass(); int N = fType.getInterfaces().length + 1; fSuperTypes = new ArrayList<>(N); // Following assumes that noone can call getSupertypes() before we have // created CAstType's for every type in the program being analyzed. fSuperTypes.add(getCAstTypeFor(superType)); for (ITypeBinding t : fType.getInterfaces()) fSuperTypes.add(getCAstTypeFor(t)); } @Override public Collection<CAstQualifier> getQualifiers() { return JDT2CAstUtils.mapModifiersToQualifiers( fType.getModifiers(), fType.isInterface(), fType.isAnnotation()); } @Override public boolean isInterface() { return fType.isInterface(); } } public static final class JdtUnionType implements Union { private final Set<CAstType> constituents; public JdtUnionType(Set<CAstType> constituents) { this.constituents = constituents; } @Override public CAstType getType() { return this; } @Override public String getName() { return "union" + constituents.toString(); } @Override public Collection<CAstType> getSupertypes() { return Collections.emptySet(); } @Override public Iterable<CAstType> getConstituents() { return constituents; } } }
8,207
33.343096
100
java
WALA
WALA-master/cast/java/ecj/src/main/java/com/ibm/wala/cast/java/translator/jdt/ecj/ECJClassLoaderFactory.java
package com.ibm.wala.cast.java.translator.jdt.ecj; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl; import com.ibm.wala.classLoader.ClassLoaderFactoryImpl; import com.ibm.wala.classLoader.ClassLoaderImpl; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.config.SetOfClasses; import java.io.IOException; public class ECJClassLoaderFactory extends ClassLoaderFactoryImpl { public ECJClassLoaderFactory(SetOfClasses exclusions) { super(exclusions); } // TODO remove code duplication with JDTClassLoaderFactory @Override protected IClassLoader makeNewClassLoader( ClassLoaderReference classLoaderReference, IClassHierarchy cha, IClassLoader parent, AnalysisScope scope) throws IOException { if (classLoaderReference.equals(JavaSourceAnalysisScope.SOURCE)) { ClassLoaderImpl cl = makeSourceLoader(classLoaderReference, cha, parent); cl.init(scope.getModules(classLoaderReference)); return cl; } else { return super.makeNewClassLoader(classLoaderReference, cha, parent, scope); } } protected JavaSourceLoaderImpl makeSourceLoader( ClassLoaderReference classLoaderReference, IClassHierarchy cha, IClassLoader parent) { return new ECJSourceLoaderImpl(classLoaderReference, parent, cha, false); } }
1,535
34.72093
92
java
WALA
WALA-master/cast/java/ecj/src/main/java/com/ibm/wala/cast/java/translator/jdt/ecj/ECJSourceLoaderImpl.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * WALA JDT Frontend is Copyright (c) 2008 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.cast.java.translator.jdt.ecj; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl; import com.ibm.wala.cast.java.translator.SourceModuleTranslator; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.types.ClassLoaderReference; public class ECJSourceLoaderImpl extends JavaSourceLoaderImpl { protected final boolean dump; public ECJSourceLoaderImpl( ClassLoaderReference loaderRef, IClassLoader parent, IClassHierarchy cha) { this(loaderRef, parent, cha, false); } public ECJSourceLoaderImpl( ClassLoaderReference loaderRef, IClassLoader parent, IClassHierarchy cha, boolean dump) { super(loaderRef, parent, cha); this.dump = dump; } @Override protected SourceModuleTranslator getTranslator() { return new ECJSourceModuleTranslator(cha.getScope(), this, dump); } }
2,810
42.246154
95
java
WALA
WALA-master/cast/java/ecj/src/main/java/com/ibm/wala/cast/java/translator/jdt/ecj/ECJSourceModuleTranslator.java
/* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * WALA JDT Frontend is Copyright (c) 2008 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.cast.java.translator.jdt.ecj; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl; import com.ibm.wala.cast.java.translator.Java2IRTranslator; import com.ibm.wala.cast.java.translator.SourceModuleTranslator; import com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cast.tree.impl.AbstractSourcePosition; import com.ibm.wala.classLoader.DirectoryTreeModule; import com.ibm.wala.classLoader.JarFileModule; import com.ibm.wala.classLoader.JarStreamModule; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.classLoader.SourceFileModule; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.config.SetOfClasses; import com.ibm.wala.util.io.TemporaryFile; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.FileASTRequestor; /** * A SourceModuleTranslator whose implementation of loadAllSources() uses the PolyglotFrontEnd * pseudo-compiler to generate DOMO IR for the sources in the compile-time classpath. * * @author rfuhrer */ // remove me comment: Jdt little-case = not OK, upper case = OK public class ECJSourceModuleTranslator implements SourceModuleTranslator { protected static class ECJJavaToCAstTranslator extends JDTJava2CAstTranslator<Position> { public ECJJavaToCAstTranslator( JavaSourceLoaderImpl sourceLoader, CompilationUnit astRoot, String fullPath, boolean replicateForDoLoops, boolean dump) { super(sourceLoader, astRoot, fullPath, replicateForDoLoops, dump); } @Override public Position makePosition(int start, int end) { return new AbstractSourcePosition() { @Override public URL getURL() { try { return new URL("file://" + fullPath); } catch (MalformedURLException e) { assert false : fullPath; return null; } } @Override public Reader getReader() throws IOException { return new InputStreamReader(getURL().openConnection().getInputStream()); } @Override public int getFirstLine() { return cu.getLineNumber(start); } @Override public int getLastLine() { return cu.getLineNumber(end); } @Override public int getFirstCol() { return cu.getColumnNumber(start); } @Override public int getLastCol() { return cu.getColumnNumber(end); } @Override public int getFirstOffset() { return start; } @Override public int getLastOffset() { return end; } }; } } private final class ECJAstToIR extends FileASTRequestor { private final Map<String, ModuleEntry> sourceMap; public ECJAstToIR(Map<String, ModuleEntry> sourceMap) { this.sourceMap = sourceMap; } @Override public void acceptAST(String source, CompilationUnit ast) { JDTJava2CAstTranslator<Position> jdt2cast = makeCAstTranslator(ast, source); final Java2IRTranslator java2ir = makeIRTranslator(); java2ir.translate(sourceMap.get(source), jdt2cast.translateToCAst()); if (!"true".equals(System.getProperty("wala.jdt.quiet"))) { IProblem[] problems = ast.getProblems(); int length = problems.length; if (length > 0) { StringBuilder buffer = new StringBuilder(); for (IProblem problem : problems) { buffer.append(problem.getMessage()); buffer.append('\n'); } if (length != 0) System.err.println("Unexpected problems in " + source + "\n " + buffer); } } } } protected boolean dump; protected ECJSourceLoaderImpl sourceLoader; private final String[] sources; private final String[] libs; private final SetOfClasses exclusions; public ECJSourceModuleTranslator(AnalysisScope scope, ECJSourceLoaderImpl sourceLoader) { this(scope, sourceLoader, false); } public ECJSourceModuleTranslator( AnalysisScope scope, ECJSourceLoaderImpl sourceLoader, boolean dump) { this.sourceLoader = sourceLoader; this.dump = dump; Pair<String[], String[]> paths = computeClassPath(scope); sources = paths.fst; libs = paths.snd; this.exclusions = scope.getExclusions(); } private static Pair<String[], String[]> computeClassPath(AnalysisScope scope) { List<String> sources = new ArrayList<>(); List<String> libs = new ArrayList<>(); for (ClassLoaderReference cl : scope.getLoaders()) { while (cl != null) { List<Module> modules = scope.getModules(cl); for (Module m : modules) { if (m instanceof JarFileModule) { JarFileModule jarFileModule = (JarFileModule) m; libs.add(jarFileModule.getAbsolutePath()); } else if (m instanceof JarStreamModule) { try { File F = File.createTempFile("tmp", "jar"); F.deleteOnExit(); TemporaryFile.streamToFile(F, ((JarStreamModule) m)); libs.add(F.getAbsolutePath()); } catch (IOException e) { assert false : e; } } else if (m instanceof DirectoryTreeModule) { DirectoryTreeModule directoryTreeModule = (DirectoryTreeModule) m; sources.add(directoryTreeModule.getPath()); } else { // Assertions.UNREACHABLE("Module entry is neither jar file nor directory"); } } cl = cl.getParent(); } } return Pair.make(sources.toArray(new String[0]), libs.toArray(new String[0])); } /* * Project -> AST code from org.eclipse.jdt.core.tests.performance */ @Override public void loadAllSources(Set<ModuleEntry> modules) { List<String> sources = new ArrayList<>(); Map<String, ModuleEntry> sourceMap = HashMapFactory.make(); for (ModuleEntry m : modules) { if (m.isSourceFile()) { SourceFileModule s = (SourceFileModule) m; sourceMap.put(s.getAbsolutePath(), s); sources.add(s.getAbsolutePath()); } } String[] sourceFiles = sources.toArray(new String[0]); @SuppressWarnings("deprecation") final ASTParser parser = ASTParser.newParser(AST.JLS8); parser.setResolveBindings(true); parser.setEnvironment(libs, this.sources, null, false); Hashtable<String, String> options = JavaCore.getOptions(); options.put(JavaCore.COMPILER_SOURCE, "11"); parser.setCompilerOptions(options); parser.createASTs( sourceFiles, null, new String[0], new ECJAstToIR(sourceMap), new NullProgressMonitor()); } protected Java2IRTranslator makeIRTranslator() { return new Java2IRTranslator(sourceLoader, exclusions); } protected JDTJava2CAstTranslator<Position> makeCAstTranslator( CompilationUnit cu, String fullPath) { return new ECJJavaToCAstTranslator(sourceLoader, cu, fullPath, false, dump); } }
9,685
34.741697
99
java
WALA
WALA-master/cast/java/ecj/src/test/java/com/ibm/wala/cast/java/test/ECJIssue666Test.java
/* * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.ibm.wala.cast.java.test; import com.ibm.wala.cast.java.client.ECJJavaSourceAnalysisEngine; import com.ibm.wala.cast.java.client.JavaSourceAnalysisEngine; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import java.util.Collection; import java.util.List; public class ECJIssue666Test extends Issue666Test { public ECJIssue666Test() { super(null); } @Override protected AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> getAnalysisEngine( final String[] mainClassDescriptors, Collection<String> sources, List<String> libs) { JavaSourceAnalysisEngine engine = new ECJJavaSourceAnalysisEngine() { @Override protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) { return Util.makeMainEntrypoints( JavaSourceAnalysisScope.SOURCE, cha, mainClassDescriptors); } }; engine.setExclusionsFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS); populateScope(engine, sources, libs); return engine; } }
1,680
37.204545
100
java
WALA
WALA-master/cast/java/ecj/src/test/java/com/ibm/wala/cast/java/test/ECJIssue667Test.java
/* * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.ibm.wala.cast.java.test; import com.ibm.wala.cast.java.client.ECJJavaSourceAnalysisEngine; import com.ibm.wala.cast.java.client.JavaSourceAnalysisEngine; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import java.util.Collection; import java.util.List; public class ECJIssue667Test extends Issue667Test { public ECJIssue667Test() { super(null); } @Override protected AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> getAnalysisEngine( final String[] mainClassDescriptors, Collection<String> sources, List<String> libs) { JavaSourceAnalysisEngine engine = new ECJJavaSourceAnalysisEngine() { @Override protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) { return Util.makeMainEntrypoints( JavaSourceAnalysisScope.SOURCE, cha, mainClassDescriptors); } }; engine.setExclusionsFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS); populateScope(engine, sources, libs); return engine; } }
1,680
37.204545
100
java
WALA
WALA-master/cast/java/ecj/src/test/java/com/ibm/wala/cast/java/test/ECJJava17IRTest.java
/* * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.ibm.wala.cast.java.test; import static com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope.SOURCE; import com.ibm.wala.cast.java.client.ECJJavaSourceAnalysisEngine; import com.ibm.wala.cast.java.client.JavaSourceAnalysisEngine; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Pair; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.Test; public class ECJJava17IRTest extends IRTests { private static final String packageName = "javaonepointseven"; public ECJJava17IRTest() { super(null); dump = true; } @Override protected AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> getAnalysisEngine( final String[] mainClassDescriptors, Collection<String> sources, List<String> libs) { JavaSourceAnalysisEngine engine = new ECJJavaSourceAnalysisEngine() { @Override protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) { return Util.makeMainEntrypoints( JavaSourceAnalysisScope.SOURCE, cha, mainClassDescriptors); } }; engine.setExclusionsFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS); populateScope(engine, sources, libs); return engine; } private final IRAssertion checkBinaryLiterals = new IRAssertion() { private final TypeReference testClass = TypeReference.findOrCreate( SOURCE, TypeName.findOrCreateClassName(packageName, "BinaryLiterals")); private final Pair<MethodReference, int[]>[] constants = new Pair[] { Pair.make( MethodReference.findOrCreate(testClass, MethodReference.clinitSelector), new int[] { 0b00110001, 0b01100010, 0b11000100, 0b10001001, 0b00010011, 0b00100110, 0b01001100, 0b10011000 }) }; @Override public void check(CallGraph cg) { for (Pair<MethodReference, int[]> m : constants) { cg.getNodes(m.fst) .forEach( (n) -> { SymbolTable st = n.getIR().getSymbolTable(); for (int value : m.snd) { check: { for (int i = 1; i <= st.getMaxValueNumber(); i++) { if (st.isIntegerConstant(i) && st.getIntValue(i) == value) { System.err.println("found " + value + " in " + n); break check; } } assert false : "cannot find " + value + " in " + n; } } }); } } }; @Test public void testBinaryLiterals() throws IllegalArgumentException, CancelException, IOException { runTest( singlePkgTestSrc("javaonepointseven"), rtJar, simplePkgTestEntryPoint("javaonepointseven"), Collections.singletonList(checkBinaryLiterals), true, null); } private final IRAssertion checkCatchMultipleExceptionTypes = new IRAssertion() { private final TypeReference testClass = TypeReference.findOrCreate( SOURCE, TypeName.findOrCreateClassName(packageName, "CatchMultipleExceptionTypes")); private final MethodReference testMethod = MethodReference.findOrCreate(testClass, "test", "(I[I)V"); @Override public void check(CallGraph cg) { Set<IClass> expectedTypes = HashSetFactory.make(); expectedTypes.add( cg.getClassHierarchy().lookupClass(TypeReference.JavaLangArithmeticException)); expectedTypes.add( cg.getClassHierarchy() .lookupClass( TypeReference.findOrCreate( ClassLoaderReference.Primordial, "Ljava/lang/IndexOutOfBoundsException"))); cg.getNodes(testMethod) .forEach( (n) -> n.getIR() .getControlFlowGraph() .forEach( (bb) -> { if (bb.isCatchBlock()) { Set<IClass> foundTypes = HashSetFactory.make(); bb.getCaughtExceptionTypes() .forEachRemaining( (t) -> foundTypes.add( cg.getClassHierarchy().lookupClass(t))); assert foundTypes.equals(expectedTypes) : n.getIR(); } })); } }; @Test public void testCatchMultipleExceptionTypes() throws IllegalArgumentException, CancelException, IOException { runTest( singlePkgTestSrc("javaonepointseven"), rtJar, simplePkgTestEntryPoint("javaonepointseven"), Collections.singletonList(checkCatchMultipleExceptionTypes), true, null); } private static final List<IRAssertion> SiSAssertions = Collections.singletonList( new InstructionOperandAssertion( "Source#" + packageName + "/StringsInSwitch#main#([Ljava/lang/String;)V", t -> (t instanceof SSAAbstractInvokeInstruction) && t.toString().contains("getTypeOfDayWithSwitchStatement"), 1, new int[] {9, 58, 9, 67})); @Test public void testStringsInSwitch() throws IllegalArgumentException, CancelException, IOException { runTest( singlePkgTestSrc("javaonepointseven"), rtJar, simplePkgTestEntryPoint("javaonepointseven"), SiSAssertions, true, null); } @Test public void testTryWithResourcesStatement() throws IllegalArgumentException, CancelException, IOException { runTest( singlePkgTestSrc("javaonepointseven"), rtJar, simplePkgTestEntryPoint("javaonepointseven"), emptyList, true, null); } @Test public void testTypeInferenceforGenericInstanceCreation() throws IllegalArgumentException, CancelException, IOException { runTest( singlePkgTestSrc("javaonepointseven"), rtJar, simplePkgTestEntryPoint("javaonepointseven"), emptyList, true, null); } @Test public void testUnderscoresInNumericLiterals() throws IllegalArgumentException, CancelException, IOException { runTest( singlePkgTestSrc("javaonepointseven"), rtJar, simplePkgTestEntryPoint("javaonepointseven"), emptyList, true, null); } }
8,280
34.540773
100
java
WALA
WALA-master/cast/java/ecj/src/test/java/com/ibm/wala/cast/java/test/ECJJavaIRTest.java
/* * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.ibm.wala.cast.java.test; import com.ibm.wala.cast.java.client.ECJJavaSourceAnalysisEngine; import com.ibm.wala.cast.java.client.JavaSourceAnalysisEngine; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import java.util.Collection; import java.util.List; public class ECJJavaIRTest extends JavaIRTests { public ECJJavaIRTest() { super(null); } @Override protected AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> getAnalysisEngine( final String[] mainClassDescriptors, Collection<String> sources, List<String> libs) { JavaSourceAnalysisEngine engine = new ECJJavaSourceAnalysisEngine() { @Override protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) { return Util.makeMainEntrypoints( JavaSourceAnalysisScope.SOURCE, cha, mainClassDescriptors); } }; engine.setExclusionsFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS); populateScope(engine, sources, libs); return engine; } }
1,675
37.090909
100
java
WALA
WALA-master/cast/java/ecj/src/test/java/com/ibm/wala/cast/java/test/ECJSyncDuplicatorTest.java
/* * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.ibm.wala.cast.java.test; import com.ibm.wala.cast.java.client.ECJJavaSourceAnalysisEngine; import com.ibm.wala.cast.java.client.JavaSourceAnalysisEngine; import com.ibm.wala.cast.java.examples.ast.SynchronizedBlockDuplicator; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.cast.java.translator.SourceModuleTranslator; import com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator; import com.ibm.wala.cast.java.translator.jdt.ecj.ECJClassLoaderFactory; import com.ibm.wala.cast.java.translator.jdt.ecj.ECJSourceLoaderImpl; import com.ibm.wala.cast.java.translator.jdt.ecj.ECJSourceModuleTranslator; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cast.tree.impl.CAstImpl; import com.ibm.wala.cast.tree.impl.RangePosition; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction.Dispatch; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.config.SetOfClasses; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.List; import org.eclipse.jdt.core.dom.CompilationUnit; public class ECJSyncDuplicatorTest extends SyncDuplicatorTests { private static final CallSiteReference guard = CallSiteReference.make( 0, MethodReference.findOrCreate( TypeReference.findOrCreate(JavaSourceAnalysisScope.SOURCE, "LMonitor2"), "randomIsolate", "()Z"), Dispatch.STATIC); @Override protected AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> getAnalysisEngine( final String[] mainClassDescriptors, Collection<String> sources, List<String> libs) { JavaSourceAnalysisEngine engine = new ECJJavaSourceAnalysisEngine() { @Override protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) { return Util.makeMainEntrypoints( JavaSourceAnalysisScope.SOURCE, cha, mainClassDescriptors); } @Override protected ClassLoaderFactory getClassLoaderFactory(SetOfClasses exclusions) { return new ECJClassLoaderFactory(exclusions) { @Override protected ECJSourceLoaderImpl makeSourceLoader( ClassLoaderReference classLoaderReference, IClassHierarchy cha, IClassLoader parent) { return new ECJSourceLoaderImpl(classLoaderReference, parent, cha) { @Override protected SourceModuleTranslator getTranslator() { return new ECJSourceModuleTranslator(cha.getScope(), this) { @Override protected JDTJava2CAstTranslator<Position> makeCAstTranslator( CompilationUnit astRoot, String fullPath) { return new JDTJava2CAstTranslator<>(sourceLoader, astRoot, fullPath, true) { @Override public CAstEntity translateToCAst() { CAstEntity ast = super.translateToCAst(); SynchronizedBlockDuplicator unwind = new SynchronizedBlockDuplicator(new CAstImpl(), true, guard); return unwind.translate(ast); } @Override public Position makePosition(int start, int end) { try { return new RangePosition( new URL("file://" + fullPath), this.cu.getLineNumber(start), start, end); } catch (MalformedURLException e) { throw new RuntimeException("bad file: " + fullPath, e); } } }; } }; } }; } }; } }; engine.setExclusionsFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS); populateScope(engine, sources, libs); return engine; } }
5,205
44.269565
100
java
WALA
WALA-master/cast/java/ecj/src/test/java/com/ibm/wala/cast/java/test/ECJTestComments.java
package com.ibm.wala.cast.java.test; import com.ibm.wala.cast.java.client.ECJJavaSourceAnalysisEngine; import com.ibm.wala.cast.java.client.JavaSourceAnalysisEngine; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.cast.loader.AstMethod; import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation; import com.ibm.wala.classLoader.Language; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.tests.callGraph.CallGraphTestUtil; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Pair; import java.io.IOException; import java.util.Collection; import java.util.List; import org.junit.Test; public class ECJTestComments extends IRTests { public ECJTestComments() { super(null); } @Override protected AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> getAnalysisEngine( final String[] mainClassDescriptors, Collection<String> sources, List<String> libs) { JavaSourceAnalysisEngine engine = new ECJJavaSourceAnalysisEngine() { @Override protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) { return Util.makeMainEntrypoints( JavaSourceAnalysisScope.SOURCE, cha, mainClassDescriptors); } }; engine.setExclusionsFile(CallGraphTestUtil.REGRESSION_EXCLUSIONS); populateScope(engine, sources, libs); return engine; } protected static final MethodReference testMethod = MethodReference.findOrCreate( TypeReference.findOrCreate( JavaSourceAnalysisScope.SOURCE, TypeName.string2TypeName("LComments")), Atom.findOrCreateUnicodeAtom("main"), Descriptor.findOrCreateUTF8(Language.JAVA, "([Ljava/lang/String;)V")); @Test public void testComments() throws IllegalArgumentException, CancelException, IOException { Pair<CallGraph, CallGraphBuilder<? super InstanceKey>> result = runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); for (CGNode node : result.fst.getNodes(testMethod)) { if (node.getMethod() instanceof AstMethod) { AstMethod m = (AstMethod) node.getMethod(); DebuggingInformation dbg = m.debugInfo(); for (SSAInstruction inst : node.getIR().getInstructions()) { System.err.println("leading for " + inst.toString(node.getIR().getSymbolTable())); System.err.println(dbg.getLeadingComment(inst.iIndex())); System.err.println("following for " + inst.toString(node.getIR().getSymbolTable())); System.err.println(dbg.getFollowingComment(inst.iIndex())); } } } } }
3,272
40.961538
100
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/analysis/typeInference/AstJavaTypeInference.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.analysis.typeInference; import com.ibm.wala.analysis.typeInference.ConeType; import com.ibm.wala.analysis.typeInference.JavaPrimitiveType; import com.ibm.wala.analysis.typeInference.PointType; import com.ibm.wala.analysis.typeInference.PrimitiveType; import com.ibm.wala.analysis.typeInference.TypeAbstraction; import com.ibm.wala.analysis.typeInference.TypeVariable; import com.ibm.wala.cast.analysis.typeInference.AstTypeInference; import com.ibm.wala.cast.ir.ssa.CAstBinaryOp; import com.ibm.wala.cast.java.ssa.AstJavaInstructionVisitor; import com.ibm.wala.cast.java.ssa.AstJavaInvokeInstruction; import com.ibm.wala.cast.java.ssa.EnclosingObjectReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.shrike.shrikeBT.IBinaryOpInstruction; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSABinaryOpInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.debug.Assertions; public class AstJavaTypeInference extends AstTypeInference { protected IClass stringClass; protected class AstJavaTypeOperatorFactory extends AstTypeOperatorFactory implements AstJavaInstructionVisitor { @Override public void visitBinaryOp(SSABinaryOpInstruction instruction) { if (doPrimitives) { IBinaryOpInstruction.IOperator op = instruction.getOperator(); if (op == CAstBinaryOp.EQ || op == CAstBinaryOp.NE || op == CAstBinaryOp.LT || op == CAstBinaryOp.GE || op == CAstBinaryOp.GT || op == CAstBinaryOp.LE) { result = new DeclaredTypeOperator( language.getPrimitive(language.getConstantType(Boolean.TRUE))); } else { result = new PrimAndStringOp(); } } } @Override public void visitEnclosingObjectReference(EnclosingObjectReference inst) { TypeReference type = inst.getEnclosingType(); IClass klass = cha.lookupClass(type); if (klass == null) { Assertions.UNREACHABLE(); } else { result = new DeclaredTypeOperator(new ConeType(klass)); } } @Override public void visitJavaInvoke(AstJavaInvokeInstruction instruction) { TypeReference type = instruction.getDeclaredResultType(); if (type.isReferenceType()) { IClass klass = cha.lookupClass(type); if (klass == null) { // a type that cannot be loaded. // be pessimistic result = new DeclaredTypeOperator(BOTTOM); } else { result = new DeclaredTypeOperator(new ConeType(klass)); } } else { if (doPrimitives && type.isPrimitiveType()) { result = new DeclaredTypeOperator(PrimitiveType.getPrimitive(type)); } else { result = null; } } } } public class AstJavaTypeVarFactory extends TypeVarFactory { @Override public TypeVariable makeVariable(int valueNumber) { SymbolTable st = ir.getSymbolTable(); if (st.isStringConstant(valueNumber)) { IClass klass = cha.lookupClass(TypeReference.JavaLangString); TypeAbstraction stringTypeAbs = new PointType(klass); return new TypeVariable(stringTypeAbs); } else { return super.makeVariable(valueNumber); } } } public AstJavaTypeInference(IR ir, boolean doPrimitives) { super(ir, JavaPrimitiveType.BOOLEAN, doPrimitives); } IClass getStringClass() { if (stringClass == null) { this.stringClass = cha.lookupClass(TypeReference.JavaLangString); } return stringClass; } @Override protected void initialize() { init(ir, new AstJavaTypeVarFactory(), new AstJavaTypeOperatorFactory()); } @Override public TypeAbstraction getConstantPrimitiveType(int valueNumber) { SymbolTable st = ir.getSymbolTable(); if (st.isBooleanConstant(valueNumber)) { return language.getPrimitive(language.getConstantType(Boolean.TRUE)); } else { return super.getConstantPrimitiveType(valueNumber); } } protected class PrimAndStringOp extends PrimitivePropagateOperator { private PrimAndStringOp() {} @Override public byte evaluate(TypeVariable lhs, TypeVariable[] rhs) { TypeAbstraction meet = null; for (TypeVariable r : rhs) { if (r != null) { TypeAbstraction ta = r.getType(); if (ta instanceof PointType) { if (ta.getType().equals(getStringClass())) { meet = new PointType(ta.getType()); break; } } else if (ta instanceof ConeType) { if (ta.getType().equals(getStringClass())) { meet = new PointType(ta.getType()); break; } } } } if (meet == null) { return super.evaluate(lhs, rhs); } else { TypeVariable L = lhs; TypeAbstraction lhsType = L.getType(); if (lhsType.equals(meet)) { return NOT_CHANGED; } else { L.setType(meet); return CHANGED; } } } /* * (non-Javadoc) * * @see com.ibm.wala.dataflow.Operator#hashCode() */ @Override public int hashCode() { return 71292; } /* * (non-Javadoc) * * @see com.ibm.wala.dataflow.Operator#equals(java.lang.Object) */ @Override public boolean equals(Object o) { return o != null && o.getClass().equals(getClass()); } } }
5,921
29.84375
81
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/client/JavaSourceAnalysisEngine.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.client; import com.ibm.wala.cast.ir.ssa.AstIRFactory; import com.ibm.wala.cast.java.client.impl.ZeroCFABuilderFactory; import com.ibm.wala.cast.java.ipa.callgraph.AstJavaZeroXCFABuilder; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.classLoader.ClassLoaderFactory; import com.ibm.wala.classLoader.Module; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.util.io.FileProvider; import com.ibm.wala.ipa.callgraph.AnalysisCacheImpl; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ssa.SSAOptions; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.config.FileOfClasses; import com.ibm.wala.util.config.SetOfClasses; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Set; /** */ public abstract class JavaSourceAnalysisEngine extends AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, Void> { /** Modules which are user-space code */ private final Set<Module> userEntries = HashSetFactory.make(); /** Modules which are source code */ private final Set<Module> sourceEntries = HashSetFactory.make(); /** Modules which are system or library code TODO: what about extension loader? */ private final Set<Module> systemEntries = HashSetFactory.make(); public JavaSourceAnalysisEngine() { super(); } /** * Adds the given source module to the source loader's module list. Clients should/may call this * method if they don't supply an IJavaProject to the constructor. */ public void addSourceModule(Module M) { sourceEntries.add(M); } /** * Adds the given compiled module to the application loader's module list. Clients should/may call * this method if they don't supply an IJavaProject to the constructor. */ public void addCompiledModule(Module M) { userEntries.add(M); } /** * Adds the given module to the primordial loader's module list. Clients should/may call this * method if they don't supply an IJavaProject to the constructor. */ public void addSystemModule(Module M) { systemEntries.add(M); } @Override protected void addApplicationModulesToScope() { ClassLoaderReference app = scope.getApplicationLoader(); for (Module M : userEntries) { scope.addToScope(app, M); } ClassLoaderReference src = ((JavaSourceAnalysisScope) scope).getSourceLoader(); for (Module M : sourceEntries) { scope.addToScope(src, M); } } @Override public void buildAnalysisScope() throws IOException { scope = makeSourceAnalysisScope(); if (getExclusionsFile() != null) { try (final InputStream is = new File(getExclusionsFile()).exists() ? new FileInputStream(getExclusionsFile()) : FileProvider.class.getClassLoader().getResourceAsStream(getExclusionsFile())) { scope.setExclusions(new FileOfClasses(is)); } } for (Module M : this.systemEntries) { scope.addToScope(scope.getPrimordialLoader(), M); } // add user stuff addApplicationModulesToScope(); } protected AnalysisScope makeSourceAnalysisScope() { return new JavaSourceAnalysisScope(); } protected abstract ClassLoaderFactory getClassLoaderFactory(SetOfClasses exclusions); @Override public IClassHierarchy buildClassHierarchy() { IClassHierarchy cha = null; ClassLoaderFactory factory = getClassLoaderFactory(scope.getExclusions()); try { cha = ClassHierarchyFactory.make(getScope(), factory); } catch (ClassHierarchyException e) { System.err.println("Class Hierarchy construction failed"); System.err.println(e); e.printStackTrace(); } return cha; } @Override protected Iterable<Entrypoint> makeDefaultEntrypoints(IClassHierarchy cha) { return Util.makeMainEntrypoints(JavaSourceAnalysisScope.SOURCE, cha); } @Override public IAnalysisCacheView makeDefaultCache() { return new AnalysisCacheImpl(AstIRFactory.makeDefaultFactory(), getOptions().getSSAOptions()); } @Override public AnalysisOptions getOptions() { AnalysisOptions options = super.getOptions(); SSAOptions so = options.getSSAOptions(); so.setDefaultValues(SymbolTable::getDefaultValue); return options; } @Override public AnalysisOptions getDefaultOptions(Iterable<Entrypoint> entrypoints) { AnalysisOptions options = new AnalysisOptions(getScope(), entrypoints); SSAOptions ssaOptions = new SSAOptions(); ssaOptions.setDefaultValues(SymbolTable::getDefaultValue); options.setSSAOptions(ssaOptions); return options; } @Override protected AstJavaZeroXCFABuilder getCallGraphBuilder( IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) { return new ZeroCFABuilderFactory().make(options, cache, cha); } }
5,871
31.804469
100
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/client/impl/ZeroCFABuilderFactory.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.client.impl; import com.ibm.wala.cast.java.ipa.callgraph.AstJavaZeroXCFABuilder; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys; import com.ibm.wala.ipa.cha.IClassHierarchy; /** * @author Julian Dolby ([email protected]) * <p>A factory to create call graph builders using 0-CFA */ public class ZeroCFABuilderFactory { public AstJavaZeroXCFABuilder make( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { Util.addDefaultSelectors(options, cha); Util.addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); return new AstJavaZeroXCFABuilder(cha, options, cache, null, null, ZeroXInstanceKeys.NONE); } }
1,243
36.69697
95
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/client/impl/ZeroOneCFABuilderFactory.java
package com.ibm.wala.cast.java.client.impl; import com.ibm.wala.cast.java.ipa.callgraph.AstJavaZeroXCFABuilder; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys; import com.ibm.wala.ipa.cha.IClassHierarchy; /** * @author Linghui Luo * <p>A factory to create call graph builders using 0-1-CFA */ public class ZeroOneCFABuilderFactory { public AstJavaZeroXCFABuilder make( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { Util.addDefaultSelectors(options, cha); Util.addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); return new AstJavaZeroXCFABuilder( cha, options, cache, null, null, ZeroXInstanceKeys.ALLOCATIONS | ZeroXInstanceKeys.SMUSH_MANY | ZeroXInstanceKeys.SMUSH_PRIMITIVE_HOLDERS | ZeroXInstanceKeys.SMUSH_STRINGS | ZeroXInstanceKeys.SMUSH_THROWABLES); } }
1,102
33.46875
79
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/client/impl/ZeroOneContainerCFABuilderFactory.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.client.impl; import com.ibm.wala.cast.java.ipa.callgraph.AstJavaZeroOneContainerCFABuilder; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; /** * @author Julian Dolby ([email protected]) * <p>A factory to create call graph builders using 0-CFA */ public class ZeroOneContainerCFABuilderFactory { public CallGraphBuilder<InstanceKey> make( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha) { Util.addDefaultSelectors(options, cha); Util.addDefaultBypassLogic(options, Util.class.getClassLoader(), cha); return new AstJavaZeroOneContainerCFABuilder(cha, options, cache, null, null); } }
1,302
37.323529
82
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/examples/ast/SynchronizedBlockDuplicator.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.examples.ast; import com.ibm.wala.cast.java.types.JavaPrimitiveTypeMap; import com.ibm.wala.cast.tree.CAst; import com.ibm.wala.cast.tree.CAstControlFlowMap; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.cast.tree.impl.CAstOperator; import com.ibm.wala.cast.tree.rewrite.CAstRewriter; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.util.collections.Pair; import java.util.Map; import java.util.Objects; /** * transforms each synchronized block to execute under a conditional test calling some method m(), * where the block is duplicated in both the if and else branches. The transformation enables a * static analysis to separately analyze the synchronized block for true and false return values * from m(). * * <p>See "Finding Concurrency-Related Bugs using Random Isolation," Kidd et al., VMCAI'09, Section * 3 */ public class SynchronizedBlockDuplicator extends CAstRewriter< CAstRewriter.RewriteContext<SynchronizedBlockDuplicator.UnwindKey>, SynchronizedBlockDuplicator.UnwindKey> { /** * key type used for cloning the synchronized blocks and the true and false branches of the * introduced conditional */ static class UnwindKey implements CAstRewriter.CopyKey<UnwindKey> { /** are we on the true or false branch? */ private final boolean testDirection; /** the AST node representing the synchronized block */ private final CAstNode syncNode; /** * key associated with the {@link com.ibm.wala.cast.tree.rewrite.CAstRewriter.RewriteContext * context} of the parent AST node of the synchronized block */ private final UnwindKey rest; private UnwindKey(boolean testDirection, CAstNode syncNode, UnwindKey rest) { this.rest = rest; this.syncNode = syncNode; this.testDirection = testDirection; } @Override public int hashCode() { return (testDirection ? 1 : -1) * System.identityHashCode(syncNode) * (rest == null ? 1 : rest.hashCode()); } @Override public UnwindKey parent() { return rest; } @Override public boolean equals(Object o) { return (o instanceof UnwindKey) && ((UnwindKey) o).testDirection == testDirection && ((UnwindKey) o).syncNode == syncNode && Objects.equals(rest, ((UnwindKey) o).rest); } @Override public String toString() { return "#" + testDirection + ((rest == null) ? "" : rest.toString()); } } // private static final boolean DEBUG = false; /** method to be invoked in the conditional test (program counter is ignored? --MS) */ private final CallSiteReference f; public SynchronizedBlockDuplicator(CAst Ast, boolean recursive, CallSiteReference f) { super(Ast, recursive, new RootContext()); this.f = f; } public CAstEntity translate(CAstEntity original) { return rewrite(original); } /** context used for nodes not contained in a synchronized block */ private static class RootContext implements RewriteContext<UnwindKey> { @Override public UnwindKey key() { return null; } } /** context used within synchronized blocks */ static class SyncContext implements RewriteContext<UnwindKey> { /** context used for the parent AST node of the synchronized block */ private final CAstRewriter.RewriteContext<UnwindKey> parent; /** are we on the true or false branch of the introduced conditional? */ private final boolean testDirection; /** the AST node representing the synchronized block */ private final CAstNode syncNode; private SyncContext( boolean testDirection, CAstNode syncNode, RewriteContext<UnwindKey> parent) { this.testDirection = testDirection; this.syncNode = syncNode; this.parent = parent; } @Override public UnwindKey key() { return new UnwindKey(testDirection, syncNode, parent.key()); } /** is n our synchronized block node or the synchronized block node of a parent? */ private boolean containsNode(CAstNode n) { if (n == syncNode) { return true; } else if (parent != null) { return contains(parent, n); } else { return false; } } } @Override protected CAstNode flowOutTo( Map<Pair<CAstNode, UnwindKey>, CAstNode> nodeMap, CAstNode oldSource, Object label, CAstNode oldTarget, CAstControlFlowMap orig, CAstSourcePositionMap src) { assert oldTarget == CAstControlFlowMap.EXCEPTION_TO_EXIT; return oldTarget; } private static boolean contains(RewriteContext<UnwindKey> c, CAstNode n) { if (c instanceof SyncContext) { return ((SyncContext) c).containsNode(n); } else { return false; } } /** * does root represent a synchronized block? if so, return the variable whose lock is acquired. * otherwise, return {@code null} */ private static String isSynchronizedOnVar(CAstNode root) { if (root.getKind() == CAstNode.UNWIND) { CAstNode unwindBody = root.getChild(0); if (unwindBody.getKind() == CAstNode.BLOCK_STMT) { CAstNode firstStmt = unwindBody.getChild(0); if (firstStmt.getKind() == CAstNode.MONITOR_ENTER) { CAstNode expr = firstStmt.getChild(0); if (expr.getKind() == CAstNode.VAR) { String varName = (String) expr.getChild(0).getValue(); CAstNode protectBody = root.getChild(1); if (protectBody.getKind() == CAstNode.MONITOR_EXIT) { CAstNode expr2 = protectBody.getChild(0); if (expr2.getKind() == CAstNode.VAR) { String varName2 = (String) expr2.getChild(0).getValue(); if (varName.equals(varName2)) { return varName; } } } } } } } return null; } @Override protected CAstNode copyNodes( CAstNode n, final CAstControlFlowMap cfg, RewriteContext<UnwindKey> c, Map<Pair<CAstNode, UnwindKey>, CAstNode> nodeMap) { String varName; // don't copy operators or constants (presumably since they are immutable?) if (n instanceof CAstOperator) { return n; } else if (n.getValue() != null) { return Ast.makeConstant(n.getValue()); } else if (!contains(c, n) && (varName = isSynchronizedOnVar(n)) != null) { // we call contains() above since we pass n to copyNodes() below for the // true and false branches of the conditional, and in those recursive // calls we want n to be copied normally // the conditional test CAstNode test = Ast.makeNode( CAstNode.CALL, Ast.makeNode(CAstNode.VOID), Ast.makeConstant(f), Ast.makeNode( CAstNode.VAR, Ast.makeConstant(varName), Ast.makeConstant(JavaPrimitiveTypeMap.lookupType("boolean")))); // the new if conditional return Ast.makeNode( CAstNode.IF_STMT, test, copyNodes(n, cfg, new SyncContext(true, n, c), nodeMap), copyNodes(n, cfg, new SyncContext(false, n, c), nodeMap)); } else { // invoke copyNodes() on the children with context c, ensuring, e.g., that // the body of a synchronized block gets cloned return copySubtreesIntoNewNode(n, cfg, c, nodeMap); } } }
7,948
31.847107
99
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ipa/callgraph/AstJavaCFABuilder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ipa.callgraph; import com.ibm.wala.classLoader.Language; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.propagation.cfa.DefaultPointerKeyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; /** Common utilities for CFA-style call graph builders. */ public class AstJavaCFABuilder extends AstJavaSSAPropagationCallGraphBuilder { public AstJavaCFABuilder(IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache) { super( Language.JAVA.getFakeRootMethod(cha, options, cache), options, cache, new DefaultPointerKeyFactory()); } }
1,083
35.133333
100
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ipa/callgraph/AstJavaSSAPropagationCallGraphBuilder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ipa.callgraph; import com.ibm.wala.analysis.typeInference.TypeInference; import com.ibm.wala.cast.ipa.callgraph.AstSSAPropagationCallGraphBuilder; import com.ibm.wala.cast.ipa.callgraph.GlobalObjectKey; import com.ibm.wala.cast.java.analysis.typeInference.AstJavaTypeInference; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl.JavaClass; import com.ibm.wala.cast.java.ssa.AstJavaInstructionVisitor; import com.ibm.wala.cast.java.ssa.AstJavaInvokeInstruction; import com.ibm.wala.cast.java.ssa.AstJavaNewEnclosingInstruction; import com.ibm.wala.cast.java.ssa.EnclosingObjectReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.fixpoint.IntSetVariable; import com.ibm.wala.fixpoint.UnaryOperator; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.propagation.AbstractFieldPointerKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerKeyFactory; import com.ibm.wala.ipa.callgraph.propagation.PointsToSetVariable; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.MethodReference; import com.ibm.wala.util.debug.Assertions; public class AstJavaSSAPropagationCallGraphBuilder extends AstSSAPropagationCallGraphBuilder { protected AstJavaSSAPropagationCallGraphBuilder( IMethod fakeRootClass, AnalysisOptions options, IAnalysisCacheView cache, PointerKeyFactory pointerKeyFactory) { super(fakeRootClass, options, cache, pointerKeyFactory); } // /////////////////////////////////////////////////////////////////////////// // // language specialization interface // // /////////////////////////////////////////////////////////////////////////// @Override protected boolean useObjectCatalog() { return false; } @Override protected AbstractFieldPointerKey fieldKeyForUnknownWrites(AbstractFieldPointerKey fieldKey) { assert false; return null; } // /////////////////////////////////////////////////////////////////////////// // // enclosing object pointer flow support // // /////////////////////////////////////////////////////////////////////////// public static class EnclosingObjectReferenceKey extends AbstractFieldPointerKey { private final IClass outer; public EnclosingObjectReferenceKey(InstanceKey inner, IClass outer) { super(inner); this.outer = outer; } @Override public int hashCode() { return getInstanceKey().hashCode() * outer.hashCode(); } @Override public boolean equals(Object o) { return (o instanceof EnclosingObjectReferenceKey) && ((EnclosingObjectReferenceKey) o).outer.equals(outer) && ((EnclosingObjectReferenceKey) o).getInstanceKey().equals(getInstanceKey()); } } // /////////////////////////////////////////////////////////////////////////// // // top-level node constraint generation // // /////////////////////////////////////////////////////////////////////////// protected TypeInference makeTypeInference(IR ir) { TypeInference ti = new AstJavaTypeInference(ir, false); if (DEBUG_TYPE_INFERENCE) { System.err.println(("IR of " + ir.getMethod())); System.err.println(ir); System.err.println(("TypeInference of " + ir.getMethod())); for (int i = 0; i <= ir.getSymbolTable().getMaxValueNumber(); i++) { if (ti.isUndefined(i)) { System.err.println((" value " + i + " is undefined")); } else { System.err.println((" value " + i + " has type " + ti.getType(i))); } } } return ti; } protected static class AstJavaInterestingVisitor extends AstInterestingVisitor implements AstJavaInstructionVisitor { protected AstJavaInterestingVisitor(int vn) { super(vn); } @Override public void visitEnclosingObjectReference(EnclosingObjectReference inst) { Assertions.UNREACHABLE(); } @Override public void visitJavaInvoke(AstJavaInvokeInstruction instruction) { bingo = true; } } @Override protected InterestingVisitor makeInterestingVisitor(CGNode node, int vn) { return new AstJavaInterestingVisitor(vn); } // /////////////////////////////////////////////////////////////////////////// // // specialized pointer analysis // // /////////////////////////////////////////////////////////////////////////// protected static class AstJavaConstraintVisitor extends AstConstraintVisitor implements AstJavaInstructionVisitor { public AstJavaConstraintVisitor(AstSSAPropagationCallGraphBuilder builder, CGNode node) { super(builder, node); } /** * For each of objKey's instance keys ik, adds the constraint lvalKey = EORK(ik,cls), where * EORK(ik,cls) will be made equivalent to the actual enclosing class by the handleNew() * function below. */ private void handleEnclosingObject( final PointerKey lvalKey, final IClass cls, final PointerKey objKey) { SymbolTable symtab = ir.getSymbolTable(); int objVal; if (objKey instanceof LocalPointerKey) { objVal = ((LocalPointerKey) objKey).getValueNumber(); } else { objVal = 0; } if (objVal > 0 && contentsAreInvariant(symtab, du, objVal)) { system.recordImplicitPointsToSet(objKey); InstanceKey[] objs = getInvariantContents(objVal); for (InstanceKey obj : objs) { PointerKey enclosing = new EnclosingObjectReferenceKey(obj, cls); system.newConstraint(lvalKey, assignOperator, enclosing); } } else { system.newSideEffect( new UnaryOperator<>() { @Override public byte evaluate(PointsToSetVariable lhs, PointsToSetVariable rhs) { IntSetVariable<?> tv = rhs; if (tv.getValue() != null) { tv.getValue() .foreach( ptr -> { InstanceKey iKey = system.getInstanceKey(ptr); PointerKey enclosing = new EnclosingObjectReferenceKey(iKey, cls); system.newConstraint(lvalKey, assignOperator, enclosing); }); } return NOT_CHANGED; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object o) { return o == this; } @Override public String toString() { return "enclosing objects of " + objKey; } }, objKey); } } @Override public void visitEnclosingObjectReference(EnclosingObjectReference inst) { PointerKey lvalKey = getPointerKeyForLocal(inst.getDef()); PointerKey objKey = getPointerKeyForLocal(1); IClass cls = getClassHierarchy().lookupClass(inst.getEnclosingType()); handleEnclosingObject(lvalKey, cls, objKey); } @Override public void visitNew(SSANewInstruction instruction) { super.visitNew(instruction); InstanceKey iKey = getInstanceKeyForAllocation(instruction.getNewSite()); if (iKey != null) { IClass klass = iKey.getConcreteType(); // in the case of a AstJavaNewEnclosingInstruction (a new instruction like outer.new Bla()), // we may need to record the instance keys if the pointer key outer is invariant (and thus // implicit) InstanceKey enclosingInvariantKeys[] = null; if (klass instanceof JavaClass) { IClass enclosingClass = ((JavaClass) klass).getEnclosingClass(); // the immediate enclosing class. if (enclosingClass != null) { PointerKey objKey; if (instruction instanceof AstJavaNewEnclosingInstruction) { int enclosingVal = ((AstJavaNewEnclosingInstruction) instruction).getEnclosing(); SymbolTable symtab = ir.getSymbolTable(); // pk 'outer' is invariant, which means it's implicit, so can't add a constraint with // the pointer key. // we should just add constraints directly to the instance keys (below) if (contentsAreInvariant(symtab, du, enclosingVal)) enclosingInvariantKeys = getInvariantContents(enclosingVal); // what happens if objKey is implicit but the contents aren't invariant?! (it this // possible?) big trouble! objKey = getPointerKeyForLocal(enclosingVal); } else objKey = getPointerKeyForLocal(1); System.err.println( ("class is " + klass + ", enclosing is " + enclosingClass + ", method is " + node.getMethod())); if (node.getMethod().isWalaSynthetic()) { return; } IClass currentCls = enclosingClass; PointerKey x = new EnclosingObjectReferenceKey(iKey, currentCls); if (enclosingInvariantKeys != null) for (InstanceKey obj : enclosingInvariantKeys) system.newConstraint(x, obj); else system.newConstraint(x, assignOperator, objKey); // If the immediate inclosing class is not a top-level class, we must make EORKs for all // enclosing classes up to the top level. // for instance, if we have "D d = c.new D()", and c is of type A$B$C, methods in D may // reference variables and functions from // A, B, and C. Therefore we must also make the links from EORK(allocsite of d,enc class // B) and EORK(allocsite of d,en class A). // We do this by getting the enclosing class of C and making a link from EORK(d,B) -> // EORK(c,B), etc. currentCls = ((JavaClass) currentCls).getEnclosingClass(); while (currentCls != null) { x = new EnclosingObjectReferenceKey( iKey, currentCls); // make EORK(d,B), EORK(d,A), etc. handleEnclosingObject(x, currentCls, objKey); // objKey is the pointer key representing the immediate inner class. // handleEnclosingObject finds x's instance keys and for each one "ik" links x to // EORK(ik,currentCls) // thus, for currentCls=B, it will find the allocation site of c and make a link from // EORK(d,B) to EORK(c,B) currentCls = ((JavaClass) currentCls).getEnclosingClass(); } } } } } @Override public void visitJavaInvoke(AstJavaInvokeInstruction instruction) { visitInvokeInternal(instruction, new DefaultInvariantComputer()); } } @Override public ConstraintVisitor makeVisitor(CGNode node) { return new AstJavaConstraintVisitor(this, node); } @Override protected boolean sameMethod(CGNode opNode, String definingMethod) { MethodReference reference = opNode.getMethod().getReference(); String selector = reference.getSelector().toString(); String containingClass = reference.getDeclaringClass().getName().toString(); return definingMethod.equals(containingClass + '/' + selector); } @Override public GlobalObjectKey getGlobalObject(Atom language) { Assertions.UNREACHABLE(); return null; } }
12,376
36.056886
100
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ipa/callgraph/AstJavaZeroOneContainerCFABuilder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ipa.callgraph; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.DefaultContextSelector; import com.ibm.wala.ipa.callgraph.impl.DelegatingContextSelector; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.cfa.ContainerContextSelector; import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys; import com.ibm.wala.ipa.cha.IClassHierarchy; /** * 0-1-CFA Call graph builder which analyzes calls to "container methods" in a context which is * defined by the receiver instance. * * @author sfink */ public class AstJavaZeroOneContainerCFABuilder extends AstJavaCFABuilder { /** * @param cha governing class hierarchy * @param options call graph construction options * @param appContextSelector application-specific logic to choose contexts * @param appContextInterpreter application-specific logic to interpret a method in context */ public AstJavaZeroOneContainerCFABuilder( IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache, ContextSelector appContextSelector, SSAContextInterpreter appContextInterpreter) { super(cha, options, cache); ContextSelector def = new DefaultContextSelector(options, cha); ContextSelector contextSelector = appContextSelector == null ? def : new DelegatingContextSelector(appContextSelector, def); SSAContextInterpreter contextInterpreter = makeDefaultContextInterpreters(appContextInterpreter, options, cha); setContextInterpreter(contextInterpreter); ZeroXInstanceKeys zik = makeInstanceKeys(cha, options, contextInterpreter); setInstanceKeys(new JavaScopeMappingInstanceKeys(this, zik)); ContextSelector CCS = makeContainerContextSelector(cha, zik); DelegatingContextSelector DCS = new DelegatingContextSelector(CCS, contextSelector); setContextSelector(DCS); } protected ZeroXInstanceKeys makeInstanceKeys( IClassHierarchy cha, AnalysisOptions options, SSAContextInterpreter contextInterpreter) { ZeroXInstanceKeys zik = new ZeroXInstanceKeys( options, cha, contextInterpreter, ZeroXInstanceKeys.ALLOCATIONS | ZeroXInstanceKeys.SMUSH_PRIMITIVE_HOLDERS | ZeroXInstanceKeys.SMUSH_STRINGS | ZeroXInstanceKeys.SMUSH_MANY | ZeroXInstanceKeys.SMUSH_THROWABLES); return zik; } /** * @return an object which creates contexts for call graph nodes based on the container * disambiguation policy */ protected ContextSelector makeContainerContextSelector( IClassHierarchy cha, ZeroXInstanceKeys keys) { return new ContainerContextSelector(cha, keys); } }
3,307
37.917647
98
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ipa/callgraph/AstJavaZeroXCFABuilder.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ipa.callgraph; import com.ibm.wala.ipa.callgraph.AnalysisOptions; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.ContextSelector; import com.ibm.wala.ipa.callgraph.IAnalysisCacheView; import com.ibm.wala.ipa.callgraph.impl.DefaultContextSelector; import com.ibm.wala.ipa.callgraph.impl.DelegatingContextSelector; import com.ibm.wala.ipa.callgraph.propagation.SSAContextInterpreter; import com.ibm.wala.ipa.callgraph.propagation.cfa.ZeroXInstanceKeys; import com.ibm.wala.ipa.cha.IClassHierarchy; /** 0-1-CFA Call graph builder, optimized to not disambiguate instances of "uninteresting" types. */ public class AstJavaZeroXCFABuilder extends AstJavaCFABuilder { public AstJavaZeroXCFABuilder( IClassHierarchy cha, AnalysisOptions options, IAnalysisCacheView cache, ContextSelector appContextSelector, SSAContextInterpreter appContextInterpreter, int instancePolicy) { super(cha, options, cache); SSAContextInterpreter contextInterpreter = makeDefaultContextInterpreters(appContextInterpreter, options, cha); setContextInterpreter(contextInterpreter); ContextSelector def = new DefaultContextSelector(options, cha); ContextSelector contextSelector = appContextSelector == null ? def : new DelegatingContextSelector(appContextSelector, def); setContextSelector(contextSelector); setInstanceKeys( new JavaScopeMappingInstanceKeys( this, new ZeroXInstanceKeys(options, cha, contextInterpreter, instancePolicy))); } /** * @param options options that govern call graph construction * @param cha governing class hierarchy * @param cl classloader that can find DOMO resources * @param scope representation of the analysis scope * @param xmlFiles set of Strings that are names of XML files holding bypass logic specifications. * @return a 0-1-Opt-CFA Call Graph Builder. */ public static AstJavaCFABuilder make( AnalysisOptions options, IAnalysisCacheView cache, IClassHierarchy cha, ClassLoader cl, AnalysisScope scope, String[] xmlFiles, byte instancePolicy) { com.ibm.wala.ipa.callgraph.impl.Util.addDefaultSelectors(options, cha); for (String xmlFile : xmlFiles) { com.ibm.wala.ipa.callgraph.impl.Util.addBypassLogic(options, cl, xmlFile, cha); } return new AstJavaZeroXCFABuilder(cha, options, cache, null, null, instancePolicy); } }
2,876
37.36
100
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ipa/callgraph/JavaScopeMappingInstanceKeys.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ipa.callgraph; import com.ibm.wala.cast.ipa.callgraph.ScopeMappingInstanceKeys; import com.ibm.wala.cast.ir.translator.AstTranslator; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl.JavaClass; import com.ibm.wala.cast.loader.AstMethod; import com.ibm.wala.cast.loader.AstMethod.LexicalParent; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.InstanceKeyFactory; import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Pair; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Set; public class JavaScopeMappingInstanceKeys extends ScopeMappingInstanceKeys { public JavaScopeMappingInstanceKeys( PropagationCallGraphBuilder builder, InstanceKeyFactory basic) { super(builder, basic); } protected LexicalParent[] getParents(InstanceKey base) { IClass cls = base.getConcreteType(); if (isPossiblyLexicalClass(cls)) { Set<LexicalParent> result = HashSetFactory.make(); for (IMethod m : cls.getAllMethods()) { if ((m instanceof AstMethod) && !m.isStatic()) { AstMethod M = (AstMethod) m; LexicalParent[] parents = M.getParents(); result.addAll(Arrays.asList(parents)); } } if (!result.isEmpty()) { if (AstTranslator.DEBUG_LEXICAL) System.err.println((base + " has parents: " + result)); return result.toArray(new LexicalParent[0]); } } if (AstTranslator.DEBUG_LEXICAL) System.err.println((base + " has no parents")); return new LexicalParent[0]; } protected boolean isPossiblyLexicalClass(IClass cls) { return cls instanceof JavaClass; } @Override protected boolean needsScopeMappingKey(InstanceKey base) { boolean result = getParents(base).length > 0; if (AstTranslator.DEBUG_LEXICAL) System.err.println(("does " + base + " need scope mapping? " + result)); return result; } @Override protected Collection<CGNode> getConstructorCallers( ScopeMappingInstanceKey smik, Pair<String, String> name) { // for Java, the creator node is exactly what we want return Collections.singleton(smik.getCreator()); } }
2,847
33.313253
96
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ipa/callgraph/JavaSourceAnalysisScope.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Sep 27, 2005 */ package com.ibm.wala.cast.java.ipa.callgraph; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.SourceDirectoryTreeModule; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.types.ClassLoaderReference; import java.util.Collection; import java.util.Collections; public class JavaSourceAnalysisScope extends AnalysisScope { public static final ClassLoaderReference SOURCE = new ClassLoaderReference( Atom.findOrCreateAsciiAtom("Source"), Atom.findOrCreateAsciiAtom("Java"), ClassLoaderReference.Application); public JavaSourceAnalysisScope() { this(Collections.singleton(Language.JAVA)); } protected void initCoreForJavaSource() { initCoreForJava(); loadersByName.put(SOURCE.getName(), SOURCE); setLoaderImpl(SOURCE, "com.ibm.wala.cast.java.translator.polyglot.PolyglotSourceLoaderImpl"); } protected JavaSourceAnalysisScope(Collection<? extends Language> languages) { super(languages); initCoreForJavaSource(); initSynthetic(SOURCE); } public ClassLoaderReference getSourceLoader() { return SOURCE; } @Override public void addToScope(ClassLoaderReference loader, Module m) { if (m instanceof SourceDirectoryTreeModule && loader.equals(ClassLoaderReference.Application)) { super.addToScope(SOURCE, m); } else { super.addToScope(loader, m); } } }
1,904
29.238095
100
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ipa/modref/AstJavaModRef.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ipa.modref; import com.ibm.wala.cast.ipa.callgraph.AstHeapModel; import com.ibm.wala.cast.ipa.modref.AstModRef; import com.ibm.wala.cast.java.ssa.AstJavaInstructionVisitor; import com.ibm.wala.cast.java.ssa.AstJavaInvokeInstruction; import com.ibm.wala.cast.java.ssa.EnclosingObjectReference; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.PointerKey; import com.ibm.wala.ipa.modref.ExtendedHeapModel; import java.util.Collection; public class AstJavaModRef<T extends InstanceKey> extends AstModRef<T> { protected static class AstJavaRefVisitor<T extends InstanceKey> extends AstRefVisitor<T> implements AstJavaInstructionVisitor { protected AstJavaRefVisitor( CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h) { super(n, result, pa, (AstHeapModel) h); } @Override public void visitJavaInvoke(AstJavaInvokeInstruction instruction) {} @Override public void visitEnclosingObjectReference(EnclosingObjectReference inst) {} } @Override protected RefVisitor<T, ? extends ExtendedHeapModel> makeRefVisitor( CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h) { return new AstJavaRefVisitor<>(n, result, pa, h); } protected static class AstJavaModVisitor<T extends InstanceKey> extends AstModVisitor<T> implements AstJavaInstructionVisitor { protected AstJavaModVisitor( CGNode n, Collection<PointerKey> result, ExtendedHeapModel h, PointerAnalysis<T> pa) { super(n, result, (AstHeapModel) h, pa); } @Override public void visitJavaInvoke(AstJavaInvokeInstruction instruction) {} @Override public void visitEnclosingObjectReference(EnclosingObjectReference inst) {} } @Override protected ModVisitor<T, ? extends ExtendedHeapModel> makeModVisitor( CGNode n, Collection<PointerKey> result, PointerAnalysis<T> pa, ExtendedHeapModel h, boolean ignoreAllocHeapDefs) { return new AstJavaModVisitor<>(n, result, h, pa); } }
2,603
34.671233
94
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ipa/slicer/AstJavaSlicer.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ipa.slicer; import com.ibm.wala.cast.ir.ssa.AstAssertInstruction; import com.ibm.wala.cast.java.ipa.modref.AstJavaModRef; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.impl.PartialCallGraph; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.slicer.NormalStatement; import com.ibm.wala.ipa.slicer.SDG; import com.ibm.wala.ipa.slicer.Slicer; import com.ibm.wala.ipa.slicer.Statement; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAArrayLoadInstruction; import com.ibm.wala.ssa.SSAArrayStoreInstruction; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAMonitorInstruction; import com.ibm.wala.ssa.SSAPutInstruction; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.graph.traverse.DFS; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.function.Predicate; public class AstJavaSlicer { /* * Use the passed-in SDG */ public static Collection<Statement> computeBackwardSlice(SDG<?> sdg, Collection<Statement> ss) throws IllegalArgumentException, CancelException { return computeSlice(sdg, ss, true); } /** @param ss a collection of statements of interest */ public static Collection<Statement> computeSlice( SDG<?> sdg, Collection<Statement> ss, boolean backward) throws CancelException { return new Slicer().slice(sdg, ss, backward); } public static Set<Statement> gatherStatements( CallGraph CG, Collection<CGNode> partialRoots, Predicate<SSAInstruction> filter) { Set<Statement> result = new HashSet<>(); for (CGNode n : DFS.getReachableNodes(CG, partialRoots)) { IR nir = n.getIR(); if (nir != null) { SSAInstruction insts[] = nir.getInstructions(); for (int i = 0; i < insts.length; i++) { if (filter.test(insts[i])) { result.add(new NormalStatement(n, i)); } } } } return result; } public static Set<Statement> gatherAssertions(CallGraph CG, Collection<CGNode> partialRoots) { return gatherStatements(CG, partialRoots, AstAssertInstruction.class::isInstance); } public static Set<Statement> gatherMonitors(CallGraph CG, Collection<CGNode> partialRoots) { return gatherStatements(CG, partialRoots, SSAMonitorInstruction.class::isInstance); } public static Set<Statement> gatherWrites(CallGraph CG, Collection<CGNode> partialRoots) { return gatherStatements( CG, partialRoots, o -> (o instanceof SSAPutInstruction) || (o instanceof SSAArrayStoreInstruction)); } public static Set<Statement> gatherReads(CallGraph CG, Collection<CGNode> partialRoots) { return gatherStatements( CG, partialRoots, o -> (o instanceof SSAGetInstruction) || (o instanceof SSAArrayLoadInstruction)); } public static Pair<Collection<Statement>, SDG<? extends InstanceKey>> computeAssertionSlice( CallGraph CG, PointerAnalysis<? extends InstanceKey> pa, Collection<CGNode> partialRoots, boolean multiThreadedCode) throws IllegalArgumentException, CancelException { CallGraph pcg = PartialCallGraph.make(CG, new LinkedHashSet<>(partialRoots)); SDG<? extends InstanceKey> sdg = new SDG<>( pcg, pa, new AstJavaModRef<>(), Slicer.DataDependenceOptions.FULL, Slicer.ControlDependenceOptions.FULL); // System.err.println(("SDG:\n" + sdg)); Set<Statement> stmts = gatherAssertions(CG, partialRoots); if (multiThreadedCode) { // Grab anything that has "side effects" under JMM stmts.addAll(gatherReads(CG, partialRoots)); stmts.addAll(gatherWrites(CG, partialRoots)); stmts.addAll(gatherMonitors(CG, partialRoots)); } return Pair.make(AstJavaSlicer.computeBackwardSlice(sdg, stmts), sdg); } }
4,516
36.330579
96
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/loader/JavaSourceLoaderImpl.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Aug 22, 2005 */ package com.ibm.wala.cast.java.loader; import com.ibm.wala.cast.ir.ssa.AssignInstruction; import com.ibm.wala.cast.ir.ssa.AstAssertInstruction; import com.ibm.wala.cast.ir.ssa.AstEchoInstruction; import com.ibm.wala.cast.ir.ssa.AstGlobalRead; import com.ibm.wala.cast.ir.ssa.AstGlobalWrite; import com.ibm.wala.cast.ir.ssa.AstIsDefinedInstruction; import com.ibm.wala.cast.ir.ssa.AstLexicalAccess.Access; import com.ibm.wala.cast.ir.ssa.AstLexicalRead; import com.ibm.wala.cast.ir.ssa.AstLexicalWrite; import com.ibm.wala.cast.ir.ssa.AstPropertyRead; import com.ibm.wala.cast.ir.ssa.AstPropertyWrite; import com.ibm.wala.cast.ir.ssa.AstYieldInstruction; import com.ibm.wala.cast.ir.translator.AstTranslator; import com.ibm.wala.cast.ir.translator.AstTranslator.AstLexicalInformation; import com.ibm.wala.cast.java.ssa.AstJavaInstructionFactory; import com.ibm.wala.cast.java.ssa.AstJavaInvokeInstruction; import com.ibm.wala.cast.java.ssa.AstJavaNewEnclosingInstruction; import com.ibm.wala.cast.java.ssa.EnclosingObjectReference; import com.ibm.wala.cast.java.translator.SourceModuleTranslator; import com.ibm.wala.cast.loader.AstClass; import com.ibm.wala.cast.loader.AstField; import com.ibm.wala.cast.loader.AstMethod; import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation; import com.ibm.wala.cast.tree.CAstAnnotation; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstSourcePositionMap; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.cast.tree.CAstType.Function; import com.ibm.wala.cfg.AbstractCFG; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.ClassLoaderImpl; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.JavaLanguage.JavaInstructionFactory; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.Module; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.ConstantElementValue; import com.ibm.wala.shrike.shrikeCT.AnnotationsReader.ElementValue; import com.ibm.wala.shrike.shrikeCT.ClassConstants; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import com.ibm.wala.util.collections.HashMapFactory; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.debug.Assertions; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** A {@link ClassLoaderImpl} that processes source file entities in the compile-time classpath. */ public abstract class JavaSourceLoaderImpl extends ClassLoaderImpl { public Map<CAstEntity, IClass> fTypeMap = HashMapFactory.make(); /* BEGIN Custom change: Common superclass is optional */ private final boolean existsCommonSuperclass; // extension to deal with X10 that has no common superclass /* END Custom change: Common superclass is optional */ /** * WALA representation of a Java class residing in a source file * * @author rfuhrer */ public class JavaClass extends AstClass { protected final IClass enclosingClass; protected final Collection<TypeName> superTypeNames; private final Collection<Annotation> annotations; public JavaClass( String typeName, Collection<TypeName> superTypeNames, CAstSourcePositionMap.Position position, Collection<CAstQualifier> qualifiers, JavaSourceLoaderImpl loader, IClass enclosingClass, Collection<Annotation> annotations) { super( position, TypeName.string2TypeName(typeName), loader, (short) mapToInt(qualifiers), new HashMap<>(), new HashMap<>()); this.superTypeNames = superTypeNames; this.enclosingClass = enclosingClass; this.annotations = annotations; } @Override public Collection<Annotation> getAnnotations() { return annotations; } @Override public IClassHierarchy getClassHierarchy() { return cha; } @Override public IClass getSuperclass() { boolean excludedSupertype = false; for (TypeName name : superTypeNames) { IClass domoType = lookupClass(name); if (domoType != null && !domoType.isInterface()) { return domoType; } if (domoType == null && getClassHierarchy() .getScope() .getExclusions() .contains(name.toString().substring(1))) { excludedSupertype = true; } } // The following test allows the root class to reside in source; without // it, the assertion requires all classes represented by a JavaClass to // have a superclass. /* BEGIN Custom change: Common superclass is optional */ // Is no longer true in new X10 - no common object super class if (existsCommonSuperclass && !getName().equals(JavaSourceLoaderImpl.this.getLanguage().getRootType().getName()) && !excludedSupertype) { /* END Custom change: Common superclass is optional */ Assertions.UNREACHABLE("Cannot find super class for " + this + " in " + superTypeNames); } if (excludedSupertype) { System.err.println( "Not tracking calls through excluded superclass of " + getName() + " extends " + superTypeNames); } return null; } @Override public Collection<IClass> getDirectInterfaces() { List<IClass> result = new ArrayList<>(); for (TypeName name : superTypeNames) { IClass domoType = lookupClass(name); if (domoType != null && domoType.isInterface()) { result.add(domoType); } if (domoType == null && !getClassHierarchy() .getScope() .getExclusions() .contains(name.toString().substring(1))) { assert false : "Failed to find non-excluded interface: " + name; } } return result; } protected void addMethod( CAstEntity methodEntity, IClass owner, AbstractCFG<?, ?> cfg, SymbolTable symtab, boolean hasCatchBlock, Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo) { declaredMethods.put( Util.methodEntityToSelector(methodEntity), new ConcreteJavaMethod( methodEntity, owner, cfg, symtab, hasCatchBlock, caughtTypes, hasMonitorOp, lexicalInfo, debugInfo)); } protected void addMethod(CAstEntity methodEntity, IClass owner) { declaredMethods.put( Util.methodEntityToSelector(methodEntity), new AbstractJavaMethod(methodEntity, owner)); } protected void addField(CAstEntity fieldEntity) { declaredFields.put( Util.fieldEntityToAtom(fieldEntity), new JavaField( fieldEntity, JavaSourceLoaderImpl.this, this, JavaSourceLoaderImpl.this.getAnnotations(fieldEntity))); } public IClass getEnclosingClass() { return enclosingClass; } @Override public String toString() { StringBuilder sb = new StringBuilder("<src-class: "); sb.append(getName().toString()); if (enclosingClass != null) { sb.append(" (within ").append(enclosingClass.getName()).append(')'); } if (annotations != null && !annotations.isEmpty()) { for (Annotation a : annotations) { sb.append('[').append(a.getType().getName().getClassName()).append(']'); } } return sb.toString(); } } protected Collection<Annotation> getAnnotations(CAstEntity e) { Collection<CAstAnnotation> annotations = e.getAnnotations(); if (annotations == null || annotations.isEmpty()) { return null; } else { Collection<Annotation> result = HashSetFactory.make(); for (CAstAnnotation ca : annotations) { TypeName walaTypeName = toWALATypeName(ca.getType()); TypeReference ref = TypeReference.findOrCreate(getReference(), walaTypeName); if (ca.getArguments() == null || ca.getArguments().isEmpty()) { result.add(Annotation.make(ref)); } else { Map<String, ElementValue> args = HashMapFactory.make(); for (Map.Entry<String, Object> a : ca.getArguments().entrySet()) { args.put(a.getKey(), new ConstantElementValue(a.getValue())); } result.add(Annotation.makeWithNamed(ref, args)); } } return result; } } /** * WALA representation of a field on a Java type that resides in a source file * * @author rfuhrer */ protected static class JavaField extends AstField { protected JavaField( CAstEntity fieldEntity, IClassLoader loader, IClass declaringClass, Collection<Annotation> annotations) { super( FieldReference.findOrCreate( declaringClass.getReference(), Atom.findOrCreateUnicodeAtom(fieldEntity.getName()), TypeReference.findOrCreate( loader.getReference(), TypeName.string2TypeName(fieldEntity.getType().getName()))), fieldEntity.getQualifiers(), declaringClass, declaringClass.getClassHierarchy(), annotations); } } /** * Generic DOMO representation of a method on a Java type that resides in a source file * * @author rfuhrer */ protected abstract class JavaEntityMethod extends AstMethod { private final TypeReference[] parameterTypes; private final TypeReference[] exceptionTypes; public JavaEntityMethod( CAstEntity methodEntity, IClass owner, AbstractCFG<?, ?> cfg, SymbolTable symtab, boolean hasCatchBlock, Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo) { super( owner, methodEntity.getQualifiers(), cfg, symtab, MethodReference.findOrCreate( owner.getReference(), Util.methodEntityToSelector(methodEntity)), hasCatchBlock, caughtTypes, hasMonitorOp, lexicalInfo, debugInfo, JavaSourceLoaderImpl.this.getAnnotations(methodEntity)); this.parameterTypes = computeParameterTypes(methodEntity); this.exceptionTypes = computeExceptionTypes(methodEntity); } public JavaEntityMethod(CAstEntity methodEntity, IClass owner) { super( owner, methodEntity.getQualifiers(), MethodReference.findOrCreate( owner.getReference(), Util.methodEntityToSelector(methodEntity)), JavaSourceLoaderImpl.this.getAnnotations(methodEntity)); this.parameterTypes = computeParameterTypes(methodEntity); this.exceptionTypes = computeExceptionTypes(methodEntity); } public int getMaxLocals() { Assertions.UNREACHABLE("AbstractJavaMethod.getMaxLocals() called"); return 0; } public int getMaxStackHeight() { Assertions.UNREACHABLE("AbstractJavaMethod.getMaxStackHeight() called"); return 0; } @Override public TypeReference getParameterType(int i) { return parameterTypes[i]; } protected TypeReference[] computeParameterTypes(CAstEntity methodEntity) { TypeReference[] types; CAstType.Function type = (Function) methodEntity.getType(); int argCount = type.getArgumentTypes().size(); if (isStatic()) { types = new TypeReference[argCount]; for (int i = 0; i < argCount; i++) { types[i] = TypeReference.findOrCreate( JavaSourceLoaderImpl.this.getReference(), type.getArgumentTypes().get(i).getName()); } } else { types = new TypeReference[argCount + 1]; types[0] = cls.getReference(); for (int i = 0; i < argCount; i++) { types[i + 1] = TypeReference.findOrCreate( JavaSourceLoaderImpl.this.getReference(), type.getArgumentTypes().get(i).getName()); } } return types; } @Override public TypeReference[] getDeclaredExceptions() { return exceptionTypes; } protected TypeReference[] computeExceptionTypes(CAstEntity methodEntity) { CAstType.Function fType = (Function) methodEntity.getType(); Collection<CAstType> exceptionTypes = fType.getExceptionTypes(); TypeReference[] result = new TypeReference[exceptionTypes.size()]; int i = 0; for (CAstType type : exceptionTypes) { result[i] = TypeReference.findOrCreate(JavaSourceLoaderImpl.this.getReference(), type.getName()); ++i; } return result; } @Override public String toString() { return "<src-method: " + this.getReference() + '>'; } } /** * DOMO representation of an abstract (body-less) method on a Java type that resides in a source * file * * @author rfuhrer */ protected class AbstractJavaMethod extends JavaEntityMethod { public AbstractJavaMethod(CAstEntity methodEntity, IClass owner) { super(methodEntity, owner); } @Override public String getLocalVariableName(int bcIndex, int localNumber) { Assertions.UNREACHABLE("AbstractJavaMethod.getLocalVariableName() called"); return null; } @Override public boolean hasLocalVariableTable() { Assertions.UNREACHABLE("AbstractJavaMethod.hasLocalVariableTable() called"); return false; } @Override public LexicalParent[] getParents() { return new LexicalParent[0]; } @Override public IClassHierarchy getClassHierarchy() { return cha; } } /** * DOMO representation of a concrete method (which has a body) on a Java type that resides in a * source file * * @author rfuhrer */ public class ConcreteJavaMethod extends JavaEntityMethod { public ConcreteJavaMethod( CAstEntity methodEntity, IClass owner, AbstractCFG<?, ?> cfg, SymbolTable symtab, boolean hasCatchBlock, Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo) { super( methodEntity, owner, cfg, symtab, hasCatchBlock, caughtTypes, hasMonitorOp, lexicalInfo, debugInfo); } @Override public IClassHierarchy getClassHierarchy() { return cha; } @Override public String getLocalVariableName(int bcIndex, int localNumber) { return null; } @Override public boolean hasLocalVariableTable() { return false; } @Override public LexicalParent[] getParents() { if (AstTranslator.DEBUG_LEXICAL) { System.err.println(("resolving parents of " + this)); } if (lexicalInfo() == null) { if (AstTranslator.DEBUG_LEXICAL) System.err.println("no info"); return new LexicalParent[0]; } final String[] parents = lexicalInfo().getScopingParents(); if (parents == null) { if (AstTranslator.DEBUG_LEXICAL) System.err.println("no parents"); return new LexicalParent[0]; } LexicalParent result[] = new LexicalParent[parents.length]; for (int i = 0; i < parents.length; i++) { int lastLeftParen = parents[i].lastIndexOf('('); int lastQ = parents[i].lastIndexOf('/', lastLeftParen); String typeName = parents[i].substring(0, lastQ); final IClass cls = lookupClass(TypeName.string2TypeName(typeName)); String sig = parents[i].substring(lastQ); int nameEnd = sig.indexOf('('); String nameStr = sig.substring(1, nameEnd); Atom name = Atom.findOrCreateUnicodeAtom(nameStr); String descStr = sig.substring(nameEnd); Descriptor desc = Descriptor.findOrCreateUTF8(Language.JAVA, descStr); final Selector sel = new Selector(name, desc); if (AstTranslator.DEBUG_LEXICAL) System.err.println(("get " + typeName + ", " + nameStr + ", " + descStr)); final int hack = i; result[i] = new LexicalParent() { @Override public String getName() { return parents[hack]; } @Override public AstMethod getMethod() { return (AstMethod) cls.getMethod(sel); } }; if (AstTranslator.DEBUG_LEXICAL) System.err.println(("parent " + result[i].getName() + " is " + result[i].getMethod())); } return result; } } public static int mapToInt(Collection<CAstQualifier> qualifiers) { int result = 0; for (CAstQualifier q : qualifiers) { if (q == CAstQualifier.PUBLIC) result |= ClassConstants.ACC_PUBLIC; if (q == CAstQualifier.PROTECTED) result |= ClassConstants.ACC_PROTECTED; if (q == CAstQualifier.PRIVATE) result |= ClassConstants.ACC_PRIVATE; if (q == CAstQualifier.STATIC) result |= ClassConstants.ACC_STATIC; if (q == CAstQualifier.FINAL) result |= ClassConstants.ACC_FINAL; if (q == CAstQualifier.SYNCHRONIZED) result |= ClassConstants.ACC_SYNCHRONIZED; if (q == CAstQualifier.TRANSIENT) result |= ClassConstants.ACC_TRANSIENT; if (q == CAstQualifier.NATIVE) result |= ClassConstants.ACC_NATIVE; if (q == CAstQualifier.INTERFACE) result |= ClassConstants.ACC_INTERFACE; if (q == CAstQualifier.ABSTRACT) result |= ClassConstants.ACC_ABSTRACT; if (q == CAstQualifier.VOLATILE) result |= ClassConstants.ACC_VOLATILE; if (q == CAstQualifier.STRICTFP) result |= ClassConstants.ACC_STRICT; } return result; } /* BEGIN Custom change: Common superclass is optional */ public JavaSourceLoaderImpl( boolean existsCommonSuperClass, ClassLoaderReference loaderRef, IClassLoader parent, IClassHierarchy cha) { super( loaderRef, cha.getScope().getArrayClassLoader(), parent, cha.getScope().getExclusions(), cha); this.existsCommonSuperclass = existsCommonSuperClass; } public JavaSourceLoaderImpl( ClassLoaderReference loaderRef, IClassLoader parent, IClassHierarchy cha) { // standard case: we have a common super class this(true, loaderRef, parent, cha); } /* END Custom change: Common superclass is optional */ public IClassHierarchy getClassHierarchy() { return cha; } @Override protected void loadAllSources(Set<ModuleEntry> modules) { getTranslator().loadAllSources(modules); } protected abstract SourceModuleTranslator getTranslator(); /* BEGIN Custom change: Optional deletion of fTypeMap */ public static volatile boolean deleteTypeMapAfterInit = true; /* END Custom change: Optional deletion of fTypeMap */ @Override public void init(List<Module> modules) throws IOException { super.init(modules); /* BEGIN Custom change: Optional deletion of fTypeMap */ if (deleteTypeMapAfterInit) { fTypeMap = null; } /* END Custom change: Optional deletion of fTypeMap */ } public void defineFunction( CAstEntity n, IClass owner, AbstractCFG<?, ?> cfg, SymbolTable symtab, boolean hasCatchBlock, Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo) { ((JavaClass) owner) .addMethod( n, owner, cfg, symtab, hasCatchBlock, caughtTypes, hasMonitorOp, lexicalInfo, debugInfo); } public void defineAbstractFunction(CAstEntity n, IClass owner) { ((JavaClass) owner).addMethod(n, owner); } public void defineField(CAstEntity n, IClass owner) { ((JavaClass) owner).addField(n); } protected static TypeName toWALATypeName(CAstType type) { return TypeName.string2TypeName(type.getName()); } public IClass defineType(CAstEntity type, String typeName, CAstEntity owner) { Collection<TypeName> superTypeNames = new ArrayList<>(); for (CAstType superType : type.getType().getSupertypes()) { superTypeNames.add(toWALATypeName(superType)); } JavaClass javaClass = new JavaClass( typeName, superTypeNames, type.getPosition(), type.getQualifiers(), this, (owner != null) ? (JavaClass) fTypeMap.get(owner) : (JavaClass) null, getAnnotations(type)); if (getParent().lookupClass(javaClass.getName()) != null) { return null; } fTypeMap.put(type, javaClass); loadedClasses.put(javaClass.getName(), javaClass); return javaClass; } @Override public String toString() { return "Java Source Loader (classes " + loadedClasses.values() + ')'; } public static class InstructionFactory extends JavaInstructionFactory implements AstJavaInstructionFactory { @Override public com.ibm.wala.cast.java.ssa.EnclosingObjectReference EnclosingObjectReference( int iindex, int lval, TypeReference type) { return new EnclosingObjectReference(iindex, lval, type); } @Override public AstJavaNewEnclosingInstruction JavaNewEnclosingInstruction( int iindex, int result, NewSiteReference site, int enclosing) { return new AstJavaNewEnclosingInstruction(iindex, result, site, enclosing); } @Override public AstJavaInvokeInstruction JavaInvokeInstruction( int iindex, int result[], int[] params, int exception, CallSiteReference site) { return result == null ? new AstJavaInvokeInstruction(iindex, params, exception, site) : new AstJavaInvokeInstruction(iindex, result[0], params, exception, site); } @Override public AstAssertInstruction AssertInstruction( int iindex, int value, boolean fromSpecification) { return new AstAssertInstruction(iindex, value, fromSpecification); } @Override public com.ibm.wala.cast.ir.ssa.AssignInstruction AssignInstruction( int iindex, int result, int val) { return new AssignInstruction(iindex, result, val); } @Override public com.ibm.wala.cast.ir.ssa.EachElementGetInstruction EachElementGetInstruction( int iindex, int value, int objectRef, int propRef) { throw new UnsupportedOperationException(); } @Override public com.ibm.wala.cast.ir.ssa.EachElementHasNextInstruction EachElementHasNextInstruction( int iindex, int value, int objectRef, int propRef) { throw new UnsupportedOperationException(); } @Override public AstEchoInstruction EchoInstruction(int iindex, int[] rvals) { throw new UnsupportedOperationException(); } @Override public AstGlobalRead GlobalRead(int iindex, int lhs, FieldReference global) { throw new UnsupportedOperationException(); } @Override public AstGlobalWrite GlobalWrite(int iindex, FieldReference global, int rhs) { throw new UnsupportedOperationException(); } @Override public AstIsDefinedInstruction IsDefinedInstruction( int iindex, int lval, int rval, int fieldVal, FieldReference fieldRef) { throw new UnsupportedOperationException(); } @Override public AstIsDefinedInstruction IsDefinedInstruction( int iindex, int lval, int rval, FieldReference fieldRef) { throw new UnsupportedOperationException(); } @Override public AstIsDefinedInstruction IsDefinedInstruction( int iindex, int lval, int rval, int fieldVal) { return new AstIsDefinedInstruction(iindex, lval, rval, fieldVal); } @Override public AstIsDefinedInstruction IsDefinedInstruction(int iindex, int lval, int rval) { throw new UnsupportedOperationException(); } @Override public AstLexicalRead LexicalRead(int iindex, Access[] accesses) { return new AstLexicalRead(iindex, accesses); } @Override public AstLexicalRead LexicalRead(int iindex, Access access) { return new AstLexicalRead(iindex, access); } @Override public AstLexicalRead LexicalRead( int iindex, int lhs, String definer, String globalName, TypeReference type) { return new AstLexicalRead(iindex, lhs, definer, globalName, type); } @Override public AstLexicalWrite LexicalWrite(int iindex, Access[] accesses) { return new AstLexicalWrite(iindex, accesses); } @Override public AstLexicalWrite LexicalWrite(int iindex, Access access) { return new AstLexicalWrite(iindex, access); } @Override public AstLexicalWrite LexicalWrite( int iindex, String definer, String globalName, TypeReference type, int rhs) { return new AstLexicalWrite(iindex, definer, globalName, type, rhs); } @Override public AstYieldInstruction YieldInstruction(int iindex, int[] rvals) { return new AstYieldInstruction(iindex, rvals); } @Override public AstPropertyRead PropertyRead(int iindex, int result, int objectRef, int memberRef) { assert false; return null; } @Override public AstPropertyWrite PropertyWrite(int iindex, int objectRef, int memberRef, int value) { assert false; return null; } } protected static final InstructionFactory insts = new InstructionFactory(); @Override public InstructionFactory getInstructionFactory() { return insts; } }
27,241
32.100851
99
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/loader/Util.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.loader; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.Selector; import com.ibm.wala.types.TypeName; public class Util { public static Selector methodEntityToSelector(CAstEntity methodEntity) { Atom name = Atom.findOrCreateUnicodeAtom(methodEntity.getName()); CAstType.Function signature = (CAstType.Function) methodEntity.getType(); // Use signature to determine # of args; (entity's args includes 'this') TypeName retTypeName = TypeName.string2TypeName(signature.getReturnType().getName()); TypeName[] argTypeNames = (signature.getArgumentCount() == 0) ? null : new TypeName[signature.getArgumentCount()]; int i = 0; for (CAstType argType : signature.getArgumentTypes()) { argTypeNames[i] = TypeName.string2TypeName(argType.getName()); ++i; } Descriptor desc = Descriptor.findOrCreate(argTypeNames, retTypeName); return new Selector(name, desc); } public static Atom fieldEntityToAtom(CAstEntity fieldEntity) { return Atom.findOrCreateUnicodeAtom(fieldEntity.getName()); } }
1,605
34.688889
96
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ssa/AstJavaAbstractInstructionVisitor.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ssa; import com.ibm.wala.cast.ir.ssa.AstAbstractInstructionVisitor; public class AstJavaAbstractInstructionVisitor extends AstAbstractInstructionVisitor implements AstJavaInstructionVisitor { @Override public void visitJavaInvoke(AstJavaInvokeInstruction instruction) {} @Override public void visitEnclosingObjectReference(EnclosingObjectReference inst) {} }
781
31.583333
84
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ssa/AstJavaInstructionFactory.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ssa; import com.ibm.wala.cast.ir.ssa.AstInstructionFactory; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.types.TypeReference; public interface AstJavaInstructionFactory extends AstInstructionFactory { AstJavaInvokeInstruction JavaInvokeInstruction( int iindex, int result[], int[] params, int exception, CallSiteReference site); EnclosingObjectReference EnclosingObjectReference(int iindex, int lval, TypeReference type); AstJavaNewEnclosingInstruction JavaNewEnclosingInstruction( int iindex, int result, NewSiteReference site, int enclosing); }
1,045
36.357143
94
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ssa/AstJavaInstructionVisitor.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ssa; import com.ibm.wala.cast.ir.ssa.AstInstructionVisitor; public interface AstJavaInstructionVisitor extends AstInstructionVisitor { void visitJavaInvoke(AstJavaInvokeInstruction instruction); void visitEnclosingObjectReference(EnclosingObjectReference inst); }
678
31.333333
74
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ssa/AstJavaInvokeInstruction.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ssa; import com.ibm.wala.cast.ir.ssa.FixedParametersInvokeInstruction; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.JavaLanguage; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SSAInvokeInstruction; import com.ibm.wala.types.TypeReference; import java.util.Collection; public class AstJavaInvokeInstruction extends FixedParametersInvokeInstruction { protected AstJavaInvokeInstruction( int iindex, int results[], int[] params, int exception, CallSiteReference site) { super(iindex, results, params, exception, site); } public AstJavaInvokeInstruction( int iindex, int result, int[] params, int exception, CallSiteReference site) { this(iindex, new int[] {result}, params, exception, site); SSAInvokeInstruction.assertParamsKosher(result, params, site); } /** Constructor InvokeInstruction. This case for void return values */ public AstJavaInvokeInstruction(int iindex, int[] params, int exception, CallSiteReference site) { this(iindex, null, params, exception, site); } @Override protected SSAInstruction copyInstruction( SSAInstructionFactory insts, int results[], int[] params, int exception) { return ((AstJavaInstructionFactory) insts) .JavaInvokeInstruction(iIndex(), results, params, exception, getCallSite()); } @Override public void visit(IVisitor v) { ((AstJavaInstructionVisitor) v).visitJavaInvoke(this); } @Override public Collection<TypeReference> getExceptionTypes() { return JavaLanguage.getNullPointerException(); } @Override public int hashCode() { return (site.hashCode() * 7529) + (exception * 9823); } }
2,139
33.516129
100
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ssa/AstJavaNewEnclosingInstruction.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ssa; import com.ibm.wala.classLoader.JavaLanguage; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.types.TypeReference; import java.util.Collection; // A new instruction with an explicit outer class, i.e. "Inner inner = outer.new Inner();" public class AstJavaNewEnclosingInstruction extends SSANewInstruction { int enclosing; @Override public int getNumberOfUses() { return 1; } @Override public int getUse(int i) { assert i == 0; return enclosing; } public AstJavaNewEnclosingInstruction( int iindex, int result, NewSiteReference site, int enclosing) throws IllegalArgumentException { super(iindex, result, site); this.enclosing = enclosing; } public int getEnclosing() { return this.enclosing; } @Override public String toString() { return super.toString() + " ENCLOSING v" + enclosing; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstJavaInstructionFactory) insts) .JavaNewEnclosingInstruction( iIndex(), defs == null ? getDef(0) : defs[0], getNewSite(), uses == null ? enclosing : uses[0]); } @Override public Collection<TypeReference> getExceptionTypes() { return JavaLanguage.getNewScalarExceptions(); } }
1,882
26.691176
90
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/ssa/EnclosingObjectReference.java
/* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.ssa; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSAInstructionFactory; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.TypeReference; import java.util.Collection; import java.util.Collections; /** * The CAst source language front end for Java has explicit support for lexically-enclosing objects, * rather than compiling them away into extra fields and access-control thwarting accessor methods * as is done in bytecode. This instruction represents a read of the object of the given type that * lexically encloses its use value. * * @author Julian Dolby ([email protected]) */ public class EnclosingObjectReference extends SSAInstruction { private final TypeReference type; private final int lval; public EnclosingObjectReference(int iindex, int lval, TypeReference type) { super(iindex); this.lval = lval; this.type = type; } @Override public boolean hasDef() { return true; } @Override public int getDef() { return lval; } @Override public int getDef(int i) { assert i == 0; return lval; } @Override public int getNumberOfDefs() { return 1; } public TypeReference getEnclosingType() { return type; } @Override public SSAInstruction copyForSSA(SSAInstructionFactory insts, int[] defs, int[] uses) { return ((AstJavaInstructionFactory) insts) .EnclosingObjectReference(iIndex(), defs == null ? lval : defs[0], type); } @Override public String toString(SymbolTable symbolTable) { return getValueString(symbolTable, lval) + " = enclosing " + type.getName(); } @Override public void visit(IVisitor v) { ((AstJavaInstructionVisitor) v).visitEnclosingObjectReference(this); } @Override public int hashCode() { return lval * type.hashCode(); } @Override public Collection<TypeReference> getExceptionTypes() { return Collections.emptySet(); } @Override public boolean isFallThrough() { return true; } }
2,393
23.9375
100
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/translator/Java2IRTranslator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Aug 22, 2005 */ package com.ibm.wala.cast.java.translator; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl; import com.ibm.wala.cast.tree.CAst; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.impl.CAstImpl; import com.ibm.wala.cast.tree.rewrite.CAstRewriter; import com.ibm.wala.cast.tree.rewrite.CAstRewriterFactory; import com.ibm.wala.cast.util.CAstPrinter; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.util.config.SetOfClasses; import java.io.PrintWriter; public class Java2IRTranslator { private final boolean DEBUG; protected final JavaSourceLoaderImpl fLoader; protected final SetOfClasses exclusions; CAstRewriterFactory<?, ?> castRewriterFactory = null; public Java2IRTranslator(JavaSourceLoaderImpl srcLoader, SetOfClasses exclusions) { this(srcLoader, null, exclusions); } public Java2IRTranslator( JavaSourceLoaderImpl srcLoader, CAstRewriterFactory<?, ?> castRewriterFactory, SetOfClasses exclusions) { this(srcLoader, castRewriterFactory, false, exclusions); } public Java2IRTranslator( JavaSourceLoaderImpl srcLoader, CAstRewriterFactory<?, ?> castRewriterFactory, boolean debug, SetOfClasses exclusions) { DEBUG = debug; fLoader = srcLoader; this.castRewriterFactory = castRewriterFactory; this.exclusions = exclusions; } public void translate(ModuleEntry module, CAstEntity ce) { if (DEBUG) { PrintWriter printWriter = new PrintWriter(System.out); CAstPrinter.printTo(ce, printWriter); printWriter.flush(); } if (castRewriterFactory != null) { CAst cast = new CAstImpl(); CAstRewriter<?, ?> rw = castRewriterFactory.createCAstRewriter(cast); ce = rw.rewrite(ce); if (DEBUG) { PrintWriter printWriter = new PrintWriter(System.out); CAstPrinter.printTo(ce, printWriter); printWriter.flush(); } } new JavaCAst2IRTranslator(module, ce, fLoader, exclusions).translate(); } }
2,427
29.734177
85
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/translator/JavaCAst2IRTranslator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Aug 22, 2005 */ package com.ibm.wala.cast.java.translator; import com.ibm.wala.cast.ir.translator.AstTranslator; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl; import com.ibm.wala.cast.java.ssa.AstJavaInvokeInstruction; import com.ibm.wala.cast.java.ssa.AstJavaNewEnclosingInstruction; import com.ibm.wala.cast.java.ssa.EnclosingObjectReference; import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation; import com.ibm.wala.cast.tree.CAstControlFlowMap; import com.ibm.wala.cast.tree.CAstEntity; import com.ibm.wala.cast.tree.CAstNode; import com.ibm.wala.cast.tree.CAstQualifier; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.cast.tree.CAstType.Method; import com.ibm.wala.cast.tree.visit.CAstVisitor; import com.ibm.wala.cfg.AbstractCFG; import com.ibm.wala.cfg.IBasicBlock; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.ModuleEntry; import com.ibm.wala.classLoader.NewSiteReference; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.config.SetOfClasses; import com.ibm.wala.util.debug.Assertions; import java.util.Collection; import java.util.Collections; import java.util.Map; public class JavaCAst2IRTranslator extends AstTranslator { private final CAstEntity fSourceEntity; private final ModuleEntry module; private final SetOfClasses exclusions; public JavaCAst2IRTranslator( ModuleEntry module, CAstEntity sourceFileEntity, JavaSourceLoaderImpl loader, SetOfClasses exclusions) { super(loader); fSourceEntity = sourceFileEntity; this.module = module; this.exclusions = exclusions; } public void translate() { translate(fSourceEntity, module); } public CAstEntity sourceFileEntity() { return fSourceEntity; } public JavaSourceLoaderImpl loader() { return (JavaSourceLoaderImpl) loader; } @Override protected boolean useDefaultInitValues() { return true; } // Java does not have standalone global variables, and let's not // adopt the nasty JavaScript practice of creating globals without // explicit definitions @Override protected boolean hasImplicitGlobals() { return false; } @Override protected TypeReference defaultCatchType() { return TypeReference.JavaLangThrowable; } @Override protected TypeReference makeType(CAstType type) { return TypeReference.findOrCreate( loader.getReference(), TypeName.string2TypeName(type.getName())); } // Java globals are disguised as fields (statics), so we should never // ask this question when parsing Java code @Override protected boolean treatGlobalsAsLexicallyScoped() { Assertions.UNREACHABLE(); return false; } @Override protected void doThrow(WalkContext context, int exception) { context .cfg() .addInstruction(insts.ThrowInstruction(context.cfg().getCurrentInstruction(), exception)); } @Override public void doArrayRead( WalkContext context, int result, int arrayValue, CAstNode arrayRefNode, int[] dimValues) { TypeReference arrayTypeRef = (TypeReference) arrayRefNode.getChild(1).getValue(); context .cfg() .addInstruction( insts.ArrayLoadInstruction( context.cfg().getCurrentInstruction(), result, arrayValue, dimValues[0], arrayTypeRef)); processExceptions(arrayRefNode, context); } @Override public void doArrayWrite( WalkContext context, int arrayValue, CAstNode arrayRefNode, int[] dimValues, int rval) { TypeReference arrayTypeRef = arrayRefNode.getKind() == CAstNode.ARRAY_LITERAL ? ((TypeReference) arrayRefNode.getChild(0).getChild(0).getValue()) .getArrayElementType() : (TypeReference) arrayRefNode.getChild(1).getValue(); context .cfg() .addInstruction( insts.ArrayStoreInstruction( context.cfg().getCurrentInstruction(), arrayValue, dimValues[0], rval, arrayTypeRef)); processExceptions(arrayRefNode, context); } @Override protected void doFieldRead( WalkContext context, int result, int receiver, CAstNode elt, CAstNode parent) { // elt is a constant CAstNode whose value is a FieldReference. FieldReference fieldRef = (FieldReference) elt.getValue(); if (receiver == -1) { // a static field: AstTranslator.getValue() produces // -1 for null, we hope context .cfg() .addInstruction( insts.GetInstruction(context.cfg().getCurrentInstruction(), result, fieldRef)); } else { context .cfg() .addInstruction( insts.GetInstruction( context.cfg().getCurrentInstruction(), result, receiver, fieldRef)); processExceptions(parent, context); } } @Override protected void doFieldWrite( WalkContext context, int receiver, CAstNode elt, CAstNode parent, int rval) { FieldReference fieldRef = (FieldReference) elt.getValue(); if (receiver == -1) { // a static field: AstTranslator.getValue() produces // -1 for null, we hope context .cfg() .addInstruction( insts.PutInstruction(context.cfg().getCurrentInstruction(), rval, fieldRef)); } else { context .cfg() .addInstruction( insts.PutInstruction( context.cfg().getCurrentInstruction(), receiver, rval, fieldRef)); processExceptions(parent, context); } } @Override protected void doMaterializeFunction( CAstNode n, WalkContext context, int result, int exception, CAstEntity fn) { // Not possible in Java (no free-standing functions) Assertions.UNREACHABLE("Real functions in Java??? I don't think so!"); } @Override protected void doNewObject( WalkContext context, CAstNode newNode, int result, Object type, int[] arguments) { TypeReference typeRef = (TypeReference) type; NewSiteReference site = NewSiteReference.make(context.cfg().getCurrentInstruction(), typeRef); if (newNode.getKind() == CAstNode.NEW_ENCLOSING) { context .cfg() .addInstruction( new AstJavaNewEnclosingInstruction( context.cfg().getCurrentInstruction(), result, site, arguments[0])); } else { context .cfg() .addInstruction( (arguments == null) ? insts.NewInstruction(context.cfg().getCurrentInstruction(), result, site) : insts.NewInstruction( context.cfg().getCurrentInstruction(), result, site, arguments)); } processExceptions(newNode, context); } private static void processExceptions(CAstNode n, WalkContext context) { context.cfg().addPreNode(n, context.getUnwindState()); context.cfg().newBlock(true); Collection<Object> labels = context.getControlFlow().getTargetLabels(n); for (Object label : labels) { CAstNode target = context.getControlFlow().getTarget(n, label); if (target == CAstControlFlowMap.EXCEPTION_TO_EXIT) context.cfg().addPreEdgeToExit(n, true); else context.cfg().addPreEdge(n, target, true); } } @Override protected void doCall( WalkContext context, CAstNode call, int result, int exception, CAstNode name, int receiver, int[] arguments) { assert name.getKind() == CAstNode.CONSTANT; CallSiteReference dummySiteRef = (CallSiteReference) name.getValue(); int instNumber = context.cfg().getCurrentInstruction(); int pc = instNumber; boolean isStatic = (receiver == -1); int[] realArgs = isStatic ? arguments : new int[arguments.length + 1]; Position[] pos; if (isStatic) { pos = new Position[arguments.length]; for (int i = 0; i < arguments.length; i++) { pos[i] = context.getSourceMap().getPosition(call.getChild(i + 2)); } } else { pos = new Position[arguments.length + 1]; pos[0] = context.getSourceMap().getPosition(call.getChild(0)); for (int i = 0; i < arguments.length; i++) { pos[i + 1] = context.getSourceMap().getPosition(call.getChild(i + 2)); } } if (!isStatic) { realArgs[0] = receiver; System.arraycopy(arguments, 0, realArgs, 1, arguments.length); } CallSiteReference realSiteRef = CallSiteReference.make( pc, dummySiteRef.getDeclaredTarget(), dummySiteRef.getInvocationCode()); if (realSiteRef.getDeclaredTarget().getReturnType().equals(TypeReference.Void)) context .cfg() .addInstruction( new AstJavaInvokeInstruction(instNumber, realArgs, exception, realSiteRef)); else context .cfg() .addInstruction( new AstJavaInvokeInstruction(instNumber, result, realArgs, exception, realSiteRef)); context.cfg().noteOperands(instNumber, pos); processExceptions(call, context); } @Override protected void doGlobalWrite(WalkContext context, String name, TypeReference type, int rval) { Assertions.UNREACHABLE("doGlobalWrite() called for Java code???"); } @Override protected void defineField(CAstEntity topEntity, WalkContext definingContext, CAstEntity n) { assert topEntity.getKind() == CAstEntity.TYPE_ENTITY; assert n.getKind() == CAstEntity.FIELD_ENTITY; // N.B.: base class may actually ask to create a synthetic type to wrap // code bodies, so we may see other things than TYPE_ENTITY here. TypeName ownerName = makeType(topEntity.getType()).getName(); IClass owner = loader.lookupClass(ownerName); assert owner != null || exclusions.contains(ownerName.toString()) : ownerName + " not found in " + loader; if (owner != null) { ((JavaSourceLoaderImpl) loader).defineField(n, owner); } } // handles abstract method declarations, which do not get defineFunction // called for them @Override protected void declareFunction(CAstEntity N, WalkContext definingContext) { CAstType.Method methodType = (Method) N.getType(); CAstType owningType = methodType.getDeclaringType(); IClass owner = loader.lookupClass(makeType(owningType).getName()); assert owner != null || exclusions.contains(owningType.getName()) : makeType(owningType).getName().toString() + " not found in " + loader; if (owner != null && N.getQualifiers().contains(CAstQualifier.ABSTRACT)) { ((JavaSourceLoaderImpl) loader).defineAbstractFunction(N, owner); } } @Override protected void defineFunction( CAstEntity N, WalkContext definingContext, AbstractCFG<SSAInstruction, ? extends IBasicBlock<SSAInstruction>> cfg, SymbolTable symtab, boolean hasCatchBlock, Map<IBasicBlock<SSAInstruction>, TypeReference[]> caughtTypes, boolean hasMonitorOp, AstLexicalInformation lexicalInfo, DebuggingInformation debugInfo) { // N.B.: base class may actually ask to create a synthetic type to wrap // code bodies, so we may see other things than TYPE_ENTITY here. CAstType.Method methodType = (Method) N.getType(); CAstType owningType = methodType.getDeclaringType(); TypeName typeName = makeType(owningType).getName(); IClass owner = loader.lookupClass(typeName); assert owner != null || exclusions.contains(owningType.getName()) : typeName.toString() + " not found in " + loader; if (owner != null) { symtab.getConstant(0); symtab.getNullConstant(); ((JavaSourceLoaderImpl) loader) .defineFunction( N, owner, cfg, symtab, hasCatchBlock, caughtTypes, hasMonitorOp, lexicalInfo, debugInfo); } } @Override protected void doPrimitive(int resultVal, WalkContext context, CAstNode primitiveCall) { // For now, no-op (no primitives in normal Java code) Assertions.UNREACHABLE("doPrimitive() called for Java code???"); } @Override protected String composeEntityName(WalkContext parent, CAstEntity f) { switch (f.getKind()) { case CAstEntity.TYPE_ENTITY: { return (parent.getName().length() == 0) ? f.getName() : parent.getName() + '/' + f.getName(); } case CAstEntity.FUNCTION_ENTITY: { // TODO properly handle types with clashing names/signatures within a // given method return parent.getName() + '/' + f.getSignature(); } default: { return parent.getName(); } } } private CAstEntity getEnclosingType(CAstEntity entity) { if (entity.getQualifiers().contains(CAstQualifier.STATIC)) return null; else return getEnclosingTypeInternal(getParent(entity)); } private CAstEntity getEnclosingTypeInternal(CAstEntity entity) { switch (entity.getKind()) { case CAstEntity.TYPE_ENTITY: { return entity; } case CAstEntity.FUNCTION_ENTITY: { if (entity.getQualifiers().contains(CAstQualifier.STATIC)) return null; else return getEnclosingTypeInternal(getParent(entity)); } case CAstEntity.FILE_ENTITY: { return null; } default: { return getEnclosingTypeInternal(getParent(entity)); } } } @Override protected boolean defineType(CAstEntity type, WalkContext wc) { CAstEntity parentType = getEnclosingType(type); // ((JavaSourceLoaderImpl)loader).defineType(type, // composeEntityName(wc,type), parentType); if (exclusions != null && exclusions.contains(type.getType().getName().substring(1))) { return false; } else { return ((JavaSourceLoaderImpl) loader).defineType(type, type.getType().getName(), parentType) != null; } } @Override protected void leaveThis(CAstNode n, WalkContext c, CAstVisitor<WalkContext> visitor) { if (n.getChildCount() == 0) { super.leaveThis(n, c, visitor); } else { int result = c.currentScope().allocateTempValue(); c.setValue(n, result); c.cfg() .addInstruction( new EnclosingObjectReference( c.cfg().getCurrentInstruction(), result, (TypeReference) n.getChild(0).getValue())); } } @Override protected boolean visitCast(CAstNode n, WalkContext context, CAstVisitor<WalkContext> visitor) { int result = context.currentScope().allocateTempValue(); context.setValue(n, result); return false; } @Override protected void leaveCast(CAstNode n, WalkContext context, CAstVisitor<WalkContext> visitor) { int result = context.getValue(n); CAstType toType = (CAstType) n.getChild(0).getValue(); TypeReference toRef = makeType(toType); CAstType fromType = (CAstType) n.getChild(2).getValue(); TypeReference fromRef = makeType(fromType); if (toRef.isPrimitiveType()) { context .cfg() .addInstruction( insts.ConversionInstruction( context.cfg().getCurrentInstruction(), result, context.getValue(n.getChild(1)), fromRef, toRef, false)); } else { context .cfg() .addInstruction( insts.CheckCastInstruction( context.cfg().getCurrentInstruction(), result, context.getValue(n.getChild(1)), toRef, true)); processExceptions(n, context); } } @Override protected boolean visitInstanceOf( CAstNode n, WalkContext context, CAstVisitor<WalkContext> visitor) { int result = context.currentScope().allocateTempValue(); context.setValue(n, result); return false; } @Override protected void leaveInstanceOf( CAstNode n, WalkContext context, CAstVisitor<WalkContext> visitor) { int result = context.getValue(n); CAstType type = (CAstType) n.getChild(0).getValue(); TypeReference ref = makeType(type); context .cfg() .addInstruction( insts.InstanceofInstruction( context.cfg().getCurrentInstruction(), result, context.getValue(n.getChild(1)), ref)); } @Override protected boolean doVisit(CAstNode n, WalkContext wc, CAstVisitor<WalkContext> visitor) { if (n.getKind() == CAstNode.MONITOR_ENTER) { visitor.visit(n.getChild(0), wc, visitor); wc.cfg() .addInstruction( insts.MonitorInstruction( wc.cfg().getCurrentInstruction(), wc.getValue(n.getChild(0)), true)); processExceptions(n, wc); return true; } else if (n.getKind() == CAstNode.MONITOR_EXIT) { visitor.visit(n.getChild(0), wc, visitor); wc.cfg() .addInstruction( insts.MonitorInstruction( wc.cfg().getCurrentInstruction(), wc.getValue(n.getChild(0)), false)); processExceptions(n, wc); return true; } else { return super.doVisit(n, wc, visitor); } } private static CAstType getType(final String name) { return new CAstType.Class() { @Override public Collection<CAstType> getSupertypes() { return Collections.emptySet(); } @Override public String getName() { return name; } @Override public boolean isInterface() { return false; } @Override public Collection<CAstQualifier> getQualifiers() { return Collections.emptySet(); } }; } @Override protected CAstType topType() { return getType("java.lang.Object"); } @Override protected CAstType exceptionType() { return getType("java.lang.Exception"); } @Override protected Position[] getParameterPositions(CAstEntity n) { int offset = 0; Position[] parameterPositions = new Position[n.getArgumentCount()]; if ((n.getType() instanceof CAstType.Method) && !((CAstType.Method) n.getType()).isStatic()) { offset = 1; } for (int i = 0; i < n.getArgumentCount() - offset; i++) { parameterPositions[i + offset] = n.getPosition(i); } return parameterPositions; } }
19,213
31.238255
99
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/translator/JavaProcedureEntity.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.translator; import com.ibm.wala.cast.tree.CAstEntity; public interface JavaProcedureEntity extends CAstEntity { @Override String getSignature(); }
560
27.05
72
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/translator/SourceModuleTranslator.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Oct 6, 2005 */ package com.ibm.wala.cast.java.translator; import com.ibm.wala.classLoader.ModuleEntry; import java.util.Set; /** * An interface used by the JavaSourceLoaderImpl to encapsulate the loading of source entities on * the compile-time classpath into the DOMO analysis infrastructure. * * @author rfuhrer */ public interface SourceModuleTranslator { void loadAllSources(Set<ModuleEntry> modules); }
810
27.964286
97
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/types/JavaPrimitiveTypeMap.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Sep 28, 2005 */ package com.ibm.wala.cast.java.types; import com.ibm.wala.cast.tree.CAstType; import com.ibm.wala.util.collections.HashMapFactory; import java.util.Collection; import java.util.Collections; import java.util.Map; public class JavaPrimitiveTypeMap { public static final Map<String, JavaPrimitiveType> primNameMap = HashMapFactory.make(); public static class JavaPrimitiveType implements CAstType.Primitive { String fLongName; String fShortName; private JavaPrimitiveType(String longName, String shortName) { fLongName = longName; fShortName = shortName; } @Override public String getName() { return fShortName; } public String getLongName() { return fLongName; } @Override public Collection<CAstType> getSupertypes() { return Collections.emptyList(); } } public static String getShortName(String longName) { return primNameMap.get(longName).getName(); } public static JavaPrimitiveType lookupType(String longName) { return primNameMap.get(longName); } public static final JavaPrimitiveType VoidType = new JavaPrimitiveType("void", "V"); static { primNameMap.put("int", new JavaPrimitiveType("int", "I")); primNameMap.put("long", new JavaPrimitiveType("long", "J")); primNameMap.put("short", new JavaPrimitiveType("short", "S")); primNameMap.put("char", new JavaPrimitiveType("char", "C")); primNameMap.put("byte", new JavaPrimitiveType("byte", "B")); primNameMap.put("boolean", new JavaPrimitiveType("boolean", "Z")); primNameMap.put("float", new JavaPrimitiveType("float", "F")); primNameMap.put("double", new JavaPrimitiveType("double", "D")); primNameMap.put("void", VoidType); } }
2,146
28.819444
89
java
WALA
WALA-master/cast/java/src/main/java/com/ibm/wala/cast/java/types/JavaType.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Sep 21, 2005 */ package com.ibm.wala.cast.java.types; import com.ibm.wala.cast.tree.CAstType; public interface JavaType extends CAstType.Class { @Override boolean isInterface(); }
579
25.363636
72
java
WALA
WALA-master/cast/java/src/testFixtures/java/com/ibm/wala/cast/java/test/IRTests.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Oct 3, 2005 */ package com.ibm.wala.cast.java.test; import com.ibm.wala.cast.java.client.JavaSourceAnalysisEngine; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.cast.loader.AstClass; import com.ibm.wala.cast.loader.AstMethod; import com.ibm.wala.cast.loader.AstMethod.DebuggingInformation; import com.ibm.wala.cast.tree.CAstSourcePositionMap.Position; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.IClassLoader; import com.ibm.wala.classLoader.IMethod; import com.ibm.wala.classLoader.JarFileModule; import com.ibm.wala.classLoader.Language; import com.ibm.wala.classLoader.SourceDirectoryTreeModule; import com.ibm.wala.classLoader.SourceFileModule; import com.ibm.wala.client.AbstractAnalysisEngine; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.properties.WalaProperties; import com.ibm.wala.ssa.IR; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.types.ClassLoaderReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.types.annotations.Annotation; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.NullProgressMonitor; import com.ibm.wala.util.collections.HashSetFactory; import com.ibm.wala.util.collections.Iterator2Iterable; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.debug.Assertions; import java.io.File; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.function.Predicate; import java.util.jar.JarFile; import org.junit.Assert; public abstract class IRTests { protected boolean dump = true; protected IRTests(String projectName) { this.projectName = projectName; } protected final String projectName; protected static String javaHomePath; private String testSrcPath = Paths.get("src", "test", "java").toString(); public static final List<String> rtJar = Arrays.asList(WalaProperties.getJ2SEJarFiles()); protected static List<IRAssertion> emptyList = Collections.emptyList(); public interface IRAssertion { void check(CallGraph cg); } protected static class EdgeAssertions implements IRAssertion { public final String srcDescriptor; public final List /* <String> */<String> tgtDescriptors = new ArrayList<>(); public EdgeAssertions(String srcDescriptor) { this.srcDescriptor = srcDescriptor; } public static EdgeAssertions make(String srcDescriptor, String tgtDescriptor) { EdgeAssertions ea = new EdgeAssertions(srcDescriptor); ea.tgtDescriptors.add(tgtDescriptor); return ea; } public static EdgeAssertions make( String srcDescriptor, String tgtDescriptor1, String tgtDescriptor2) { EdgeAssertions ea = new EdgeAssertions(srcDescriptor); ea.tgtDescriptors.add(tgtDescriptor1); ea.tgtDescriptors.add(tgtDescriptor2); return ea; } public static EdgeAssertions make( String srcDescriptor, String tgtDescriptor1, String tgtDescriptor2, String tgtDescriptor3) { EdgeAssertions ea = new EdgeAssertions(srcDescriptor); ea.tgtDescriptors.add(tgtDescriptor1); ea.tgtDescriptors.add(tgtDescriptor2); ea.tgtDescriptors.add(tgtDescriptor3); return ea; } public static EdgeAssertions make( String srcDescriptor, String tgtDescriptor1, String tgtDescriptor2, String tgtDescriptor3, String tgtDescriptor4) { EdgeAssertions ea = new EdgeAssertions(srcDescriptor); ea.tgtDescriptors.add(tgtDescriptor1); ea.tgtDescriptors.add(tgtDescriptor2); ea.tgtDescriptors.add(tgtDescriptor3); ea.tgtDescriptors.add(tgtDescriptor4); return ea; } @Override public void check(CallGraph callGraph) { MethodReference srcMethod = descriptorToMethodRef(this.srcDescriptor, callGraph.getClassHierarchy()); Set<CGNode> srcNodes = callGraph.getNodes(srcMethod); if (srcNodes.size() == 0) { System.err.println(("Unreachable/non-existent method: " + srcMethod)); return; } if (srcNodes.size() > 1) { System.err.println("Context-sensitive call graph?"); } // Assume only one node for src method CGNode srcNode = srcNodes.iterator().next(); for (String target : this.tgtDescriptors) { MethodReference tgtMethod = descriptorToMethodRef(target, callGraph.getClassHierarchy()); // Assume only one node for target method Set<CGNode> tgtNodes = callGraph.getNodes(tgtMethod); if (tgtNodes.size() == 0) { System.err.println(("Unreachable/non-existent method: " + tgtMethod)); continue; } CGNode tgtNode = tgtNodes.iterator().next(); boolean found = false; for (CGNode succ : Iterator2Iterable.make(callGraph.getSuccNodes(srcNode))) { if (tgtNode == succ) { found = true; break; } } if (!found) { System.err.println(("Missing edge: " + srcMethod + " -> " + tgtMethod)); } } } } protected static class InstructionOperandAssertion implements IRAssertion { private final String method; private final Predicate<SSAInstruction> findInstruction; private final int operand; private final int[] position; public InstructionOperandAssertion( String method, Predicate<SSAInstruction> findInstruction, int operand, int[] position) { this.method = method; this.findInstruction = findInstruction; this.operand = operand; this.position = position; } @Override public void check(CallGraph cg) { MethodReference mref = descriptorToMethodRef(method, cg.getClassHierarchy()); boolean found = false; for (CGNode cgNode : cg.getNodes(mref)) { assert cgNode.getMethod() instanceof AstMethod; DebuggingInformation dbg = ((AstMethod) cgNode.getMethod()).debugInfo(); for (SSAInstruction inst : cgNode.getIR().getInstructions()) { if (findInstruction.test(inst)) { Position pos = dbg.getOperandPosition(inst.iIndex(), operand); if (pos != null) { if (pos.getFirstLine() == position[0] && pos.getFirstCol() == position[1] && pos.getLastLine() == position[2] && pos.getLastCol() == position[3]) { found = true; } } } } } assert found; } } protected static class SourceMapAssertion implements IRAssertion { private final String method; private final String variableName; private final int definingLineNumber; protected SourceMapAssertion(String method, String variableName, int definingLineNumber) { this.method = method; this.variableName = variableName; this.definingLineNumber = definingLineNumber; } @Override public void check(CallGraph cg) { MethodReference mref = descriptorToMethodRef(method, cg.getClassHierarchy()); for (CGNode cgNode : cg.getNodes(mref)) { Assert.assertTrue( "failed for " + this.variableName + " in " + cgNode + "\n" + cgNode.getIR(), this.check(cgNode.getMethod(), cgNode.getIR())); } } boolean check(IMethod m, IR ir) { System.err.println(("check for " + variableName + " defined at " + definingLineNumber)); SSAInstruction[] insts = ir.getInstructions(); for (int i = 0; i < insts.length; i++) { if (insts[i] != null) { int ln = m.getLineNumber(i); if (ln == definingLineNumber) { System.err.println((" found " + insts[i] + " at " + ln)); for (int j = 0; j < insts[i].getNumberOfDefs(); j++) { int def = insts[i].getDef(j); System.err.println((" looking at def " + j + ": " + def)); String[] names = ir.getLocalNames(i, def); if (names != null) { for (String name : names) { System.err.println((" looking at name " + name)); if (name.equals(variableName)) { return true; } } } } } } } return false; } } protected static class AnnotationAssertions implements IRAssertion { public static class ClassAnnotation { private final String className; private final String annotationTypeName; public ClassAnnotation(String className, String annotationTypeName) { super(); this.className = className; this.annotationTypeName = annotationTypeName; } } public static class MethodAnnotation { private final String methodSig; private final String annotationTypeName; public MethodAnnotation(String methodSig, String annotationTypeName) { super(); this.methodSig = methodSig; this.annotationTypeName = annotationTypeName; } } public final Set<ClassAnnotation> classAnnotations = HashSetFactory.make(); public final Set<MethodAnnotation> methodAnnotations = HashSetFactory.make(); @Override public void check(CallGraph cg) { classes: for (ClassAnnotation ca : classAnnotations) { IClass cls = cg.getClassHierarchy() .lookupClass( TypeReference.findOrCreate(ClassLoaderReference.Application, ca.className)); IClass at = cg.getClassHierarchy() .lookupClass( TypeReference.findOrCreate( ClassLoaderReference.Application, ca.annotationTypeName)); for (Annotation a : cls.getAnnotations()) { if (a.getType().equals(at.getReference())) { continue classes; } } Assert.assertFalse("cannot find " + at + " in " + cls, false); } annot: for (MethodAnnotation ma : methodAnnotations) { IClass at = cg.getClassHierarchy() .lookupClass( TypeReference.findOrCreate( ClassLoaderReference.Application, ma.annotationTypeName)); for (CGNode n : cg) { if (n.getMethod().getSignature().equals(ma.methodSig)) { for (Annotation a : n.getMethod().getAnnotations()) { if (a.getType().equals(at.getReference())) { continue annot; } } Assert.assertFalse("cannot find " + at, false); } } } } } protected Collection<String> singleTestSrc() { return Collections.singletonList(getTestSrcPath() + File.separator + singleJavaInputForTest()); } protected Collection<String> singleTestSrc(final String folder) { return Collections.singletonList( getTestSrcPath() + File.separator + folder + File.separator + singleJavaInputForTest()); } protected Collection<String> singlePkgTestSrc(String pkgName) { return Collections.singletonList( getTestSrcPath() + File.separator + singleJavaPkgInputForTest(pkgName)); } protected String getTestName() { StackTraceElement stack[] = new Throwable().getStackTrace(); for (int i = 0; i <= stack.length; i++) { if (stack[i].getMethodName().startsWith("test")) { return stack[i].getMethodName(); } } throw new Error("test method not found"); } protected String[] simpleTestEntryPoint() { return new String[] {'L' + getTestName().substring(4)}; } protected String[] simplePkgTestEntryPoint(String pkgName) { return new String[] {"L" + pkgName + "/" + getTestName().substring(4)}; } protected abstract AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> getAnalysisEngine( String[] mainClassDescriptors, Collection<String> sources, List<String> libs); public Pair<CallGraph, CallGraphBuilder<? super InstanceKey>> runTest( Collection<String> sources, List<String> libs, String[] mainClassDescriptors, List<? extends IRAssertion> ca, boolean assertReachable, String exclusionsFile) throws IllegalArgumentException, CancelException, IOException { AbstractAnalysisEngine<InstanceKey, CallGraphBuilder<InstanceKey>, ?> engine = getAnalysisEngine(mainClassDescriptors, sources, libs); if (exclusionsFile != null) { engine.setExclusionsFile(exclusionsFile); } CallGraphBuilder<? super InstanceKey> builder = engine.defaultCallGraphBuilder(); CallGraph callGraph = builder.makeCallGraph(engine.getOptions(), new NullProgressMonitor()); // System.err.println(callGraph.toString()); // If we've gotten this far, IR has been produced. if (dump) { dumpIR(callGraph, sources, assertReachable); } // Now check any assertions as to source mapping for (IRAssertion IRAssertion : ca) { IRAssertion.check(callGraph); } return Pair.make(callGraph, builder); } protected static void dumpIR(CallGraph cg, Collection<String> sources, boolean assertReachable) { Set<String> sourcePaths = HashSetFactory.make(); for (String src : sources) { sourcePaths.add(src.substring(src.lastIndexOf(File.separator) + 1)); } Set<IMethod> unreachable = HashSetFactory.make(); IClassHierarchy cha = cg.getClassHierarchy(); IClassLoader sourceLoader = cha.getLoader(JavaSourceAnalysisScope.SOURCE); for (IClass clazz : Iterator2Iterable.make(sourceLoader.iterateAllClasses())) { System.err.println(clazz); if (clazz.isInterface()) continue; for (IMethod m : clazz.getDeclaredMethods()) { if (m.isAbstract()) { System.err.println(m); } else { Iterator<CGNode> nodeIter = cg.getNodes(m.getReference()).iterator(); if (!nodeIter.hasNext()) { if (m instanceof AstMethod) { String fn = ((AstClass) m.getDeclaringClass()).getSourcePosition().getURL().getFile(); if (sourcePaths.contains(fn.substring(fn.lastIndexOf(File.separator) + 1))) { System.err.println(("Method " + m.getReference() + " not reachable?")); unreachable.add(m); } } continue; } CGNode node = nodeIter.next(); System.err.println(node.getIR()); } } } if (assertReachable) { Assert.assertTrue("unreachable methods: " + unreachable, unreachable.isEmpty()); } } /** * @param srcMethodDescriptor a full method descriptor of the form ldr#type#methName#methSig * example: Source#Simple1#main#([Ljava/lang/String;)V */ public static MethodReference descriptorToMethodRef( String srcMethodDescriptor, IClassHierarchy cha) { String[] ldrTypeMeth = srcMethodDescriptor.split("#"); String loaderName = ldrTypeMeth[0]; String typeStr = ldrTypeMeth[1]; String methName = ldrTypeMeth[2]; String methSig = ldrTypeMeth[3]; TypeReference typeRef = findOrCreateTypeReference(loaderName, typeStr, cha); Language l = cha.getLoader(typeRef.getClassLoader()).getLanguage(); return MethodReference.findOrCreate(l, typeRef, methName, methSig); } static TypeReference findOrCreateTypeReference( String loaderName, String typeStr, IClassHierarchy cha) { ClassLoaderReference clr = findLoader(loaderName, cha); TypeName typeName = TypeName.string2TypeName('L' + typeStr); TypeReference typeRef = TypeReference.findOrCreate(clr, typeName); return typeRef; } private static ClassLoaderReference findLoader(String loaderName, IClassHierarchy cha) { Atom loaderAtom = Atom.findOrCreateUnicodeAtom(loaderName); IClassLoader[] loaders = cha.getLoaders(); for (IClassLoader loader : loaders) { if (loader.getName() == loaderAtom) { return loader.getReference(); } } Assertions.UNREACHABLE(); return null; } public static void populateScope( JavaSourceAnalysisEngine engine, Collection<String> sources, List<String> libs) { boolean foundLib = false; for (String lib : libs) { File libFile = new File(lib); if (libFile.exists()) { foundLib = true; try { engine.addSystemModule(new JarFileModule(new JarFile(libFile, false))); } catch (IOException e) { Assert.fail(e.getMessage()); } } } assert foundLib : "couldn't find library file from " + libs; for (String srcFilePath : sources) { String srcFileName = srcFilePath.substring(srcFilePath.lastIndexOf(File.separator) + 1); File f = new File(srcFilePath); Assert.assertTrue("couldn't find " + srcFilePath, f.exists()); if (f.isDirectory()) { engine.addSourceModule(new SourceDirectoryTreeModule(f)); } else { engine.addSourceModule(new SourceFileModule(f, srcFileName, null)); } } } protected void setTestSrcPath(String testSrcPath) { this.testSrcPath = testSrcPath; } protected String getTestSrcPath() { return testSrcPath; } protected String singleJavaInputForTest() { return getTestName().substring(4) + ".java"; } protected String singleInputForTest() { return getTestName().substring(4); } protected String singleJavaPkgInputForTest(String pkgName) { return pkgName + File.separator + getTestName().substring(4) + ".java"; } }
18,409
33.347015
100
java
WALA
WALA-master/cast/java/src/testFixtures/java/com/ibm/wala/cast/java/test/Issue666Test.java
package com.ibm.wala.cast.java.test; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Pair; import java.io.IOException; import org.junit.Test; public abstract class Issue666Test extends IRTests { public Issue666Test(String projectName) { super(projectName); } @Test public void testPeekErrorCase() throws CancelException, IOException { Pair<CallGraph, ?> result = runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); assert result != null; MethodReference cm = MethodReference.findOrCreate( TypeReference.findOrCreate( JavaSourceAnalysisScope.SOURCE, TypeName.string2TypeName("LPeekErrorCase")), Atom.findOrCreateUnicodeAtom("start"), Descriptor.findOrCreateUTF8(Language.JAVA, "()V")); assert cm != null; } }
1,230
30.564103
92
java
WALA
WALA-master/cast/java/src/testFixtures/java/com/ibm/wala/cast/java/test/Issue667Test.java
package com.ibm.wala.cast.java.test; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.cfg.cdg.ControlDependenceGraph; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ssa.ISSABasicBlock; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Pair; import java.io.IOException; import org.junit.Test; public abstract class Issue667Test extends IRTests { public Issue667Test(String projectName) { super(projectName); } @Test public void testDominanceFrontierCase() throws CancelException, IOException { Pair<CallGraph, ?> result = runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); MethodReference cm = MethodReference.findOrCreate( TypeReference.findOrCreate( JavaSourceAnalysisScope.SOURCE, TypeName.string2TypeName("LDominanceFrontierCase")), Atom.findOrCreateUnicodeAtom("convert"), Descriptor.findOrCreateUTF8(Language.JAVA, "(Ljava/lang/Integer;)I")); result .fst .getNodes(cm) .forEach( n -> { try { ControlDependenceGraph<ISSABasicBlock> cdg = new ControlDependenceGraph<>(n.getIR().getControlFlowGraph()); assert cdg != null; } catch (IllegalArgumentException e) { System.err.println(n.getIR()); throw e; } }); } }
1,747
33.27451
100
java
WALA
WALA-master/cast/java/src/testFixtures/java/com/ibm/wala/cast/java/test/JLexTest.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.test; import com.ibm.wala.util.CancelException; import java.io.IOException; import org.junit.Test; public abstract class JLexTest extends IRTests { public JLexTest() { super(null); } @Override protected String singleJavaInputForTest() { return "JLex"; } @Test public void testJLex() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, new String[] {"LJLex/Main"}, emptyList, false, null); } @Override protected String singleJavaPkgInputForTest(String pkgName) { return ""; } }
971
24.578947
89
java
WALA
WALA-master/cast/java/src/testFixtures/java/com/ibm/wala/cast/java/test/JavaIRTests.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ /* * Created on Oct 21, 2005 */ package com.ibm.wala.cast.java.test; import static com.ibm.wala.ipa.slicer.SlicerUtil.dumpSlice; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.cast.java.ipa.modref.AstJavaModRef; import com.ibm.wala.cast.java.ipa.slicer.AstJavaSlicer; import com.ibm.wala.cast.java.loader.JavaSourceLoaderImpl; import com.ibm.wala.cast.java.ssa.EnclosingObjectReference; import com.ibm.wala.classLoader.IClass; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CGNode; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.ipa.callgraph.propagation.LocalPointerKey; import com.ibm.wala.ipa.callgraph.propagation.PointerAnalysis; import com.ibm.wala.ipa.callgraph.propagation.PropagationCallGraphBuilder; import com.ibm.wala.ipa.callgraph.util.CallGraphSearchUtil; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.ipa.slicer.SDG; import com.ibm.wala.ipa.slicer.Slicer; import com.ibm.wala.ipa.slicer.SlicerUtil; import com.ibm.wala.ipa.slicer.Statement; import com.ibm.wala.ipa.slicer.thin.ThinSlicer; import com.ibm.wala.ssa.SSAAbstractInvokeInstruction; import com.ibm.wala.ssa.SSAArrayLengthInstruction; import com.ibm.wala.ssa.SSAArrayReferenceInstruction; import com.ibm.wala.ssa.SSAArrayStoreInstruction; import com.ibm.wala.ssa.SSAGetInstruction; import com.ibm.wala.ssa.SSAInstruction; import com.ibm.wala.ssa.SSANewInstruction; import com.ibm.wala.ssa.SymbolTable; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.FieldReference; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Pair; import com.ibm.wala.util.io.TemporaryFile; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.Test; public abstract class JavaIRTests extends IRTests { public JavaIRTests(String projectName) { super(projectName); } public JavaIRTests() { this(null); } @Test public void testSimple1() throws IllegalArgumentException, CancelException, IOException { List<? extends IRAssertion> assertions = Arrays.asList( new SourceMapAssertion("Source#Simple1#doStuff#(I)V", "prod", 24), new SourceMapAssertion("Source#Simple1#doStuff#(I)V", "j", 23), new SourceMapAssertion("Source#Simple1#main#([Ljava/lang/String;)V", "s", 32), new SourceMapAssertion("Source#Simple1#main#([Ljava/lang/String;)V", "i", 28), new SourceMapAssertion("Source#Simple1#main#([Ljava/lang/String;)V", "sum", 29), EdgeAssertions.make( "Source#Simple1#main#([Ljava/lang/String;)V", "Source#Simple1#doStuff#(I)V"), EdgeAssertions.make( "Source#Simple1#instanceMethod1#()V", "Source#Simple1#instanceMethod2#()V")); // this needs soure positions to work too runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), assertions, true, null); } @Test public void testTwoClasses() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Collections.singletonList( cg -> { final String typeStr = singleInputForTest(); final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()); final IClass iClass = cg.getClassHierarchy().lookupClass(type); Assert.assertNotNull("Could not find class " + typeStr, iClass); /* Assert.assertEquals("Expected two classes.", iClass.getClassLoader().getNumberOfClasses(), 2); for (IClass cls : Iterator2Iterable.make(iClass.getClassLoader().iterateAllClasses())) { Assert.assertTrue("Expected class to be either " + typeStr + " or " + "Bar", cls.getName().getClassName().toString() .equals(typeStr) || cls.getName().getClassName().toString().equals("Bar")); } */ }), true, null); } @Test public void testInterfaceTest1() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Arrays.asList( cg -> { final String typeStr = "IFoo"; final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()); final IClass iClass = cg.getClassHierarchy().lookupClass(type); Assert.assertNotNull("Could not find class " + typeStr, iClass); Assert.assertTrue("Expected IFoo to be an interface.", iClass.isInterface()); }, cg -> { final String typeStr = "FooIT1"; final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()); final IClass iClass = cg.getClassHierarchy().lookupClass(type); Assert.assertNotNull("Could not find class " + typeStr, iClass); final Collection<? extends IClass> interfaces = iClass.getDirectInterfaces(); Assert.assertEquals("Expected one single interface.", interfaces.size(), 1); Assert.assertTrue( "Expected Foo to implement IFoo", interfaces.contains( cg.getClassHierarchy() .lookupClass( findOrCreateTypeReference( "Source", "IFoo", cg.getClassHierarchy())))); }), true, null); } @Test public void testInheritance1() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Collections.singletonList( cg -> { final String typeStr = "Derived"; final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()); final IClass derivedClass = cg.getClassHierarchy().lookupClass(type); Assert.assertNotNull("Could not find class " + typeStr, derivedClass); final TypeReference baseType = findOrCreateTypeReference("Source", "Base", cg.getClassHierarchy()); final IClass baseClass = cg.getClassHierarchy().lookupClass(baseType); Assert.assertEquals( "Expected 'Base' to be the superclass of 'Derived'", derivedClass.getSuperclass(), baseClass); Collection<IClass> subclasses = cg.getClassHierarchy().computeSubClasses(baseType); Assert.assertTrue( "Expected subclasses of 'Base' to be 'Base' and 'Derived'.", subclasses.contains(derivedClass) && subclasses.contains(baseClass)); }), true, null); } @Test public void testArray1() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Collections.singletonList( /* * 'foo' has four array instructions: - 2 SSAArrayLengthInstruction - 1 * SSAArrayLoadInstruction - 1 SSAArrayStoreInstruction */ new IRAssertion() { @Override public void check(CallGraph cg) { MethodReference mref = descriptorToMethodRef("Source#Array1#foo#()V", cg.getClassHierarchy()); int count = 0; CGNode node = cg.getNodes(mref).iterator().next(); for (SSAInstruction s : node.getIR().getInstructions()) { if (isArrayInstruction(s)) { count++; } } Assert.assertEquals("Unexpected number of array instructions in 'foo'.", count, 4); } private boolean isArrayInstruction(SSAInstruction s) { return s instanceof SSAArrayReferenceInstruction || s instanceof SSAArrayLengthInstruction; } }), true, null); } @Test public void testArrayLiteral1() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Collections.singletonList( cg -> { MethodReference mref = descriptorToMethodRef( "Source#ArrayLiteral1#main#([Ljava/lang/String;)V", cg.getClassHierarchy()); CGNode node = cg.getNodes(mref).iterator().next(); SSAInstruction s = node.getIR().getInstructions()[2]; Assert.assertTrue( "Did not find new array instruction.", s instanceof SSANewInstruction); Assert.assertTrue( "", ((SSANewInstruction) s).getNewSite().getDeclaredType().isArrayType()); }), true, null); } @Test public void testArrayLiteral2() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Collections.singletonList( cg -> { MethodReference mref = descriptorToMethodRef( "Source#ArrayLiteral2#main#([Ljava/lang/String;)V", cg.getClassHierarchy()); CGNode node = cg.getNodes(mref).iterator().next(); final SSAInstruction[] instructions = node.getIR().getInstructions(); // test 1 { SSAInstruction s1 = instructions[2]; if (s1 instanceof SSANewInstruction) { Assert.assertTrue( "", ((SSANewInstruction) s1).getNewSite().getDeclaredType().isArrayType()); } else { Assert.fail("Expected 3rd to be a new array instruction."); } } // test 2 { SSAInstruction s2 = instructions[3]; if (s2 instanceof SSANewInstruction) { Assert.assertTrue( "", ((SSANewInstruction) s2).getNewSite().getDeclaredType().isArrayType()); } else { Assert.fail("Expected 4th to be a new array instruction."); } } // test 3: the last 4 instructions are of the form y[i] = i+1; { final SymbolTable symbolTable = node.getIR().getSymbolTable(); for (int i = 4; i <= 7; i++) { Assert.assertTrue( "Expected only array stores.", instructions[i] instanceof SSAArrayStoreInstruction); SSAArrayStoreInstruction as = (SSAArrayStoreInstruction) instructions[i]; Assert.assertEquals( "Expected an array store to 'y'.", node.getIR().getLocalNames(i, as.getArrayRef())[0], "y"); final Integer valueOfArrayIndex = ((Integer) symbolTable.getConstantValue(as.getIndex())); final Integer valueAssigned = (Integer) symbolTable.getConstantValue(as.getValue()); Assert.assertEquals( "Expected an array store to 'y' with value " + (valueOfArrayIndex + 1), valueAssigned.intValue(), valueOfArrayIndex + 1); } } }), true, null); } @Test public void testInheritedField() throws IllegalArgumentException, CancelException, IOException { List<EdgeAssertions> edgeAssertionses = Arrays.asList( EdgeAssertions.make( "Source#InheritedField#main#([Ljava/lang/String;)V", "Source#B#foo#()V"), EdgeAssertions.make( "Source#InheritedField#main#([Ljava/lang/String;)V", "Source#B#bar#()V")); runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), edgeAssertionses, true, null); } @Test public void testQualifiedStatic() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Collections.singletonList( cg -> { MethodReference mref = descriptorToMethodRef( "Source#QualifiedStatic#main#([Ljava/lang/String;)V", cg.getClassHierarchy()); CGNode node = cg.getNodes(mref).iterator().next(); SSAInstruction s = node.getIR().getInstructions()[4]; Assert.assertTrue( "Did not find a getstatic instruction.", s instanceof SSAGetInstruction && ((SSAGetInstruction) s).isStatic()); final FieldReference field = ((SSAGetInstruction) s).getDeclaredField(); Assert.assertEquals( "Expected a getstatic for 'value'.", field.getName().toString(), "value"); Assert.assertEquals( "Expected a getstatic for 'value'.", field.getDeclaringClass().getName().toString(), "LFooQ"); }), true, null); } @Test public void testStaticNesting() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Collections.singletonList( cg -> { final String typeStr = singleInputForTest() + "$WhatsIt"; final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()); final IClass iClass = cg.getClassHierarchy().lookupClass(type); Assert.assertNotNull("Could not find class " + typeStr, iClass); // todo: this fails: Assert.assertNotNull("Expected to be enclosed in // 'StaticNesting'.", // ((JavaSourceLoaderImpl.JavaClass)iClass).getEnclosingClass()); // todo: is there the concept of CompilationUnit? /* * {@link JavaCAst2IRTranslator#getEnclosingType} return null for static inner * classes..? */ }), true, null); } @Test public void testCastFromNull() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), new ArrayList<>(), true, null); } @Test public void testInnerClass() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Collections.singletonList( cg -> { final String typeStr = singleInputForTest(); final TypeReference type = findOrCreateTypeReference("Source", typeStr + "$WhatsIt", cg.getClassHierarchy()); final IClass iClass = cg.getClassHierarchy().lookupClass(type); Assert.assertNotNull("Could not find class " + typeStr, iClass); Assert.assertEquals( "Expected to be enclosed in 'InnerClass'.", ((JavaSourceLoaderImpl.JavaClass) iClass) .getEnclosingClass(), // todo is there another way? cg.getClassHierarchy() .lookupClass( findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()))); }), true, null); } @Test public void testNullArrayInit() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), new ArrayList<>(), true, null); } @Test public void testInnerClassA() throws IllegalArgumentException, CancelException, IOException { Pair<CallGraph, CallGraphBuilder<? super InstanceKey>> x = runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), new ArrayList<>(), true, null); // can't do an IRAssertion() -- we need the pointer analysis CallGraph cg = x.fst; PointerAnalysis<? extends InstanceKey> pa = ((PropagationCallGraphBuilder) x.snd).getPointerAnalysis(); for (CGNode n : cg) { // assume in the test we have one enclosing instruction for each of the methods here. String methodSigs[] = { "InnerClassA$AB.getA_X_from_AB()I", "InnerClassA$AB.getA_X_thru_AB()I", "InnerClassA$AB$ABSubA.getA_X()I", "InnerClassA$AB$ABA$ABAA.getABA_X()I", "InnerClassA$AB$ABA$ABAA.getA_X()I", "InnerClassA$AB$ABA$ABAB.getABA_X()I", "InnerClassA$AB$ABSubA$ABSubAA.getABA_X()I", "InnerClassA$AB$ABSubA$ABSubAA.getA_X()I", }; // each type suffixed by "," String ikConcreteTypeStrings[] = { "LInnerClassA,", "LInnerClassA,", "LInnerClassA,", "LInnerClassA$AB$ABSubA,LInnerClassA$AB$ABA,", "LInnerClassA,", "LInnerClassA$AB$ABA,", "LInnerClassA$AB$ABSubA,", "LInnerClassA,", }; Assert.assertEquals("Buggy test", methodSigs.length, ikConcreteTypeStrings.length); for (int i = 0; i < methodSigs.length; i++) { if (n.getMethod().getSignature().equals(methodSigs[i])) { // find enclosing instruction for (SSAInstruction instr : n.getIR().getInstructions()) { if (instr instanceof EnclosingObjectReference) { StringBuilder allIksBuilder = new StringBuilder(); for (InstanceKey ik : pa.getPointsToSet(new LocalPointerKey(n, instr.getDef()))) { allIksBuilder.append(ik.getConcreteType().getName()).append(','); } // System.out.printf("in method %s, got ik %s\n", methodSigs[i], allIks); final String allIks = allIksBuilder.toString(); Assert.assertEquals( "assertion failed: expecting ik " + ikConcreteTypeStrings[i] + " in method " + methodSigs[i] + ", got " + allIks + "\n", allIks, ikConcreteTypeStrings[i]); break; } } } } } } @Test public void testInnerClassSuper() throws IllegalArgumentException, CancelException, IOException { Pair<CallGraph, CallGraphBuilder<? super InstanceKey>> x = runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), new ArrayList<>(), true, null); // can't do an IRAssertion() -- we need the pointer analysis CallGraph cg = x.fst; PointerAnalysis<? extends InstanceKey> pa = ((PropagationCallGraphBuilder) x.snd).getPointerAnalysis(); for (CGNode n : cg) { if (n.getMethod().getSignature().equals("LInnerClassSuper$SuperOuter.test()V")) { // find enclosing instruction for (SSAInstruction instr : n.getIR().getInstructions()) { if (instr instanceof EnclosingObjectReference) { StringBuilder allIksBuilder = new StringBuilder(); for (InstanceKey ik : pa.getPointsToSet(new LocalPointerKey(n, instr.getDef()))) { allIksBuilder.append(ik.getConcreteType().getName()).append(','); } final String allIks = allIksBuilder.toString(); Assert.assertEquals( "assertion failed: expecting ik \"LSub,\" in method, got \"" + allIks + "\"\n", "LSub,", allIks); break; } } } } } @Test public void testLocalClass() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Collections.singletonList( cg -> { final String typeStr = singleInputForTest(); final String localClassStr = "Foo"; // Observe the descriptor for a class local to a method. final TypeReference mainFooType = findOrCreateTypeReference( "Source", typeStr + "/main([Ljava/lang/String;)V/" + localClassStr, cg.getClassHierarchy()); // Observe the descriptor for a class local to a method. final IClass mainFooClass = cg.getClassHierarchy().lookupClass(mainFooType); Assert.assertNotNull("Could not find class " + mainFooType, mainFooClass); final TypeReference methodFooType = findOrCreateTypeReference( "Source", typeStr + "/method()V/" + localClassStr, cg.getClassHierarchy()); final IClass methodFooClass = cg.getClassHierarchy().lookupClass(methodFooType); Assert.assertNotNull("Could not find class " + methodFooType, methodFooClass); final IClass localClass = cg.getClassHierarchy() .lookupClass( findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy())); Assert.assertSame( "'Foo' is enclosed in 'Local'", ((JavaSourceLoaderImpl.JavaClass) methodFooClass).getEnclosingClass(), localClass); // todo: is this failing because 'main' is static? // Assert.assertSame("'Foo' is enclosed in 'Local'", // ((JavaSourceLoaderImpl.JavaClass)mainFooClass).getEnclosingClass(), // localClass); }), true, null); } @Test public void testAnonymousClass() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), Collections.singletonList( cg -> { final String typeStr = singleInputForTest(); final TypeReference type = findOrCreateTypeReference("Source", typeStr, cg.getClassHierarchy()); final IClass iClass = cg.getClassHierarchy().lookupClass(type); Assert.assertNotNull("Could not find class " + typeStr, iClass); // todo what to check?? could not find anything in the APIs for // anonymous }), true, null); } @Test public void testWhileTest1() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } @Test public void testSwitch1() { try { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } catch (IllegalArgumentException | IOException | CancelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void testException1() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } @Test public void testException2() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } @Test public void testFinally1() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } @Test public void testScoping1() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } @Test public void testScoping2() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } @Test public void testNonPrimaryTopLevel() throws IllegalArgumentException, CancelException, IOException { runTest(singlePkgTestSrc("p"), rtJar, simplePkgTestEntryPoint("p"), emptyList, true, null); } private static final List<IRAssertion> MLAssertions = Collections.singletonList( new InstructionOperandAssertion( "Source#MiniaturList#main#([Ljava/lang/String;)V", t -> (t instanceof SSAAbstractInvokeInstruction) && t.toString().contains("cons"), 1, new int[] {53, 38, 53, 60})); @Test public void testMiniaturList() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), MLAssertions, true, null); } @Test public void testMonitor() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } @Test public void testStaticInitializers() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } @Test public void testThread1() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } @Test public void testCasts() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } @Test public void testBreaks() throws IllegalArgumentException, CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } private static MethodReference getSliceRootReference( String className, String methodName, String methodDescriptor) { TypeName clsName = TypeName.string2TypeName('L' + className.replace('.', '/')); TypeReference clsRef = TypeReference.findOrCreate(JavaSourceAnalysisScope.SOURCE, clsName); Atom nameAtom = Atom.findOrCreateUnicodeAtom(methodName); Descriptor descr = Descriptor.findOrCreateUTF8(Language.JAVA, methodDescriptor); return MethodReference.findOrCreate(clsRef, nameAtom, descr); } @Test public void testMiniaturSliceBug() throws IllegalArgumentException, CancelException, IOException { Pair<CallGraph, CallGraphBuilder<? super InstanceKey>> x = runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); PointerAnalysis<? extends InstanceKey> pa = ((PropagationCallGraphBuilder) x.snd).getPointerAnalysis(); CallGraph cg = x.fst; // test partial slice MethodReference sliceRootRef = getSliceRootReference("MiniaturSliceBug", "validNonDispatchedCall", "(LIntWrapper;)V"); Set<CGNode> roots = cg.getNodes(sliceRootRef); Pair<Collection<Statement>, SDG<? extends InstanceKey>> y = AstJavaSlicer.computeAssertionSlice(cg, pa, roots, false); Collection<Statement> slice = y.fst; dumpSlice(slice); Assert.assertEquals(0, SlicerUtil.countAllocations(slice, false)); Assert.assertEquals(1, SlicerUtil.countPutfields(slice)); // test slice from main sliceRootRef = getSliceRootReference("MiniaturSliceBug", "main", "([Ljava/lang/String;)V"); roots = cg.getNodes(sliceRootRef); y = AstJavaSlicer.computeAssertionSlice(cg, pa, roots, false); slice = y.fst; // SlicerUtil.dumpSlice(slice); Assert.assertEquals(2, SlicerUtil.countAllocations(slice, false)); Assert.assertEquals(2, SlicerUtil.countPutfields(slice)); } @Test public void testThinSlice() throws CancelException, IOException { String testName = "MiniaturSliceBug"; List<String> sources = Collections.singletonList(getTestSrcPath() + File.separator + testName + ".java"); Pair<CallGraph, CallGraphBuilder<? super InstanceKey>> x = runTest(sources, rtJar, new String[] {'L' + testName}, emptyList, true, null); PointerAnalysis<InstanceKey> pa = ((PropagationCallGraphBuilder) x.snd).getPointerAnalysis(); CallGraph cg = x.fst; // we just run context-sensitive and context-insensitive thin slicing, to make sure // it doesn't crash Statement statement = SlicerUtil.findCallTo(CallGraphSearchUtil.findMainMethod(cg), "validNonDispatchedCall"); AstJavaModRef<InstanceKey> modRef = new AstJavaModRef<>(); SDG<InstanceKey> sdg = new SDG<>( cg, pa, modRef, Slicer.DataDependenceOptions.NO_BASE_PTRS, Slicer.ControlDependenceOptions.NONE); Collection<Statement> slice = AstJavaSlicer.computeBackwardSlice(sdg, Collections.singleton(statement)); dumpSlice(slice); ThinSlicer ts = new ThinSlicer(cg, pa, modRef); slice = ts.computeBackwardThinSlice(statement); dumpSlice(slice); } @Test public void testDoWhileInCase() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc("bugfixes"), rtJar, simplePkgTestEntryPoint("bugfixes"), emptyList, true, null); } @Test public void testVarDeclInSwitch() throws IllegalArgumentException, CancelException, IOException { runTest( singleTestSrc("bugfixes"), rtJar, simplePkgTestEntryPoint("bugfixes"), emptyList, true, null); } @Test public void testExclusions() throws IllegalArgumentException, CancelException, IOException { File exclusions = TemporaryFile.stringToFile(File.createTempFile("exl", "txt"), "Exclusions.Excluded\n"); Pair<CallGraph, CallGraphBuilder<? super InstanceKey>> x = runTest( singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, exclusions.getAbsolutePath()); IClassHierarchy cha = x.fst.getClassHierarchy(); TypeReference topType = TypeReference.findOrCreate( JavaSourceAnalysisScope.SOURCE, TypeName.findOrCreate("LExclusions")); assert cha.lookupClass(topType) != null; TypeReference inclType = TypeReference.findOrCreate( JavaSourceAnalysisScope.SOURCE, TypeName.findOrCreate("LExclusions$Included")); assert cha.lookupClass(inclType) != null; TypeReference exclType = TypeReference.findOrCreate( JavaSourceAnalysisScope.SOURCE, TypeName.findOrCreate("LExclusions$Excluded")); assert cha.lookupClass(exclType) == null; } @Test public void testLexicalAccessOfMethodVariablesFromAnonymousClass() throws CancelException, IOException { runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); } }
31,827
37.439614
132
java
WALA
WALA-master/cast/java/src/testFixtures/java/com/ibm/wala/cast/java/test/SyncDuplicatorTests.java
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.cast.java.test; import com.ibm.wala.cast.java.ipa.callgraph.JavaSourceAnalysisScope; import com.ibm.wala.classLoader.CallSiteReference; import com.ibm.wala.classLoader.Language; import com.ibm.wala.core.util.strings.Atom; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.CallGraphBuilder; import com.ibm.wala.ipa.callgraph.propagation.InstanceKey; import com.ibm.wala.shrike.shrikeBT.IInvokeInstruction; import com.ibm.wala.types.Descriptor; import com.ibm.wala.types.MethodReference; import com.ibm.wala.types.TypeName; import com.ibm.wala.types.TypeReference; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.collections.Pair; import java.io.IOException; import org.junit.Test; public abstract class SyncDuplicatorTests extends IRTests { public SyncDuplicatorTests() { super(null); } protected static final CallSiteReference testMethod = CallSiteReference.make( 0, MethodReference.findOrCreate( TypeReference.findOrCreate( JavaSourceAnalysisScope.SOURCE, TypeName.string2TypeName("LMonitor2")), Atom.findOrCreateUnicodeAtom("test"), Descriptor.findOrCreateUTF8(Language.JAVA, "(Ljava/lang/Object;)Z")), IInvokeInstruction.Dispatch.STATIC); @Test public void testMonitor2() throws IllegalArgumentException, CancelException, IOException { Pair<CallGraph, CallGraphBuilder<? super InstanceKey>> result = runTest(singleTestSrc(), rtJar, simpleTestEntryPoint(), emptyList, true, null); System.err.println(result.fst); } }
1,996
36.679245
92
java