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
JSAT
JSAT-master/JSAT/test/jsat/outlier/DensityOutlierTest.java
/* * Copyright (C) 2018 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.outlier; import jsat.SimpleDataSet; import jsat.distributions.Normal; import jsat.distributions.multivariate.NormalM; import jsat.utils.GridDataGenerator; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class DensityOutlierTest { public DensityOutlierTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of fit method, of class LinearOCSVM. */ @Test public void testFit() { System.out.println("fit"); int N = 5000; SimpleDataSet trainData = new GridDataGenerator(new Normal(), 1,1,1).generateData(N); SimpleDataSet outlierData = new GridDataGenerator(new Normal(10, 1.0), 1,1,1).generateData(N); DensityOutlier instance = new DensityOutlier(); instance.setDensityDistribution(new NormalM()); for(boolean parallel : new boolean[]{false, true}) for(double v : new double[]{0.01, 0.05, 0.1}) { instance.setOutlierFraction(v); instance.fit(trainData, parallel); double numOutliersInTrain = trainData.getDataPoints().stream().mapToDouble(instance::score).filter(x->x<0).count(); assertEquals(0, numOutliersInTrain/trainData.size(), v*3);//Better say something like v% or less of training data is an outlier! double numOutliersInOutliers = outlierData.getDataPoints().stream().mapToDouble(instance::score).filter(x->x<0).count(); assertEquals(1.0, numOutliersInOutliers/outlierData.size(), 0.1);//Better say 90% are outliers! } } }
2,717
29.2
144
java
JSAT
JSAT-master/JSAT/test/jsat/outlier/IsolationForestTest.java
/* * Copyright (C) 2018 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.outlier; import jsat.outlier.IsolationForest; import jsat.DataSet; import jsat.SimpleDataSet; import jsat.classifiers.DataPoint; import jsat.datatransform.kernel.RFF_RBF; import jsat.distributions.Normal; import jsat.distributions.kernels.RBFKernel; import jsat.utils.GridDataGenerator; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class IsolationForestTest { public IsolationForestTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of fit method, of class LinearOCSVM. */ @Test public void testFit() { System.out.println("fit"); int N = 5000; SimpleDataSet trainData = new GridDataGenerator(new Normal(), 1,1,1).generateData(N); SimpleDataSet outlierData = new GridDataGenerator(new Normal(10, 1.0), 1,1,1).generateData(N); IsolationForest instance = new IsolationForest(); instance.fit(trainData, false); double numOutliersInTrain = trainData.getDataPoints().stream().mapToDouble(instance::score).filter(x -> x < 0).count(); assertEquals(0, numOutliersInTrain / trainData.size(), 0.05);//Better say something like 95% are inliers! double numOutliersInOutliers = outlierData.getDataPoints().stream().mapToDouble(instance::score).filter(x -> x < 0).count(); assertEquals(1.0, numOutliersInOutliers / outlierData.size(), 0.1);//Better say 90% are outliers! } }
2,549
27.651685
132
java
JSAT
JSAT-master/JSAT/test/jsat/outlier/LOFTest.java
/* * Copyright (C) 2018 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.outlier; import jsat.outlier.IsolationForest; import jsat.DataSet; import jsat.SimpleDataSet; import jsat.classifiers.DataPoint; import jsat.datatransform.kernel.RFF_RBF; import jsat.distributions.Normal; import jsat.distributions.kernels.RBFKernel; import jsat.utils.GridDataGenerator; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class LOFTest { public LOFTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of fit method, of class LinearOCSVM. */ @Test public void testFit() { System.out.println("fit"); int N = 5000; SimpleDataSet trainData = new GridDataGenerator(new Normal(), 1,1,1).generateData(N); SimpleDataSet outlierData = new GridDataGenerator(new Normal(10, 1.0), 1,1,1).generateData(N); LOF instance = new LOF(); for(boolean parallel : new boolean[]{false, true}) { instance.fit(trainData, parallel); double numOutliersInTrain = trainData.getDataPoints().stream().mapToDouble(instance::score).filter(x -> x < 0).count(); assertEquals(0, numOutliersInTrain / trainData.size(), 0.05);//Better say something like 95% are inliers! double numOutliersInOutliers = outlierData.getDataPoints().stream().mapToDouble(instance::score).filter(x -> x < 0).count(); assertEquals(1.0, numOutliersInOutliers / outlierData.size(), 0.1);//Better say 90% are outliers! } } }
2,633
27.021277
136
java
JSAT
JSAT-master/JSAT/test/jsat/outlier/LinearOCSVMTest.java
/* * Copyright (C) 2018 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.outlier; import jsat.outlier.LinearOCSVM; import jsat.DataSet; import jsat.SimpleDataSet; import jsat.classifiers.DataPoint; import jsat.datatransform.kernel.RFF_RBF; import jsat.distributions.Normal; import jsat.distributions.kernels.RBFKernel; import jsat.utils.GridDataGenerator; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class LinearOCSVMTest { public LinearOCSVMTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of fit method, of class LinearOCSVM. */ @Test public void testFit() { System.out.println("fit"); int N = 5000; SimpleDataSet trainData = new GridDataGenerator(new Normal(), 1,1,1).generateData(N); RFF_RBF rff = new RFF_RBF(RBFKernel.guessSigma(trainData).median(), 64); rff.fit(trainData); trainData.applyTransform(rff); SimpleDataSet outlierData = new GridDataGenerator(new Normal(10, 1.0), 1,1,1).generateData(N); outlierData.applyTransform(rff); LinearOCSVM instance = new LinearOCSVM(); for(double v : new double[]{0.01, 0.05, 0.1}) { instance.setV(v); instance.fit(trainData, false); double numOutliersInTrain = trainData.getDataPoints().stream().mapToDouble(instance::score).filter(x->x<0).count(); // System.out.println(v + " " + numOutliersInTrain + " " + v*N); assertEquals(0, numOutliersInTrain/trainData.size(), 15);//Better say something like 15% or less of training data is an outlier! double numOutliersInOutliers = outlierData.getDataPoints().stream().mapToDouble(instance::score).filter(x->x<0).count(); // System.out.println("Outliers: " + numOutliersInOutliers/outlierData.getSampleSize()); assertEquals(1.0, numOutliersInOutliers/outlierData.size(), 0.1);//Better say 90% are outliers! } } }
3,063
29.949495
140
java
JSAT
JSAT-master/JSAT/test/jsat/outlier/LoOPTest.java
/* * Copyright (C) 2018 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.outlier; import jsat.SimpleDataSet; import jsat.distributions.Normal; import jsat.utils.GridDataGenerator; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class LoOPTest { public LoOPTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of fit method, of class . */ @Test public void testFit() { System.out.println("fit"); int N = 5000; SimpleDataSet trainData = new GridDataGenerator(new Normal(), 1,1,1).generateData(N); SimpleDataSet outlierData = new GridDataGenerator(new Normal(10, 1.0), 1,1,1).generateData(N); LoOP instance = new LoOP(); for(boolean parallel : new boolean[]{false, true}) { instance.fit(trainData, parallel); double numOutliersInTrain = trainData.getDataPoints().stream().mapToDouble(instance::score).filter(x -> x < 0).count(); assertEquals(0, numOutliersInTrain / trainData.size(), 0.05);//Better say something like 95% are inliers! double numOutliersInOutliers = outlierData.getDataPoints().stream().mapToDouble(instance::score).filter(x -> x < 0).count(); assertEquals(1.0, numOutliersInOutliers / outlierData.size(), 0.1);//Better say 90% are outliers! } } }
2,437
26.704545
136
java
JSAT
JSAT-master/JSAT/test/jsat/parameters/GridSearchTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.parameters; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.DataSet; import jsat.classifiers.*; import jsat.distributions.Distribution; import jsat.distributions.Uniform; import jsat.distributions.discrete.UniformDiscrete; import jsat.linear.DenseVector; import jsat.parameters.Parameter.WarmParameter; import jsat.regression.RegressionDataSet; import jsat.regression.Regressor; import jsat.regression.WarmRegressor; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class GridSearchTest { ClassificationDataSet classData ; RegressionDataSet regData; public GridSearchTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { classData = new ClassificationDataSet(1, new CategoricalData[0], new CategoricalData(2)); for(int i = 0; i < 100; i++) classData.addDataPoint(DenseVector.toDenseVec(1.0*i), 0); for(int i = 0; i < 100; i++) classData.addDataPoint(DenseVector.toDenseVec(-1.0*i), 1); regData = new RegressionDataSet(1, new CategoricalData[0]); for(int i = 0; i < 100; i++) regData.addDataPoint(DenseVector.toDenseVec(1.0*i), 0); for(int i = 0; i < 100; i++) regData.addDataPoint(DenseVector.toDenseVec(-1.0*i), 1); } @After public void tearDown() { } @Test public void testClassificationWarm() { System.out.println("setUseWarmStarts"); GridSearch instance = new GridSearch((Classifier)new DumbModel(), 5); instance.setUseWarmStarts(true); instance.addParameter("Param1", 0, 1, 2, 3, 4, 5); instance.addParameter("Param2", 0.0, 1.0, 2.0, 3.0, 4.0, 5.0); instance.addParameter("Param3", 0, 1, 2, 3, 4, 5); instance = instance.clone(); instance.train(classData); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedClassifier(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.0); assertEquals(3, model.param3); assertTrue(model.wasWarmStarted); } @Test public void testClassificationWarmExec() { System.out.println("setUseWarmStarts"); GridSearch instance = new GridSearch((Classifier)new DumbModel(), 5); instance.setUseWarmStarts(true); instance.addParameter("Param1", 0, 1, 2, 3, 4, 5); instance.addParameter("Param2", 0.0, 1.0, 2.0, 3.0, 4.0, 5.0); instance.addParameter("Param3", 0, 1, 2, 3, 4, 5); instance = instance.clone(); instance.train(classData, true); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedClassifier(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.0); assertEquals(3, model.param3); assertTrue(model.wasWarmStarted); } @Test public void testClassification() { System.out.println("setUseWarmStarts"); GridSearch instance = new GridSearch((Classifier)new DumbModel(), 5); instance.setUseWarmStarts(false); instance.addParameter("Param1", 0, 1, 2, 3, 4, 5); instance.addParameter("Param2", 0.0, 1.0, 2.0, 3.0, 4.0, 5.0); instance.addParameter("Param3", 0, 1, 2, 3, 4, 5); instance = instance.clone(); instance.train(classData); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedClassifier(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.0); assertEquals(3, model.param3); assertFalse(model.wasWarmStarted); } @Test public void testClassificationAutoAdd() { System.out.println("classificationAutoAdd"); GridSearch instance = new GridSearch((Classifier)new DumbModel(), 5); instance.setUseWarmStarts(false); instance.autoAddParameters(classData); instance = instance.clone(); instance.train(classData); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedClassifier(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.5); assertEquals(3, model.param3); assertFalse(model.wasWarmStarted); } @Test public void testClassificationExec() { System.out.println("setUseWarmStarts"); GridSearch instance = new GridSearch((Classifier)new DumbModel(), 5); instance.setUseWarmStarts(false); instance.addParameter("Param1", 0, 1, 2, 3, 4, 5); instance.addParameter("Param2", 0.0, 1.0, 2.0, 3.0, 4.0, 5.0); instance.addParameter("Param3", 0, 1, 2, 3, 4, 5); instance = instance.clone(); instance.train(classData, true); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedClassifier(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.0); assertEquals(3, model.param3); assertFalse(model.wasWarmStarted); } @Test public void testRegressionWarm() { System.out.println("setUseWarmStarts"); GridSearch instance = new GridSearch((Regressor)new DumbModel(), 5); instance.setUseWarmStarts(true); instance.addParameter("Param1", 0, 1, 2, 3, 4, 5); instance.addParameter("Param2", 0.0, 1.0, 2.0, 3.0, 4.0, 5.0); instance.addParameter("Param3", 0, 1, 2, 3, 4, 5); instance = instance.clone(); instance.train(regData); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedRegressor(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.0); assertEquals(3, model.param3); assertTrue(model.wasWarmStarted); } @Test public void testRegressionWarmExec() { System.out.println("setUseWarmStarts"); GridSearch instance = new GridSearch((Regressor)new DumbModel(), 5); instance.setUseWarmStarts(true); instance.addParameter("Param1", 0, 1, 2, 3, 4, 5); instance.addParameter("Param2", 0.0, 1.0, 2.0, 3.0, 4.0, 5.0); instance.addParameter("Param3", 0, 1, 2, 3, 4, 5); instance = instance.clone(); instance.train(regData, true); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedRegressor(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.0); assertEquals(3, model.param3); assertTrue(model.wasWarmStarted); } @Test public void testRegression() { System.out.println("setUseWarmStarts"); GridSearch instance = new GridSearch((Regressor)new DumbModel(), 5); instance.setUseWarmStarts(false); instance.addParameter("Param1", 0, 1, 2, 3, 4, 5); instance.addParameter("Param2", 0.0, 1.0, 2.0, 3.0, 4.0, 5.0); instance.addParameter("Param3", 0, 1, 2, 3, 4, 5); instance = instance.clone(); instance.train(regData); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedRegressor(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.0); assertEquals(3, model.param3); assertFalse(model.wasWarmStarted); } @Test public void testRegressionExec() { System.out.println("setUseWarmStarts"); GridSearch instance = new GridSearch((Regressor)new DumbModel(), 5); instance.setUseWarmStarts(false); instance.addParameter("Param1", 0, 1, 2, 3, 4, 5); instance.addParameter("Param2", 0.0, 1.0, 2.0, 3.0, 4.0, 5.0); instance.addParameter("Param3", 0, 1, 2, 3, 4, 5); instance = instance.clone(); instance.train(regData, true); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedRegressor(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.0); assertEquals(3, model.param3); assertFalse(model.wasWarmStarted); } /** * This model is dumb. It always returns the same thing, unless the parameters are set to specific values. Then it returns a 2nd option as well. */ static class DumbModel implements WarmClassifier, WarmRegressor, Parameterized { int param1; double param2; int param3; boolean wasWarmStarted = false; public void setParam1(int param1) { this.param1 = param1; } public int getParam1() { return param1; } public Distribution guessParam1(DataSet d) { return new UniformDiscrete(0, 5); } public void setParam2(double param2) { this.param2 = param2; } public double getParam2() { return param2; } public Distribution guessParam2(DataSet d) { return new Uniform(0.0, 5.0); } @WarmParameter(prefLowToHigh = false) public void setParam3(int param3) { this.param3 = param3; } public int getParam3() { return param3; } public Distribution guessParam3(DataSet d) { return new UniformDiscrete(0, 5); } @Override public boolean warmFromSameDataOnly() { return false; } @Override public void train(ClassificationDataSet dataSet, Classifier warmSolution, boolean parallel) { wasWarmStarted = ((DumbModel)warmSolution).param3 == this.param3; } @Override public void train(ClassificationDataSet dataSet, Classifier warmSolution) { wasWarmStarted = ((DumbModel)warmSolution).param3 == this.param3; } @Override public CategoricalResults classify(DataPoint data) { //range check done so that RandomSearch can re-use this class for its own test boolean param2InRange = 1.5 < param2 && param2 < 2.5; if(param1 == 1 && param2InRange && param3 == 3) if(data.getNumericalValues().get(0) < 0) return new CategoricalResults(new double[]{0.0, 1.0}); return new CategoricalResults(new double[]{1.0, 0.0}); } @Override public void train(ClassificationDataSet dataSet, boolean parallel) { wasWarmStarted = false; } @Override public void train(ClassificationDataSet dataSet) { wasWarmStarted = false; } @Override public boolean supportsWeightedData() { return true; } @Override public void train(RegressionDataSet dataSet, Regressor warmSolution, boolean parallel) { wasWarmStarted = ((DumbModel)warmSolution).param3 == this.param3; } @Override public void train(RegressionDataSet dataSet, Regressor warmSolution) { wasWarmStarted = ((DumbModel)warmSolution).param3 == this.param3; } @Override public double regress(DataPoint data) { //range check done so that RandomSearch can re-use this class for its own test boolean param2InRange = 1.5 < param2 && param2 < 2.5; if(param1 == 1 && param2InRange && param3 == 3) if (data.getNumericalValues().get(0) < 0) return 1; return 0; } @Override public void train(RegressionDataSet dataSet, boolean parallel) { wasWarmStarted = false; } @Override public void train(RegressionDataSet dataSet) { wasWarmStarted = false; } @Override public DumbModel clone() { DumbModel toRet = new DumbModel(); toRet.param1 = this.param1; toRet.param2 = this.param2; toRet.param3 = this.param3; toRet.wasWarmStarted = this.wasWarmStarted; return toRet; } } }
13,661
30.625
149
java
JSAT
JSAT-master/JSAT/test/jsat/parameters/RandomSearchTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.parameters; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.classifiers.CategoricalData; import jsat.classifiers.ClassificationDataSet; import jsat.classifiers.Classifier; import jsat.distributions.Uniform; import jsat.distributions.discrete.UniformDiscrete; import jsat.linear.DenseVector; import jsat.parameters.GridSearchTest.DumbModel; import jsat.regression.RegressionDataSet; import jsat.regression.Regressor; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class RandomSearchTest { ClassificationDataSet classData ; RegressionDataSet regData; public RandomSearchTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { classData = new ClassificationDataSet(1, new CategoricalData[0], new CategoricalData(2)); for (int i = 0; i < 100; i++) classData.addDataPoint(DenseVector.toDenseVec(1.0 * i), 0); for (int i = 0; i < 100; i++) classData.addDataPoint(DenseVector.toDenseVec(-1.0 * i), 1); regData = new RegressionDataSet(1, new CategoricalData[0]); for (int i = 0; i < 100; i++) regData.addDataPoint(DenseVector.toDenseVec(1.0 * i), 0); for (int i = 0; i < 100; i++) regData.addDataPoint(DenseVector.toDenseVec(-1.0 * i), 1); } @After public void tearDown() { } @Test public void testClassification() { System.out.println("testClassification"); RandomSearch instance = new RandomSearch((Classifier)new DumbModel(), 5); instance.setTrials(5*5*5*5*5); instance.addParameter("Param1", new UniformDiscrete(0, 5)); instance.addParameter("Param2", new Uniform(0.0, 5.0)); instance.addParameter("Param3", new UniformDiscrete(0, 5)); instance = instance.clone(); instance.train(classData); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedClassifier(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.5); assertEquals(3, model.param3); assertFalse(model.wasWarmStarted); } @Test public void testClassificationAutoAdd() { System.out.println("testClassificationAutoAdd"); RandomSearch instance = new RandomSearch((Classifier)new DumbModel(), 5); instance.setTrials(5*5*5*5*5); instance.autoAddParameters(classData); instance = instance.clone(); instance.train(classData); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedClassifier(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.5); assertEquals(3, model.param3); assertFalse(model.wasWarmStarted); } @Test public void testClassificationEx() { System.out.println("testClassificationEx"); RandomSearch instance = new RandomSearch((Classifier)new DumbModel(), 5); instance.setTrials(5*5*5*5*5); instance.addParameter("Param1", new UniformDiscrete(0, 5)); instance.addParameter("Param2", new Uniform(0.0, 5.0)); instance.addParameter("Param3", new UniformDiscrete(0, 5)); instance = instance.clone(); instance.train(classData, true); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedClassifier(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.5); assertEquals(3, model.param3); assertFalse(model.wasWarmStarted); } @Test public void testRegression() { System.out.println("testRegression"); RandomSearch instance = new RandomSearch((Regressor)new DumbModel(), 5); instance.setTrials(5*5*5*5*5); instance.addParameter("Param1", new UniformDiscrete(0, 5)); instance.addParameter("Param2", new Uniform(0.0, 5.0)); instance.addParameter("Param3", new UniformDiscrete(0, 5)); instance = instance.clone(); instance.train(regData); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedRegressor(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.5); assertEquals(3, model.param3); assertFalse(model.wasWarmStarted); } @Test public void testRegressionEx() { System.out.println("testRegressionEx"); RandomSearch instance = new RandomSearch((Regressor)new DumbModel(), 5); instance.setTrials(5*5*5*5*5); instance.addParameter("Param1", new UniformDiscrete(0, 5)); instance.addParameter("Param2", new Uniform(0.0, 5.0)); instance.addParameter("Param3", new UniformDiscrete(0, 5)); instance = instance.clone(); instance.train(regData, true); instance = instance.clone(); DumbModel model = (DumbModel) instance.getTrainedRegressor(); assertEquals(1, model.param1); assertEquals(2, model.param2, 0.5); assertEquals(3, model.param3); assertFalse(model.wasWarmStarted); } }
6,322
31.761658
97
java
JSAT
JSAT-master/JSAT/test/jsat/regression/AveragedRegressorTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.regression; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.datatransform.LinearTransform; import jsat.distributions.kernels.LinearKernel; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class AveragedRegressorTest { public AveragedRegressorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); AveragedRegressor instance = new AveragedRegressor(new KernelRLS(new LinearKernel(1), 1e-1), new KernelRLS(new LinearKernel(1), 1e-2), new KernelRLS(new LinearKernel(1), 1e-4)); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); AveragedRegressor instance = new AveragedRegressor(new KernelRLS(new LinearKernel(1), 1e-1), new KernelRLS(new LinearKernel(1), 1e-2), new KernelRLS(new LinearKernel(1), 1e-4)); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testClone() { System.out.println("clone"); AveragedRegressor instance = new AveragedRegressor(new KernelRLS(new LinearKernel(1), 1e-1), new KernelRLS(new LinearKernel(1), 1e-2), new KernelRLS(new LinearKernel(1), 1e-4)); RegressionDataSet t1 = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionDataSet t2 = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); t2.applyTransform(new LinearTransform(t2, 1, 10)); instance = instance.clone(); instance.train(t1); AveragedRegressor result = instance.clone(); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), result.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*0.5); result.train(t2); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), instance.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*0.5); for (int i = 0; i < t2.size(); i++) assertEquals(t2.getTargetValue(i), result.regress(t2.getDataPoint(i)), t2.getTargetValues().mean()*0.5); } }
4,190
31.742188
185
java
JSAT
JSAT-master/JSAT/test/jsat/regression/KernelRLSTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.regression; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.datatransform.LinearTransform; import jsat.distributions.kernels.LinearKernel; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class KernelRLSTest { public KernelRLSTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); KernelRLS instance = new KernelRLS(new LinearKernel(1), 1e-1); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); KernelRLS instance = new KernelRLS(new LinearKernel(1), 1e-1); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testClone() { System.out.println("clone"); KernelRLS instance = new KernelRLS(new LinearKernel(1), 1e-1); RegressionDataSet t1 = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionDataSet t2 = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); t2.applyTransform(new LinearTransform(t2, 1, 10)); instance = instance.clone(); instance.train(t1); KernelRLS result = instance.clone(); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), result.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*0.5); result.train(t2); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), instance.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*0.5); for (int i = 0; i < t2.size(); i++) assertEquals(t2.getTargetValue(i), result.regress(t2.getDataPoint(i)), t2.getTargetValues().mean()*0.5); } }
3,816
29.055118
118
java
JSAT
JSAT-master/JSAT/test/jsat/regression/KernelRidgeRegressionTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.regression; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.datatransform.LinearTransform; import jsat.distributions.kernels.LinearKernel; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class KernelRidgeRegressionTest { public KernelRidgeRegressionTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); KernelRLS instance = new KernelRLS(new LinearKernel(1), 1e-1); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); KernelRidgeRegression instance = new KernelRidgeRegression(1e-1, new LinearKernel(1)); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testClone() { System.out.println("clone"); KernelRidgeRegression instance = new KernelRidgeRegression(1e-1, new LinearKernel(1)); RegressionDataSet t1 = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionDataSet t2 = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); t2.applyTransform(new LinearTransform(t2, 1, 10)); instance = instance.clone(); instance.train(t1); KernelRidgeRegression result = instance.clone(); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), result.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*0.5); result.train(t2); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), instance.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*0.5); for (int i = 0; i < t2.size(); i++) assertEquals(t2.getTargetValue(i), result.regress(t2.getDataPoint(i)), t2.getTargetValues().mean()*0.5); } }
3,909
29.546875
118
java
JSAT
JSAT-master/JSAT/test/jsat/regression/NadarayaWatsonTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.regression; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.TestTools; import jsat.datatransform.LinearTransform; import jsat.distributions.multivariate.MetricKDE; import jsat.distributions.multivariate.MultivariateKDE; import jsat.distributions.multivariate.ProductKDE; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class NadarayaWatsonTest { public NadarayaWatsonTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); for(MultivariateKDE kde : new MultivariateKDE[]{new MetricKDE(), new ProductKDE()}) { NadarayaWatson instance = new NadarayaWatson(kde); int tries = 3; do { if(TestTools.regressEvalLinear(instance)) break; } while(tries-->0); assertTrue(tries >= 0); } } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); for(MultivariateKDE kde : new MultivariateKDE[]{new MetricKDE(), new ProductKDE()}) { NadarayaWatson instance = new NadarayaWatson(kde); ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); int tries = 3; do { if(TestTools.regressEvalLinear(instance, ex)) break; } while(tries-->0); assertTrue(tries >= 0); ex.shutdownNow(); } } @Test public void testClone() { System.out.println("clone"); for(MultivariateKDE kde : new MultivariateKDE[]{new MetricKDE(), new ProductKDE()}) { NadarayaWatson instance = new NadarayaWatson(kde); RegressionDataSet t1 = FixedProblems.getLinearRegression(200, RandomUtil.getRandom()); RegressionDataSet t2 = FixedProblems.getLinearRegression(200, RandomUtil.getRandom()); t2.applyTransform(new LinearTransform(t2, 1, 10)); instance = instance.clone(); instance.train(t1); NadarayaWatson result = instance.clone(); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), result.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*1.7); result.train(t2); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), instance.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*1.7); for (int i = 0; i < t2.size(); i++) assertEquals(t2.getTargetValue(i), result.regress(t2.getDataPoint(i)), t2.getTargetValues().mean()*1.7); } } }
4,094
27.4375
122
java
JSAT
JSAT-master/JSAT/test/jsat/regression/OrdinaryKrigingTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.regression; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.datatransform.LinearTransform; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class OrdinaryKrigingTest { public OrdinaryKrigingTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); OrdinaryKriging instance = new OrdinaryKriging(new OrdinaryKriging.PowVariogram()); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); OrdinaryKriging instance = new OrdinaryKriging(new OrdinaryKriging.PowVariogram()); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testClone() { System.out.println("clone"); OrdinaryKriging instance = new OrdinaryKriging(new OrdinaryKriging.PowVariogram()); RegressionDataSet t1 = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionDataSet t2 = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); t2.applyTransform(new LinearTransform(t2, 1, 10)); instance = instance.clone(); instance.train(t1); OrdinaryKriging result = instance.clone(); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), result.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*0.5); result.train(t2); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), instance.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*0.5); for (int i = 0; i < t2.size(); i++) assertEquals(t2.getTargetValue(i), result.regress(t2.getDataPoint(i)), t2.getTargetValues().mean()*0.5); } }
3,854
29.354331
118
java
JSAT
JSAT-master/JSAT/test/jsat/regression/RANSACTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.regression; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.datatransform.LinearTransform; import jsat.distributions.kernels.LinearKernel; import jsat.linear.DenseVector; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class RANSACTest { public RANSACTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); RANSAC instance = new RANSAC(new KernelRLS(new LinearKernel(1), 1e-1), 10, 20, 40, 5); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); for(int i = 0; i < 20; i++) train.addDataPoint(DenseVector.random(train.getNumNumericalVars()), train.getTargetValues().mean()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); RANSAC instance = new RANSAC(new KernelRLS(new LinearKernel(1), 1e-1), 10, 20, 40, 5); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); for(int i = 0; i < 20; i++) train.addDataPoint(DenseVector.random(train.getNumNumericalVars()), train.getTargetValues().mean()); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testClone() { System.out.println("clone"); RANSAC instance = new RANSAC(new KernelRLS(new LinearKernel(1), 1e-1), 10, 20, 40, 5); RegressionDataSet t1 = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); for(int i = 0; i < 20; i++) t1.addDataPoint(DenseVector.random(t1.getNumNumericalVars()), t1.getTargetValues().mean()); RegressionDataSet t2 = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); t2.applyTransform(new LinearTransform(t2, 1, 10)); instance = instance.clone(); instance.train(t1); RANSAC result = instance.clone(); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), result.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()); result.train(t2); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), instance.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()); for (int i = 0; i < t2.size(); i++) assertEquals(t2.getTargetValue(i), result.regress(t2.getDataPoint(i)), t2.getTargetValues().mean()*0.5); } }
4,346
31.2
116
java
JSAT
JSAT-master/JSAT/test/jsat/regression/RidgeRegressionTest.java
package jsat.regression; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.DataPointPair; import jsat.utils.SystemInfo; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class RidgeRegressionTest { public RidgeRegressionTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrain_RegressionDataSet_Executor() { System.out.println("train"); Random rand = new Random(2); for(RidgeRegression.SolverMode mode : RidgeRegression.SolverMode.values()) { RidgeRegression regressor = new RidgeRegression(1e-9, mode); regressor.train(FixedProblems.getLinearRegression(400, rand), true); for(DataPointPair<Double> dpp : FixedProblems.getLinearRegression(100, new Random(3)).getAsDPPList()) { double truth = dpp.getPair(); double pred = regressor.regress(dpp.getDataPoint()); double relErr = (truth-pred)/truth; assertEquals(0.0, relErr, 0.05); } } } @Test public void testTrain_RegressionDataSet() { System.out.println("train"); Random rand = new Random(2); for(RidgeRegression.SolverMode mode : RidgeRegression.SolverMode.values()) { RidgeRegression regressor = new RidgeRegression(1e-9, mode); regressor.train(FixedProblems.getLinearRegression(400, rand)); for(DataPointPair<Double> dpp : FixedProblems.getLinearRegression(100, new Random(3)).getAsDPPList()) { double truth = dpp.getPair(); double pred = regressor.regress(dpp.getDataPoint()); double relErr = (truth-pred)/truth; assertEquals(0.0, relErr, 0.05); } } } }
2,376
24.287234
113
java
JSAT
JSAT-master/JSAT/test/jsat/regression/StochasticGradientBoostingTest.java
/* * Copyright (C) 2015 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.regression; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.classifiers.trees.DecisionStump; import jsat.classifiers.trees.DecisionTree; import jsat.datatransform.LinearTransform; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff <[email protected]> */ public class StochasticGradientBoostingTest { public StochasticGradientBoostingTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); StochasticGradientBoosting instance = new StochasticGradientBoosting(new DecisionTree(), 50); RegressionDataSet train = FixedProblems.get2DLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.get2DLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); StochasticGradientBoosting instance = new StochasticGradientBoosting(new DecisionTree(), 50); RegressionDataSet train = FixedProblems.get2DLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet test = FixedProblems.get2DLinearRegression(100, RandomUtil.getRandom()); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.25); } @Test public void testClone() { System.out.println("clone"); StochasticGradientBoosting instance = new StochasticGradientBoosting(new DecisionTree(), 50); RegressionDataSet t1 = FixedProblems.get2DLinearRegression(500, RandomUtil.getRandom()); RegressionDataSet t2 = FixedProblems.get2DLinearRegression(100, RandomUtil.getRandom()); t2.applyTransform(new LinearTransform(t2, 1, 10)); instance = instance.clone(); instance.train(t1); StochasticGradientBoosting result = instance.clone(); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), result.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*0.5); result.train(t2); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), instance.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()*0.5); for (int i = 0; i < t2.size(); i++) assertEquals(t2.getTargetValue(i), result.regress(t2.getDataPoint(i)), t2.getTargetValues().mean()*0.5); } }
4,018
30.155039
118
java
JSAT
JSAT-master/JSAT/test/jsat/regression/StochasticRidgeRegressionTest.java
package jsat.regression; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.FixedProblems; import jsat.datatransform.DenseSparceTransform; import jsat.datatransform.LinearTransform; import jsat.linear.DenseVector; import jsat.math.decayrates.LinearDecay; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class StochasticRidgeRegressionTest { public StochasticRidgeRegressionTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testTrainC_RegressionDataSet() { System.out.println("train"); for(int batchSize : new int[]{1, 10, 20}) { StochasticRidgeRegression instance = new StochasticRidgeRegression(1e-9, 40, batchSize, 0.01); instance.setEpochs(100); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); LinearTransform lt = new LinearTransform(train); train.applyTransform(lt); for(int i = 0; i < 20; i++) train.addDataPoint(DenseVector.random(train.getNumNumericalVars()), train.getTargetValues().mean()); if(batchSize == 10) train.applyTransform(new DenseSparceTransform(1)); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); test.applyTransform(lt); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.35); } } @Test public void testTrainC_RegressionDataSet_ExecutorService() { System.out.println("train"); for(int batchSize : new int[]{1, 10, 20}) { StochasticRidgeRegression instance = new StochasticRidgeRegression(1e-9, 40, batchSize, 0.01); instance.setEpochs(100); RegressionDataSet train = FixedProblems.getLinearRegression(500, RandomUtil.getRandom()); LinearTransform lt = new LinearTransform(train); train.applyTransform(lt); for(int i = 0; i < 20; i++) train.addDataPoint(DenseVector.random(train.getNumNumericalVars()), train.getTargetValues().mean()); if(batchSize == 10) train.applyTransform(new DenseSparceTransform(1)); RegressionDataSet test = FixedProblems.getLinearRegression(100, RandomUtil.getRandom()); test.applyTransform(lt); RegressionModelEvaluation rme = new RegressionModelEvaluation(instance, train, true); rme.evaluateTestSet(test); assertTrue(rme.getMeanError() <= test.getTargetValues().mean() * 0.35); } } @Test public void testClone() { System.out.println("clone"); for(int batchSize : new int[]{1, 10, 20}) { StochasticRidgeRegression instance = new StochasticRidgeRegression(1e-9, 40, batchSize, 0.01); instance.setEpochs(100); RegressionDataSet t1 = FixedProblems.getLinearRegression(5000, RandomUtil.getRandom()); for(int i = 0; i < 20; i++) t1.addDataPoint(DenseVector.random(t1.getNumNumericalVars()), t1.getTargetValues().mean()); RegressionDataSet t2 = FixedProblems.getLinearRegression(1000, RandomUtil.getRandom()); t2.applyTransform(new LinearTransform(t2, -1, 1)); if(batchSize == 10) { instance.setLearningDecay(new LinearDecay(0.5, 500));//just to exercise another part of the code t1.applyTransform(new DenseSparceTransform(1)); } instance = instance.clone(); instance.train(t1); StochasticRidgeRegression result = instance.clone(); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), result.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()); result.train(t2); for (int i = 0; i < t1.size(); i++) assertEquals(t1.getTargetValue(i), instance.regress(t1.getDataPoint(i)), t1.getTargetValues().mean()); for (int i = 0; i < t2.size(); i++) assertEquals(t2.getTargetValue(i), result.regress(t2.getDataPoint(i)), t2.getTargetValues().mean()*0.5); } } }
4,917
32.455782
120
java
JSAT
JSAT-master/JSAT/test/jsat/regression/evaluation/CoefficientOfDeterminationTest.java
package jsat.regression.evaluation; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class CoefficientOfDeterminationTest { public CoefficientOfDeterminationTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class CoefficientOfDetermination. */ @Test public void testGetScore() { System.out.println("getScore"); CoefficientOfDetermination scorer = new CoefficientOfDetermination(); CoefficientOfDetermination otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertTrue(scorer.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); double[] pred = new double[] { 0, 2, 4, 6, 8, 9 }; double[] truth = new double[] { 0.5, 2, 3, 1, 8.5, 10 }; scorer.prepare(); otherHalf.prepare(); for(int i = 0; i < pred.length/2; i++) scorer.addResult(pred[i], truth[i], 1); for(int i = pred.length/2; i < pred.length; i++) otherHalf.addResult(pred[i], truth[i], 1); scorer.addResults(otherHalf); assertEquals(0.69894, scorer.getScore(), 1e-1); scorer = scorer.clone(); assertEquals(0.69894, scorer.getScore(), 1e-1); } }
1,912
20.494382
77
java
JSAT
JSAT-master/JSAT/test/jsat/regression/evaluation/MeanAbsoluteErrorTest.java
package jsat.regression.evaluation; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MeanAbsoluteErrorTest { public MeanAbsoluteErrorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class MeanAbsoluteError. */ @Test public void testGetScore() { System.out.println("getScore"); MeanAbsoluteError scorer = new MeanAbsoluteError(); MeanAbsoluteError otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertTrue(scorer.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); double[] pred = new double[] { 0, 2, 4, 6, 8, 9 }; double[] truth = new double[] { 0.5, 2, 3, 1, 8.5, 10 }; scorer.prepare(); otherHalf.prepare(); for(int i = 0; i < pred.length/2; i++) scorer.addResult(pred[i], truth[i], 1); for(int i = pred.length/2; i < pred.length; i++) otherHalf.addResult(pred[i], truth[i], 1); scorer.addResults(otherHalf); assertEquals((0.5+1+5+0.5+1)/6, scorer.getScore(), 1e-4); assertEquals((0.5+1+5+0.5+1)/6, scorer.clone().getScore(), 1e-4); } }
1,808
20.795181
73
java
JSAT
JSAT-master/JSAT/test/jsat/regression/evaluation/MeanSquaredErrorTest.java
package jsat.regression.evaluation; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class MeanSquaredErrorTest { public MeanSquaredErrorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class MeanSquaredError. */ @Test public void testGetScore() { System.out.println("getScore"); MeanSquaredError scorer = new MeanSquaredError(); MeanSquaredError otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertTrue(scorer.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); double[] pred = new double[] { 0, 2, 4, 6, 8, 9 }; double[] truth = new double[] { 0.5, 2, 3, 1, 8.5, 10 }; scorer.prepare(); otherHalf.prepare(); for(int i = 0; i < pred.length/2; i++) scorer.addResult(pred[i], truth[i], 1); for(int i = pred.length/2; i < pred.length; i++) otherHalf.addResult(pred[i], truth[i], 1); scorer.addResults(otherHalf); assertEquals((0.25+1+25+0.25+1)/6, scorer.getScore(), 1e-4); assertEquals((0.25+1+25+0.25+1)/6, scorer.clone().getScore(), 1e-4); scorer.setRMSE(true); assertEquals(Math.sqrt((0.25+1+25+0.25+1)/6), scorer.getScore(), 1e-4); assertEquals(Math.sqrt((0.25+1+25+0.25+1)/6), scorer.clone().getScore(), 1e-4); } }
2,006
22.337209
87
java
JSAT
JSAT-master/JSAT/test/jsat/regression/evaluation/RelativeAbsoluteErrorTest.java
package jsat.regression.evaluation; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class RelativeAbsoluteErrorTest { public RelativeAbsoluteErrorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class RelativeAbsoluteError. */ @Test public void testGetScore() { System.out.println("getScore"); RelativeAbsoluteError scorer = new RelativeAbsoluteError(); RelativeAbsoluteError otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertTrue(scorer.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); double[] pred = new double[] { 0, 2, 4, 6, 8, 9 }; double[] truth = new double[] { 0.5, 2, 3, 1, 8.5, 10 }; scorer.prepare(); otherHalf.prepare(); for(int i = 0; i < pred.length/2; i++) scorer.addResult(pred[i], truth[i], 1); for(int i = pred.length/2; i < pred.length; i++) otherHalf.addResult(pred[i], truth[i], 1); scorer.addResults(otherHalf); assertEquals((0.5+1+5+0.5+1)/20.3333333, scorer.getScore(), 1e-4); assertEquals((0.5+1+5+0.5+1)/20.3333333, scorer.clone().getScore(), 1e-4); } }
1,854
21.349398
82
java
JSAT
JSAT-master/JSAT/test/jsat/regression/evaluation/RelativeSquaredErrorTest.java
package jsat.regression.evaluation; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class RelativeSquaredErrorTest { public RelativeSquaredErrorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of getScore method, of class RelativeSquaredError. */ @Test public void testGetScore() { System.out.println("getScore"); RelativeSquaredError scorer = new RelativeSquaredError(); RelativeSquaredError otherHalf = scorer.clone(); assertEquals(scorer, otherHalf); assertEquals(scorer.hashCode(), otherHalf.hashCode()); assertTrue(scorer.lowerIsBetter()); assertFalse(scorer.equals("")); assertFalse(scorer.hashCode() == "".hashCode()); double[] pred = new double[] { 0, 2, 4, 6, 8, 9 }; double[] truth = new double[] { 0.5, 2, 3, 1, 8.5, 10 }; scorer.prepare(); otherHalf.prepare(); for(int i = 0; i < pred.length/2; i++) scorer.addResult(pred[i], truth[i], 1); for(int i = pred.length/2; i < pred.length; i++) otherHalf.addResult(pred[i], truth[i], 1); scorer.addResults(otherHalf); assertEquals((0.25+1+25+0.25+1)/82.334, scorer.getScore(), 1e-4); assertEquals((0.25+1+25+0.25+1)/82.334, scorer.clone().getScore(), 1e-4); } }
1,838
21.156627
81
java
JSAT
JSAT-master/JSAT/test/jsat/text/stemming/LovinsStemmerTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.text.stemming; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class LovinsStemmerTest { public LovinsStemmerTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of stem method, of class LovinsStemmer. */ @Test public void testStem() { System.out.println("stem"); String[] origSent = ("such an analysis can reveal features that are not easily visible " + "from the variations in the individual genes and can lead to a picture of " + "expression that is more biologically transparent and accessible to " + "interpretation").split(" "); LovinsStemmer instance = new LovinsStemmer(); String[] expResult = ("such an analys can reve featur that ar not eas vis from th " + "vari in th individu gen and can lead to a pictur of expres that is mor " + "biolog transpar and acces to interpres").split(" "); for(int i = 0; i < origSent.length; i++) assertEquals(expResult[i], instance.stem(origSent[i])); } }
2,174
26.884615
96
java
JSAT
JSAT-master/JSAT/test/jsat/text/stemming/PaiceHuskStemmerTest.java
package jsat.text.stemming; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class PaiceHuskStemmerTest { public static String[] original; public static String[] expected; public PaiceHuskStemmerTest() { } @BeforeClass public static void setUpClass() { original = new String[] { "am", "is", "are", "be", "being", "been", "have", "has", "having", "had", "do", "does", "doing", "did", "hello", "ear", "owel", "owed", "police", "policy", "dog", "cat", "sinner", "sinners", "discrimination", "counties", "county", "country", "countries", "fighters", "civilization", "civilizations", "currencies", "constructed", "constructing", "stemming", "stemmer", "connection", "connections", "connective", "connected", "connecting", "fortification", "electricity", "fantastically", "contemplative", "conspirator", "relativity", "instinctively", "incapability", "charitably", "famously", }; expected = new String[] { "am", "is", "ar", "be", "being", "been", "hav", "has", "hav", "had", "do", "doe", "doing", "did", "hello", "ear", "owel", "ow", "pol", "policy", "dog", "cat", "sin", "sin", "discrimin", "county", "county", "country", "country", "fight", "civil", "civil", "cur", "construct", "construct", "stem", "stem", "connect", "connect", "connect", "connect", "connect", "fort", "elect", "fantast", "contempl", "conspir", "rel", "instinct", "incap", "charit", "fam", }; } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of stem method, of class PaiceHuskStemmer. */ @Test public void testStem() { System.out.println("stem"); PaiceHuskStemmer stemmer = new PaiceHuskStemmer(); for (int i = 0; i < original.length; i++) assertEquals("Stemming results incorrect for \"" + original[i] + "\"", expected[i], stemmer.stem(original[i])); } }
3,465
19.388235
123
java
JSAT
JSAT-master/JSAT/test/jsat/text/stemming/PorterStemmerTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.text.stemming; import java.util.LinkedHashMap; import java.util.Map; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class PorterStemmerTest { private static final Map<String, String> testCases = new LinkedHashMap<String, String>(); public PorterStemmerTest() { } @BeforeClass public static void setUpClass() { testCases.put("a", "a"); testCases.put("caresses", "caress"); testCases.put("ponies", "poni"); testCases.put("ties", "ti"); testCases.put("carress", "carress"); testCases.put("cats", "cat"); testCases.put("feed", "feed"); testCases.put("agreed", "agre"); testCases.put("plastered", "plaster"); testCases.put("bled", "bled"); testCases.put("motoring", "motor"); testCases.put("sing", "sing"); testCases.put("conflated", "conflat"); testCases.put("troubling", "troubl"); testCases.put("sized", "size"); testCases.put("falling", "fall"); testCases.put("happy", "happi"); testCases.put("sky", "sky"); testCases.put("relational", "relat"); testCases.put("conditional", "condit"); testCases.put("vileli", "vile"); testCases.put("analogousli", "analog"); testCases.put("vietnamization", "vietnam"); testCases.put("predication", "predic"); testCases.put("operator", "oper"); testCases.put("feudalism", "feudal"); testCases.put("decisiveness", "decis"); testCases.put("hopefulness", "hope"); testCases.put("callousness", "callous"); testCases.put("formaliti", "formal"); testCases.put("sensitiviti", "sensit"); testCases.put("sensibiliti", "sensibl"); testCases.put("triplicate", "triplic"); testCases.put("formative", "form"); testCases.put("formalize", "formal"); testCases.put("electriciti", "electr"); testCases.put("electrical", "electr"); testCases.put("hopeful", "hope"); testCases.put("goodness", "good"); testCases.put("revival", "reviv"); testCases.put("allowance", "allow"); testCases.put("inference", "infer"); testCases.put("airliner", "airlin"); testCases.put("gyroscopic", "gyroscop"); testCases.put("adjustable", "adjust"); testCases.put("defensible", "defens"); testCases.put("irritant", "irrit"); testCases.put("replacement", "replac"); testCases.put("adjustment", "adjust"); testCases.put("dependent", "depend"); testCases.put("adoption", "adopt"); testCases.put("homologou", "homolog"); testCases.put("communism", "commun"); testCases.put("activate", "activ"); testCases.put("angulariti", "angular"); testCases.put("homologous", "homolog"); testCases.put("effective", "effect"); testCases.put("bowdlerize", "bowdler"); testCases.put("probate", "probat"); testCases.put("rate", "rate"); testCases.put("cease", "ceas"); testCases.put("controll", "control"); testCases.put("roll", "roll"); testCases.put("ions", "ion"); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of stem method, of class PorterStemmer. */ @Test public void testStem() { System.out.println("stem"); PorterStemmer instance = new PorterStemmer(); for(Map.Entry<String, String> entry : testCases.entrySet()) assertEquals("Looking for '" + entry.getValue() + "' from '" + entry.getKey() + "'", entry.getValue(), instance.stem(entry.getKey())); } }
4,668
33.080292
146
java
JSAT
JSAT-master/JSAT/test/jsat/text/tokenizer/NGramTokenizerTest.java
package jsat.text.tokenizer; import java.util.Arrays; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class NGramTokenizerTest { public NGramTokenizerTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of tokenize method, of class NGramTokenizer. */ @Test public void testTokenize_String() { System.out.println("tokenize"); String input = "the dog barked"; NaiveTokenizer naiveToken = new NaiveTokenizer(); NGramTokenizer instance = new NGramTokenizer(3, naiveToken, true); List<String> expResult = Arrays.asList("the", "dog", "barked", "the dog", "dog barked", "the dog barked"); List<String> result = instance.tokenize(input); assertEquals(expResult.size(), result.size()); for(int i = 0; i < expResult.size(); i++) assertEquals(expResult.get(i), result.get(i)); } }
1,311
19.825397
114
java
JSAT
JSAT-master/JSAT/test/jsat/text/topicmodel/OnlineLDAsviTest.java
package jsat.text.topicmodel; import jsat.text.topicmodel.OnlineLDAsvi; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jsat.SimpleDataSet; import jsat.classifiers.CategoricalData; import jsat.classifiers.DataPoint; import jsat.distributions.multivariate.Dirichlet; import jsat.linear.*; import jsat.utils.IntSet; import jsat.utils.SystemInfo; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class OnlineLDAsviTest { private static final int rows = 5; public OnlineLDAsviTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of model method, of class OnlineLDAsvi. */ @Test public void testModel() { System.out.println("model"); ExecutorService ex = Executors.newFixedThreadPool(SystemInfo.LogicalCores); for(int iters = 0; iters < 2; iters++)//controls whether parallel or single threaded verison is run { int attempts = 3; do { //create the basis set to sample from List<Vec> basis = new ArrayList<Vec>(); for(int i = 0; i < rows; i++) { Vec b0 = new SparseVector(rows*rows); for(int a = 0; a < rows; a++) b0.set(i*5+a, 1.0); Vec b1 = new SparseVector(rows*rows); for(int a = 0; a < rows; a++) b1.set(a*rows+i, 1.0); b0.mutableDivide(b0.sum()); b1.mutableDivide(b1.sum()); basis.add(b0); basis.add(b1); } //create the training set double alpha = 0.1; List<DataPoint> docs = new ArrayList<DataPoint>(); Dirichlet dirichlet = new Dirichlet(new ConstantVector(alpha, basis.size())); Random rand = RandomUtil.getRandom(); for(Vec topicSample : dirichlet.sample(100000, rand)) { Vec doc = new DenseVector(basis.get(0).length()); //sample 40 times for(int i = 0; i < 100; i++) { double topicRand = rand.nextDouble(); int topic = 0; double sum = topicSample.get(0); while(sum < topicRand) { sum+= topicSample.get(++topic); } //sample and index from the topic Vec basisVec = basis.get(topic); int randBasisWord = rand.nextInt(basisVec.nnz()); int pos = 0; for(IndexValue iv : basisVec) { if(pos == randBasisWord) { doc.increment(iv.getIndex() , 1.0); break; } pos++; } } docs.add(new DataPoint(doc, new int[0], new CategoricalData[0])); } // OnlineLDAsvi lda = new OnlineLDAsvi(); lda.setAlpha(0.1); lda.setEta(1.0/basis.size()); lda.setKappa(0.6); lda.setMiniBatchSize(256); lda.setTau0(64); lda.setEpochs(1); if(iters == 0) lda.model(new SimpleDataSet(docs), basis.size()); else lda.model(new SimpleDataSet(docs), basis.size(), ex); if(passTest(lda, basis, dirichlet, rand)) break; //you did it , skip out of here } while(attempts-- > 0); assertTrue(attempts > 0); } ex.shutdown(); } public boolean passTest(OnlineLDAsvi lda, List<Vec> basis, Dirichlet dirichlet, Random rand) { //map from the LDA topics to the basis topics Map<Integer, Integer> ldaTopicToBasis = new HashMap<Integer, Integer>(); for(int i = 0; i < lda.getK(); i++) { Vec topic = lda.getTopicVec(i); int minIndx = 0; double minDist = topic.subtract(basis.get(0)).pNorm(2); for(int j = 1; j < basis.size(); j++) { double dist = topic.subtract(basis.get(j)).pNorm(2); if(dist <minDist) { minDist = dist; minIndx = j; } } ldaTopicToBasis.put(i, minIndx); if(minDist > 0.025)//values of around 0.1 are when failure happens return false; } //make sure no basis was closest to 2 or more topics if(basis.size() != new IntSet(ldaTopicToBasis.values()).size()) return false; //make sure that computing the topic distirbution works for(Vec topicSample : dirichlet.sample(100, rand)) { Vec doc = new DenseVector(basis.get(0).length()); //sample 40 times for(int i = 0; i < 100; i++) { double topicRand = rand.nextDouble(); int topic = 0; double sum = topicSample.get(0); while(sum < topicRand) { sum+= topicSample.get(++topic); } //sample and index from the topic Vec basisVec = basis.get(topic); int randBasisWord = rand.nextInt(basisVec.nnz()); int pos = 0; for(IndexValue iv : basisVec) { if(pos == randBasisWord) { doc.increment(iv.getIndex(), 1.0); break; } pos++; } } Vec ldaTopics = lda.getTopics(doc); for(int i = 0; i < ldaTopics.length(); i++) { double ldaVal = ldaTopics.get(i); if(ldaVal > 0.2) { if(Math.abs(topicSample.get(ldaTopicToBasis.get(i)) - ldaVal) > 0.25) return false; } } } return true; } }
7,061
29.704348
107
java
JSAT
JSAT-master/JSAT/test/jsat/utils/FibHeapTest.java
/* * Copyright (C) 2015 Edward Raff * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils; import java.util.*; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class FibHeapTest { public FibHeapTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testDecreaseKey() { System.out.println("decreaseKey"); FibHeap<Character> h1 = new FibHeap<Character>(); List<FibHeap.FibNode<Character>> nodes = new ArrayList<FibHeap.FibNode<Character>>(); List<Character> expectedOrder = new ArrayList<Character>(); for(char c = 'A'; c < 'z'; c++) { nodes.add(h1.insert(c, c)); expectedOrder.add(0, c); } Collections.shuffle(nodes); for(FibHeap.FibNode<Character> node : nodes) h1.decreaseKey(node, -node.value); assertEquals(expectedOrder.size(), h1.size()); int pos = 0; while(h1.size() > 0) { FibHeap.FibNode<Character> min = h1.removeMin(); assertEquals(expectedOrder.get(pos), min.value); pos++; } } /** * Test of union method, of class FibHeap. */ @Test public void testUnion() { System.out.println("union"); FibHeap<String> h1 = new FibHeap<String>(); FibHeap<String> h2 = new FibHeap<String>(); double value = 0.0; int counter= 0; List<String> added = new ArrayList<String>(); for(char c = 'A'; c <= 'Z'; c++) { counter++; String s = Character.toString(c); if(c % 2 == 0) h1.insert(s, value--); else h2.insert(s, value--); added.add(0, s); // if(c % 2 == 0) // h1.insert(s, value++); // else // h2.insert(s, value++); // added.add(s); } FibHeap<String> heap = FibHeap.union(h1, h2); assertEquals(counter, heap.size()); counter = 0; while(heap.size() > 0) { String s = heap.removeMin().value; assertEquals(added.get(counter), s); counter++; } } /** * Test of getMinKey method, of class FibHeap. */ @Test public void testGetMinKey() { System.out.println("getMinKey"); FibHeap<String> heap = new FibHeap<String>(); FibHeap.FibNode<String> min; assertEquals(0, heap.size()); heap.insert("A", 1.0); heap.insert("B", 0.5); heap.insert("C", 2.0); assertEquals(3, heap.size()); assertEquals("B", heap.getMinValue()); min = heap.removeMin(); assertEquals("B", min.value); assertEquals(2, heap.size()); assertEquals("A", heap.getMinValue()); min = heap.removeMin(); assertEquals("A", min.value); assertEquals(1, heap.size()); assertEquals("C", heap.getMinValue()); min = heap.removeMin(); assertEquals("C", min.value); assertEquals(0, heap.size()); } @Test public void testRandom() { System.out.println("testRandp,"); FibHeap<Long> heap = new FibHeap<Long>(); SortedMap<Long, Double> map = new TreeMap<Long, Double>(); Map<Long, FibHeap.FibNode<Long>> heapNodes = new HashMap<Long, FibHeap.FibNode<Long>>(); Random rand = RandomUtil.getRandom(); for(int trials = 0; trials < 10; trials++) for(int maxSize = 1; maxSize < 2000; maxSize*=2) { while(map.size() < maxSize) { if(map.size() > 0 && rand.nextDouble() < 0.1) {//ocasionally remove the min eliment long entry = map.firstKey(); double value = map.get(entry); for( Map.Entry<Long, Double> mapEntry : map.entrySet()) if(mapEntry.getValue() < value) { entry = mapEntry.getKey(); value = mapEntry.getValue(); } map.remove(entry); FibHeap.FibNode<Long> min = heap.removeMin(); heapNodes.remove(entry); assertEquals(entry, min.value.longValue()); assertEquals(value, min.key, 0.0); } else if(map.size() > 0 && rand.nextDouble() < 0.4) {//lest decrease a random key's value long partitioner = rand.nextLong(); SortedMap<Long, Double> subMap = map.tailMap(partitioner); long valToDecrease; if(subMap.isEmpty()) { subMap = map.headMap(partitioner); valToDecrease = map.lastKey(); } else { valToDecrease = map.firstKey(); } double newVal = map.get(valToDecrease)/2; map.put(valToDecrease, newVal); heap.decreaseKey(heapNodes.get(valToDecrease), newVal); } //then add something long entry = rand.nextLong(); double value = rand.nextDouble(); while(map.containsKey(entry)) entry = rand.nextLong(); map.put(entry, value); heapNodes.put(entry, heap.insert(entry, value)); } //its full, now lets remove everything! while(map.size() > 0) { long entry = map.firstKey(); double value = map.get(entry); for (Map.Entry<Long, Double> mapEntry : map.entrySet()) if (mapEntry.getValue() < value) { entry = mapEntry.getKey(); value = mapEntry.getValue(); } map.remove(entry); FibHeap.FibNode<Long> min = heap.removeMin(); heapNodes.remove(entry); assertEquals(entry, min.value.longValue()); assertEquals(value, min.key, 0.0); } } } }
7,725
29.179688
96
java
JSAT
JSAT-master/JSAT/test/jsat/utils/IndexTableTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.utils; import java.util.List; import java.util.Arrays; import java.util.Comparator; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class IndexTableTest { static final double[] array = new double[] {9.0, 4.0, 3.0, 2.0, 1.0, 10.0, 11.0 }; static final Double[] arrayD = new Double[] {9.0, 4.0, 3.0, 2.0, 1.0, 10.0, 11.0 }; static final List<Double> list = Arrays.asList(arrayD); public IndexTableTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testSortD() { IndexTable idt = new IndexTable(array); for(int i = 0; i < idt.length()-1; i++) assertTrue(array[idt.index(i)] <= array[idt.index(i+1)]); } @Test public void testSortG() { IndexTable idt = new IndexTable(arrayD); for(int i = 0; i < idt.length()-1; i++) assertTrue(arrayD[idt.index(i)].compareTo(arrayD[idt.index(i+1)]) <= 0); } @Test public void testSortList() { IndexTable idt = new IndexTable(list); for(int i = 0; i < idt.length()-1; i++) assertTrue(list.get(idt.index(i)).compareTo(list.get(idt.index(i+1))) <= 0); } @Test public void testSortListComparator() { IndexTable idt = new IndexTable(list, new Comparator<Double>() { @Override public int compare(Double o1, Double o2) { return -o1.compareTo(o2); } }); for(int i = 0; i < idt.length()-1; i++) assertTrue(list.get(idt.index(i)).compareTo(list.get(idt.index(i+1))) >= 0); } @Test public void testApply_double() { IndexTable idt = new IndexTable(array); double[] test = Arrays.copyOf(array, array.length); idt.apply(test); for(int i = 0; i < test.length-1; i++) assertTrue(test[i] <= test[i+1]); } @Test public void testApply_List() { IndexTable idt = new IndexTable(array); List<Double> test = new DoubleList(); for(double d : array) test.add(d); idt.apply(test); for(int i = 0; i < test.size()-1; i++) assertTrue(test.get(i) <= test.get(i+1)); } @Test public void testSwap() { System.out.println("swap"); int i = 0; int j = 1; IndexTable idx = new IndexTable(array); double di = array[idx.index(i)]; double dj = array[idx.index(j)]; idx.swap(i, j); assertTrue(di == array[idx.index(j)]); assertTrue(dj == array[idx.index(i)]); assertTrue(di != dj); idx.swap(j, i); assertTrue(di != array[idx.index(j)]); assertTrue(dj != array[idx.index(i)]); assertTrue(di == array[idx.index(i)]); assertTrue(dj == array[idx.index(j)]); } }
3,382
24.059259
88
java
JSAT
JSAT-master/JSAT/test/jsat/utils/IntDoubleMapArrayTest.java
package jsat.utils; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * * @author Edward Raff */ public class IntDoubleMapArrayTest { private static final int TEST_SIZE = 2000; private static final int MAX_INDEX = 10000; Random rand; public IntDoubleMapArrayTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { rand = RandomUtil.getRandom(); } @After public void tearDown() { } /** * Test of put method, of class IntDoubleMap. */ @Test public void testPut_Integer_Double() { System.out.println("put"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMapArray idMap = new IntDoubleMapArray(); for(int i = 0; i < TEST_SIZE; i++) { key = rand.nextInt(MAX_INDEX); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); //will call the iterator remove on everythin removeEvenByIterator(idMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, idMap); for(Entry<Integer, Double> entry : idMap.entrySet()) entry.setValue(1.0); for(Entry<Integer, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, idMap); ///again, random keys - and make them colide truthMap = new HashMap<Integer, Double>(); idMap = new IntDoubleMapArray(); for(int i = 0; i < TEST_SIZE; i++) { key = Integer.valueOf(rand.nextInt(50000)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); //will call the iterator remove on everythin removeEvenByIterator(idMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, idMap); for(Entry<Integer, Double> entry : idMap.entrySet()) entry.setValue(1.0); for(Entry<Integer, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, idMap); } private void removeEvenByIterator(Iterator<Entry<Integer, Double>> iterator) { while(iterator.hasNext()) { Entry<Integer, Double> entry = iterator.next(); if(entry.getKey() % 2 == 0) iterator.remove(); } } private void assertEntriesAreEqual(Map<Integer, Double> truthMap, IntDoubleMapArray idMap) { assertEquals(truthMap.size(), idMap.size()); Map<Integer, Double> copy = new HashMap<Integer, Double>(); for(Entry<Integer, Double> entry : truthMap.entrySet()) assertEquals(entry.getValue(), idMap.get(entry.getKey())); int observed = 0; for(Entry<Integer, Double> entry : idMap.entrySet()) { copy.put(entry.getKey(), entry.getValue()); observed++; assertTrue(truthMap.containsKey(entry.getKey())); assertEquals(truthMap.get(entry.getKey()), entry.getValue()); } assertEquals(truthMap.size(), observed); //make sure we put every value into the copy! for(Entry<Integer, Double> entry : truthMap.entrySet()) assertEquals(truthMap.get(entry.getKey()), copy.get(entry.getKey())); } /** * Test of put method, of class IntDoubleMap. */ @Test public void testPut_int_double() { System.out.println("put"); int key; double value; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMapArray idMap = new IntDoubleMapArray(); for(int i = 0; i < TEST_SIZE; i++) { key = rand.nextInt(MAX_INDEX); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); if(prev.isNaN()) prev = null; assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); //will call the iterator remove on everythin removeEvenByIterator(idMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, idMap); for(Entry<Integer, Double> entry : idMap.entrySet()) entry.setValue(1.0); for(Entry<Integer, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, idMap); ///again, random keys - and make them colide truthMap = new HashMap<Integer, Double>(); idMap = new IntDoubleMapArray(); for(int i = 0; i < TEST_SIZE; i++) { key = Integer.valueOf(rand.nextInt(50000)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); if(prev.isNaN()) prev = null; assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); //will call the iterator remove on everythin removeEvenByIterator(idMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, idMap); for(Entry<Integer, Double> entry : idMap.entrySet()) entry.setValue(1.0); for(Entry<Integer, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, idMap); } /** * Test of increment method, of class IntDoubleMap. */ @Test public void testIncrement() { System.out.println("increment"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMapArray idMap = new IntDoubleMapArray(); int MAX = TEST_SIZE/2; int times =0; for(int i = 0; i < MAX; i++) { key = Integer.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); if(truthMap.containsKey(key)) times++; Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); if(prev == null && prevTruth != null) System.out.println(idMap.put(key, value)); assertEquals(prevTruth, prev); if(idMap.size() != truthMap.size()) { System.out.println(); } assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); for(Entry<Integer, Double> entry : truthMap.entrySet()) { double delta = Double.valueOf(rand.nextInt(100)); double trueNewValue =entry.getValue()+delta; entry.setValue(trueNewValue); double newValue = idMap.increment(entry.getKey(), delta); assertEquals(trueNewValue, newValue, 0.0); } for(int i = MAX; i < MAX*2; i++) { key = Integer.valueOf(i);//force it to be new value = Double.valueOf(rand.nextInt(1000)); truthMap.put(key, value); double ldNew =idMap.increment(key, value); assertEquals(value.doubleValue(), ldNew, 0.0); } assertEntriesAreEqual(truthMap, idMap); } /** * Test of remove method, of class IntDoubleMap. */ @Test public void testRemove_Object() { System.out.println("remove"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMapArray ldMap = new IntDoubleMapArray(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Integer.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); for(int i = 0; i < MAX/4; i++) { key = Integer.valueOf(rand.nextInt(MAX)); Double prevTruth = truthMap.remove(key); Double prev = ldMap.remove(key); if(prevTruth == null && prev != null) prev = ldMap.remove(key); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); } /** * Test of remove method, of class IntDoubleMap. */ @Test public void testRemove_int() { System.out.println("remove"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMapArray idMap = new IntDoubleMapArray(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Integer.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); for(int i = 0; i < MAX/4; i++) { key = Integer.valueOf(rand.nextInt(MAX)); Double prevTruth = truthMap.remove(key); Double prev = idMap.remove(key.intValue()); if(prev.isNaN()) prev = null; assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); } /** * Test of containsKey method, of class IntDoubleMap. */ @Test public void testContainsKey_Object() { System.out.println("containsKey"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMapArray idMap = new IntDoubleMapArray(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Integer.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); for(Integer keyInSet : truthMap.keySet()) assertTrue(idMap.containsKey(keyInSet)); for(long i = MAX+1; i < MAX*2; i++) assertFalse(idMap.containsKey(Long.valueOf(i))); } /** * Test of containsKey method, of class IntDoubleMap. */ @Test public void testContainsKey_int() { System.out.println("containsKey"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMapArray idMap = new IntDoubleMapArray(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Integer.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); for(Integer keyInSet : truthMap.keySet()) assertTrue(idMap.containsKey(keyInSet.intValue())); for(long i = MAX+1; i < MAX*2; i++) assertFalse(idMap.containsKey(i)); } }
13,915
29.855876
94
java
JSAT
JSAT-master/JSAT/test/jsat/utils/IntDoubleMapTest.java
package jsat.utils; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class IntDoubleMapTest { private static final int TEST_SIZE = 2000; Random rand; public IntDoubleMapTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { rand = RandomUtil.getRandom(); } @After public void tearDown() { } /** * Test of put method, of class IntDoubleMap. */ @Test public void testPut_Integer_Double() { System.out.println("put"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMap idMap = new IntDoubleMap(); for(int i = 0; i < TEST_SIZE; i++) { key = rand.nextInt(); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); //will call the iterator remove on everythin removeEvenByIterator(idMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, idMap); for(Entry<Integer, Double> entry : idMap.entrySet()) entry.setValue(1.0); for(Entry<Integer, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, idMap); ///again, random keys - and make them colide truthMap = new HashMap<Integer, Double>(); idMap = new IntDoubleMap(); for(int i = 0; i < TEST_SIZE; i++) { key = Integer.valueOf(rand.nextInt(50000)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); //will call the iterator remove on everythin removeEvenByIterator(idMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, idMap); for(Entry<Integer, Double> entry : idMap.entrySet()) entry.setValue(1.0); for(Entry<Integer, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, idMap); } private void removeEvenByIterator(Iterator<Entry<Integer, Double>> iterator) { while(iterator.hasNext()) { Entry<Integer, Double> entry = iterator.next(); if(entry.getKey() % 2 == 0) iterator.remove(); } } private void assertEntriesAreEqual(Map<Integer, Double> truthMap, IntDoubleMap idMap) { assertEquals(truthMap.size(), idMap.size()); Map<Integer, Double> copy = new HashMap<Integer, Double>(); for(Entry<Integer, Double> entry : truthMap.entrySet()) assertEquals(entry.getValue(), idMap.get(entry.getKey())); int observed = 0; for(Entry<Integer, Double> entry : idMap.entrySet()) { copy.put(entry.getKey(), entry.getValue()); observed++; assertTrue(truthMap.containsKey(entry.getKey())); assertEquals(truthMap.get(entry.getKey()), entry.getValue()); } assertEquals(truthMap.size(), observed); //make sure we put every value into the copy! for(Entry<Integer, Double> entry : truthMap.entrySet()) assertEquals(truthMap.get(entry.getKey()), copy.get(entry.getKey())); } /** * Test of put method, of class IntDoubleMap. */ @Test public void testPut_int_double() { System.out.println("put"); int key; double value; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMap idMap = new IntDoubleMap(); for(int i = 0; i < TEST_SIZE; i++) { key = rand.nextInt(); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); if(prev.isNaN()) prev = null; assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); //will call the iterator remove on everythin removeEvenByIterator(idMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, idMap); for(Entry<Integer, Double> entry : idMap.entrySet()) entry.setValue(1.0); for(Entry<Integer, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, idMap); ///again, random keys - and make them colide truthMap = new HashMap<Integer, Double>(); idMap = new IntDoubleMap(); for(int i = 0; i < TEST_SIZE; i++) { key = Integer.valueOf(rand.nextInt(50000)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); if(prev.isNaN()) prev = null; assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); //will call the iterator remove on everythin removeEvenByIterator(idMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, idMap); for(Entry<Integer, Double> entry : idMap.entrySet()) entry.setValue(1.0); for(Entry<Integer, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, idMap); } /** * Test of increment method, of class IntDoubleMap. */ @Test public void testIncrement() { System.out.println("increment"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMap idMap = new IntDoubleMap(); int MAX = TEST_SIZE/2; int times =0; for(int i = 0; i < MAX; i++) { key = Integer.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); if(truthMap.containsKey(key)) times++; Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); if(prev == null && prevTruth != null) System.out.println(idMap.put(key, value)); assertEquals(prevTruth, prev); if(idMap.size() != truthMap.size()) { System.out.println(); } assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); for(Entry<Integer, Double> entry : truthMap.entrySet()) { double delta = Double.valueOf(rand.nextInt(100)); double trueNewValue =entry.getValue()+delta; entry.setValue(trueNewValue); double newValue = idMap.increment(entry.getKey(), delta); assertEquals(trueNewValue, newValue, 0.0); } for(int i = MAX; i < MAX*2; i++) { key = Integer.valueOf(i);//force it to be new value = Double.valueOf(rand.nextInt(1000)); truthMap.put(key, value); double ldNew =idMap.increment(key, value); assertEquals(value.doubleValue(), ldNew, 0.0); } assertEntriesAreEqual(truthMap, idMap); } /** * Test of remove method, of class IntDoubleMap. */ @Test public void testRemove_Object() { System.out.println("remove"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMap ldMap = new IntDoubleMap(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Integer.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); for(int i = 0; i < MAX/4; i++) { key = Integer.valueOf(rand.nextInt(MAX)); Double prevTruth = truthMap.remove(key); Double prev = ldMap.remove(key); if(prevTruth == null && prev != null) prev = ldMap.remove(key); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); } /** * Test of remove method, of class IntDoubleMap. */ @Test public void testRemove_int() { System.out.println("remove"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMap idMap = new IntDoubleMap(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Integer.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); for(int i = 0; i < MAX/4; i++) { key = Integer.valueOf(rand.nextInt(MAX)); Double prevTruth = truthMap.remove(key); Double prev = idMap.remove(key.intValue()); if(prev.isNaN()) prev = null; assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); } /** * Test of containsKey method, of class IntDoubleMap. */ @Test public void testContainsKey_Object() { System.out.println("containsKey"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMap idMap = new IntDoubleMap(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Integer.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); for(Integer keyInSet : truthMap.keySet()) assertTrue(idMap.containsKey(keyInSet)); for(long i = MAX+1; i < MAX*2; i++) assertFalse(idMap.containsKey(Long.valueOf(i))); } /** * Test of containsKey method, of class IntDoubleMap. */ @Test public void testContainsKey_int() { System.out.println("containsKey"); Integer key = null; Double value = null; Map<Integer, Double> truthMap = new HashMap<Integer, Double>(); IntDoubleMap idMap = new IntDoubleMap(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Integer.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = idMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), idMap.size()); } assertEntriesAreEqual(truthMap, idMap); for(Integer keyInSet : truthMap.keySet()) assertTrue(idMap.containsKey(keyInSet.intValue())); for(long i = MAX+1; i < MAX*2; i++) assertFalse(idMap.containsKey(i)); } }
13,750
29.625835
89
java
JSAT
JSAT-master/JSAT/test/jsat/utils/IntListTest.java
/* * Copyright (C) 2016 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author edwardraff */ public class IntListTest { public IntListTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of clear method, of class IntList. */ @Test public void testAdd_int_int() { System.out.println("clear"); IntList list = new IntList(); for(int sizes = 2; sizes < 100; sizes++) { for(int i = sizes-1; i >= 0; i--) list.add(0, i); for(int i = 0; i < sizes; i++) assertEquals(i, list.getI(i)); } } }
1,724
21.402597
72
java
JSAT
JSAT-master/JSAT/test/jsat/utils/IntPriorityQueueTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.utils; import java.util.Random; import org.junit.*; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class IntPriorityQueueTest { public IntPriorityQueueTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testGeneralStanrdardMode() { IntPriorityQueue ipq = new IntPriorityQueue(8, IntPriorityQueue.Mode.STANDARD); runSmallGambit(ipq); } @Test public void testGeneralHashdMode() { IntPriorityQueue ipq = new IntPriorityQueue(8, IntPriorityQueue.Mode.HASH); runSmallGambit(ipq); } @Test public void testGeneralBoundedMode() { IntPriorityQueue ipq = new IntPriorityQueue(8, IntPriorityQueue.Mode.BOUNDED); runSmallGambit(ipq); } private void runSmallGambit(IntPriorityQueue ipq) { ipq.add(2); assertEquals(1, ipq.size()); assertEquals(2L, ipq.peek().intValue()); assertEquals(1, ipq.size()); assertEquals(2L, ipq.poll().intValue()); assertEquals(0, ipq.size()); assertNull(ipq.peek()); assertNull(ipq.poll()); ipq.add(3); ipq.add(1); ipq.add(7); assertEquals(1, ipq.peek().intValue()); assertEquals(3, ipq.size()); ipq.remove(1); ipq.add(2); assertEquals(2, ipq.peek().intValue()); assertEquals(3, ipq.size()); ipq.add(1); assertEquals(1, ipq.peek().intValue()); assertEquals(4, ipq.size()); assertTrue(ipq.contains(1)); assertTrue(ipq.contains(2)); assertTrue(ipq.contains(3)); assertFalse(ipq.contains(4)); assertFalse(ipq.contains(5)); assertTrue(ipq.contains(7)); assertEquals(1, ipq.poll().intValue()); assertEquals(3, ipq.size()); assertEquals(2, ipq.poll().intValue()); assertEquals(2, ipq.size()); assertEquals(3, ipq.poll().intValue()); assertEquals(1, ipq.size()); assertEquals(7, ipq.poll().intValue()); assertEquals(0, ipq.size()); assertNull(ipq.poll()); assertEquals(0, ipq.size()); Random rand = new Random(2); for(int i = 0; i < 100; i++) ipq.add(rand.nextInt(200)); int prev = -1; while(!ipq.isEmpty()) { int pop = ipq.poll(); assertTrue(prev <= pop); prev = pop; } } }
2,898
22.379032
87
java
JSAT
JSAT-master/JSAT/test/jsat/utils/IntSetFixedSizeTest.java
package jsat.utils; import java.util.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class IntSetFixedSizeTest { public IntSetFixedSizeTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of add method, of class IntSetFixedSize. */ @Test public void testAdd_Integer() { System.out.println("add"); IntSetFixedSize set = new IntSetFixedSize(5); assertTrue(set.add(new Integer(1))); assertTrue(set.add(new Integer(2))); assertFalse(set.add( new Integer(1) )); assertTrue(set.add( new Integer(3) )); for (int badVal : Arrays.asList(-1, 5, 10, -23)) try { set.add( new Integer(badVal)); fail("Should not have been added"); } catch (Exception ex) { } } /** * Test of add method, of class IntSetFixedSize. */ @Test public void testAdd_int() { System.out.println("add"); IntSetFixedSize set = new IntSetFixedSize(5); assertTrue(set.add(1)); assertTrue(set.add(2)); assertFalse(set.add(1)); assertTrue(set.add(3)); for (int badVal : Arrays.asList(-1, 5, 10, -23)) try { set.add(badVal); fail("Should not have been added"); } catch (Exception ex) { } } /** * Test of contains method, of class IntSetFixedSize. */ @Test public void testContains_Object() { System.out.println("contains"); IntSetFixedSize instance = new IntSetFixedSize(100); List<Integer> intList = new IntList(); ListUtils.addRange(intList, 0, 100, 1); Collections.shuffle(intList); instance.addAll(intList.subList(0, 50)); for(int i : intList.subList(0, 50)) assertTrue(instance.contains(i)); for(int i : intList.subList(50, 100)) assertFalse(instance.contains(i)); } /** * Test of contains method, of class IntSetFixedSize. */ @Test public void testContains_int() { System.out.println("contains"); IntSetFixedSize instance = new IntSetFixedSize(100); List<Integer> intList = new IntList(); ListUtils.addRange(intList, 0, 100, 1); Collections.shuffle(intList); instance.addAll(intList.subList(0, 50)); for(int i : intList.subList(0, 50)) assertTrue(instance.contains(i)); for(int i : intList.subList(50, 100)) assertFalse(instance.contains(i)); } /** * Test of iterator method, of class IntSetFixedSize. */ @Test public void testIterator() { System.out.println("iterator"); IntSetFixedSize set = new IntSetFixedSize(10); set.add(5); set.add(3); set.add(4); set.add(1); set.add(2); Set<Integer> copySet = new IntSet(set); int prev = Integer.MIN_VALUE; Iterator<Integer> iter = set.iterator(); int count = 0; while(iter.hasNext()) { int val = iter.next(); copySet.remove(val); count++; } assertEquals(5, set.size()); assertEquals(5, count); assertEquals(0, copySet.size()); //Test removing some elements iter = set.iterator(); while(iter.hasNext()) { int val = iter.next(); if(val == 2 || val == 4) iter.remove(); } assertEquals(3, set.size()); //Make sure the corect values were actually removed iter = set.iterator(); count = 0; while(iter.hasNext()) { int val = iter.next(); assertFalse(val == 2 || val == 4); count++; } assertEquals(3, set.size()); assertEquals(3, count); } /** * Test of size method, of class IntSetFixedSize. */ @Test public void testSize() { System.out.println("size"); IntSetFixedSize set = new IntSetFixedSize(10); assertEquals(0, set.size()); set.add(1); assertEquals(1, set.size()); set.add(1); set.add(2); assertEquals(2, set.size()); set.add(5); set.add(7); set.add(2); assertEquals(4, set.size()); } }
4,886
23.313433
60
java
JSAT
JSAT-master/JSAT/test/jsat/utils/IntSetTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.utils; import java.util.Iterator; import org.junit.*; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class IntSetTest { public IntSetTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of add method, of class IntSet. */ @Test public void testAdd() { System.out.println("add"); IntSet set = new IntSet(); assertFalse(set.add(null)); assertTrue(set.add(1)); assertTrue(set.add(2)); assertFalse(set.add(1)); assertFalse(set.add(null)); assertTrue(set.add(3)); } /** * Test of iterator method, of class IntSet. */ @Test public void testIterator() { System.out.println("iterator"); IntSet set = new IntSet(); set.add(5); set.add(3); set.add(4); set.add(1); set.add(2); int prev = Integer.MIN_VALUE; Iterator<Integer> iter = set.iterator(); int count = 0; while(iter.hasNext()) { int val = iter.next(); count++; prev = val; } assertEquals(5, set.size()); assertEquals(5, count); //Test removing some elements iter = set.iterator(); while(iter.hasNext()) { int val = iter.next(); if(val == 2 || val == 4) iter.remove(); } assertEquals(3, set.size()); //Make sure the corect values were actually removed iter = set.iterator(); count = 0; while(iter.hasNext()) { int val = iter.next(); assertFalse(val == 2 || val == 4); count++; } assertEquals(3, set.size()); assertEquals(3, count); } /** * Test of size method, of class IntSet. */ @Test public void testSize() { System.out.println("size"); IntSet set = new IntSet(); assertEquals(0, set.size()); set.add(1); assertEquals(1, set.size()); set.add(1); set.add(2); assertEquals(2, set.size()); set.add(5); set.add(-4); set.add(2); assertEquals(4, set.size()); } }
2,625
19.84127
59
java
JSAT
JSAT-master/JSAT/test/jsat/utils/IntSortedSetTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.utils; import java.util.Iterator; import java.util.Random; import java.util.SortedSet; import java.util.TreeSet; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.*; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class IntSortedSetTest { public IntSortedSetTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of add method, of class IntSet. */ @Test public void testAdd() { System.out.println("add"); IntSortedSet set = new IntSortedSet(); assertFalse(set.add(null)); assertTrue(set.add(1)); assertTrue(set.add(2)); assertFalse(set.add(1)); assertFalse(set.add(null)); assertTrue(set.add(3)); } /** * Test of iterator method, of class IntSet. */ @Test public void testIterator() { System.out.println("iterator"); IntSortedSet set = new IntSortedSet(); set.add(5); set.add(3); set.add(4); set.add(1); set.add(2); int prev = Integer.MIN_VALUE; Iterator<Integer> iter = set.iterator(); int count = 0; while(iter.hasNext()) { int val = iter.next(); count++; assertTrue(prev < val); prev = val; } assertEquals(5, set.size()); assertEquals(5, count); //Test removing some elements iter = set.iterator(); while(iter.hasNext()) { int val = iter.next(); if(val == 2 || val == 4) iter.remove(); } assertEquals(3, set.size()); //Make sure the corect values were actually removed iter = set.iterator(); count = 0; while(iter.hasNext()) { int val = iter.next(); assertFalse(val == 2 || val == 4); count++; } assertEquals(3, set.size()); assertEquals(3, count); } /** * Test of size method, of class IntSet. */ @Test public void testSize() { System.out.println("size"); IntSortedSet set = new IntSortedSet(); assertEquals(0, set.size()); set.add(1); assertEquals(1, set.size()); set.add(1); set.add(2); assertEquals(2, set.size()); set.add(5); set.add(-4); set.add(2); assertEquals(4, set.size()); } @Test public void testLinearAdd() { //this test exists b/c IntSortedSet has a hot path for adding in this fashion System.out.println("testLinearAdd"); SortedSet<Integer> groundTruth = new TreeSet<Integer>(); IntSortedSet testSet = new IntSortedSet(); XORWOW rand = new XORWOW(); int cur = rand.nextInt(10); groundTruth.add(cur); testSet.add(cur); assertSameContent(groundTruth, testSet); for(int i = 0; i < 1000; i++) { cur = cur + rand.nextInt(10); groundTruth.add(cur); testSet.add(cur); assertSameContent(groundTruth, testSet); } } @Test public void testSubSet() { System.out.println("subset"); SortedSet<Integer> groundTruth = new TreeSet<Integer>(); IntSortedSet testSet = new IntSortedSet(); for (int i = 1; i < 20; i++) for (int j = i * 20; j < (i + 1) * 20; j += i) { groundTruth.add(j); testSet.add(j); } assertSameContent(groundTruth, testSet); Random rand = RandomUtil.getRandom(); testHeadSet(groundTruth, testSet, rand, 3); testTailSet(groundTruth, testSet, rand, 3); testSubSet(groundTruth, testSet, rand, 3); } private void testHeadSet(SortedSet<Integer> groundTruth, SortedSet<Integer> testSet, Random rand, int depth) { if(groundTruth.isEmpty() || groundTruth.last() - groundTruth.first() <= 0 || groundTruth.last() <= 0)//avoid bad tests return; int toElement = rand.nextInt(groundTruth.last()); SortedSet<Integer> g_s = groundTruth.headSet(toElement); SortedSet<Integer> t_s = testSet.headSet(toElement); assertSameContent(g_s, t_s); for(int i = 0; i < 5; i++) { int new_val; if(toElement <= 0) new_val = Math.min(toElement-1, -rand.nextInt(1000)); else new_val = rand.nextInt(toElement); g_s.add(new_val); t_s.add(new_val); } assertSameContent(g_s, t_s); assertSameContent(groundTruth, testSet); if(depth-- > 0) testHeadSet(g_s, t_s, rand, depth); assertSameContent(groundTruth, testSet); } private void testTailSet(SortedSet<Integer> groundTruth, SortedSet<Integer> testSet, Random rand, int depth) { if(groundTruth.isEmpty() || groundTruth.last() - groundTruth.first() <= 0)//avoid bad tests return; int fromElement = groundTruth.first() + rand.nextInt(groundTruth.last() - groundTruth.first()); SortedSet<Integer> g_s = groundTruth.tailSet(fromElement); SortedSet<Integer> t_s = testSet.tailSet(fromElement); assertSameContent(g_s, t_s); for(int i = 0; i < 5; i++) { int new_val = fromElement+rand.nextInt(10000); g_s.add(new_val); t_s.add(new_val); } assertSameContent(g_s, t_s); assertSameContent(groundTruth, testSet); if(depth-- > 0) testTailSet(g_s, t_s, rand, depth); assertSameContent(groundTruth, testSet); } private void testSubSet(SortedSet<Integer> groundTruth, SortedSet<Integer> testSet, Random rand, int depth) { if(groundTruth.isEmpty() || groundTruth.last() - groundTruth.first() <= 0)//avoid bad tests return; int fromElement = groundTruth.first() + rand.nextInt(groundTruth.last() - groundTruth.first()); int toElement = fromElement + rand.nextInt(groundTruth.last() - fromElement); SortedSet<Integer> g_s = groundTruth.subSet(fromElement, toElement); SortedSet<Integer> t_s = testSet.subSet(fromElement, toElement); assertSameContent(g_s, t_s); for(int i = 0; i < 5; i++) { if(fromElement == toElement) continue;//we can't add anything int new_val = fromElement+rand.nextInt(toElement-fromElement); g_s.add(new_val); t_s.add(new_val); } assertSameContent(g_s, t_s); assertSameContent(groundTruth, testSet); if(depth-- > 0) testSubSet(g_s, t_s, rand, depth); assertSameContent(groundTruth, testSet); } public void assertSameContent(SortedSet<Integer> a, SortedSet<Integer> b) { assertEquals(a.size(), b.size()); int counted_a = 0; for(int v : a) { assertTrue(b.contains(v)); counted_a++; } assertEquals(a.size(), counted_a); int counted_b = 0; for(int v : b) { assertTrue(a.contains(v)); counted_b++; } assertEquals(b.size(), counted_b); } }
7,865
26.6
126
java
JSAT
JSAT-master/JSAT/test/jsat/utils/ListUtilsTest.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jsat.utils; import java.util.List; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class ListUtilsTest { public ListUtilsTest() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { } /** * Test of splitList method, of class ListUtils. */ @Test public void testSplitList() { System.out.println("splitList"); List<Integer> sourceList = new IntList(500); for(int i = 0; i < 500; i++) sourceList.add(i); List<List<Integer>> ll1 = ListUtils.splitList(sourceList, 5); assertEquals(5, ll1.size()); for(int i = 0; i < 5; i++) { List<Integer> l = ll1.get(i); assertEquals(100, l.size()); for(int j = 0; j < l.size(); j++) assertEquals( i*100+j, l.get(j).intValue());//intValue called b/c it becomes ambigous to the compiler without it } ll1 = ListUtils.splitList(sourceList, 7);//Non divisible amount assertEquals(7, ll1.size()); int pos = 0; for(List<Integer> l : ll1) { assertTrue("List should have had only 71 or 72 values", l.size() == 72 || l.size() == 71 ); for(int j = 0; j < l.size(); j++) { assertEquals(pos+j, l.get(j).intValue()); } pos += l.size(); } assertEquals(500, pos); } @Test public void testSwap() { System.out.println("swap"); List<Long> test = new LongList(); test.add(1L); test.add(2L); ListUtils.swap(test, 0, 1); assertEquals(2, test.get(0).longValue()); assertEquals(1, test.get(1).longValue()); ListUtils.swap(test, 0, 1); assertEquals(1, test.get(0).longValue()); assertEquals(2, test.get(1).longValue()); ListUtils.swap(test, 0, 0); assertEquals(1, test.get(0).longValue()); assertEquals(2, test.get(1).longValue()); } }
2,433
24.092784
128
java
JSAT
JSAT-master/JSAT/test/jsat/utils/LongDoubleMapTest.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package jsat.utils; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class LongDoubleMapTest { private static final int TEST_SIZE = 2000; Random rand; public LongDoubleMapTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { rand = RandomUtil.getRandom(); } @After public void tearDown() { } /** * Test of put method, of class LongDoubleMap. */ @Test public void testPut_Long_Double() { System.out.println("put"); Long key = null; Double value = null; Map<Long, Double> truthMap = new HashMap<Long, Double>(); LongDoubleMap ldMap = new LongDoubleMap(); for(int i = 0; i < TEST_SIZE; i++) { key = rand.nextLong(); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); //will call the iterator remove on everythin removeEvenByIterator(ldMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, ldMap); for(Entry<Long, Double> entry : ldMap.entrySet()) entry.setValue(1.0); for(Entry<Long, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, ldMap); ///again, random keys - and make them colide truthMap = new HashMap<Long, Double>(); ldMap = new LongDoubleMap(); for(int i = 0; i < TEST_SIZE; i++) { key = Long.valueOf(rand.nextInt(50000)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); //will call the iterator remove on everythin removeEvenByIterator(ldMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, ldMap); for(Entry<Long, Double> entry : ldMap.entrySet()) entry.setValue(1.0); for(Entry<Long, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, ldMap); } private void removeEvenByIterator(Iterator<Entry<Long, Double>> iterator) { while(iterator.hasNext()) { Entry<Long, Double> entry = iterator.next(); if(entry.getKey() % 2 == 0) iterator.remove(); } } private void assertEntriesAreEqual(Map<Long, Double> truthMap, LongDoubleMap ldMap) { assertEquals(truthMap.size(), ldMap.size()); Map<Long, Double> copy = new HashMap<Long, Double>(); for(Entry<Long, Double> entry : truthMap.entrySet()) assertEquals(entry.getValue(), ldMap.get(entry.getKey())); int observed = 0; for(Entry<Long, Double> entry : ldMap.entrySet()) { copy.put(entry.getKey(), entry.getValue()); observed++; assertTrue(truthMap.containsKey(entry.getKey())); assertEquals(truthMap.get(entry.getKey()), entry.getValue()); } assertEquals(truthMap.size(), observed); //make sure we put every value into the copy! for(Entry<Long, Double> entry : truthMap.entrySet()) assertEquals(truthMap.get(entry.getKey()), copy.get(entry.getKey())); } /** * Test of put method, of class LongDoubleMap. */ @Test public void testPut_long_double() { System.out.println("put"); long key; double value; Map<Long, Double> truthMap = new HashMap<Long, Double>(); LongDoubleMap ldMap = new LongDoubleMap(); for(int i = 0; i < TEST_SIZE; i++) { key = rand.nextLong(); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); if(prev.isNaN()) prev = null; assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); //will call the iterator remove on everythin removeEvenByIterator(ldMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, ldMap); for(Entry<Long, Double> entry : ldMap.entrySet()) entry.setValue(1.0); for(Entry<Long, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, ldMap); ///again, random keys - and make them colide truthMap = new HashMap<Long, Double>(); ldMap = new LongDoubleMap(); for(int i = 0; i < TEST_SIZE; i++) { key = Long.valueOf(rand.nextInt(50000)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); if(prev.isNaN()) prev = null; assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); //will call the iterator remove on everythin removeEvenByIterator(ldMap.entrySet().iterator()); removeEvenByIterator(truthMap.entrySet().iterator()); assertEntriesAreEqual(truthMap, ldMap); for(Entry<Long, Double> entry : ldMap.entrySet()) entry.setValue(1.0); for(Entry<Long, Double> entry : truthMap.entrySet()) entry.setValue(1.0); assertEntriesAreEqual(truthMap, ldMap); } /** * Test of increment method, of class LongDoubleMap. */ @Test public void testIncrement() { System.out.println("increment"); Long key = null; Double value = null; Map<Long, Double> truthMap = new HashMap<Long, Double>(); LongDoubleMap ldMap = new LongDoubleMap(); int MAX = TEST_SIZE/2; int times =0; for(int i = 0; i < MAX; i++) { key = Long.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); if(truthMap.containsKey(key)) times++; Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); if(prev == null && prevTruth != null) System.out.println(ldMap.put(key, value)); assertEquals(prevTruth, prev); if(ldMap.size() != truthMap.size()) { System.out.println(); } assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); for(Entry<Long, Double> entry : truthMap.entrySet()) { double delta = Double.valueOf(rand.nextInt(100)); double trueNewValue =entry.getValue()+delta; entry.setValue(trueNewValue); double newValue = ldMap.increment(entry.getKey(), delta); assertEquals(trueNewValue, newValue, 0.0); } for(int i = MAX; i < MAX*2; i++) { key = Long.valueOf(i);//force it to be new value = Double.valueOf(rand.nextInt(1000)); truthMap.put(key, value); double ldNew =ldMap.increment(key, value); assertEquals(value.doubleValue(), ldNew, 0.0); } assertEntriesAreEqual(truthMap, ldMap); } /** * Test of remove method, of class LongDoubleMap. */ @Test public void testRemove_Object() { System.out.println("remove"); Long key = null; Double value = null; Map<Long, Double> truthMap = new HashMap<Long, Double>(); LongDoubleMap ldMap = new LongDoubleMap(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Long.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); for(int i = 0; i < MAX/4; i++) { key = Long.valueOf(rand.nextInt(MAX)); Double prevTruth = truthMap.remove(key); Double prev = ldMap.remove(key); if(prevTruth == null && prev != null) prev = ldMap.remove(key); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); } /** * Test of remove method, of class LongDoubleMap. */ @Test public void testRemove_long() { System.out.println("remove"); Long key = null; Double value = null; Map<Long, Double> truthMap = new HashMap<Long, Double>(); LongDoubleMap ldMap = new LongDoubleMap(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Long.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); for(int i = 0; i < MAX/4; i++) { key = Long.valueOf(rand.nextInt(MAX)); Double prevTruth = truthMap.remove(key); Double prev = ldMap.remove(key.longValue()); if(prev.isNaN()) prev = null; assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); } /** * Test of containsKey method, of class LongDoubleMap. */ @Test public void testContainsKey_Object() { System.out.println("containsKey"); Long key = null; Double value = null; Map<Long, Double> truthMap = new HashMap<Long, Double>(); LongDoubleMap ldMap = new LongDoubleMap(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Long.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); for(Long keyInSet : truthMap.keySet()) assertTrue(ldMap.containsKey(keyInSet)); for(long i = MAX+1; i < MAX*2; i++) assertFalse(ldMap.containsKey(Long.valueOf(i))); } /** * Test of containsKey method, of class LongDoubleMap. */ @Test public void testContainsKey_long() { System.out.println("containsKey"); Long key = null; Double value = null; Map<Long, Double> truthMap = new HashMap<Long, Double>(); LongDoubleMap ldMap = new LongDoubleMap(); int MAX = TEST_SIZE/2; for(int i = 0; i < MAX; i++) { key = Long.valueOf(rand.nextInt(MAX)); value = Double.valueOf(rand.nextInt(1000)); Double prevTruth = truthMap.put(key, value); Double prev = ldMap.put(key, value); assertEquals(prevTruth, prev); assertEquals(truthMap.size(), ldMap.size()); } assertEntriesAreEqual(truthMap, ldMap); for(Long keyInSet : truthMap.keySet()) assertTrue(ldMap.containsKey(keyInSet.longValue())); for(long i = MAX+1; i < MAX*2; i++) assertFalse(ldMap.containsKey(i)); } }
13,812
29.492274
87
java
JSAT
JSAT-master/JSAT/test/jsat/utils/LongListTest.java
/* * Copyright (C) 2016 Edward Raff <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package jsat.utils; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author edwardraff */ public class LongListTest { public LongListTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testAdd_int_long() { System.out.println("clear"); LongList list = new LongList(); for(int sizes = 2; sizes < 100; sizes++) { for(int i = sizes-1; i >= 0; i--) list.add(0, i); for(int i = 0; i < sizes; i++) assertEquals(i, list.getL(i)); } } }
1,666
21.527027
72
java
JSAT
JSAT-master/JSAT/test/jsat/utils/QuickSortTest.java
package jsat.utils; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import jsat.utils.random.RandomUtil; import jsat.utils.random.XORWOW; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class QuickSortTest { public QuickSortTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of sort method, of class QuickSort. */ @Test public void testSortD() { System.out.println("sort"); Random rand = RandomUtil.getRandom(); for(int size = 2; size < 10000; size*=2) { double[] x = new double[size]; for(int i = 0; i < x.length; i++) if(rand.nextInt(10) == 0)//force behavrio of multiple pivots with exact same value x[i] = rand.nextInt(10); else x[i] = rand.nextDouble(); QuickSort.sort(x, 0, size); for(int i = 0; i < x.length-1; i++) assertTrue(x[i] <= x[i+1]); } } @Test public void testSortDP() { System.out.println("sort"); IntList ints = new IntList(); Collection<List<?>> paired = new ArrayList<List<?>>(); paired.add(ints); for(int size = 2; size < 10000; size*=2) { ints.clear(); double[] x = new double[size]; for(int i = 0; i < x.length; i++) { x[i] = x.length-i; ints.add(i); } QuickSort.sort(x, 0, size, paired); for(int i = 0; i < x.length-1; i++) { assertTrue(x[i] <= x[i+1]); assertTrue(ints.get(i) > ints.get(i+1)); } } } @Test public void testSortFP() { System.out.println("sort"); IntList ints = new IntList(); Collection<List<?>> paired = new ArrayList<List<?>>(); paired.add(ints); for(int size = 2; size < 10000; size*=2) { ints.clear(); float[] x = new float[size]; for(int i = 0; i < x.length; i++) { x[i] = x.length-i; ints.add(i); } QuickSort.sort(x, 0, size, paired); for(int i = 0; i < x.length-1; i++) { assertTrue(x[i] <= x[i+1]); assertTrue(ints.get(i) > ints.get(i+1)); } } } }
2,945
22.19685
98
java
JSAT
JSAT-master/JSAT/test/jsat/utils/SimpleListTest.java
package jsat.utils; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class SimpleListTest { public SimpleListTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of get method, of class SimpleList. */ @Test public void testGet() { System.out.println("get"); SimpleList instance = new SimpleList(); try { Object obj = instance.get(0); fail("Should not have been able to obtain " + obj); } catch(Exception ex) { } instance.add("a"); instance.add("b"); assertEquals("a", instance.get(0)); assertEquals("b", instance.get(1)); assertEquals("a", instance.remove(0)); assertEquals("b", instance.get(0)); try { Object obj = instance.get(1); fail("Should not have been able to obtain " + obj); } catch(Exception ex) { } instance.add("c"); instance.add("d"); assertEquals("b", instance.get(0)); assertEquals("c", instance.get(1)); assertEquals("d", instance.get(2)); try { Object obj = instance.get(3); fail("Should not have been able to obtain " + obj); } catch(Exception ex) { } } /** * Test of size method, of class SimpleList. */ @Test public void testSize() { System.out.println("size"); SimpleList instance = new SimpleList(); assertEquals(0, instance.size()); instance.add("a"); instance.add("b"); assertEquals(2, instance.size()); assertEquals("a", instance.remove(0)); assertEquals(1, instance.size()); instance.add("c"); instance.add("d"); assertEquals(3, instance.size()); } @Test public void testAdd() { System.out.println("add"); SimpleList<String> instance = new SimpleList<String>(); instance.add("a"); instance.add(0, "c"); instance.add(1, "b"); assertEquals("c", instance.get(0)); assertEquals("b", instance.get(1)); assertEquals("a", instance.get(2)); } /** * Test of set method, of class SimpleList. */ @Test public void testSet() { System.out.println("set"); SimpleList<String> instance = new SimpleList<String>(); try { Object obj = instance.get(0); fail("Should not have been able to obtain " + obj); } catch(Exception ex) { } instance.add("A"); instance.add("B"); instance.set(0, instance.get(0).toLowerCase()); instance.set(1, instance.get(1).toLowerCase()); assertEquals("a", instance.get(0)); assertEquals("b", instance.get(1)); assertEquals("a", instance.remove(0)); assertEquals("b", instance.get(0)); try { Object obj = instance.get(1); fail("Should not have been able to obtain " + obj); } catch(Exception ex) { } instance.add("C"); instance.add("D"); instance.set(1, instance.get(1).toLowerCase()); instance.set(2, instance.get(2).toLowerCase()); assertEquals("b", instance.get(0)); assertEquals("c", instance.get(1)); assertEquals("d", instance.get(2)); try { Object obj = instance.get(3); fail("Should not have been able to obtain " + obj); } catch(Exception ex) { } } }
4,140
22.005556
63
java
JSAT
JSAT-master/JSAT/test/jsat/utils/StringUtilsTest.java
package jsat.utils; import java.util.Random; import jsat.utils.random.RandomUtil; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Edward Raff */ public class StringUtilsTest { public StringUtilsTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of parseInt method, of class StringUtils. */ @Test public void testParseInt() { System.out.println("parseInt"); Random rand = RandomUtil.getRandom(); for(int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) { for(int trials = 0; trials < 1000; trials++) { String preFix = ""; String postFix = ""; int prefixSize = rand.nextInt(3); int postFixSize = rand.nextInt(3); for(int i =0 ; i < prefixSize; i++) preFix += Character.toString((char) rand.nextInt(128)); for(int i =0 ; i < postFixSize; i++) postFix += Character.toString((char) rand.nextInt(128)); //first test a large int int truth = rand.nextInt(); String test = preFix + Integer.toString(truth, radix) + postFix; assertEquals(truth, StringUtils.parseInt(test, prefixSize, test.length()-postFixSize, radix)); //now a small one //first test a large int truth = rand.nextInt(10)*(rand.nextInt(1)*2-1); test = preFix + Integer.toString(truth, radix) + postFix; assertEquals(truth, StringUtils.parseInt(test, prefixSize, test.length()-postFixSize, radix)); } } } @Test public void testParseDouble() { System.out.println("parseDouble"); Random rand = new Random(42); String[] signOps = new String[]{"+", "-", ""}; String[] Es = new String[]{"e", "E"}; String[] zeros = new String[]{"","", "", "0", "00", "000", "0000"}; double truth, attempt; String toTest; for (int trials = 0; trials < 10000; trials++) { String preFix = ""; String postFix = ""; int prefixSize = 0;//rand.nextInt(3); int postFixSize = 0;//rand.nextInt(3); for (int i = 0; i < prefixSize; i++) preFix += Character.toString((char) rand.nextInt(128)); for (int i = 0; i < postFixSize; i++) postFix += Character.toString((char) rand.nextInt(128)); //easy cases that should all be exact //[sign][val] toTest = signOps[rand.nextInt(3)] + zeros[rand.nextInt(zeros.length)] + rand.nextInt((int) Math.round(Math.pow(10, rand.nextInt(6)))) + "" + rand.nextInt((int) Math.round(Math.pow(10, rand.nextInt(6)))); truth = Double.parseDouble(toTest); attempt = StringUtils.parseDouble(toTest, 0, toTest.length()); assertRelativeEquals(truth, attempt); //[sign][val].[val] toTest = signOps[rand.nextInt(3)] + zeros[rand.nextInt(zeros.length)] + rand.nextInt((int) Math.round(Math.pow(10, rand.nextInt(6)))) + "." + zeros[rand.nextInt(zeros.length)] + rand.nextInt((int) Math.round(Math.pow(10, rand.nextInt(6)))); truth = Double.parseDouble(toTest); attempt = StringUtils.parseDouble(toTest, 0, toTest.length()); assertRelativeEquals(truth, attempt); //[sign][val][eE][sign][val] toTest = signOps[rand.nextInt(3)] + zeros[rand.nextInt(zeros.length)] + rand.nextInt((int) Math.round(Math.pow(10, rand.nextInt(6)))) + Es[rand.nextInt(2)] + signOps[rand.nextInt(3)] + zeros[rand.nextInt(zeros.length)] + rand.nextInt((int) Math.round(Math.pow(10, rand.nextInt(2)))); truth = Double.parseDouble(toTest); attempt = StringUtils.parseDouble(toTest, 0, toTest.length()); assertRelativeEquals(truth, attempt); //harder cases, may have nonsense values (over flow to Inf/NegInf, underflows to 0) //[sign][val] //XXX This code generates a random signed integer and then computes the absolute value of that random integer. If the number returned by the random number generator is Integer.MIN_VALUE, then the result will be negative as well (since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE). (Same problem arised for long values as well). toTest = signOps[rand.nextInt(3)].replace("-", "") + zeros[rand.nextInt(zeros.length)] + Math.max(Math.abs(rand.nextLong()), 0); truth = Double.parseDouble(toTest); attempt = StringUtils.parseDouble(toTest, 0, toTest.length()); assertRelativeEquals(truth, attempt); //[sign][val].[val] toTest = signOps[rand.nextInt(3)] + rand.nextInt(Integer.MAX_VALUE) + zeros[rand.nextInt(zeros.length)] + "." + zeros[rand.nextInt(zeros.length)] + rand.nextInt(Integer.MAX_VALUE) ; truth = Double.parseDouble(toTest); attempt = StringUtils.parseDouble(toTest, 0, toTest.length()); assertRelativeEquals(truth, attempt); //[sign][val][eE][sign][val] toTest = signOps[rand.nextInt(3)] + zeros[rand.nextInt(zeros.length)] + rand.nextInt((int) Math.round(Math.pow(10, rand.nextInt(8)))) + Es[rand.nextInt(2)] + signOps[rand.nextInt(3)] + zeros[rand.nextInt(zeros.length)] + rand.nextInt(450); truth = Double.parseDouble(toTest); attempt = StringUtils.parseDouble(toTest, 0, toTest.length()); assertRelativeEquals(truth, attempt); } } protected void assertRelativeEquals(double truth, double attempt) { String message = "Expteced " + truth + " but was " + attempt; if (Double.isNaN(truth)) assertTrue(message, Double.isNaN(attempt)); else if (Double.isInfinite(truth)) { assertTrue(message, Double.isInfinite(attempt)); assertTrue(Double.doubleToRawLongBits(truth) == Double.doubleToRawLongBits(attempt));//get the signs right } else { double relDiff = Math.abs(truth - attempt) / (Math.max(Math.abs(Math.max(truth, attempt)), 1e-14)); assertEquals(message, 0, relDiff, 1e-14); } } }
6,823
39.141176
344
java
FOADA
FOADA-master/old/src/app/FOADA.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package app; import exception.FOADAException; import exception.InputFileNotFoundException; import exception.UnknownConsoleOptionException; import parser.ParserTools; import parser.ParserTools.ParserType; import structure.Automaton; import utility.Console; import utility.Console.ConsoleType; import utility.Solver; public class FOADA { // FOADA Version public static final String FOADA_version = "1.0"; /** < FOADA welcome > </br> * FOADA execution with no argument */ private static void welcome() { System.out.println("------------------------------"); System.out.print(" FOADA Version "); System.out.println(FOADA_version); System.out.println("------------------------------"); help(); } /** < FOADA help menu > </br> * FOADA execution with argument <b> -h </b> or <b> --help </b> */ private static void help() { Console.printInfo(ConsoleType.FOADA, "Showing all the options..."); // -h , --help System.out.println("-h, --help \t\t\thelp menu"); // -c , --check System.out.println("-c, --check \t\t\tsolver checking"); // -e, --empty System.out.println("-e, --empty <input> <options>\temptiness checking using BFS "); // additional options for emptiness checking System.out.println("\tadditional options:"); // -d, --dfs System.out.println("\t-d, --dfs\t\tusing DFS instead of using BFS"); // -o, --occurrences System.out.println("\t-o, --occurrences\tfinding occurrences of predicates instead of universally quantifying arguments"); // -i, --inclusion System.out.println("-i, --inclusion <input1> <input2> <options>\tinclusion checking using BFS "); // additional options for inclusion checking System.out.println("\tadditional options:"); // -d, --dfs System.out.println("\t-d, --dfs\t\tusing DFS instead of using BFS"); // -o, --occurrences System.out.println("\t-o, --occurrences\tfinding occurrences of predicates instead of universally quantifying arguments"); // -v , --version System.out.println("-v, --version \t\t\tinstalled version"); Console.printFOADAEndOfSession(); } /** < FOADA solver checking > </br> * FOADA execution with argument <b> -c </b> or <b> --check </b> */ private static void checkSolvers() { Console.printInfo(ConsoleType.FOADA, "Start checking all the solvers..."); Solver.checkSMTINTERPOL(); Solver.checkZ3(); Solver.checkMATHSAT5(); Solver.checkPRINCESS(); Console.printFOADAEndOfSession(); } /** < FOADA emptiness checking > </br> * FOADA execution with argument <b> -e </b> or <b> --empty </b> * @param filename name of the input file * @param searchMode mode of tree search: <b> BFS </b> / <b> DFS </b> * @param transitionMode mode of transition rules: <b> universally quantifier arguments </b> / <b> find occurrences </b> */ private static void checkEmpty(String filename, utility.TreeSearch.Mode searchMode, utility.Impact.Mode transitionMode) throws FOADAException { ParserType parserType = ParserTools.selectAccordingToInputFile(filename); Automaton automaton = ParserTools.buildAutomatonFromFile(filename, parserType); if(searchMode == utility.TreeSearch.Mode.BFS) { if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (BFS / Universally Quantify Arguments) ... "); } else if(transitionMode == utility.Impact.Mode.FindOccurrences) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (BFS / Find Occurrences) ... "); Console.printInfo(ConsoleType.FOADA, Console.RED_BRIGHT + "WARNING : " + Console.RESET + "This version does not work with transition quantifiers."); } } else if(searchMode == utility.TreeSearch.Mode.DFS) { if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (DFS / Universally Quantify Arguments) ... "); } else if(transitionMode == utility.Impact.Mode.FindOccurrences) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (DFS / Find Occurrences) ... "); Console.printInfo(ConsoleType.FOADA, Console.RED_BRIGHT + "WARNING : " + Console.RESET + "This version does not work with transition quantifiers."); } } if(automaton.isEmpty(searchMode, transitionMode)) { Console.printInfo(ConsoleType.FOADA, "The automaton is empty..."); } else { Console.printInfo(ConsoleType.FOADA, "The automaton is not empty..."); } Console.printFOADAEndOfSession(); } /** < FOADA inclusion checking > </br> * FOADA execution with argument <b> -i </b> or <b> --inclusion </b> * @param filename1 name of the input file 1 * @param filename2 name of the input file 2 * @param searchMode mode of tree search: <b> BFS </b> / <b> DFS </b> * @param transitionMode mode of transition rules: <b> universally quantifier arguments </b> / <b> find occurrences </b> */ private static void checkInclusion(String filename1, String filename2, utility.TreeSearch.Mode searchMode, utility.Impact.Mode transitionMode) throws FOADAException { Console.printInfo(ConsoleType.FOADA, "Building automaton 1 ... "); ParserType parser1Type = ParserTools.selectAccordingToInputFile(filename1); Automaton automaton1 = ParserTools.buildAutomatonFromFile(filename1, parser1Type); /*System.out.println("Predicates: " + automaton1.namesOfPredicates); System.out.println("Initial: " + automaton1.initial); System.out.println("Final: " + automaton1.namesOfFinalStates); System.out.println("Events: " + automaton1.events); System.out.println("Nb of Variables: " + automaton1.nbOfVariables); System.out.println(automaton1.renameMap); for(Map.Entry<String, FOADATransition> xx : automaton1.transitions.entrySet()) { System.out.println(xx.getValue()); } System.out.println();*/ Console.printInfo(ConsoleType.FOADA, "Building automaton 2 ... "); ParserType parser2Type = ParserTools.selectAccordingToInputFile(filename2); Automaton automaton2 = ParserTools.buildAutomatonFromFile(filename2, parser2Type); /*System.out.println("Predicates: " + automaton2.namesOfPredicates); System.out.println("Initial: " + automaton2.initial); System.out.println("Final: " + automaton2.namesOfFinalStates); System.out.println("Events: " + automaton2.events); System.out.println("Nb of Variables: " + automaton2.nbOfVariables); System.out.println(automaton2.renameMap); for(Map.Entry<String, FOADATransition> xx : automaton2.transitions.entrySet()) { System.out.println(xx.getValue()); } System.out.println();*/ Console.printInfo(ConsoleType.FOADA, "Complementing automaton 2 ... "); Automaton complementOfAutomaton2 = automaton2.complements(); /*System.out.println("Predicates: " + complementOfAutomaton2.namesOfPredicates); System.out.println("Initial: " + complementOfAutomaton2.initial); System.out.println("Final: " + complementOfAutomaton2.namesOfFinalStates); System.out.println("Events: " + complementOfAutomaton2.events); System.out.println("Nb of Variables: " + complementOfAutomaton2.nbOfVariables); System.out.println(complementOfAutomaton2.renameMap); for(Map.Entry<String, FOADATransition> xx : complementOfAutomaton2.transitions.entrySet()) { System.out.println(xx.getValue()); } System.out.println();*/ Console.printInfo(ConsoleType.FOADA, "Intersecting automaton 1 with complement of automaton 2 ... "); Automaton automaton = automaton1.intersects(complementOfAutomaton2); /*System.out.println("Predicates: " + automaton.namesOfPredicates); System.out.println("Initial: " + automaton.initial); System.out.println("Final: " + automaton.namesOfFinalStates); System.out.println("Events: " + automaton.events); System.out.println("Nb of Variables: " + automaton.nbOfVariables); System.out.println(automaton.renameMap); for(Map.Entry<String, FOADATransition> xx : automaton.transitions.entrySet()) { System.out.println(xx.getValue()); } System.out.println();*/ if(searchMode == utility.TreeSearch.Mode.BFS) { if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (BFS / Universally Quantify Arguments) ... "); } else if(transitionMode == utility.Impact.Mode.FindOccurrences) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (BFS / Find Occurrences) ... "); Console.printInfo(ConsoleType.FOADA, Console.RED_BRIGHT + "WARNING : " + Console.RESET + "This version does not work with transition quantifiers."); } } else if(searchMode == utility.TreeSearch.Mode.DFS) { if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (DFS / Universally Quantify Arguments) ... "); } else if(transitionMode == utility.Impact.Mode.FindOccurrences) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (DFS / Find Occurrences) ... "); Console.printInfo(ConsoleType.FOADA, Console.RED_BRIGHT + "WARNING : " + Console.RESET + "This version does not work with transition quantifiers."); } } if(automaton.isEmpty(searchMode, transitionMode)) { Console.printInfo(ConsoleType.FOADA, "The automaton is empty..."); } else { Console.printInfo(ConsoleType.FOADA, "The automaton is not empty..."); } Console.printFOADAEndOfSession(); } /** < FOADA installed version > </br> * FOADA execution with argument <b> -v </b> or <b> --version </b> */ private static void version() { Console.printInfo(ConsoleType.FOADA, "Version " + FOADA_version); Console.printFOADAEndOfSession(); } /** < FOADA execution > * @param args command-line arguments */ public static void main(String[] args) { try { // welcome if(args.length == 0) { welcome(); } // help menu else if(args[0].equals("-h") || args[0].equals("--help")) { help(); } // solver checking else if(args[0].equals("-c") || args[0].equals("--check")) { checkSolvers(); } // emptiness checking else if(args[0].equals("-e") || args[0].equals("--empty")) { if(args.length < 2) { throw new InputFileNotFoundException(null); } else if(args.length == 2) { checkEmpty(args[1], utility.TreeSearch.Mode.BFS, utility.Impact.Mode.UniversallyQuantifyArguments); } else if(args.length == 3 && (args[2].equals("-d") || args[2].equals("--dfs"))) { checkEmpty(args[1], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.UniversallyQuantifyArguments); } else if(args.length == 3 && (args[2].equals("-o") || args[2].equals("--occurrences"))){ checkEmpty(args[1], utility.TreeSearch.Mode.BFS, utility.Impact.Mode.FindOccurrences); } else if(args.length == 4 && (args[2].equals("-d") || args[2].equals("--dfs")) && (args[3].equals("-o") || args[3].equals("--occurrences"))) { checkEmpty(args[1], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); } else if(args.length == 4 && (args[2].equals("-o") || args[2].equals("--occurrences")) && (args[3].equals("-d") || args[3].equals("--dfs"))) { checkEmpty(args[1], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); } } // inclusion checking else if(args[0].equals("-i") || args[0].equals("--inclusion")) { if(args.length < 3) { throw new InputFileNotFoundException(null); } else if(args.length == 3) { checkInclusion(args[1], args[2], utility.TreeSearch.Mode.BFS, utility.Impact.Mode.UniversallyQuantifyArguments); } else if(args.length == 4 && (args[3].equals("-d") || args[3].equals("--dfs"))) { checkInclusion(args[1], args[2], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.UniversallyQuantifyArguments); } else if(args.length == 4 && (args[3].equals("-o") || args[3].equals("--occurrences"))){ checkInclusion(args[1], args[2], utility.TreeSearch.Mode.BFS, utility.Impact.Mode.FindOccurrences); } else if(args.length == 5 && (args[3].equals("-d") || args[3].equals("--dfs")) && (args[4].equals("-o") || args[4].equals("--occurrences"))) { checkInclusion(args[1], args[2], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); } else if(args.length == 5 && (args[3].equals("-o") || args[3].equals("--occurrences")) && (args[4].equals("-d") || args[4].equals("--dfs"))) { checkInclusion(args[1], args[2], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); } } // installed version else if(args[0].equals("-v") || args[0].equals("--version")) { version(); } // unknown option else { throw new UnknownConsoleOptionException(args[0]); } } catch(FOADAException e) { e.printErrorMessage(); Console.printFOADAEndOfSession(); } } }
13,634
43.558824
152
java
FOADA
FOADA-master/old/src/exception/ANTLR4ParseCancellationException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import org.antlr.v4.runtime.misc.ParseCancellationException; import utility.Console; import utility.Console.ConsoleType; @SuppressWarnings("serial") public class ANTLR4ParseCancellationException extends FOADAException { private ParseCancellationException ANTLR4Exception; public ANTLR4ParseCancellationException(ParseCancellationException ANTLR4Exception) { type = ExceptionType.ANTLR4ParseCancellation; this.ANTLR4Exception = ANTLR4Exception; } public String getInfo() { return ANTLR4Exception.getMessage(); } public void printErrorMessage() { Console.printError(ConsoleType.ANTLR4, getInfo()); } }
1,471
28.44
84
java
FOADA
FOADA-master/old/src/exception/FOADAException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import utility.Console; import utility.Console.*; // general structure for FOADA exception (abstract class) @SuppressWarnings("serial") public abstract class FOADAException extends Throwable { public enum ExceptionType { ANTLR4ParseCancellation, ImplicationProverEnvironment, InputFileNotFound, InputFileUnsupported, InterpolatingProverEnvironment, JavaIO, JavaSMTInvalidConfiguration, UnknownConsoleOption }; public ExceptionType type; public abstract String getInfo(); public void printErrorMessage() { Console.printError(ConsoleType.FOADA, getInfo()); } }
1,437
26.132075
82
java
FOADA
FOADA-master/old/src/exception/ImplicationProverEnvironmentException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import org.sosy_lab.java_smt.api.SolverException; import utility.Console; import utility.Console.ConsoleType; @SuppressWarnings("serial") public class ImplicationProverEnvironmentException extends FOADAException { private SolverException javaSMTSolverException; private InterruptedException javaInterruptedException; public ImplicationProverEnvironmentException(SolverException javaSMTSolverException) { type = ExceptionType.ImplicationProverEnvironment; this.javaSMTSolverException = javaSMTSolverException; javaInterruptedException = null; } public ImplicationProverEnvironmentException(InterruptedException javaInterruptedException) { type = ExceptionType.ImplicationProverEnvironment; this.javaInterruptedException = javaInterruptedException; javaSMTSolverException = null; } public String getInfo() { if(javaSMTSolverException == null) { return javaInterruptedException.getMessage(); } else { return javaSMTSolverException.getMessage(); } } public void printErrorMessage() { if(javaSMTSolverException == null) { Console.printError(ConsoleType.Java, getInfo()); } else { Console.printError(ConsoleType.JavaSMT, getInfo()); } } }
1,954
26.152778
91
java
FOADA
FOADA-master/old/src/exception/InputFileNotFoundException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; // the input file cannot be found @SuppressWarnings("serial") public class InputFileNotFoundException extends FOADAException { private String filename; public InputFileNotFoundException(String filename) { type = ExceptionType.InputFileNotFound; this.filename = filename; } public String getInfo() { if(filename == null) { return "No input file is given."; } else { return "The file < " + filename + " > cannot be found."; } } }
1,303
26.744681
82
java
FOADA
FOADA-master/old/src/exception/InputFileUnsupportedException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; // the input file is not supported @SuppressWarnings("serial") public class InputFileUnsupportedException extends FOADAException { private String filename; public InputFileUnsupportedException(String filename) { type = ExceptionType.InputFileUnsupported; this.filename = filename; } public String getInfo() { return "The input file \"" + filename + "\" is not supported."; } }
1,241
27.883721
82
java
FOADA
FOADA-master/old/src/exception/InterpolatingProverEnvironmentException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import org.sosy_lab.java_smt.api.SolverException; import utility.Console; import utility.Console.ConsoleType; @SuppressWarnings("serial") public class InterpolatingProverEnvironmentException extends FOADAException { private SolverException javaSMTSolverException; private InterruptedException javaInterruptedException; public InterpolatingProverEnvironmentException(SolverException javaSMTSolverException) { type = ExceptionType.InterpolatingProverEnvironment; this.javaSMTSolverException = javaSMTSolverException; javaInterruptedException = null; } public InterpolatingProverEnvironmentException(InterruptedException javaInterruptedException) { type = ExceptionType.InterpolatingProverEnvironment; this.javaInterruptedException = javaInterruptedException; javaSMTSolverException = null; } public String getInfo() { if(javaSMTSolverException == null) { return javaInterruptedException.getMessage(); } else { return javaSMTSolverException.getMessage(); } } public void printErrorMessage() { if(javaSMTSolverException == null) { Console.printError(ConsoleType.Java, getInfo()); } else { Console.printError(ConsoleType.JavaSMT, getInfo()); } } }
2,056
27.569444
94
java
FOADA
FOADA-master/old/src/exception/JavaIOException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import java.io.IOException; import utility.Console; import utility.Console.ConsoleType; @SuppressWarnings("serial") public class JavaIOException extends FOADAException { private IOException javaIOException; public JavaIOException(IOException javaIOException) { type = ExceptionType.JavaIO; this.javaIOException = javaIOException; } public String getInfo() { return javaIOException.getMessage(); } public void printErrorMessage() { Console.printError(ConsoleType.Java, getInfo()); } }
1,355
26.12
82
java
FOADA
FOADA-master/old/src/exception/JavaSMTInvalidConfigurationException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import org.sosy_lab.common.configuration.InvalidConfigurationException; import utility.Console; import utility.Console.ConsoleType; //invalid configuration when create JavaSMT solver context @SuppressWarnings("serial") public class JavaSMTInvalidConfigurationException extends FOADAException { private InvalidConfigurationException javaSMTInvalidConfigurationException; public JavaSMTInvalidConfigurationException(InvalidConfigurationException javaSMTInvalidConfigurationException) { type = ExceptionType.JavaSMTInvalidConfiguration; this.javaSMTInvalidConfigurationException = javaSMTInvalidConfigurationException; } public String getInfo() { return javaSMTInvalidConfigurationException.getMessage(); } public void printErrorMessage() { Console.printError(ConsoleType.JavaSMT, getInfo()); } }
1,667
30.471698
112
java
FOADA
FOADA-master/old/src/exception/UnknownConsoleOptionException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; // the given console option is unknown @SuppressWarnings("serial") public class UnknownConsoleOptionException extends FOADAException { private String option; public UnknownConsoleOptionException(String option) { type = ExceptionType.UnknownConsoleOption; this.option = option; } public String getInfo() { return "Unknown option < " + option + " >."; } }
1,218
27.348837
82
java
FOADA
FOADA-master/old/src/parser/ParserTools.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import exception.ANTLR4ParseCancellationException; import exception.FOADAException; import exception.InputFileNotFoundException; import exception.InputFileUnsupportedException; import exception.JavaIOException; import parser.ADA.ANTLR4.ADALexerANTLR4; import parser.ADA.ANTLR4.ADAParserANTLR4; import parser.FOADA.ANTLR4.FOADALexerANTLR4; import parser.FOADA.ANTLR4.FOADAParserANTLR4; import parser.PA.ANTLR4.PALexerANTLR4; import parser.PA.ANTLR4.PAParserANTLR4; import structure.Automaton; import utility.Console; import utility.Console.ConsoleType; // general structure for Parser (abstract class) @SuppressWarnings("deprecation") public abstract class ParserTools { public enum ParserType { PAParser, ADAParser, FOADAParser }; public static ParserType selectAccordingToInputFile(String filename) throws FOADAException { int strLength = filename.length(); if(strLength >= 3 && filename.substring(strLength - 3, strLength).equals(".pa")) { Console.printInfo(ConsoleType.FOADA, "Type of the input file is < " + Console.YELLOW_BRIGHT + "*.pa" + Console.RESET + " >."); return ParserType.PAParser; } else if(strLength >= 4 && filename.substring(strLength - 4, strLength).equals(".ada")) { Console.printInfo(ConsoleType.FOADA, "Type of the input file is < " + Console.YELLOW_BRIGHT + "*.ada" + Console.RESET + " >."); return ParserType.ADAParser; } else if(strLength >= 6 && filename.substring(strLength - 6, strLength).equals(".foada")) { Console.printInfo(ConsoleType.FOADA, "Type of the input file is < " + Console.YELLOW_BRIGHT + "*.foada" + Console.RESET + " >."); return ParserType.FOADAParser; } else { throw new InputFileUnsupportedException(filename); } } public static Automaton buildAutomatonFromFile(String filename, ParserType parserType) throws FOADAException { try { InputStream istream = new FileInputStream(filename); //System.out.println(istream); Console.printInfo(ConsoleType.ANTLR4, "Parsing and checking the syntax in the input..."); Lexer lexer = null; Parser parser = null; CommonTokenStream tokens = null; Automaton result = null; switch(parserType) { case PAParser: lexer = new PALexerANTLR4(new ANTLRInputStream(istream)); lexer.removeErrorListeners(); lexer.addErrorListener(utility.ErrorListenerWithExceptions.listener); tokens = new CommonTokenStream(lexer); parser = new PAParserANTLR4(tokens); parser.removeErrorListeners(); parser.addErrorListener(utility.ErrorListenerWithExceptions.listener); istream.close(); result = ((PAParserANTLR4)parser).automaton().jData; break; case ADAParser: lexer = new ADALexerANTLR4(new ANTLRInputStream(istream)); lexer.removeErrorListeners(); lexer.addErrorListener(utility.ErrorListenerWithExceptions.listener); tokens = new CommonTokenStream(lexer); parser = new ADAParserANTLR4(tokens); parser.removeErrorListeners(); parser.addErrorListener(utility.ErrorListenerWithExceptions.listener); istream.close(); result = ((ADAParserANTLR4)parser).automaton().jData; break; case FOADAParser: lexer = new FOADALexerANTLR4(new ANTLRInputStream(istream)); lexer.removeErrorListeners(); lexer.addErrorListener(utility.ErrorListenerWithExceptions.listener); tokens = new CommonTokenStream(lexer); parser = new FOADAParserANTLR4(tokens); parser.removeErrorListeners(); parser.addErrorListener(utility.ErrorListenerWithExceptions.listener); istream.close(); result = ((FOADAParserANTLR4)parser).automaton().jData; break; default: lexer = null; parser = null; break; } Console.printInfo(ConsoleType.ANTLR4, "Syntax checking succeeded..."); return result; } catch(ParseCancellationException e) { throw new ANTLR4ParseCancellationException(e); } catch(FileNotFoundException e) { throw new InputFileNotFoundException(filename); } catch(IOException e) { throw new JavaIOException(e); } } }
5,544
38.049296
132
java
FOADA
FOADA-master/old/src/parser/ADA/ADAParserFunctions.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.ADA; import java.util.ArrayList; import java.util.List; import structure.Automaton; import structure.FOADAExpression; import structure.FOADAExpression.ExpressionType; import structure.FOADATransition; public abstract class ADAParserFunctions { public static void addPredicate(Automaton automaton, String nameOfPredicate) { String newName = "q" + automaton.namesOfPredicates.size() + "c"; automaton.renameMap.put(nameOfPredicate, newName); automaton.namesOfPredicates.add(newName); } public static void setInitial(Automaton automaton, FOADAExpression initial) { for(String original : automaton.renameMap.keySet()) { initial.substitute(original, automaton.renameMap.get(original)); } automaton.initial = initial; } public static void addFinal(Automaton automaton, String nameOfPredicate) { automaton.namesOfFinalStates.add(automaton.renameMap.get(nameOfPredicate)); } public static void addEvent(Automaton automaton, String nameOfEvent) { String newName = "e" + automaton.events.size() + "c"; automaton.renameMap.put(nameOfEvent, newName); automaton.events.add(newName); } public static void addVariable(Automaton automaton, String nameOfVariable) { String original0 = nameOfVariable + "0"; String newName0 = "a" + automaton.nbOfVariables + "c"; String original1 = nameOfVariable + "1"; String newName1 = "v" + automaton.nbOfVariables + "c"; automaton.renameMap.put(original0, newName0); automaton.renameMap.put(original1, newName1); automaton.nbOfVariables = automaton.nbOfVariables + 1; } public static void setInitArguments(Automaton automaton) { automaton.initial.addInitArguments(automaton.nbOfVariables); } public static void addTransition(Automaton automaton, String nameOfPredicate, String event, FOADAExpression post) { List<String> argumentsNames = new ArrayList<String>(); List<ExpressionType> argumentsTypes = new ArrayList<ExpressionType>(); List<String> inputVarNames = new ArrayList<String>(); List<ExpressionType> inputVarTypes = new ArrayList<ExpressionType>(); for(String original : automaton.renameMap.keySet()) { post.substitute(original, automaton.renameMap.get(original)); } for(int i = 0; i < automaton.nbOfVariables; i++) { argumentsNames.add("a" + i + "c"); argumentsTypes.add(ExpressionType.Integer); inputVarNames.add("v" + i + "c"); inputVarTypes.add(ExpressionType.Integer); } FOADATransition transition = new FOADATransition(automaton.renameMap.get(nameOfPredicate), argumentsNames, argumentsTypes, automaton.renameMap.get(event), inputVarNames, inputVarTypes, post); transition.right.finishTypes(); transition.right.addArguments(automaton.nbOfVariables); automaton.transitions.put(automaton.renameMap.get(nameOfPredicate) + "+" + automaton.renameMap.get(event), transition); } }
3,664
35.65
193
java
FOADA
FOADA-master/old/src/parser/ADA/ANTLR4/ADALexerANTLR4.java
// Generated from src/parser/ADA/ANTLR4/ADALexerANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.ADA.ANTLR4; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class ADALexerANTLR4 extends Lexer { static { RuntimeMetaData.checkVersion("4.7.1", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int STATES=1, INITIAL=2, FINAL=3, SYMBOLS=4, VARIABLES=5, TRANSITIONS=6, TRUE=7, FALSE=8, NOT=9, AND=10, OR=11, DISTINCT=12, ID=13, INTEGER=14, SHARP=15, LP=16, RP=17, PLUS=18, MINUS=19, TIMES=20, SLASH=21, GT=22, LT=23, GEQ=24, LEQ=25, EQUALS=26, WS=27, COMMENT=28; public static String[] channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }; public static String[] modeNames = { "DEFAULT_MODE" }; public static final String[] ruleNames = { "STATES", "INITIAL", "FINAL", "SYMBOLS", "VARIABLES", "TRANSITIONS", "TRUE", "FALSE", "NOT", "AND", "OR", "DISTINCT", "LETTER", "DIGIT", "ID", "INTEGER", "SHARP", "LP", "RP", "PLUS", "MINUS", "TIMES", "SLASH", "GT", "LT", "GEQ", "LEQ", "EQUALS", "WS", "COMMENT" }; private static final String[] _LITERAL_NAMES = { null, "'STATES'", "'INITIAL'", "'FINAL'", "'SYMBOLS'", "'VARIABLES'", "'TRANSITIONS'", "'true'", "'false'", "'not'", "'and'", "'or'", "'distinct'", null, null, "'#'", "'('", "')'", "'+'", "'-'", "'*'", "'/'", "'>'", "'<'", "'>='", "'<='", "'='" }; private static final String[] _SYMBOLIC_NAMES = { null, "STATES", "INITIAL", "FINAL", "SYMBOLS", "VARIABLES", "TRANSITIONS", "TRUE", "FALSE", "NOT", "AND", "OR", "DISTINCT", "ID", "INTEGER", "SHARP", "LP", "RP", "PLUS", "MINUS", "TIMES", "SLASH", "GT", "LT", "GEQ", "LEQ", "EQUALS", "WS", "COMMENT" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public ADALexerANTLR4(CharStream input) { super(input); _interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } @Override public String getGrammarFileName() { return "ADALexerANTLR4.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } @Override public void action(RuleContext _localctx, int ruleIndex, int actionIndex) { switch (ruleIndex) { case 28: WS_action((RuleContext)_localctx, actionIndex); break; case 29: COMMENT_action((RuleContext)_localctx, actionIndex); break; } } private void WS_action(RuleContext _localctx, int actionIndex) { switch (actionIndex) { case 0: skip(); break; } } private void COMMENT_action(RuleContext _localctx, int actionIndex) { switch (actionIndex) { case 1: skip(); break; } } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\36\u00d1\b\1\4\2"+ "\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4"+ "\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22"+ "\t\22\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31"+ "\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\3\2"+ "\3\2\3\2\3\2\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3"+ "\4\3\4\3\4\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\3\6"+ "\3\6\3\6\3\6\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\b\3\b\3"+ "\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\13\3\13\3\13\3\13"+ "\3\f\3\f\3\f\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\r\3\16\3\16\3\17\3\17\3"+ "\20\3\20\5\20\u0098\n\20\3\20\3\20\3\20\7\20\u009d\n\20\f\20\16\20\u00a0"+ "\13\20\3\21\3\21\3\21\7\21\u00a5\n\21\f\21\16\21\u00a8\13\21\5\21\u00aa"+ "\n\21\3\22\3\22\3\23\3\23\3\24\3\24\3\25\3\25\3\26\3\26\3\27\3\27\3\30"+ "\3\30\3\31\3\31\3\32\3\32\3\33\3\33\3\33\3\34\3\34\3\34\3\35\3\35\3\36"+ "\3\36\3\36\3\37\3\37\7\37\u00cb\n\37\f\37\16\37\u00ce\13\37\3\37\3\37"+ "\2\2 \3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\2\35"+ "\2\37\17!\20#\21%\22\'\23)\24+\25-\26/\27\61\30\63\31\65\32\67\339\34"+ ";\35=\36\3\2\6\4\2C\\c|\4\2&&aa\5\2\13\f\17\17\"\"\3\2\f\f\2\u00d5\2\3"+ "\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2"+ "\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31"+ "\3\2\2\2\2\37\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)"+ "\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2"+ "\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\3?\3\2\2\2\5"+ "F\3\2\2\2\7N\3\2\2\2\tT\3\2\2\2\13\\\3\2\2\2\rf\3\2\2\2\17r\3\2\2\2\21"+ "w\3\2\2\2\23}\3\2\2\2\25\u0081\3\2\2\2\27\u0085\3\2\2\2\31\u0088\3\2\2"+ "\2\33\u0091\3\2\2\2\35\u0093\3\2\2\2\37\u0097\3\2\2\2!\u00a9\3\2\2\2#"+ "\u00ab\3\2\2\2%\u00ad\3\2\2\2\'\u00af\3\2\2\2)\u00b1\3\2\2\2+\u00b3\3"+ "\2\2\2-\u00b5\3\2\2\2/\u00b7\3\2\2\2\61\u00b9\3\2\2\2\63\u00bb\3\2\2\2"+ "\65\u00bd\3\2\2\2\67\u00c0\3\2\2\29\u00c3\3\2\2\2;\u00c5\3\2\2\2=\u00c8"+ "\3\2\2\2?@\7U\2\2@A\7V\2\2AB\7C\2\2BC\7V\2\2CD\7G\2\2DE\7U\2\2E\4\3\2"+ "\2\2FG\7K\2\2GH\7P\2\2HI\7K\2\2IJ\7V\2\2JK\7K\2\2KL\7C\2\2LM\7N\2\2M\6"+ "\3\2\2\2NO\7H\2\2OP\7K\2\2PQ\7P\2\2QR\7C\2\2RS\7N\2\2S\b\3\2\2\2TU\7U"+ "\2\2UV\7[\2\2VW\7O\2\2WX\7D\2\2XY\7Q\2\2YZ\7N\2\2Z[\7U\2\2[\n\3\2\2\2"+ "\\]\7X\2\2]^\7C\2\2^_\7T\2\2_`\7K\2\2`a\7C\2\2ab\7D\2\2bc\7N\2\2cd\7G"+ "\2\2de\7U\2\2e\f\3\2\2\2fg\7V\2\2gh\7T\2\2hi\7C\2\2ij\7P\2\2jk\7U\2\2"+ "kl\7K\2\2lm\7V\2\2mn\7K\2\2no\7Q\2\2op\7P\2\2pq\7U\2\2q\16\3\2\2\2rs\7"+ "v\2\2st\7t\2\2tu\7w\2\2uv\7g\2\2v\20\3\2\2\2wx\7h\2\2xy\7c\2\2yz\7n\2"+ "\2z{\7u\2\2{|\7g\2\2|\22\3\2\2\2}~\7p\2\2~\177\7q\2\2\177\u0080\7v\2\2"+ "\u0080\24\3\2\2\2\u0081\u0082\7c\2\2\u0082\u0083\7p\2\2\u0083\u0084\7"+ "f\2\2\u0084\26\3\2\2\2\u0085\u0086\7q\2\2\u0086\u0087\7t\2\2\u0087\30"+ "\3\2\2\2\u0088\u0089\7f\2\2\u0089\u008a\7k\2\2\u008a\u008b\7u\2\2\u008b"+ "\u008c\7v\2\2\u008c\u008d\7k\2\2\u008d\u008e\7p\2\2\u008e\u008f\7e\2\2"+ "\u008f\u0090\7v\2\2\u0090\32\3\2\2\2\u0091\u0092\t\2\2\2\u0092\34\3\2"+ "\2\2\u0093\u0094\4\62;\2\u0094\36\3\2\2\2\u0095\u0098\5\33\16\2\u0096"+ "\u0098\t\3\2\2\u0097\u0095\3\2\2\2\u0097\u0096\3\2\2\2\u0098\u009e\3\2"+ "\2\2\u0099\u009d\5\33\16\2\u009a\u009d\5\35\17\2\u009b\u009d\t\3\2\2\u009c"+ "\u0099\3\2\2\2\u009c\u009a\3\2\2\2\u009c\u009b\3\2\2\2\u009d\u00a0\3\2"+ "\2\2\u009e\u009c\3\2\2\2\u009e\u009f\3\2\2\2\u009f \3\2\2\2\u00a0\u009e"+ "\3\2\2\2\u00a1\u00aa\7\62\2\2\u00a2\u00a6\4\63;\2\u00a3\u00a5\5\35\17"+ "\2\u00a4\u00a3\3\2\2\2\u00a5\u00a8\3\2\2\2\u00a6\u00a4\3\2\2\2\u00a6\u00a7"+ "\3\2\2\2\u00a7\u00aa\3\2\2\2\u00a8\u00a6\3\2\2\2\u00a9\u00a1\3\2\2\2\u00a9"+ "\u00a2\3\2\2\2\u00aa\"\3\2\2\2\u00ab\u00ac\7%\2\2\u00ac$\3\2\2\2\u00ad"+ "\u00ae\7*\2\2\u00ae&\3\2\2\2\u00af\u00b0\7+\2\2\u00b0(\3\2\2\2\u00b1\u00b2"+ "\7-\2\2\u00b2*\3\2\2\2\u00b3\u00b4\7/\2\2\u00b4,\3\2\2\2\u00b5\u00b6\7"+ ",\2\2\u00b6.\3\2\2\2\u00b7\u00b8\7\61\2\2\u00b8\60\3\2\2\2\u00b9\u00ba"+ "\7@\2\2\u00ba\62\3\2\2\2\u00bb\u00bc\7>\2\2\u00bc\64\3\2\2\2\u00bd\u00be"+ "\7@\2\2\u00be\u00bf\7?\2\2\u00bf\66\3\2\2\2\u00c0\u00c1\7>\2\2\u00c1\u00c2"+ "\7?\2\2\u00c28\3\2\2\2\u00c3\u00c4\7?\2\2\u00c4:\3\2\2\2\u00c5\u00c6\t"+ "\4\2\2\u00c6\u00c7\b\36\2\2\u00c7<\3\2\2\2\u00c8\u00cc\7=\2\2\u00c9\u00cb"+ "\n\5\2\2\u00ca\u00c9\3\2\2\2\u00cb\u00ce\3\2\2\2\u00cc\u00ca\3\2\2\2\u00cc"+ "\u00cd\3\2\2\2\u00cd\u00cf\3\2\2\2\u00ce\u00cc\3\2\2\2\u00cf\u00d0\b\37"+ "\3\2\u00d0>\3\2\2\2\t\2\u0097\u009c\u009e\u00a6\u00a9\u00cc\4\3\36\2\3"+ "\37\3"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
9,798
41.604348
97
java
FOADA
FOADA-master/old/src/parser/ADA/ANTLR4/ADAParserANTLR4.java
// Generated from ADAParserANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.ADA.ANTLR4; import exception.FOADAException; import structure.Automaton; import structure.FOADAExpression; import structure.FOADAExpression.ExpressionCategory; import structure.FOADAExpression.ExpressionType; import java.util.List; import java.util.Iterator; import java.util.ArrayList; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class ADAParserANTLR4 extends Parser { static { RuntimeMetaData.checkVersion("4.7.1", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int STATES=1, INITIAL=2, FINAL=3, SYMBOLS=4, VARIABLES=5, TRANSITIONS=6, TRUE=7, FALSE=8, NOT=9, AND=10, OR=11, DISTINCT=12, ID=13, INTEGER=14, SHARP=15, LP=16, RP=17, PLUS=18, MINUS=19, TIMES=20, SLASH=21, GT=22, LT=23, GEQ=24, LEQ=25, EQUALS=26, WS=27, COMMENT=28; public static final int RULE_automaton = 0, RULE_expression = 1; public static final String[] ruleNames = { "automaton", "expression" }; private static final String[] _LITERAL_NAMES = { null, "'STATES'", "'INITIAL'", "'FINAL'", "'SYMBOLS'", "'VARIABLES'", "'TRANSITIONS'", "'true'", "'false'", "'not'", "'and'", "'or'", "'distinct'", null, null, "'#'", "'('", "')'", "'+'", "'-'", "'*'", "'/'", "'>'", "'<'", "'>='", "'<='", "'='" }; private static final String[] _SYMBOLIC_NAMES = { null, "STATES", "INITIAL", "FINAL", "SYMBOLS", "VARIABLES", "TRANSITIONS", "TRUE", "FALSE", "NOT", "AND", "OR", "DISTINCT", "ID", "INTEGER", "SHARP", "LP", "RP", "PLUS", "MINUS", "TIMES", "SLASH", "GT", "LT", "GEQ", "LEQ", "EQUALS", "WS", "COMMENT" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "ADAParserANTLR4.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public ADAParserANTLR4(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class AutomatonContext extends ParserRuleContext { public Automaton jData; public Token nameOfPredicate; public ExpressionContext init; public Token nameOfFinal; public Token nameOfEvent; public Token nameOfVariable; public ExpressionContext post; public TerminalNode STATES() { return getToken(ADAParserANTLR4.STATES, 0); } public TerminalNode INITIAL() { return getToken(ADAParserANTLR4.INITIAL, 0); } public TerminalNode FINAL() { return getToken(ADAParserANTLR4.FINAL, 0); } public TerminalNode SYMBOLS() { return getToken(ADAParserANTLR4.SYMBOLS, 0); } public TerminalNode VARIABLES() { return getToken(ADAParserANTLR4.VARIABLES, 0); } public TerminalNode TRANSITIONS() { return getToken(ADAParserANTLR4.TRANSITIONS, 0); } public List<ExpressionContext> expression() { return getRuleContexts(ExpressionContext.class); } public ExpressionContext expression(int i) { return getRuleContext(ExpressionContext.class,i); } public List<TerminalNode> SHARP() { return getTokens(ADAParserANTLR4.SHARP); } public TerminalNode SHARP(int i) { return getToken(ADAParserANTLR4.SHARP, i); } public List<TerminalNode> ID() { return getTokens(ADAParserANTLR4.ID); } public TerminalNode ID(int i) { return getToken(ADAParserANTLR4.ID, i); } public AutomatonContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_automaton; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof ADAParserANTLR4Listener ) ((ADAParserANTLR4Listener)listener).enterAutomaton(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof ADAParserANTLR4Listener ) ((ADAParserANTLR4Listener)listener).exitAutomaton(this); } } public final AutomatonContext automaton() throws RecognitionException, FOADAException { AutomatonContext _localctx = new AutomatonContext(_ctx, getState()); enterRule(_localctx, 0, RULE_automaton); int _la; try { enterOuterAlt(_localctx, 1); { ((AutomatonContext)_localctx).jData = new Automaton(); setState(5); match(STATES); setState(10); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(6); ((AutomatonContext)_localctx).nameOfPredicate = match(ID); parser.ADA.ADAParserFunctions.addPredicate(_localctx.jData, (((AutomatonContext)_localctx).nameOfPredicate!=null?((AutomatonContext)_localctx).nameOfPredicate.getText():null)); } } setState(12); _errHandler.sync(this); _la = _input.LA(1); } setState(13); match(INITIAL); setState(14); ((AutomatonContext)_localctx).init = expression(); parser.ADA.ADAParserFunctions.setInitial(_localctx.jData, ((AutomatonContext)_localctx).init.jData); setState(16); match(FINAL); setState(21); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(17); ((AutomatonContext)_localctx).nameOfFinal = match(ID); parser.ADA.ADAParserFunctions.addFinal(_localctx.jData, (((AutomatonContext)_localctx).nameOfFinal!=null?((AutomatonContext)_localctx).nameOfFinal.getText():null)); } } setState(23); _errHandler.sync(this); _la = _input.LA(1); } setState(24); match(SYMBOLS); setState(29); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(25); ((AutomatonContext)_localctx).nameOfEvent = match(ID); parser.ADA.ADAParserFunctions.addEvent(_localctx.jData, (((AutomatonContext)_localctx).nameOfEvent!=null?((AutomatonContext)_localctx).nameOfEvent.getText():null)); } } setState(31); _errHandler.sync(this); _la = _input.LA(1); } setState(32); match(VARIABLES); setState(37); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(33); ((AutomatonContext)_localctx).nameOfVariable = match(ID); parser.ADA.ADAParserFunctions.addVariable(_localctx.jData, (((AutomatonContext)_localctx).nameOfVariable!=null?((AutomatonContext)_localctx).nameOfVariable.getText():null)); } } setState(39); _errHandler.sync(this); _la = _input.LA(1); } parser.ADA.ADAParserFunctions.setInitArguments(_localctx.jData); setState(41); match(TRANSITIONS); setState(50); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(42); ((AutomatonContext)_localctx).nameOfEvent = match(ID); setState(43); ((AutomatonContext)_localctx).nameOfPredicate = match(ID); setState(44); ((AutomatonContext)_localctx).post = expression(); setState(45); match(SHARP); parser.ADA.ADAParserFunctions.addTransition(_localctx.jData, (((AutomatonContext)_localctx).nameOfPredicate!=null?((AutomatonContext)_localctx).nameOfPredicate.getText():null), (((AutomatonContext)_localctx).nameOfEvent!=null?((AutomatonContext)_localctx).nameOfEvent.getText():null), ((AutomatonContext)_localctx).post.jData); } } setState(52); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ExpressionContext extends ParserRuleContext { public FOADAExpression jData; public Token INTEGER; public ExpressionContext e; public ExpressionContext e1; public ExpressionContext e2; public Token i; public TerminalNode MINUS() { return getToken(ADAParserANTLR4.MINUS, 0); } public TerminalNode INTEGER() { return getToken(ADAParserANTLR4.INTEGER, 0); } public TerminalNode TRUE() { return getToken(ADAParserANTLR4.TRUE, 0); } public TerminalNode FALSE() { return getToken(ADAParserANTLR4.FALSE, 0); } public TerminalNode LP() { return getToken(ADAParserANTLR4.LP, 0); } public TerminalNode NOT() { return getToken(ADAParserANTLR4.NOT, 0); } public TerminalNode RP() { return getToken(ADAParserANTLR4.RP, 0); } public List<ExpressionContext> expression() { return getRuleContexts(ExpressionContext.class); } public ExpressionContext expression(int i) { return getRuleContext(ExpressionContext.class,i); } public TerminalNode AND() { return getToken(ADAParserANTLR4.AND, 0); } public TerminalNode OR() { return getToken(ADAParserANTLR4.OR, 0); } public TerminalNode GT() { return getToken(ADAParserANTLR4.GT, 0); } public TerminalNode LT() { return getToken(ADAParserANTLR4.LT, 0); } public TerminalNode GEQ() { return getToken(ADAParserANTLR4.GEQ, 0); } public TerminalNode LEQ() { return getToken(ADAParserANTLR4.LEQ, 0); } public TerminalNode EQUALS() { return getToken(ADAParserANTLR4.EQUALS, 0); } public TerminalNode DISTINCT() { return getToken(ADAParserANTLR4.DISTINCT, 0); } public TerminalNode ID() { return getToken(ADAParserANTLR4.ID, 0); } public TerminalNode PLUS() { return getToken(ADAParserANTLR4.PLUS, 0); } public TerminalNode TIMES() { return getToken(ADAParserANTLR4.TIMES, 0); } public TerminalNode SLASH() { return getToken(ADAParserANTLR4.SLASH, 0); } public ExpressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_expression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof ADAParserANTLR4Listener ) ((ADAParserANTLR4Listener)listener).enterExpression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof ADAParserANTLR4Listener ) ((ADAParserANTLR4Listener)listener).exitExpression(this); } } public final ExpressionContext expression() throws RecognitionException { ExpressionContext _localctx = new ExpressionContext(_ctx, getState()); enterRule(_localctx, 2, RULE_expression); int _la; try { setState(179); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,8,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(53); match(MINUS); setState(54); ((ExpressionContext)_localctx).INTEGER = match(INTEGER); ((ExpressionContext)_localctx).jData = new FOADAExpression(Integer.parseInt("-" + (((ExpressionContext)_localctx).INTEGER!=null?((ExpressionContext)_localctx).INTEGER.getText():null))); } break; case 2: enterOuterAlt(_localctx, 2); { setState(56); ((ExpressionContext)_localctx).INTEGER = match(INTEGER); ((ExpressionContext)_localctx).jData = new FOADAExpression(Integer.parseInt((((ExpressionContext)_localctx).INTEGER!=null?((ExpressionContext)_localctx).INTEGER.getText():null))); } break; case 3: enterOuterAlt(_localctx, 3); { setState(58); match(TRUE); ((ExpressionContext)_localctx).jData = new FOADAExpression(true); } break; case 4: enterOuterAlt(_localctx, 4); { setState(60); match(FALSE); ((ExpressionContext)_localctx).jData = new FOADAExpression(false); } break; case 5: enterOuterAlt(_localctx, 5); { setState(62); match(LP); setState(63); match(NOT); setState(64); ((ExpressionContext)_localctx).e = expression(); setState(65); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Not, ((ExpressionContext)_localctx).e.jData); } break; case 6: enterOuterAlt(_localctx, 6); { setState(68); match(LP); setState(69); match(AND); setState(70); ((ExpressionContext)_localctx).e1 = expression(); ((ExpressionContext)_localctx).jData = ((ExpressionContext)_localctx).e1.jData; setState(75); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(72); ((ExpressionContext)_localctx).e2 = expression(); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.And, _localctx.jData, ((ExpressionContext)_localctx).e2.jData); } } setState(77); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TRUE) | (1L << FALSE) | (1L << ID) | (1L << INTEGER) | (1L << LP) | (1L << MINUS))) != 0) ); setState(79); match(RP); } break; case 7: enterOuterAlt(_localctx, 7); { setState(81); match(LP); setState(82); match(OR); setState(83); ((ExpressionContext)_localctx).e1 = expression(); ((ExpressionContext)_localctx).jData = ((ExpressionContext)_localctx).e1.jData; setState(88); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(85); ((ExpressionContext)_localctx).e2 = expression(); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Or, _localctx.jData, ((ExpressionContext)_localctx).e2.jData); } } setState(90); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TRUE) | (1L << FALSE) | (1L << ID) | (1L << INTEGER) | (1L << LP) | (1L << MINUS))) != 0) ); setState(92); match(RP); } break; case 8: enterOuterAlt(_localctx, 8); { setState(94); match(LP); setState(95); match(GT); setState(96); ((ExpressionContext)_localctx).e1 = expression(); setState(97); ((ExpressionContext)_localctx).e2 = expression(); setState(98); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.GT, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 9: enterOuterAlt(_localctx, 9); { setState(101); match(LP); setState(102); match(LT); setState(103); ((ExpressionContext)_localctx).e1 = expression(); setState(104); ((ExpressionContext)_localctx).e2 = expression(); setState(105); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.LT, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 10: enterOuterAlt(_localctx, 10); { setState(108); match(LP); setState(109); match(GEQ); setState(110); ((ExpressionContext)_localctx).e1 = expression(); setState(111); ((ExpressionContext)_localctx).e2 = expression(); setState(112); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.GEQ, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 11: enterOuterAlt(_localctx, 11); { setState(115); match(LP); setState(116); match(LEQ); setState(117); ((ExpressionContext)_localctx).e1 = expression(); setState(118); ((ExpressionContext)_localctx).e2 = expression(); setState(119); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.LEQ, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 12: enterOuterAlt(_localctx, 12); { setState(122); match(LP); setState(123); match(EQUALS); setState(124); ((ExpressionContext)_localctx).e1 = expression(); setState(125); ((ExpressionContext)_localctx).e2 = expression(); setState(126); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Equals, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 13: enterOuterAlt(_localctx, 13); { setState(129); match(LP); setState(130); match(DISTINCT); setState(131); ((ExpressionContext)_localctx).e1 = expression(); setState(132); ((ExpressionContext)_localctx).e2 = expression(); setState(133); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Distinct, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 14: enterOuterAlt(_localctx, 14); { setState(136); ((ExpressionContext)_localctx).i = match(ID); ((ExpressionContext)_localctx).jData = new FOADAExpression((((ExpressionContext)_localctx).i!=null?((ExpressionContext)_localctx).i.getText():null)); } break; case 15: enterOuterAlt(_localctx, 15); { setState(138); match(LP); setState(139); match(PLUS); setState(140); ((ExpressionContext)_localctx).e1 = expression(); setState(141); ((ExpressionContext)_localctx).e2 = expression(); setState(142); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Plus, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 16: enterOuterAlt(_localctx, 16); { setState(145); match(LP); setState(146); match(TIMES); setState(147); ((ExpressionContext)_localctx).e1 = expression(); setState(148); ((ExpressionContext)_localctx).e2 = expression(); setState(149); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Times, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 17: enterOuterAlt(_localctx, 17); { setState(152); match(LP); setState(153); match(MINUS); setState(154); ((ExpressionContext)_localctx).e1 = expression(); setState(155); ((ExpressionContext)_localctx).e2 = expression(); setState(156); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Minus, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 18: enterOuterAlt(_localctx, 18); { setState(159); match(LP); setState(160); match(SLASH); setState(161); ((ExpressionContext)_localctx).e1 = expression(); setState(162); ((ExpressionContext)_localctx).e2 = expression(); setState(163); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Slash, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 19: enterOuterAlt(_localctx, 19); { setState(166); match(LP); setState(167); ((ExpressionContext)_localctx).i = match(ID); List<FOADAExpression> arguments = new ArrayList<FOADAExpression>(); setState(172); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(169); ((ExpressionContext)_localctx).e = expression(); ((ExpressionContext)_localctx).e.jData.type = ExpressionType.Integer; arguments.add(((ExpressionContext)_localctx).e.jData); } } setState(174); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TRUE) | (1L << FALSE) | (1L << ID) | (1L << INTEGER) | (1L << LP) | (1L << MINUS))) != 0) ); ((ExpressionContext)_localctx).jData = new FOADAExpression((((ExpressionContext)_localctx).i!=null?((ExpressionContext)_localctx).i.getText():null), ExpressionType.Boolean, arguments); setState(177); match(RP); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\36\u00b8\4\2\t\2"+ "\4\3\t\3\3\2\3\2\3\2\3\2\7\2\13\n\2\f\2\16\2\16\13\2\3\2\3\2\3\2\3\2\3"+ "\2\3\2\7\2\26\n\2\f\2\16\2\31\13\2\3\2\3\2\3\2\7\2\36\n\2\f\2\16\2!\13"+ "\2\3\2\3\2\3\2\7\2&\n\2\f\2\16\2)\13\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2"+ "\7\2\63\n\2\f\2\16\2\66\13\2\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\6\3N\n\3\r\3\16\3O\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\6\3[\n\3\r\3\16\3\\\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\3\3\3\3\3\3\3\3\6\3\u00af\n\3\r\3\16\3\u00b0\3\3\3\3\3\3\5\3\u00b6"+ "\n\3\3\3\2\2\4\2\4\2\2\2\u00cf\2\6\3\2\2\2\4\u00b5\3\2\2\2\6\7\b\2\1\2"+ "\7\f\7\3\2\2\b\t\7\17\2\2\t\13\b\2\1\2\n\b\3\2\2\2\13\16\3\2\2\2\f\n\3"+ "\2\2\2\f\r\3\2\2\2\r\17\3\2\2\2\16\f\3\2\2\2\17\20\7\4\2\2\20\21\5\4\3"+ "\2\21\22\b\2\1\2\22\27\7\5\2\2\23\24\7\17\2\2\24\26\b\2\1\2\25\23\3\2"+ "\2\2\26\31\3\2\2\2\27\25\3\2\2\2\27\30\3\2\2\2\30\32\3\2\2\2\31\27\3\2"+ "\2\2\32\37\7\6\2\2\33\34\7\17\2\2\34\36\b\2\1\2\35\33\3\2\2\2\36!\3\2"+ "\2\2\37\35\3\2\2\2\37 \3\2\2\2 \"\3\2\2\2!\37\3\2\2\2\"\'\7\7\2\2#$\7"+ "\17\2\2$&\b\2\1\2%#\3\2\2\2&)\3\2\2\2\'%\3\2\2\2\'(\3\2\2\2(*\3\2\2\2"+ ")\'\3\2\2\2*+\b\2\1\2+\64\7\b\2\2,-\7\17\2\2-.\7\17\2\2./\5\4\3\2/\60"+ "\7\21\2\2\60\61\b\2\1\2\61\63\3\2\2\2\62,\3\2\2\2\63\66\3\2\2\2\64\62"+ "\3\2\2\2\64\65\3\2\2\2\65\3\3\2\2\2\66\64\3\2\2\2\678\7\25\2\289\7\20"+ "\2\29\u00b6\b\3\1\2:;\7\20\2\2;\u00b6\b\3\1\2<=\7\t\2\2=\u00b6\b\3\1\2"+ ">?\7\n\2\2?\u00b6\b\3\1\2@A\7\22\2\2AB\7\13\2\2BC\5\4\3\2CD\7\23\2\2D"+ "E\b\3\1\2E\u00b6\3\2\2\2FG\7\22\2\2GH\7\f\2\2HI\5\4\3\2IM\b\3\1\2JK\5"+ "\4\3\2KL\b\3\1\2LN\3\2\2\2MJ\3\2\2\2NO\3\2\2\2OM\3\2\2\2OP\3\2\2\2PQ\3"+ "\2\2\2QR\7\23\2\2R\u00b6\3\2\2\2ST\7\22\2\2TU\7\r\2\2UV\5\4\3\2VZ\b\3"+ "\1\2WX\5\4\3\2XY\b\3\1\2Y[\3\2\2\2ZW\3\2\2\2[\\\3\2\2\2\\Z\3\2\2\2\\]"+ "\3\2\2\2]^\3\2\2\2^_\7\23\2\2_\u00b6\3\2\2\2`a\7\22\2\2ab\7\30\2\2bc\5"+ "\4\3\2cd\5\4\3\2de\7\23\2\2ef\b\3\1\2f\u00b6\3\2\2\2gh\7\22\2\2hi\7\31"+ "\2\2ij\5\4\3\2jk\5\4\3\2kl\7\23\2\2lm\b\3\1\2m\u00b6\3\2\2\2no\7\22\2"+ "\2op\7\32\2\2pq\5\4\3\2qr\5\4\3\2rs\7\23\2\2st\b\3\1\2t\u00b6\3\2\2\2"+ "uv\7\22\2\2vw\7\33\2\2wx\5\4\3\2xy\5\4\3\2yz\7\23\2\2z{\b\3\1\2{\u00b6"+ "\3\2\2\2|}\7\22\2\2}~\7\34\2\2~\177\5\4\3\2\177\u0080\5\4\3\2\u0080\u0081"+ "\7\23\2\2\u0081\u0082\b\3\1\2\u0082\u00b6\3\2\2\2\u0083\u0084\7\22\2\2"+ "\u0084\u0085\7\16\2\2\u0085\u0086\5\4\3\2\u0086\u0087\5\4\3\2\u0087\u0088"+ "\7\23\2\2\u0088\u0089\b\3\1\2\u0089\u00b6\3\2\2\2\u008a\u008b\7\17\2\2"+ "\u008b\u00b6\b\3\1\2\u008c\u008d\7\22\2\2\u008d\u008e\7\24\2\2\u008e\u008f"+ "\5\4\3\2\u008f\u0090\5\4\3\2\u0090\u0091\7\23\2\2\u0091\u0092\b\3\1\2"+ "\u0092\u00b6\3\2\2\2\u0093\u0094\7\22\2\2\u0094\u0095\7\26\2\2\u0095\u0096"+ "\5\4\3\2\u0096\u0097\5\4\3\2\u0097\u0098\7\23\2\2\u0098\u0099\b\3\1\2"+ "\u0099\u00b6\3\2\2\2\u009a\u009b\7\22\2\2\u009b\u009c\7\25\2\2\u009c\u009d"+ "\5\4\3\2\u009d\u009e\5\4\3\2\u009e\u009f\7\23\2\2\u009f\u00a0\b\3\1\2"+ "\u00a0\u00b6\3\2\2\2\u00a1\u00a2\7\22\2\2\u00a2\u00a3\7\27\2\2\u00a3\u00a4"+ "\5\4\3\2\u00a4\u00a5\5\4\3\2\u00a5\u00a6\7\23\2\2\u00a6\u00a7\b\3\1\2"+ "\u00a7\u00b6\3\2\2\2\u00a8\u00a9\7\22\2\2\u00a9\u00aa\7\17\2\2\u00aa\u00ae"+ "\b\3\1\2\u00ab\u00ac\5\4\3\2\u00ac\u00ad\b\3\1\2\u00ad\u00af\3\2\2\2\u00ae"+ "\u00ab\3\2\2\2\u00af\u00b0\3\2\2\2\u00b0\u00ae\3\2\2\2\u00b0\u00b1\3\2"+ "\2\2\u00b1\u00b2\3\2\2\2\u00b2\u00b3\b\3\1\2\u00b3\u00b4\7\23\2\2\u00b4"+ "\u00b6\3\2\2\2\u00b5\67\3\2\2\2\u00b5:\3\2\2\2\u00b5<\3\2\2\2\u00b5>\3"+ "\2\2\2\u00b5@\3\2\2\2\u00b5F\3\2\2\2\u00b5S\3\2\2\2\u00b5`\3\2\2\2\u00b5"+ "g\3\2\2\2\u00b5n\3\2\2\2\u00b5u\3\2\2\2\u00b5|\3\2\2\2\u00b5\u0083\3\2"+ "\2\2\u00b5\u008a\3\2\2\2\u00b5\u008c\3\2\2\2\u00b5\u0093\3\2\2\2\u00b5"+ "\u009a\3\2\2\2\u00b5\u00a1\3\2\2\2\u00b5\u00a8\3\2\2\2\u00b6\5\3\2\2\2"+ "\13\f\27\37\'\64O\\\u00b0\u00b5"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
26,823
33.345711
333
java
FOADA
FOADA-master/old/src/parser/ADA/ANTLR4/ADAParserANTLR4BaseListener.java
// Generated from ADAParserANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.ADA.ANTLR4; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.TerminalNode; /** * This class provides an empty implementation of {@link ADAParserANTLR4Listener}, * which can be extended to create a listener which only needs to handle a subset * of the available methods. */ public class ADAParserANTLR4BaseListener implements ADAParserANTLR4Listener { /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAutomaton(ADAParserANTLR4.AutomatonContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAutomaton(ADAParserANTLR4.AutomatonContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterExpression(ADAParserANTLR4.ExpressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitExpression(ADAParserANTLR4.ExpressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
2,567
28.860465
82
java
FOADA
FOADA-master/old/src/parser/ADA/ANTLR4/ADAParserANTLR4Listener.java
// Generated from ADAParserANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.ADA.ANTLR4; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link ADAParserANTLR4}. */ public interface ADAParserANTLR4Listener extends ParseTreeListener { /** * Enter a parse tree produced by {@link ADAParserANTLR4#automaton}. * @param ctx the parse tree */ void enterAutomaton(ADAParserANTLR4.AutomatonContext ctx); /** * Exit a parse tree produced by {@link ADAParserANTLR4#automaton}. * @param ctx the parse tree */ void exitAutomaton(ADAParserANTLR4.AutomatonContext ctx); /** * Enter a parse tree produced by {@link ADAParserANTLR4#expression}. * @param ctx the parse tree */ void enterExpression(ADAParserANTLR4.ExpressionContext ctx); /** * Exit a parse tree produced by {@link ADAParserANTLR4#expression}. * @param ctx the parse tree */ void exitExpression(ADAParserANTLR4.ExpressionContext ctx); }
1,821
32.740741
82
java
FOADA
FOADA-master/old/src/parser/FOADA/FOADAParserFunctions.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.FOADA; import java.util.List; import structure.Automaton; import structure.FOADAExpression; import structure.FOADATransition; public abstract class FOADAParserFunctions { public static void addPredicate(Automaton automaton, String nameOfPredicate) { String newName = "q" + automaton.namesOfPredicates.size() + "c"; automaton.renameMap.put(nameOfPredicate, newName); automaton.namesOfPredicates.add(newName); } public static void addEvent(Automaton automaton, String nameOfEvent) { String newName = "e" + automaton.events.size() + "c"; automaton.renameMap.put(nameOfEvent, newName); automaton.events.add(newName); } public static void setInitial(Automaton automaton, FOADAExpression initial) { for(String original : automaton.renameMap.keySet()) { initial.substitute(original, automaton.renameMap.get(original)); } automaton.initial = initial; } public static void addFinal(Automaton automaton, String nameOfPredicate) { automaton.namesOfFinalStates.add(automaton.renameMap.get(nameOfPredicate)); } public static void addTransition(Automaton automaton, String nameOfPredicate, List<String> argumentsNames, List<FOADAExpression.ExpressionType> argumentsTypes, String event, List<String> inputVarNames, List<FOADAExpression.ExpressionType> inputVarTypes, FOADAExpression post) { for(int i = 0; i < inputVarNames.size(); i++) { String original = inputVarNames.get(i); if(automaton.renameMap.containsKey(original)) { inputVarNames.set(i, automaton.renameMap.get(original)); } else { String newName = "v" + automaton.nbOfVariables + "c"; automaton.renameMap.put(original, newName); automaton.nbOfVariables = automaton.nbOfVariables + 1; inputVarNames.set(i, newName); } } for(String original : automaton.renameMap.keySet()) { post.substitute(original, automaton.renameMap.get(original)); } int nbRenamedArguments = 0; for(int i = 0; i < argumentsNames.size(); i++) { String original = argumentsNames.get(i); String newName = "a" + nbRenamedArguments + "c"; post.substitute(original, newName); nbRenamedArguments++; argumentsNames.set(i, newName); } FOADATransition transition = new FOADATransition(automaton.renameMap.get(nameOfPredicate), argumentsNames, argumentsTypes, automaton.renameMap.get(event), inputVarNames, inputVarTypes, post); automaton.transitions.put(automaton.renameMap.get(nameOfPredicate) + "+" + automaton.renameMap.get(event), transition); } }
3,390
34.322917
193
java
FOADA
FOADA-master/old/src/parser/FOADA/ANTLR4/FOADALexerANTLR4.java
// Generated from FOADALexerANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.FOADA.ANTLR4; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class FOADALexerANTLR4 extends Lexer { static { RuntimeMetaData.checkVersion("4.7.1", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int PRED=1, EVENT=2, INITIAL=3, FINAL=4, TRANS=5, TRUE=6, FALSE=7, NOT=8, AND=9, OR=10, DISTINCT=11, INT=12, BOOL=13, ID=14, INTEGER=15, LP=16, RP=17, PLUS=18, MINUS=19, TIMES=20, SLASH=21, GT=22, LT=23, GEQ=24, LEQ=25, EQUALS=26, WS=27, COMMENT=28; public static String[] channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }; public static String[] modeNames = { "DEFAULT_MODE" }; public static final String[] ruleNames = { "PRED", "EVENT", "INITIAL", "FINAL", "TRANS", "TRUE", "FALSE", "NOT", "AND", "OR", "DISTINCT", "INT", "BOOL", "LETTER", "DIGIT", "ID", "INTEGER", "LP", "RP", "PLUS", "MINUS", "TIMES", "SLASH", "GT", "LT", "GEQ", "LEQ", "EQUALS", "WS", "COMMENT" }; private static final String[] _LITERAL_NAMES = { null, "'pred'", "'event'", "'initial'", "'final'", "'trans'", "'true'", "'false'", "'not'", "'and'", "'or'", "'distinct'", "'Int'", "'Bool'", null, null, "'('", "')'", "'+'", "'-'", "'*'", "'/'", "'>'", "'<'", "'>='", "'<='", "'='" }; private static final String[] _SYMBOLIC_NAMES = { null, "PRED", "EVENT", "INITIAL", "FINAL", "TRANS", "TRUE", "FALSE", "NOT", "AND", "OR", "DISTINCT", "INT", "BOOL", "ID", "INTEGER", "LP", "RP", "PLUS", "MINUS", "TIMES", "SLASH", "GT", "LT", "GEQ", "LEQ", "EQUALS", "WS", "COMMENT" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public FOADALexerANTLR4(CharStream input) { super(input); _interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } @Override public String getGrammarFileName() { return "FOADALexerANTLR4.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } @Override public void action(RuleContext _localctx, int ruleIndex, int actionIndex) { switch (ruleIndex) { case 28: WS_action((RuleContext)_localctx, actionIndex); break; case 29: COMMENT_action((RuleContext)_localctx, actionIndex); break; } } private void WS_action(RuleContext _localctx, int actionIndex) { switch (actionIndex) { case 0: skip(); break; } } private void COMMENT_action(RuleContext _localctx, int actionIndex) { switch (actionIndex) { case 1: skip(); break; } } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\36\u00c4\b\1\4\2"+ "\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4"+ "\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22"+ "\t\22\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31"+ "\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\3\2"+ "\3\2\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3"+ "\4\3\5\3\5\3\5\3\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3\7\3\7\3\7"+ "\3\b\3\b\3\b\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\13\3\13\3\13"+ "\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\r\3\r\3\r\3\r\3\16\3\16\3\16\3"+ "\16\3\16\3\17\3\17\3\20\3\20\3\21\3\21\5\21\u008d\n\21\3\21\3\21\3\21"+ "\7\21\u0092\n\21\f\21\16\21\u0095\13\21\3\22\3\22\3\22\7\22\u009a\n\22"+ "\f\22\16\22\u009d\13\22\5\22\u009f\n\22\3\23\3\23\3\24\3\24\3\25\3\25"+ "\3\26\3\26\3\27\3\27\3\30\3\30\3\31\3\31\3\32\3\32\3\33\3\33\3\33\3\34"+ "\3\34\3\34\3\35\3\35\3\36\3\36\3\36\3\37\3\37\7\37\u00be\n\37\f\37\16"+ "\37\u00c1\13\37\3\37\3\37\2\2 \3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13"+ "\25\f\27\r\31\16\33\17\35\2\37\2!\20#\21%\22\'\23)\24+\25-\26/\27\61\30"+ "\63\31\65\32\67\339\34;\35=\36\3\2\6\4\2C\\c|\4\2&&aa\5\2\13\f\17\17\""+ "\"\3\2\f\f\2\u00c8\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13"+ "\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2"+ "\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2"+ "\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2"+ "\2\2\2\63\3\2\2\2\2\65\3\2\2\2\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3"+ "\2\2\2\3?\3\2\2\2\5D\3\2\2\2\7J\3\2\2\2\tR\3\2\2\2\13X\3\2\2\2\r^\3\2"+ "\2\2\17c\3\2\2\2\21i\3\2\2\2\23m\3\2\2\2\25q\3\2\2\2\27t\3\2\2\2\31}\3"+ "\2\2\2\33\u0081\3\2\2\2\35\u0086\3\2\2\2\37\u0088\3\2\2\2!\u008c\3\2\2"+ "\2#\u009e\3\2\2\2%\u00a0\3\2\2\2\'\u00a2\3\2\2\2)\u00a4\3\2\2\2+\u00a6"+ "\3\2\2\2-\u00a8\3\2\2\2/\u00aa\3\2\2\2\61\u00ac\3\2\2\2\63\u00ae\3\2\2"+ "\2\65\u00b0\3\2\2\2\67\u00b3\3\2\2\29\u00b6\3\2\2\2;\u00b8\3\2\2\2=\u00bb"+ "\3\2\2\2?@\7r\2\2@A\7t\2\2AB\7g\2\2BC\7f\2\2C\4\3\2\2\2DE\7g\2\2EF\7x"+ "\2\2FG\7g\2\2GH\7p\2\2HI\7v\2\2I\6\3\2\2\2JK\7k\2\2KL\7p\2\2LM\7k\2\2"+ "MN\7v\2\2NO\7k\2\2OP\7c\2\2PQ\7n\2\2Q\b\3\2\2\2RS\7h\2\2ST\7k\2\2TU\7"+ "p\2\2UV\7c\2\2VW\7n\2\2W\n\3\2\2\2XY\7v\2\2YZ\7t\2\2Z[\7c\2\2[\\\7p\2"+ "\2\\]\7u\2\2]\f\3\2\2\2^_\7v\2\2_`\7t\2\2`a\7w\2\2ab\7g\2\2b\16\3\2\2"+ "\2cd\7h\2\2de\7c\2\2ef\7n\2\2fg\7u\2\2gh\7g\2\2h\20\3\2\2\2ij\7p\2\2j"+ "k\7q\2\2kl\7v\2\2l\22\3\2\2\2mn\7c\2\2no\7p\2\2op\7f\2\2p\24\3\2\2\2q"+ "r\7q\2\2rs\7t\2\2s\26\3\2\2\2tu\7f\2\2uv\7k\2\2vw\7u\2\2wx\7v\2\2xy\7"+ "k\2\2yz\7p\2\2z{\7e\2\2{|\7v\2\2|\30\3\2\2\2}~\7K\2\2~\177\7p\2\2\177"+ "\u0080\7v\2\2\u0080\32\3\2\2\2\u0081\u0082\7D\2\2\u0082\u0083\7q\2\2\u0083"+ "\u0084\7q\2\2\u0084\u0085\7n\2\2\u0085\34\3\2\2\2\u0086\u0087\t\2\2\2"+ "\u0087\36\3\2\2\2\u0088\u0089\4\62;\2\u0089 \3\2\2\2\u008a\u008d\5\35"+ "\17\2\u008b\u008d\t\3\2\2\u008c\u008a\3\2\2\2\u008c\u008b\3\2\2\2\u008d"+ "\u0093\3\2\2\2\u008e\u0092\5\35\17\2\u008f\u0092\5\37\20\2\u0090\u0092"+ "\t\3\2\2\u0091\u008e\3\2\2\2\u0091\u008f\3\2\2\2\u0091\u0090\3\2\2\2\u0092"+ "\u0095\3\2\2\2\u0093\u0091\3\2\2\2\u0093\u0094\3\2\2\2\u0094\"\3\2\2\2"+ "\u0095\u0093\3\2\2\2\u0096\u009f\7\62\2\2\u0097\u009b\4\63;\2\u0098\u009a"+ "\5\37\20\2\u0099\u0098\3\2\2\2\u009a\u009d\3\2\2\2\u009b\u0099\3\2\2\2"+ "\u009b\u009c\3\2\2\2\u009c\u009f\3\2\2\2\u009d\u009b\3\2\2\2\u009e\u0096"+ "\3\2\2\2\u009e\u0097\3\2\2\2\u009f$\3\2\2\2\u00a0\u00a1\7*\2\2\u00a1&"+ "\3\2\2\2\u00a2\u00a3\7+\2\2\u00a3(\3\2\2\2\u00a4\u00a5\7-\2\2\u00a5*\3"+ "\2\2\2\u00a6\u00a7\7/\2\2\u00a7,\3\2\2\2\u00a8\u00a9\7,\2\2\u00a9.\3\2"+ "\2\2\u00aa\u00ab\7\61\2\2\u00ab\60\3\2\2\2\u00ac\u00ad\7@\2\2\u00ad\62"+ "\3\2\2\2\u00ae\u00af\7>\2\2\u00af\64\3\2\2\2\u00b0\u00b1\7@\2\2\u00b1"+ "\u00b2\7?\2\2\u00b2\66\3\2\2\2\u00b3\u00b4\7>\2\2\u00b4\u00b5\7?\2\2\u00b5"+ "8\3\2\2\2\u00b6\u00b7\7?\2\2\u00b7:\3\2\2\2\u00b8\u00b9\t\4\2\2\u00b9"+ "\u00ba\b\36\2\2\u00ba<\3\2\2\2\u00bb\u00bf\7=\2\2\u00bc\u00be\n\5\2\2"+ "\u00bd\u00bc\3\2\2\2\u00be\u00c1\3\2\2\2\u00bf\u00bd\3\2\2\2\u00bf\u00c0"+ "\3\2\2\2\u00c0\u00c2\3\2\2\2\u00c1\u00bf\3\2\2\2\u00c2\u00c3\b\37\3\2"+ "\u00c3>\3\2\2\2\t\2\u008c\u0091\u0093\u009b\u009e\u00bf\4\3\36\2\3\37"+ "\3"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
9,398
40.773333
97
java
FOADA
FOADA-master/old/src/parser/FOADA/ANTLR4/FOADAParserANTLR4.java
// Generated from FOADAParserANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.FOADA.ANTLR4; import exception.FOADAException; import structure.Automaton; import structure.FOADAExpression; import structure.FOADAExpression.ExpressionCategory; import structure.FOADAExpression.ExpressionType; import java.util.List; import java.util.Iterator; import java.util.ArrayList; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class FOADAParserANTLR4 extends Parser { static { RuntimeMetaData.checkVersion("4.7.1", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int PRED=1, EVENT=2, INITIAL=3, FINAL=4, TRANS=5, TRUE=6, FALSE=7, NOT=8, AND=9, OR=10, DISTINCT=11, INT=12, BOOL=13, ID=14, INTEGER=15, LP=16, RP=17, PLUS=18, MINUS=19, TIMES=20, SLASH=21, GT=22, LT=23, GEQ=24, LEQ=25, EQUALS=26, WS=27, COMMENT=28; public static final int RULE_automaton = 0, RULE_type = 1, RULE_expression = 2; public static final String[] ruleNames = { "automaton", "type", "expression" }; private static final String[] _LITERAL_NAMES = { null, "'pred'", "'event'", "'initial'", "'final'", "'trans'", "'true'", "'false'", "'not'", "'and'", "'or'", "'distinct'", "'Int'", "'Bool'", null, null, "'('", "')'", "'+'", "'-'", "'*'", "'/'", "'>'", "'<'", "'>='", "'<='", "'='" }; private static final String[] _SYMBOLIC_NAMES = { null, "PRED", "EVENT", "INITIAL", "FINAL", "TRANS", "TRUE", "FALSE", "NOT", "AND", "OR", "DISTINCT", "INT", "BOOL", "ID", "INTEGER", "LP", "RP", "PLUS", "MINUS", "TIMES", "SLASH", "GT", "LT", "GEQ", "LEQ", "EQUALS", "WS", "COMMENT" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "FOADAParserANTLR4.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public FOADAParserANTLR4(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class AutomatonContext extends ParserRuleContext { public Automaton jData; public Token nameOfPredicate; public Token nameOfEvent; public ExpressionContext init; public Token nameOfFinal; public Token argumentName; public TypeContext argumentType; public Token event; public Token inputVarName; public TypeContext inputVarType; public ExpressionContext post; public List<TerminalNode> LP() { return getTokens(FOADAParserANTLR4.LP); } public TerminalNode LP(int i) { return getToken(FOADAParserANTLR4.LP, i); } public TerminalNode PRED() { return getToken(FOADAParserANTLR4.PRED, 0); } public List<TerminalNode> RP() { return getTokens(FOADAParserANTLR4.RP); } public TerminalNode RP(int i) { return getToken(FOADAParserANTLR4.RP, i); } public TerminalNode EVENT() { return getToken(FOADAParserANTLR4.EVENT, 0); } public TerminalNode INITIAL() { return getToken(FOADAParserANTLR4.INITIAL, 0); } public TerminalNode FINAL() { return getToken(FOADAParserANTLR4.FINAL, 0); } public List<ExpressionContext> expression() { return getRuleContexts(ExpressionContext.class); } public ExpressionContext expression(int i) { return getRuleContext(ExpressionContext.class,i); } public List<TerminalNode> TRANS() { return getTokens(FOADAParserANTLR4.TRANS); } public TerminalNode TRANS(int i) { return getToken(FOADAParserANTLR4.TRANS, i); } public List<TerminalNode> ID() { return getTokens(FOADAParserANTLR4.ID); } public TerminalNode ID(int i) { return getToken(FOADAParserANTLR4.ID, i); } public List<TypeContext> type() { return getRuleContexts(TypeContext.class); } public TypeContext type(int i) { return getRuleContext(TypeContext.class,i); } public AutomatonContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_automaton; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).enterAutomaton(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).exitAutomaton(this); } } public final AutomatonContext automaton() throws RecognitionException, FOADAException { AutomatonContext _localctx = new AutomatonContext(_ctx, getState()); enterRule(_localctx, 0, RULE_automaton); int _la; try { enterOuterAlt(_localctx, 1); { ((AutomatonContext)_localctx).jData = new Automaton(); setState(7); match(LP); setState(8); match(PRED); setState(9); match(LP); setState(14); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(10); ((AutomatonContext)_localctx).nameOfPredicate = match(ID); parser.FOADA.FOADAParserFunctions.addPredicate(_localctx.jData, (((AutomatonContext)_localctx).nameOfPredicate!=null?((AutomatonContext)_localctx).nameOfPredicate.getText():null)); } } setState(16); _errHandler.sync(this); _la = _input.LA(1); } setState(17); match(RP); setState(18); match(RP); setState(19); match(LP); setState(20); match(EVENT); setState(21); match(LP); setState(26); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(22); ((AutomatonContext)_localctx).nameOfEvent = match(ID); parser.FOADA.FOADAParserFunctions.addEvent(_localctx.jData, (((AutomatonContext)_localctx).nameOfEvent!=null?((AutomatonContext)_localctx).nameOfEvent.getText():null)); } } setState(28); _errHandler.sync(this); _la = _input.LA(1); } setState(29); match(RP); setState(30); match(RP); setState(31); match(LP); setState(32); match(INITIAL); setState(33); ((AutomatonContext)_localctx).init = expression(); setState(34); match(RP); parser.FOADA.FOADAParserFunctions.setInitial(_localctx.jData, ((AutomatonContext)_localctx).init.jData); setState(36); match(LP); setState(37); match(FINAL); setState(38); match(LP); setState(43); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(39); ((AutomatonContext)_localctx).nameOfFinal = match(ID); parser.FOADA.FOADAParserFunctions.addFinal(_localctx.jData, (((AutomatonContext)_localctx).nameOfFinal!=null?((AutomatonContext)_localctx).nameOfFinal.getText():null)); } } setState(45); _errHandler.sync(this); _la = _input.LA(1); } setState(46); match(RP); setState(47); match(RP); setState(90); _errHandler.sync(this); _la = _input.LA(1); while (_la==LP) { { { setState(48); match(LP); setState(49); match(TRANS); setState(50); match(LP); setState(51); ((AutomatonContext)_localctx).nameOfPredicate = match(ID); setState(52); match(LP); List<String> argumentsNames = new ArrayList<String>(); List<FOADAExpression.ExpressionType> argumentsTypes = new ArrayList<FOADAExpression.ExpressionType>(); setState(62); _errHandler.sync(this); _la = _input.LA(1); while (_la==LP) { { { setState(54); match(LP); setState(55); ((AutomatonContext)_localctx).argumentName = match(ID); setState(56); ((AutomatonContext)_localctx).argumentType = type(); setState(57); match(RP); argumentsNames.add((((AutomatonContext)_localctx).argumentName!=null?((AutomatonContext)_localctx).argumentName.getText():null)); argumentsTypes.add(((AutomatonContext)_localctx).argumentType.jData); } } setState(64); _errHandler.sync(this); _la = _input.LA(1); } setState(65); match(RP); setState(66); match(RP); setState(67); match(LP); setState(68); ((AutomatonContext)_localctx).event = match(ID); setState(69); match(LP); List<String> inputVarNames = new ArrayList<String>(); List<FOADAExpression.ExpressionType> inputVarTypes = new ArrayList<FOADAExpression.ExpressionType>(); setState(79); _errHandler.sync(this); _la = _input.LA(1); while (_la==LP) { { { setState(71); match(LP); setState(72); ((AutomatonContext)_localctx).inputVarName = match(ID); setState(73); ((AutomatonContext)_localctx).inputVarType = type(); setState(74); match(RP); inputVarNames.add((((AutomatonContext)_localctx).inputVarName!=null?((AutomatonContext)_localctx).inputVarName.getText():null)); inputVarTypes.add(((AutomatonContext)_localctx).inputVarType.jData); } } setState(81); _errHandler.sync(this); _la = _input.LA(1); } setState(82); match(RP); setState(83); match(RP); setState(84); ((AutomatonContext)_localctx).post = expression(); parser.FOADA.FOADAParserFunctions.addTransition(_localctx.jData, (((AutomatonContext)_localctx).nameOfPredicate!=null?((AutomatonContext)_localctx).nameOfPredicate.getText():null), argumentsNames, argumentsTypes, (((AutomatonContext)_localctx).event!=null?((AutomatonContext)_localctx).event.getText():null), inputVarNames, inputVarTypes, ((AutomatonContext)_localctx).post.jData); setState(86); match(RP); } } setState(92); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class TypeContext extends ParserRuleContext { public FOADAExpression.ExpressionType jData; public TerminalNode INT() { return getToken(FOADAParserANTLR4.INT, 0); } public TerminalNode BOOL() { return getToken(FOADAParserANTLR4.BOOL, 0); } public TypeContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_type; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).enterType(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).exitType(this); } } public final TypeContext type() throws RecognitionException { TypeContext _localctx = new TypeContext(_ctx, getState()); enterRule(_localctx, 2, RULE_type); try { setState(97); _errHandler.sync(this); switch (_input.LA(1)) { case INT: enterOuterAlt(_localctx, 1); { setState(93); match(INT); ((TypeContext)_localctx).jData = FOADAExpression.ExpressionType.Integer; } break; case BOOL: enterOuterAlt(_localctx, 2); { setState(95); match(BOOL); ((TypeContext)_localctx).jData = FOADAExpression.ExpressionType.Boolean; } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ExpressionContext extends ParserRuleContext { public FOADAExpression jData; public Token INTEGER; public ExpressionContext e; public ExpressionContext e1; public ExpressionContext e2; public Token i; public TerminalNode MINUS() { return getToken(FOADAParserANTLR4.MINUS, 0); } public TerminalNode INTEGER() { return getToken(FOADAParserANTLR4.INTEGER, 0); } public TerminalNode TRUE() { return getToken(FOADAParserANTLR4.TRUE, 0); } public TerminalNode FALSE() { return getToken(FOADAParserANTLR4.FALSE, 0); } public TerminalNode LP() { return getToken(FOADAParserANTLR4.LP, 0); } public TerminalNode NOT() { return getToken(FOADAParserANTLR4.NOT, 0); } public TerminalNode RP() { return getToken(FOADAParserANTLR4.RP, 0); } public List<ExpressionContext> expression() { return getRuleContexts(ExpressionContext.class); } public ExpressionContext expression(int i) { return getRuleContext(ExpressionContext.class,i); } public TerminalNode AND() { return getToken(FOADAParserANTLR4.AND, 0); } public TerminalNode OR() { return getToken(FOADAParserANTLR4.OR, 0); } public TerminalNode GT() { return getToken(FOADAParserANTLR4.GT, 0); } public TerminalNode LT() { return getToken(FOADAParserANTLR4.LT, 0); } public TerminalNode GEQ() { return getToken(FOADAParserANTLR4.GEQ, 0); } public TerminalNode LEQ() { return getToken(FOADAParserANTLR4.LEQ, 0); } public TerminalNode EQUALS() { return getToken(FOADAParserANTLR4.EQUALS, 0); } public TerminalNode DISTINCT() { return getToken(FOADAParserANTLR4.DISTINCT, 0); } public TerminalNode ID() { return getToken(FOADAParserANTLR4.ID, 0); } public TerminalNode PLUS() { return getToken(FOADAParserANTLR4.PLUS, 0); } public TerminalNode TIMES() { return getToken(FOADAParserANTLR4.TIMES, 0); } public TerminalNode SLASH() { return getToken(FOADAParserANTLR4.SLASH, 0); } public ExpressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_expression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).enterExpression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).exitExpression(this); } } public final ExpressionContext expression() throws RecognitionException { ExpressionContext _localctx = new ExpressionContext(_ctx, getState()); enterRule(_localctx, 4, RULE_expression); int _la; try { setState(225); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,10,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(99); match(MINUS); setState(100); ((ExpressionContext)_localctx).INTEGER = match(INTEGER); ((ExpressionContext)_localctx).jData = new FOADAExpression(Integer.parseInt("-" + (((ExpressionContext)_localctx).INTEGER!=null?((ExpressionContext)_localctx).INTEGER.getText():null))); } break; case 2: enterOuterAlt(_localctx, 2); { setState(102); ((ExpressionContext)_localctx).INTEGER = match(INTEGER); ((ExpressionContext)_localctx).jData = new FOADAExpression(Integer.parseInt((((ExpressionContext)_localctx).INTEGER!=null?((ExpressionContext)_localctx).INTEGER.getText():null))); } break; case 3: enterOuterAlt(_localctx, 3); { setState(104); match(TRUE); ((ExpressionContext)_localctx).jData = new FOADAExpression(true); } break; case 4: enterOuterAlt(_localctx, 4); { setState(106); match(FALSE); ((ExpressionContext)_localctx).jData = new FOADAExpression(false); } break; case 5: enterOuterAlt(_localctx, 5); { setState(108); match(LP); setState(109); match(NOT); setState(110); ((ExpressionContext)_localctx).e = expression(); setState(111); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Not, ((ExpressionContext)_localctx).e.jData); } break; case 6: enterOuterAlt(_localctx, 6); { setState(114); match(LP); setState(115); match(AND); setState(116); ((ExpressionContext)_localctx).e1 = expression(); ((ExpressionContext)_localctx).jData = ((ExpressionContext)_localctx).e1.jData; setState(121); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(118); ((ExpressionContext)_localctx).e2 = expression(); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.And, _localctx.jData, ((ExpressionContext)_localctx).e2.jData); } } setState(123); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TRUE) | (1L << FALSE) | (1L << ID) | (1L << INTEGER) | (1L << LP) | (1L << MINUS))) != 0) ); setState(125); match(RP); } break; case 7: enterOuterAlt(_localctx, 7); { setState(127); match(LP); setState(128); match(OR); setState(129); ((ExpressionContext)_localctx).e1 = expression(); ((ExpressionContext)_localctx).jData = ((ExpressionContext)_localctx).e1.jData; setState(134); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(131); ((ExpressionContext)_localctx).e2 = expression(); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Or, _localctx.jData, ((ExpressionContext)_localctx).e2.jData); } } setState(136); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TRUE) | (1L << FALSE) | (1L << ID) | (1L << INTEGER) | (1L << LP) | (1L << MINUS))) != 0) ); setState(138); match(RP); } break; case 8: enterOuterAlt(_localctx, 8); { setState(140); match(LP); setState(141); match(GT); setState(142); ((ExpressionContext)_localctx).e1 = expression(); setState(143); ((ExpressionContext)_localctx).e2 = expression(); setState(144); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.GT, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 9: enterOuterAlt(_localctx, 9); { setState(147); match(LP); setState(148); match(LT); setState(149); ((ExpressionContext)_localctx).e1 = expression(); setState(150); ((ExpressionContext)_localctx).e2 = expression(); setState(151); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.LT, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 10: enterOuterAlt(_localctx, 10); { setState(154); match(LP); setState(155); match(GEQ); setState(156); ((ExpressionContext)_localctx).e1 = expression(); setState(157); ((ExpressionContext)_localctx).e2 = expression(); setState(158); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.GEQ, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 11: enterOuterAlt(_localctx, 11); { setState(161); match(LP); setState(162); match(LEQ); setState(163); ((ExpressionContext)_localctx).e1 = expression(); setState(164); ((ExpressionContext)_localctx).e2 = expression(); setState(165); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.LEQ, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 12: enterOuterAlt(_localctx, 12); { setState(168); match(LP); setState(169); match(EQUALS); setState(170); ((ExpressionContext)_localctx).e1 = expression(); setState(171); ((ExpressionContext)_localctx).e2 = expression(); setState(172); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Equals, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 13: enterOuterAlt(_localctx, 13); { setState(175); match(LP); setState(176); match(DISTINCT); setState(177); ((ExpressionContext)_localctx).e1 = expression(); setState(178); ((ExpressionContext)_localctx).e2 = expression(); setState(179); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Distinct, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 14: enterOuterAlt(_localctx, 14); { setState(182); ((ExpressionContext)_localctx).i = match(ID); ((ExpressionContext)_localctx).jData = new FOADAExpression((((ExpressionContext)_localctx).i!=null?((ExpressionContext)_localctx).i.getText():null)); } break; case 15: enterOuterAlt(_localctx, 15); { setState(184); match(LP); setState(185); match(PLUS); setState(186); ((ExpressionContext)_localctx).e1 = expression(); setState(187); ((ExpressionContext)_localctx).e2 = expression(); setState(188); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Plus, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 16: enterOuterAlt(_localctx, 16); { setState(191); match(LP); setState(192); match(TIMES); setState(193); ((ExpressionContext)_localctx).e1 = expression(); setState(194); ((ExpressionContext)_localctx).e2 = expression(); setState(195); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Times, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 17: enterOuterAlt(_localctx, 17); { setState(198); match(LP); setState(199); match(MINUS); setState(200); ((ExpressionContext)_localctx).e1 = expression(); setState(201); ((ExpressionContext)_localctx).e2 = expression(); setState(202); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Minus, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 18: enterOuterAlt(_localctx, 18); { setState(205); match(LP); setState(206); match(SLASH); setState(207); ((ExpressionContext)_localctx).e1 = expression(); setState(208); ((ExpressionContext)_localctx).e2 = expression(); setState(209); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Slash, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 19: enterOuterAlt(_localctx, 19); { setState(212); match(LP); setState(213); ((ExpressionContext)_localctx).i = match(ID); List<FOADAExpression> arguments = new ArrayList<FOADAExpression>(); setState(218); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(215); ((ExpressionContext)_localctx).e = expression(); ((ExpressionContext)_localctx).e.jData.type = ExpressionType.Integer; arguments.add(((ExpressionContext)_localctx).e.jData); } } setState(220); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TRUE) | (1L << FALSE) | (1L << ID) | (1L << INTEGER) | (1L << LP) | (1L << MINUS))) != 0) ); ((ExpressionContext)_localctx).jData = new FOADAExpression((((ExpressionContext)_localctx).i!=null?((ExpressionContext)_localctx).i.getText():null), ExpressionType.Boolean, arguments); setState(223); match(RP); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\36\u00e6\4\2\t\2"+ "\4\3\t\3\4\4\t\4\3\2\3\2\3\2\3\2\3\2\3\2\7\2\17\n\2\f\2\16\2\22\13\2\3"+ "\2\3\2\3\2\3\2\3\2\3\2\3\2\7\2\33\n\2\f\2\16\2\36\13\2\3\2\3\2\3\2\3\2"+ "\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\7\2,\n\2\f\2\16\2/\13\2\3\2\3\2\3\2\3"+ "\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\7\2?\n\2\f\2\16\2B\13\2\3\2"+ "\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\7\2P\n\2\f\2\16\2S\13\2\3"+ "\2\3\2\3\2\3\2\3\2\3\2\7\2[\n\2\f\2\16\2^\13\2\3\3\3\3\3\3\3\3\5\3d\n"+ "\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4"+ "\3\4\3\4\3\4\3\4\3\4\6\4|\n\4\r\4\16\4}\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3"+ "\4\3\4\6\4\u0089\n\4\r\4\16\4\u008a\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3"+ "\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4"+ "\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3"+ "\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4"+ "\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3"+ "\4\3\4\6\4\u00dd\n\4\r\4\16\4\u00de\3\4\3\4\3\4\5\4\u00e4\n\4\3\4\2\2"+ "\5\2\4\6\2\2\2\u00fe\2\b\3\2\2\2\4c\3\2\2\2\6\u00e3\3\2\2\2\b\t\b\2\1"+ "\2\t\n\7\22\2\2\n\13\7\3\2\2\13\20\7\22\2\2\f\r\7\20\2\2\r\17\b\2\1\2"+ "\16\f\3\2\2\2\17\22\3\2\2\2\20\16\3\2\2\2\20\21\3\2\2\2\21\23\3\2\2\2"+ "\22\20\3\2\2\2\23\24\7\23\2\2\24\25\7\23\2\2\25\26\7\22\2\2\26\27\7\4"+ "\2\2\27\34\7\22\2\2\30\31\7\20\2\2\31\33\b\2\1\2\32\30\3\2\2\2\33\36\3"+ "\2\2\2\34\32\3\2\2\2\34\35\3\2\2\2\35\37\3\2\2\2\36\34\3\2\2\2\37 \7\23"+ "\2\2 !\7\23\2\2!\"\7\22\2\2\"#\7\5\2\2#$\5\6\4\2$%\7\23\2\2%&\b\2\1\2"+ "&\'\7\22\2\2\'(\7\6\2\2(-\7\22\2\2)*\7\20\2\2*,\b\2\1\2+)\3\2\2\2,/\3"+ "\2\2\2-+\3\2\2\2-.\3\2\2\2.\60\3\2\2\2/-\3\2\2\2\60\61\7\23\2\2\61\\\7"+ "\23\2\2\62\63\7\22\2\2\63\64\7\7\2\2\64\65\7\22\2\2\65\66\7\20\2\2\66"+ "\67\7\22\2\2\67@\b\2\1\289\7\22\2\29:\7\20\2\2:;\5\4\3\2;<\7\23\2\2<="+ "\b\2\1\2=?\3\2\2\2>8\3\2\2\2?B\3\2\2\2@>\3\2\2\2@A\3\2\2\2AC\3\2\2\2B"+ "@\3\2\2\2CD\7\23\2\2DE\7\23\2\2EF\7\22\2\2FG\7\20\2\2GH\7\22\2\2HQ\b\2"+ "\1\2IJ\7\22\2\2JK\7\20\2\2KL\5\4\3\2LM\7\23\2\2MN\b\2\1\2NP\3\2\2\2OI"+ "\3\2\2\2PS\3\2\2\2QO\3\2\2\2QR\3\2\2\2RT\3\2\2\2SQ\3\2\2\2TU\7\23\2\2"+ "UV\7\23\2\2VW\5\6\4\2WX\b\2\1\2XY\7\23\2\2Y[\3\2\2\2Z\62\3\2\2\2[^\3\2"+ "\2\2\\Z\3\2\2\2\\]\3\2\2\2]\3\3\2\2\2^\\\3\2\2\2_`\7\16\2\2`d\b\3\1\2"+ "ab\7\17\2\2bd\b\3\1\2c_\3\2\2\2ca\3\2\2\2d\5\3\2\2\2ef\7\25\2\2fg\7\21"+ "\2\2g\u00e4\b\4\1\2hi\7\21\2\2i\u00e4\b\4\1\2jk\7\b\2\2k\u00e4\b\4\1\2"+ "lm\7\t\2\2m\u00e4\b\4\1\2no\7\22\2\2op\7\n\2\2pq\5\6\4\2qr\7\23\2\2rs"+ "\b\4\1\2s\u00e4\3\2\2\2tu\7\22\2\2uv\7\13\2\2vw\5\6\4\2w{\b\4\1\2xy\5"+ "\6\4\2yz\b\4\1\2z|\3\2\2\2{x\3\2\2\2|}\3\2\2\2}{\3\2\2\2}~\3\2\2\2~\177"+ "\3\2\2\2\177\u0080\7\23\2\2\u0080\u00e4\3\2\2\2\u0081\u0082\7\22\2\2\u0082"+ "\u0083\7\f\2\2\u0083\u0084\5\6\4\2\u0084\u0088\b\4\1\2\u0085\u0086\5\6"+ "\4\2\u0086\u0087\b\4\1\2\u0087\u0089\3\2\2\2\u0088\u0085\3\2\2\2\u0089"+ "\u008a\3\2\2\2\u008a\u0088\3\2\2\2\u008a\u008b\3\2\2\2\u008b\u008c\3\2"+ "\2\2\u008c\u008d\7\23\2\2\u008d\u00e4\3\2\2\2\u008e\u008f\7\22\2\2\u008f"+ "\u0090\7\30\2\2\u0090\u0091\5\6\4\2\u0091\u0092\5\6\4\2\u0092\u0093\7"+ "\23\2\2\u0093\u0094\b\4\1\2\u0094\u00e4\3\2\2\2\u0095\u0096\7\22\2\2\u0096"+ "\u0097\7\31\2\2\u0097\u0098\5\6\4\2\u0098\u0099\5\6\4\2\u0099\u009a\7"+ "\23\2\2\u009a\u009b\b\4\1\2\u009b\u00e4\3\2\2\2\u009c\u009d\7\22\2\2\u009d"+ "\u009e\7\32\2\2\u009e\u009f\5\6\4\2\u009f\u00a0\5\6\4\2\u00a0\u00a1\7"+ "\23\2\2\u00a1\u00a2\b\4\1\2\u00a2\u00e4\3\2\2\2\u00a3\u00a4\7\22\2\2\u00a4"+ "\u00a5\7\33\2\2\u00a5\u00a6\5\6\4\2\u00a6\u00a7\5\6\4\2\u00a7\u00a8\7"+ "\23\2\2\u00a8\u00a9\b\4\1\2\u00a9\u00e4\3\2\2\2\u00aa\u00ab\7\22\2\2\u00ab"+ "\u00ac\7\34\2\2\u00ac\u00ad\5\6\4\2\u00ad\u00ae\5\6\4\2\u00ae\u00af\7"+ "\23\2\2\u00af\u00b0\b\4\1\2\u00b0\u00e4\3\2\2\2\u00b1\u00b2\7\22\2\2\u00b2"+ "\u00b3\7\r\2\2\u00b3\u00b4\5\6\4\2\u00b4\u00b5\5\6\4\2\u00b5\u00b6\7\23"+ "\2\2\u00b6\u00b7\b\4\1\2\u00b7\u00e4\3\2\2\2\u00b8\u00b9\7\20\2\2\u00b9"+ "\u00e4\b\4\1\2\u00ba\u00bb\7\22\2\2\u00bb\u00bc\7\24\2\2\u00bc\u00bd\5"+ "\6\4\2\u00bd\u00be\5\6\4\2\u00be\u00bf\7\23\2\2\u00bf\u00c0\b\4\1\2\u00c0"+ "\u00e4\3\2\2\2\u00c1\u00c2\7\22\2\2\u00c2\u00c3\7\26\2\2\u00c3\u00c4\5"+ "\6\4\2\u00c4\u00c5\5\6\4\2\u00c5\u00c6\7\23\2\2\u00c6\u00c7\b\4\1\2\u00c7"+ "\u00e4\3\2\2\2\u00c8\u00c9\7\22\2\2\u00c9\u00ca\7\25\2\2\u00ca\u00cb\5"+ "\6\4\2\u00cb\u00cc\5\6\4\2\u00cc\u00cd\7\23\2\2\u00cd\u00ce\b\4\1\2\u00ce"+ "\u00e4\3\2\2\2\u00cf\u00d0\7\22\2\2\u00d0\u00d1\7\27\2\2\u00d1\u00d2\5"+ "\6\4\2\u00d2\u00d3\5\6\4\2\u00d3\u00d4\7\23\2\2\u00d4\u00d5\b\4\1\2\u00d5"+ "\u00e4\3\2\2\2\u00d6\u00d7\7\22\2\2\u00d7\u00d8\7\20\2\2\u00d8\u00dc\b"+ "\4\1\2\u00d9\u00da\5\6\4\2\u00da\u00db\b\4\1\2\u00db\u00dd\3\2\2\2\u00dc"+ "\u00d9\3\2\2\2\u00dd\u00de\3\2\2\2\u00de\u00dc\3\2\2\2\u00de\u00df\3\2"+ "\2\2\u00df\u00e0\3\2\2\2\u00e0\u00e1\b\4\1\2\u00e1\u00e2\7\23\2\2\u00e2"+ "\u00e4\3\2\2\2\u00e3e\3\2\2\2\u00e3h\3\2\2\2\u00e3j\3\2\2\2\u00e3l\3\2"+ "\2\2\u00e3n\3\2\2\2\u00e3t\3\2\2\2\u00e3\u0081\3\2\2\2\u00e3\u008e\3\2"+ "\2\2\u00e3\u0095\3\2\2\2\u00e3\u009c\3\2\2\2\u00e3\u00a3\3\2\2\2\u00e3"+ "\u00aa\3\2\2\2\u00e3\u00b1\3\2\2\2\u00e3\u00b8\3\2\2\2\u00e3\u00ba\3\2"+ "\2\2\u00e3\u00c1\3\2\2\2\u00e3\u00c8\3\2\2\2\u00e3\u00cf\3\2\2\2\u00e3"+ "\u00d6\3\2\2\2\u00e4\7\3\2\2\2\r\20\34-@Q\\c}\u008a\u00de\u00e3"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
32,131
32.752101
388
java
FOADA
FOADA-master/old/src/parser/FOADA/ANTLR4/FOADAParserANTLR4BaseListener.java
// Generated from FOADAParserANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.FOADA.ANTLR4; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.TerminalNode; /** * This class provides an empty implementation of {@link FOADAParserANTLR4Listener}, * which can be extended to create a listener which only needs to handle a subset * of the available methods. */ public class FOADAParserANTLR4BaseListener implements FOADAParserANTLR4Listener { /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAutomaton(FOADAParserANTLR4.AutomatonContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAutomaton(FOADAParserANTLR4.AutomatonContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterType(FOADAParserANTLR4.TypeContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitType(FOADAParserANTLR4.TypeContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterExpression(FOADAParserANTLR4.ExpressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitExpression(FOADAParserANTLR4.ExpressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
2,896
28.561224
84
java
FOADA
FOADA-master/old/src/parser/FOADA/ANTLR4/FOADAParserANTLR4Listener.java
// Generated from FOADAParserANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.FOADA.ANTLR4; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link FOADAParserANTLR4}. */ public interface FOADAParserANTLR4Listener extends ParseTreeListener { /** * Enter a parse tree produced by {@link FOADAParserANTLR4#automaton}. * @param ctx the parse tree */ void enterAutomaton(FOADAParserANTLR4.AutomatonContext ctx); /** * Exit a parse tree produced by {@link FOADAParserANTLR4#automaton}. * @param ctx the parse tree */ void exitAutomaton(FOADAParserANTLR4.AutomatonContext ctx); /** * Enter a parse tree produced by {@link FOADAParserANTLR4#type}. * @param ctx the parse tree */ void enterType(FOADAParserANTLR4.TypeContext ctx); /** * Exit a parse tree produced by {@link FOADAParserANTLR4#type}. * @param ctx the parse tree */ void exitType(FOADAParserANTLR4.TypeContext ctx); /** * Enter a parse tree produced by {@link FOADAParserANTLR4#expression}. * @param ctx the parse tree */ void enterExpression(FOADAParserANTLR4.ExpressionContext ctx); /** * Exit a parse tree produced by {@link FOADAParserANTLR4#expression}. * @param ctx the parse tree */ void exitExpression(FOADAParserANTLR4.ExpressionContext ctx); }
2,161
32.78125
82
java
FOADA
FOADA-master/old/src/parser/PA/PAParserFunctions.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.PA; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import structure.Automaton; import structure.FOADAExpression; import structure.FOADAExpression.ExpressionType; import structure.FOADATransition; public abstract class PAParserFunctions { public static void setInitial(Automaton automaton, FOADAExpression initial) { automaton.initial = initial; } public static void setFinal(Automaton automaton, List<String> finalList) { automaton.namesOfFinalStates.addAll(finalList); } public static void addTransition(Automaton automaton, String left, List<String> argumentList, String event, String inputVarName, FOADAExpression post) { String newNameLeft; if(!automaton.renameMap.containsKey(left.replaceAll("\\s*", ""))) { newNameLeft = "q" + automaton.namesOfPredicates.size() + "c"; automaton.renameMap.put(left.replaceAll("\\s*", ""), newNameLeft); automaton.namesOfPredicates.add(newNameLeft); } else { newNameLeft = automaton.renameMap.get(left.replaceAll("\\s*", "")); } int nbRenamedArguments = 0; for(int i = 0; i < argumentList.size(); i++) { String original = argumentList.get(i); String newNameArgument = "a" + nbRenamedArguments + "c"; post.substitute(original, newNameArgument); nbRenamedArguments++; argumentList.set(i, newNameArgument); } List<ExpressionType> argumentsTypes = new ArrayList<ExpressionType>(); for(int i = 1; i <= argumentList.size(); i++) { argumentsTypes.add(ExpressionType.Integer); } String newNameEvent; if(!automaton.renameMap.containsKey(event.replaceAll("\\s*", ""))) { newNameEvent = "e" + automaton.events.size() + "c"; automaton.renameMap.put(event.replaceAll("\\s*", ""), newNameEvent); automaton.events.add(newNameEvent); } else { newNameEvent = automaton.renameMap.get(event.replaceAll("\\s*", "")); } List<String> inputVarNames = new ArrayList<String>(); String newNameInputVar = "v0c"; post.substitute(inputVarName, newNameInputVar); inputVarNames.add(newNameInputVar); List<ExpressionType> inputVarTypes = new ArrayList<ExpressionType>(); inputVarTypes.add(ExpressionType.Integer); FOADATransition transition = new FOADATransition(newNameLeft, argumentList, argumentsTypes, newNameEvent, inputVarNames, inputVarTypes, post); automaton.transitions.put(newNameLeft + "+" + newNameEvent, transition); } public static void finalize(Automaton automaton) { for(Entry<String, String> e : automaton.renameMap.entrySet()) { automaton.initial.substitute(e.getKey(), e.getValue()); for(int i = 0; i < automaton.namesOfFinalStates.size(); i++) { if(automaton.namesOfFinalStates.get(i).equals(e.getKey())) { automaton.namesOfFinalStates.set(i, e.getValue()); } } for(FOADATransition transition : automaton.transitions.values()) { if(transition.event.equals(e.getKey())) { transition.event = e.getValue(); } transition.right.substitute(e.getKey(), e.getValue()); } } automaton.nbOfVariables = 1; } }
3,864
34.787037
151
java
FOADA
FOADA-master/old/src/parser/PA/ANTLR4/PALexerANTLR4.java
// Generated from PALexerANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.PA.ANTLR4; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class PALexerANTLR4 extends Lexer { static { RuntimeMetaData.checkVersion("4.7.1", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int START=1, FINAL=2, NONE=3, FALSE=4, TRUE=5, FORALL=6, EXISTS=7, TL=8, TR=9, AND=10, OR=11, EQUALS=12, DISTINCTS=13, INTEGER=14, ID=15, LP=16, RP=17, POINT=18, TWOPOINTS=19, COM=20, WS=21, COMMENT=22; public static String[] channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }; public static String[] modeNames = { "DEFAULT_MODE" }; public static final String[] ruleNames = { "START", "FINAL", "NONE", "FALSE", "TRUE", "FORALL", "EXISTS", "TL", "TR", "AND", "OR", "EQUALS", "DISTINCTS", "LETTER", "DIGIT", "INTEGER", "ID", "LP", "RP", "POINT", "TWOPOINTS", "COM", "WS", "COMMENT" }; private static final String[] _LITERAL_NAMES = { null, "'start'", "'final'", "'none'", "'false'", "'true'", "'forall'", "'exists'", "'--('", "')->'", "'/\\'", "'\\/'", "'='", "'!='", null, null, "'('", "')'", "'.'", "':'", "','" }; private static final String[] _SYMBOLIC_NAMES = { null, "START", "FINAL", "NONE", "FALSE", "TRUE", "FORALL", "EXISTS", "TL", "TR", "AND", "OR", "EQUALS", "DISTINCTS", "INTEGER", "ID", "LP", "RP", "POINT", "TWOPOINTS", "COM", "WS", "COMMENT" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public PALexerANTLR4(CharStream input) { super(input); _interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } @Override public String getGrammarFileName() { return "PALexerANTLR4.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } @Override public void action(RuleContext _localctx, int ruleIndex, int actionIndex) { switch (ruleIndex) { case 22: WS_action((RuleContext)_localctx, actionIndex); break; case 23: COMMENT_action((RuleContext)_localctx, actionIndex); break; } } private void WS_action(RuleContext _localctx, int actionIndex) { switch (actionIndex) { case 0: skip(); break; } } private void COMMENT_action(RuleContext _localctx, int actionIndex) { switch (actionIndex) { case 1: skip(); break; } } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\30\u00bd\b\1\4\2"+ "\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4"+ "\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22"+ "\t\22\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31"+ "\t\31\3\2\3\2\3\2\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4"+ "\3\4\3\5\3\5\3\5\3\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3\7\3\7\3\7\3"+ "\7\3\7\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\13"+ "\3\13\3\13\3\f\3\f\3\f\3\r\3\r\3\16\3\16\3\16\3\17\3\17\3\20\3\20\3\21"+ "\3\21\3\21\7\21x\n\21\f\21\16\21{\13\21\5\21}\n\21\3\22\3\22\3\22\3\22"+ "\7\22\u0083\n\22\f\22\16\22\u0086\13\22\3\22\3\22\7\22\u008a\n\22\f\22"+ "\16\22\u008d\13\22\3\22\3\22\3\22\7\22\u0092\n\22\f\22\16\22\u0095\13"+ "\22\3\22\3\22\3\22\7\22\u009a\n\22\f\22\16\22\u009d\13\22\3\22\3\22\5"+ "\22\u00a1\n\22\3\23\3\23\3\24\3\24\3\25\3\25\3\26\3\26\3\27\3\27\3\30"+ "\3\30\3\30\3\31\3\31\3\31\3\31\7\31\u00b4\n\31\f\31\16\31\u00b7\13\31"+ "\3\31\3\31\3\31\3\31\3\31\2\2\32\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23"+ "\13\25\f\27\r\31\16\33\17\35\2\37\2!\20#\21%\22\'\23)\24+\25-\26/\27\61"+ "\30\3\2\t\4\2C\\c|\6\2,-//\61\61>@\3\2@@\3\2__\3\2\177\177\5\2\13\f\17"+ "\17\"\"\3\2\f\f\2\u00c7\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2"+ "\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25"+ "\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2"+ "\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2"+ "\61\3\2\2\2\3\63\3\2\2\2\59\3\2\2\2\7?\3\2\2\2\tD\3\2\2\2\13J\3\2\2\2"+ "\rO\3\2\2\2\17V\3\2\2\2\21]\3\2\2\2\23a\3\2\2\2\25e\3\2\2\2\27h\3\2\2"+ "\2\31k\3\2\2\2\33m\3\2\2\2\35p\3\2\2\2\37r\3\2\2\2!|\3\2\2\2#\u00a0\3"+ "\2\2\2%\u00a2\3\2\2\2\'\u00a4\3\2\2\2)\u00a6\3\2\2\2+\u00a8\3\2\2\2-\u00aa"+ "\3\2\2\2/\u00ac\3\2\2\2\61\u00af\3\2\2\2\63\64\7u\2\2\64\65\7v\2\2\65"+ "\66\7c\2\2\66\67\7t\2\2\678\7v\2\28\4\3\2\2\29:\7h\2\2:;\7k\2\2;<\7p\2"+ "\2<=\7c\2\2=>\7n\2\2>\6\3\2\2\2?@\7p\2\2@A\7q\2\2AB\7p\2\2BC\7g\2\2C\b"+ "\3\2\2\2DE\7h\2\2EF\7c\2\2FG\7n\2\2GH\7u\2\2HI\7g\2\2I\n\3\2\2\2JK\7v"+ "\2\2KL\7t\2\2LM\7w\2\2MN\7g\2\2N\f\3\2\2\2OP\7h\2\2PQ\7q\2\2QR\7t\2\2"+ "RS\7c\2\2ST\7n\2\2TU\7n\2\2U\16\3\2\2\2VW\7g\2\2WX\7z\2\2XY\7k\2\2YZ\7"+ "u\2\2Z[\7v\2\2[\\\7u\2\2\\\20\3\2\2\2]^\7/\2\2^_\7/\2\2_`\7*\2\2`\22\3"+ "\2\2\2ab\7+\2\2bc\7/\2\2cd\7@\2\2d\24\3\2\2\2ef\7\61\2\2fg\7^\2\2g\26"+ "\3\2\2\2hi\7^\2\2ij\7\61\2\2j\30\3\2\2\2kl\7?\2\2l\32\3\2\2\2mn\7#\2\2"+ "no\7?\2\2o\34\3\2\2\2pq\t\2\2\2q\36\3\2\2\2rs\4\62;\2s \3\2\2\2t}\7\62"+ "\2\2uy\4\63;\2vx\5\37\20\2wv\3\2\2\2x{\3\2\2\2yw\3\2\2\2yz\3\2\2\2z}\3"+ "\2\2\2{y\3\2\2\2|t\3\2\2\2|u\3\2\2\2}\"\3\2\2\2~\u0084\5\35\17\2\177\u0083"+ "\5\35\17\2\u0080\u0083\5\37\20\2\u0081\u0083\t\3\2\2\u0082\177\3\2\2\2"+ "\u0082\u0080\3\2\2\2\u0082\u0081\3\2\2\2\u0083\u0086\3\2\2\2\u0084\u0082"+ "\3\2\2\2\u0084\u0085\3\2\2\2\u0085\u00a1\3\2\2\2\u0086\u0084\3\2\2\2\u0087"+ "\u008b\7>\2\2\u0088\u008a\n\4\2\2\u0089\u0088\3\2\2\2\u008a\u008d\3\2"+ "\2\2\u008b\u0089\3\2\2\2\u008b\u008c\3\2\2\2\u008c\u008e\3\2\2\2\u008d"+ "\u008b\3\2\2\2\u008e\u00a1\7@\2\2\u008f\u0093\7]\2\2\u0090\u0092\n\5\2"+ "\2\u0091\u0090\3\2\2\2\u0092\u0095\3\2\2\2\u0093\u0091\3\2\2\2\u0093\u0094"+ "\3\2\2\2\u0094\u0096\3\2\2\2\u0095\u0093\3\2\2\2\u0096\u00a1\7_\2\2\u0097"+ "\u009b\7}\2\2\u0098\u009a\n\6\2\2\u0099\u0098\3\2\2\2\u009a\u009d\3\2"+ "\2\2\u009b\u0099\3\2\2\2\u009b\u009c\3\2\2\2\u009c\u009e\3\2\2\2\u009d"+ "\u009b\3\2\2\2\u009e\u00a1\7\177\2\2\u009f\u00a1\7&\2\2\u00a0~\3\2\2\2"+ "\u00a0\u0087\3\2\2\2\u00a0\u008f\3\2\2\2\u00a0\u0097\3\2\2\2\u00a0\u009f"+ "\3\2\2\2\u00a1$\3\2\2\2\u00a2\u00a3\7*\2\2\u00a3&\3\2\2\2\u00a4\u00a5"+ "\7+\2\2\u00a5(\3\2\2\2\u00a6\u00a7\7\60\2\2\u00a7*\3\2\2\2\u00a8\u00a9"+ "\7<\2\2\u00a9,\3\2\2\2\u00aa\u00ab\7.\2\2\u00ab.\3\2\2\2\u00ac\u00ad\t"+ "\7\2\2\u00ad\u00ae\b\30\2\2\u00ae\60\3\2\2\2\u00af\u00b0\7*\2\2\u00b0"+ "\u00b1\7,\2\2\u00b1\u00b5\3\2\2\2\u00b2\u00b4\n\b\2\2\u00b3\u00b2\3\2"+ "\2\2\u00b4\u00b7\3\2\2\2\u00b5\u00b3\3\2\2\2\u00b5\u00b6\3\2\2\2\u00b6"+ "\u00b8\3\2\2\2\u00b7\u00b5\3\2\2\2\u00b8\u00b9\7,\2\2\u00b9\u00ba\7+\2"+ "\2\u00ba\u00bb\3\2\2\2\u00bb\u00bc\b\31\3\2\u00bc\62\3\2\2\2\f\2y|\u0082"+ "\u0084\u008b\u0093\u009b\u00a0\u00b5\4\3\30\2\3\31\3"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
9,172
40.506787
97
java
FOADA
FOADA-master/old/src/parser/PA/ANTLR4/PAParserANTLR4.java
// Generated from PAParserANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.PA.ANTLR4; import exception.FOADAException; import structure.Automaton; import structure.FOADAExpression; import structure.FOADAExpression.ExpressionCategory; import structure.FOADAExpression.ExpressionType; import java.util.List; import java.util.Iterator; import java.util.ArrayList; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class PAParserANTLR4 extends Parser { static { RuntimeMetaData.checkVersion("4.7.1", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int START=1, FINAL=2, NONE=3, FALSE=4, TRUE=5, FORALL=6, EXISTS=7, TL=8, TR=9, AND=10, OR=11, EQUALS=12, DISTINCTS=13, INTEGER=14, ID=15, LP=16, RP=17, POINT=18, TWOPOINTS=19, COM=20, WS=21, COMMENT=22; public static final int RULE_automaton = 0, RULE_final_list = 1, RULE_expression = 2, RULE_or_expression = 3, RULE_and_expression = 4, RULE_basic_expression = 5, RULE_eq_expression = 6, RULE_argument_list = 7; public static final String[] ruleNames = { "automaton", "final_list", "expression", "or_expression", "and_expression", "basic_expression", "eq_expression", "argument_list" }; private static final String[] _LITERAL_NAMES = { null, "'start'", "'final'", "'none'", "'false'", "'true'", "'forall'", "'exists'", "'--('", "')->'", "'/\\'", "'\\/'", "'='", "'!='", null, null, "'('", "')'", "'.'", "':'", "','" }; private static final String[] _SYMBOLIC_NAMES = { null, "START", "FINAL", "NONE", "FALSE", "TRUE", "FORALL", "EXISTS", "TL", "TR", "AND", "OR", "EQUALS", "DISTINCTS", "INTEGER", "ID", "LP", "RP", "POINT", "TWOPOINTS", "COM", "WS", "COMMENT" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "PAParserANTLR4.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public PAParserANTLR4(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class AutomatonContext extends ParserRuleContext { public Automaton jData; public ExpressionContext init; public Final_listContext finalList; public Token left; public Argument_listContext argumentList; public Token event; public Token inputVarName; public ExpressionContext post; public TerminalNode START() { return getToken(PAParserANTLR4.START, 0); } public List<TerminalNode> TWOPOINTS() { return getTokens(PAParserANTLR4.TWOPOINTS); } public TerminalNode TWOPOINTS(int i) { return getToken(PAParserANTLR4.TWOPOINTS, i); } public List<TerminalNode> POINT() { return getTokens(PAParserANTLR4.POINT); } public TerminalNode POINT(int i) { return getToken(PAParserANTLR4.POINT, i); } public TerminalNode FINAL() { return getToken(PAParserANTLR4.FINAL, 0); } public TerminalNode EOF() { return getToken(PAParserANTLR4.EOF, 0); } public List<ExpressionContext> expression() { return getRuleContexts(ExpressionContext.class); } public ExpressionContext expression(int i) { return getRuleContext(ExpressionContext.class,i); } public Final_listContext final_list() { return getRuleContext(Final_listContext.class,0); } public List<TerminalNode> LP() { return getTokens(PAParserANTLR4.LP); } public TerminalNode LP(int i) { return getToken(PAParserANTLR4.LP, i); } public List<TerminalNode> RP() { return getTokens(PAParserANTLR4.RP); } public TerminalNode RP(int i) { return getToken(PAParserANTLR4.RP, i); } public List<TerminalNode> TL() { return getTokens(PAParserANTLR4.TL); } public TerminalNode TL(int i) { return getToken(PAParserANTLR4.TL, i); } public List<TerminalNode> TR() { return getTokens(PAParserANTLR4.TR); } public TerminalNode TR(int i) { return getToken(PAParserANTLR4.TR, i); } public List<TerminalNode> ID() { return getTokens(PAParserANTLR4.ID); } public TerminalNode ID(int i) { return getToken(PAParserANTLR4.ID, i); } public List<Argument_listContext> argument_list() { return getRuleContexts(Argument_listContext.class); } public Argument_listContext argument_list(int i) { return getRuleContext(Argument_listContext.class,i); } public AutomatonContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_automaton; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).enterAutomaton(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).exitAutomaton(this); } } public final AutomatonContext automaton() throws RecognitionException, FOADAException { AutomatonContext _localctx = new AutomatonContext(_ctx, getState()); enterRule(_localctx, 0, RULE_automaton); int _la; try { enterOuterAlt(_localctx, 1); { ((AutomatonContext)_localctx).jData = new Automaton(); setState(17); match(START); setState(18); match(TWOPOINTS); setState(19); ((AutomatonContext)_localctx).init = expression(); setState(20); match(POINT); parser.PA.PAParserFunctions.setInitial(_localctx.jData, ((AutomatonContext)_localctx).init.jData); setState(22); match(FINAL); setState(23); match(TWOPOINTS); setState(24); ((AutomatonContext)_localctx).finalList = final_list(); setState(25); match(POINT); parser.PA.PAParserFunctions.setFinal(_localctx.jData, ((AutomatonContext)_localctx).finalList.jData); setState(42); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(27); ((AutomatonContext)_localctx).left = match(ID); setState(28); match(LP); setState(29); ((AutomatonContext)_localctx).argumentList = argument_list(); setState(30); match(RP); setState(31); match(TL); setState(32); ((AutomatonContext)_localctx).event = match(ID); setState(33); match(TWOPOINTS); setState(34); ((AutomatonContext)_localctx).inputVarName = match(ID); setState(35); match(TR); setState(36); ((AutomatonContext)_localctx).post = expression(); setState(37); match(POINT); parser.PA.PAParserFunctions.addTransition(_localctx.jData, (((AutomatonContext)_localctx).left!=null?((AutomatonContext)_localctx).left.getText():null), ((AutomatonContext)_localctx).argumentList.jData, (((AutomatonContext)_localctx).event!=null?((AutomatonContext)_localctx).event.getText():null), (((AutomatonContext)_localctx).inputVarName!=null?((AutomatonContext)_localctx).inputVarName.getText():null), ((AutomatonContext)_localctx).post.jData); } } setState(44); _errHandler.sync(this); _la = _input.LA(1); } setState(45); match(EOF); parser.PA.PAParserFunctions.finalize(_localctx.jData); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Final_listContext extends ParserRuleContext { public List<String> jData; public Token ID; public TerminalNode NONE() { return getToken(PAParserANTLR4.NONE, 0); } public List<TerminalNode> ID() { return getTokens(PAParserANTLR4.ID); } public TerminalNode ID(int i) { return getToken(PAParserANTLR4.ID, i); } public List<TerminalNode> COM() { return getTokens(PAParserANTLR4.COM); } public TerminalNode COM(int i) { return getToken(PAParserANTLR4.COM, i); } public Final_listContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_final_list; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).enterFinal_list(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).exitFinal_list(this); } } public final Final_listContext final_list() throws RecognitionException { Final_listContext _localctx = new Final_listContext(_ctx, getState()); enterRule(_localctx, 2, RULE_final_list); int _la; try { setState(60); _errHandler.sync(this); switch (_input.LA(1)) { case NONE: enterOuterAlt(_localctx, 1); { setState(48); match(NONE); ((Final_listContext)_localctx).jData = new ArrayList<String>(); } break; case ID: enterOuterAlt(_localctx, 2); { setState(50); ((Final_listContext)_localctx).ID = match(ID); ((Final_listContext)_localctx).jData = new ArrayList<String>(); _localctx.jData.add((((Final_listContext)_localctx).ID!=null?((Final_listContext)_localctx).ID.getText():null).replaceAll("\\s*", "")); setState(57); _errHandler.sync(this); _la = _input.LA(1); while (_la==COM) { { { setState(52); match(COM); setState(53); ((Final_listContext)_localctx).ID = match(ID); _localctx.jData.add((((Final_listContext)_localctx).ID!=null?((Final_listContext)_localctx).ID.getText():null).replaceAll("\\s*", "")); } } setState(59); _errHandler.sync(this); _la = _input.LA(1); } } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ExpressionContext extends ParserRuleContext { public FOADAExpression jData; public Or_expressionContext oe; public Or_expressionContext or_expression() { return getRuleContext(Or_expressionContext.class,0); } public ExpressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_expression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).enterExpression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).exitExpression(this); } } public final ExpressionContext expression() throws RecognitionException { ExpressionContext _localctx = new ExpressionContext(_ctx, getState()); enterRule(_localctx, 4, RULE_expression); try { enterOuterAlt(_localctx, 1); { setState(62); ((ExpressionContext)_localctx).oe = or_expression(); ((ExpressionContext)_localctx).jData = ((ExpressionContext)_localctx).oe.jData; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Or_expressionContext extends ParserRuleContext { public FOADAExpression jData; public And_expressionContext ae1; public And_expressionContext ae2; public Or_expressionContext oe; public List<And_expressionContext> and_expression() { return getRuleContexts(And_expressionContext.class); } public And_expressionContext and_expression(int i) { return getRuleContext(And_expressionContext.class,i); } public List<TerminalNode> OR() { return getTokens(PAParserANTLR4.OR); } public TerminalNode OR(int i) { return getToken(PAParserANTLR4.OR, i); } public TerminalNode LP() { return getToken(PAParserANTLR4.LP, 0); } public TerminalNode RP() { return getToken(PAParserANTLR4.RP, 0); } public Or_expressionContext or_expression() { return getRuleContext(Or_expressionContext.class,0); } public Or_expressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_or_expression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).enterOr_expression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).exitOr_expression(this); } } public final Or_expressionContext or_expression() throws RecognitionException { Or_expressionContext _localctx = new Or_expressionContext(_ctx, getState()); enterRule(_localctx, 6, RULE_or_expression); try { int _alt; setState(81); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,4,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(65); ((Or_expressionContext)_localctx).ae1 = and_expression(); ((Or_expressionContext)_localctx).jData = ((Or_expressionContext)_localctx).ae1.jData; setState(73); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,3,_ctx); while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) { if ( _alt==1 ) { { { setState(67); match(OR); setState(68); ((Or_expressionContext)_localctx).ae2 = and_expression(); ((Or_expressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Or, ((Or_expressionContext)_localctx).ae1.jData, ((Or_expressionContext)_localctx).ae2.jData); } } } setState(75); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,3,_ctx); } } break; case 2: enterOuterAlt(_localctx, 2); { setState(76); match(LP); setState(77); ((Or_expressionContext)_localctx).oe = or_expression(); setState(78); match(RP); ((Or_expressionContext)_localctx).jData = ((Or_expressionContext)_localctx).oe.jData; } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class And_expressionContext extends ParserRuleContext { public FOADAExpression jData; public Basic_expressionContext be; public Or_expressionContext oe; public Or_expressionContext oe1; public Or_expressionContext oe2; public Basic_expressionContext basic_expression() { return getRuleContext(Basic_expressionContext.class,0); } public List<TerminalNode> AND() { return getTokens(PAParserANTLR4.AND); } public TerminalNode AND(int i) { return getToken(PAParserANTLR4.AND, i); } public List<Or_expressionContext> or_expression() { return getRuleContexts(Or_expressionContext.class); } public Or_expressionContext or_expression(int i) { return getRuleContext(Or_expressionContext.class,i); } public TerminalNode LP() { return getToken(PAParserANTLR4.LP, 0); } public TerminalNode RP() { return getToken(PAParserANTLR4.RP, 0); } public And_expressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_and_expression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).enterAnd_expression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).exitAnd_expression(this); } } public final And_expressionContext and_expression() throws RecognitionException { And_expressionContext _localctx = new And_expressionContext(_ctx, getState()); enterRule(_localctx, 8, RULE_and_expression); try { int _alt; setState(107); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,7,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(83); ((And_expressionContext)_localctx).be = basic_expression(); ((And_expressionContext)_localctx).jData = ((And_expressionContext)_localctx).be.jData; setState(91); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,5,_ctx); while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) { if ( _alt==1 ) { { { setState(85); match(AND); setState(86); ((And_expressionContext)_localctx).oe = or_expression(); ((And_expressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.And, ((And_expressionContext)_localctx).be.jData, ((And_expressionContext)_localctx).oe.jData); } } } setState(93); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,5,_ctx); } } break; case 2: enterOuterAlt(_localctx, 2); { setState(94); match(LP); setState(95); ((And_expressionContext)_localctx).oe1 = or_expression(); setState(96); match(RP); ((And_expressionContext)_localctx).jData = ((And_expressionContext)_localctx).oe1.jData; setState(104); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,6,_ctx); while ( _alt!=2 && _alt!=org.antlr.v4.runtime.atn.ATN.INVALID_ALT_NUMBER ) { if ( _alt==1 ) { { { setState(98); match(AND); setState(99); ((And_expressionContext)_localctx).oe2 = or_expression(); ((And_expressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.And, ((And_expressionContext)_localctx).oe1.jData, ((And_expressionContext)_localctx).oe2.jData); } } } setState(106); _errHandler.sync(this); _alt = getInterpreter().adaptivePredict(_input,6,_ctx); } } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Basic_expressionContext extends ParserRuleContext { public FOADAExpression jData; public Argument_listContext al; public ExpressionContext e; public Eq_expressionContext ee; public Token ID; public TerminalNode TRUE() { return getToken(PAParserANTLR4.TRUE, 0); } public TerminalNode FALSE() { return getToken(PAParserANTLR4.FALSE, 0); } public TerminalNode EXISTS() { return getToken(PAParserANTLR4.EXISTS, 0); } public TerminalNode POINT() { return getToken(PAParserANTLR4.POINT, 0); } public Argument_listContext argument_list() { return getRuleContext(Argument_listContext.class,0); } public ExpressionContext expression() { return getRuleContext(ExpressionContext.class,0); } public TerminalNode FORALL() { return getToken(PAParserANTLR4.FORALL, 0); } public Eq_expressionContext eq_expression() { return getRuleContext(Eq_expressionContext.class,0); } public TerminalNode ID() { return getToken(PAParserANTLR4.ID, 0); } public TerminalNode LP() { return getToken(PAParserANTLR4.LP, 0); } public TerminalNode RP() { return getToken(PAParserANTLR4.RP, 0); } public Basic_expressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_basic_expression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).enterBasic_expression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).exitBasic_expression(this); } } public final Basic_expressionContext basic_expression() throws RecognitionException { Basic_expressionContext _localctx = new Basic_expressionContext(_ctx, getState()); enterRule(_localctx, 10, RULE_basic_expression); try { setState(134); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,8,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(109); match(TRUE); ((Basic_expressionContext)_localctx).jData = new FOADAExpression(true); } break; case 2: enterOuterAlt(_localctx, 2); { setState(111); match(FALSE); ((Basic_expressionContext)_localctx).jData = new FOADAExpression(false); } break; case 3: enterOuterAlt(_localctx, 3); { setState(113); match(EXISTS); setState(114); ((Basic_expressionContext)_localctx).al = argument_list(); setState(115); match(POINT); setState(116); ((Basic_expressionContext)_localctx).e = expression(); List<FOADAExpression> subExpressions = new ArrayList<FOADAExpression>(); for(String s : ((Basic_expressionContext)_localctx).al.jData) { FOADAExpression argument = new FOADAExpression(s, ExpressionType.Integer); subExpressions.add(argument); } subExpressions.add(((Basic_expressionContext)_localctx).e.jData); ((Basic_expressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Exists, subExpressions); } break; case 4: enterOuterAlt(_localctx, 4); { setState(119); match(FORALL); setState(120); ((Basic_expressionContext)_localctx).al = argument_list(); setState(121); match(POINT); setState(122); ((Basic_expressionContext)_localctx).e = expression(); List<FOADAExpression> subExpressions = new ArrayList<FOADAExpression>(); for(String s : ((Basic_expressionContext)_localctx).al.jData) { FOADAExpression argument = new FOADAExpression(s, ExpressionType.Integer); subExpressions.add(argument); } subExpressions.add(((Basic_expressionContext)_localctx).e.jData); ((Basic_expressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Forall, subExpressions); } break; case 5: enterOuterAlt(_localctx, 5); { setState(125); ((Basic_expressionContext)_localctx).ee = eq_expression(); ((Basic_expressionContext)_localctx).jData = ((Basic_expressionContext)_localctx).ee.jData; } break; case 6: enterOuterAlt(_localctx, 6); { setState(128); ((Basic_expressionContext)_localctx).ID = match(ID); setState(129); match(LP); setState(130); ((Basic_expressionContext)_localctx).al = argument_list(); setState(131); match(RP); List<FOADAExpression> subExpressions = new ArrayList<FOADAExpression>(); for(String s : ((Basic_expressionContext)_localctx).al.jData) { FOADAExpression argument = new FOADAExpression(s, ExpressionType.Integer); subExpressions.add(argument); } ((Basic_expressionContext)_localctx).jData = new FOADAExpression((((Basic_expressionContext)_localctx).ID!=null?((Basic_expressionContext)_localctx).ID.getText():null).replaceAll("\\s*", ""), ExpressionType.Boolean, subExpressions); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Eq_expressionContext extends ParserRuleContext { public FOADAExpression jData; public Token i1; public Token i2; public Eq_expressionContext ee; public TerminalNode EQUALS() { return getToken(PAParserANTLR4.EQUALS, 0); } public List<TerminalNode> ID() { return getTokens(PAParserANTLR4.ID); } public TerminalNode ID(int i) { return getToken(PAParserANTLR4.ID, i); } public TerminalNode DISTINCTS() { return getToken(PAParserANTLR4.DISTINCTS, 0); } public TerminalNode LP() { return getToken(PAParserANTLR4.LP, 0); } public TerminalNode RP() { return getToken(PAParserANTLR4.RP, 0); } public Eq_expressionContext eq_expression() { return getRuleContext(Eq_expressionContext.class,0); } public Eq_expressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_eq_expression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).enterEq_expression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).exitEq_expression(this); } } public final Eq_expressionContext eq_expression() throws RecognitionException { Eq_expressionContext _localctx = new Eq_expressionContext(_ctx, getState()); enterRule(_localctx, 12, RULE_eq_expression); try { setState(149); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,9,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(136); ((Eq_expressionContext)_localctx).i1 = match(ID); setState(137); match(EQUALS); setState(138); ((Eq_expressionContext)_localctx).i2 = match(ID); FOADAExpression left = new FOADAExpression((((Eq_expressionContext)_localctx).i1!=null?((Eq_expressionContext)_localctx).i1.getText():null).replaceAll("\\s*", ""), ExpressionType.Integer); FOADAExpression right = new FOADAExpression((((Eq_expressionContext)_localctx).i2!=null?((Eq_expressionContext)_localctx).i2.getText():null).replaceAll("\\s*", ""), ExpressionType.Integer); ((Eq_expressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Equals, left, right); } break; case 2: enterOuterAlt(_localctx, 2); { setState(140); ((Eq_expressionContext)_localctx).i1 = match(ID); setState(141); match(DISTINCTS); setState(142); ((Eq_expressionContext)_localctx).i2 = match(ID); FOADAExpression left = new FOADAExpression((((Eq_expressionContext)_localctx).i1!=null?((Eq_expressionContext)_localctx).i1.getText():null).replaceAll("\\s*", ""), ExpressionType.Integer); FOADAExpression right = new FOADAExpression((((Eq_expressionContext)_localctx).i2!=null?((Eq_expressionContext)_localctx).i2.getText():null).replaceAll("\\s*", ""), ExpressionType.Integer); ((Eq_expressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Distinct, left, right); } break; case 3: enterOuterAlt(_localctx, 3); { setState(144); match(LP); setState(145); ((Eq_expressionContext)_localctx).ee = eq_expression(); setState(146); match(RP); ((Eq_expressionContext)_localctx).jData = ((Eq_expressionContext)_localctx).ee.jData; } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class Argument_listContext extends ParserRuleContext { public List<String> jData; public Token i1; public Token i2; public List<TerminalNode> ID() { return getTokens(PAParserANTLR4.ID); } public TerminalNode ID(int i) { return getToken(PAParserANTLR4.ID, i); } public List<TerminalNode> COM() { return getTokens(PAParserANTLR4.COM); } public TerminalNode COM(int i) { return getToken(PAParserANTLR4.COM, i); } public Argument_listContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_argument_list; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).enterArgument_list(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof PAParserANTLR4Listener ) ((PAParserANTLR4Listener)listener).exitArgument_list(this); } } public final Argument_listContext argument_list() throws RecognitionException { Argument_listContext _localctx = new Argument_listContext(_ctx, getState()); enterRule(_localctx, 14, RULE_argument_list); int _la; try { enterOuterAlt(_localctx, 1); { ((Argument_listContext)_localctx).jData = new ArrayList<String>(); setState(162); _errHandler.sync(this); _la = _input.LA(1); if (_la==ID) { { setState(152); ((Argument_listContext)_localctx).i1 = match(ID); _localctx.jData.add((((Argument_listContext)_localctx).i1!=null?((Argument_listContext)_localctx).i1.getText():null).replaceAll("\\s*", "")); setState(159); _errHandler.sync(this); _la = _input.LA(1); while (_la==COM) { { { setState(154); match(COM); setState(155); ((Argument_listContext)_localctx).i2 = match(ID); _localctx.jData.add((((Argument_listContext)_localctx).i2!=null?((Argument_listContext)_localctx).i2.getText():null).replaceAll("\\s*", "")); } } setState(161); _errHandler.sync(this); _la = _input.LA(1); } } } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\30\u00a7\4\2\t\2"+ "\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\3\2\3\2\3\2\3"+ "\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2"+ "\3\2\3\2\3\2\7\2+\n\2\f\2\16\2.\13\2\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3"+ "\3\3\3\7\3:\n\3\f\3\16\3=\13\3\5\3?\n\3\3\4\3\4\3\4\3\5\3\5\3\5\3\5\3"+ "\5\3\5\7\5J\n\5\f\5\16\5M\13\5\3\5\3\5\3\5\3\5\3\5\5\5T\n\5\3\6\3\6\3"+ "\6\3\6\3\6\3\6\7\6\\\n\6\f\6\16\6_\13\6\3\6\3\6\3\6\3\6\3\6\3\6\3\6\3"+ "\6\7\6i\n\6\f\6\16\6l\13\6\5\6n\n\6\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3"+ "\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\3\7\5\7"+ "\u0089\n\7\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\3\b\5\b\u0098"+ "\n\b\3\t\3\t\3\t\3\t\3\t\3\t\7\t\u00a0\n\t\f\t\16\t\u00a3\13\t\5\t\u00a5"+ "\n\t\3\t\2\2\n\2\4\6\b\n\f\16\20\2\2\2\u00af\2\22\3\2\2\2\4>\3\2\2\2\6"+ "@\3\2\2\2\bS\3\2\2\2\nm\3\2\2\2\f\u0088\3\2\2\2\16\u0097\3\2\2\2\20\u0099"+ "\3\2\2\2\22\23\b\2\1\2\23\24\7\3\2\2\24\25\7\25\2\2\25\26\5\6\4\2\26\27"+ "\7\24\2\2\27\30\b\2\1\2\30\31\7\4\2\2\31\32\7\25\2\2\32\33\5\4\3\2\33"+ "\34\7\24\2\2\34,\b\2\1\2\35\36\7\21\2\2\36\37\7\22\2\2\37 \5\20\t\2 !"+ "\7\23\2\2!\"\7\n\2\2\"#\7\21\2\2#$\7\25\2\2$%\7\21\2\2%&\7\13\2\2&\'\5"+ "\6\4\2\'(\7\24\2\2()\b\2\1\2)+\3\2\2\2*\35\3\2\2\2+.\3\2\2\2,*\3\2\2\2"+ ",-\3\2\2\2-/\3\2\2\2.,\3\2\2\2/\60\7\2\2\3\60\61\b\2\1\2\61\3\3\2\2\2"+ "\62\63\7\5\2\2\63?\b\3\1\2\64\65\7\21\2\2\65;\b\3\1\2\66\67\7\26\2\2\67"+ "8\7\21\2\28:\b\3\1\29\66\3\2\2\2:=\3\2\2\2;9\3\2\2\2;<\3\2\2\2<?\3\2\2"+ "\2=;\3\2\2\2>\62\3\2\2\2>\64\3\2\2\2?\5\3\2\2\2@A\5\b\5\2AB\b\4\1\2B\7"+ "\3\2\2\2CD\5\n\6\2DK\b\5\1\2EF\7\r\2\2FG\5\n\6\2GH\b\5\1\2HJ\3\2\2\2I"+ "E\3\2\2\2JM\3\2\2\2KI\3\2\2\2KL\3\2\2\2LT\3\2\2\2MK\3\2\2\2NO\7\22\2\2"+ "OP\5\b\5\2PQ\7\23\2\2QR\b\5\1\2RT\3\2\2\2SC\3\2\2\2SN\3\2\2\2T\t\3\2\2"+ "\2UV\5\f\7\2V]\b\6\1\2WX\7\f\2\2XY\5\b\5\2YZ\b\6\1\2Z\\\3\2\2\2[W\3\2"+ "\2\2\\_\3\2\2\2][\3\2\2\2]^\3\2\2\2^n\3\2\2\2_]\3\2\2\2`a\7\22\2\2ab\5"+ "\b\5\2bc\7\23\2\2cj\b\6\1\2de\7\f\2\2ef\5\b\5\2fg\b\6\1\2gi\3\2\2\2hd"+ "\3\2\2\2il\3\2\2\2jh\3\2\2\2jk\3\2\2\2kn\3\2\2\2lj\3\2\2\2mU\3\2\2\2m"+ "`\3\2\2\2n\13\3\2\2\2op\7\7\2\2p\u0089\b\7\1\2qr\7\6\2\2r\u0089\b\7\1"+ "\2st\7\t\2\2tu\5\20\t\2uv\7\24\2\2vw\5\6\4\2wx\b\7\1\2x\u0089\3\2\2\2"+ "yz\7\b\2\2z{\5\20\t\2{|\7\24\2\2|}\5\6\4\2}~\b\7\1\2~\u0089\3\2\2\2\177"+ "\u0080\5\16\b\2\u0080\u0081\b\7\1\2\u0081\u0089\3\2\2\2\u0082\u0083\7"+ "\21\2\2\u0083\u0084\7\22\2\2\u0084\u0085\5\20\t\2\u0085\u0086\7\23\2\2"+ "\u0086\u0087\b\7\1\2\u0087\u0089\3\2\2\2\u0088o\3\2\2\2\u0088q\3\2\2\2"+ "\u0088s\3\2\2\2\u0088y\3\2\2\2\u0088\177\3\2\2\2\u0088\u0082\3\2\2\2\u0089"+ "\r\3\2\2\2\u008a\u008b\7\21\2\2\u008b\u008c\7\16\2\2\u008c\u008d\7\21"+ "\2\2\u008d\u0098\b\b\1\2\u008e\u008f\7\21\2\2\u008f\u0090\7\17\2\2\u0090"+ "\u0091\7\21\2\2\u0091\u0098\b\b\1\2\u0092\u0093\7\22\2\2\u0093\u0094\5"+ "\16\b\2\u0094\u0095\7\23\2\2\u0095\u0096\b\b\1\2\u0096\u0098\3\2\2\2\u0097"+ "\u008a\3\2\2\2\u0097\u008e\3\2\2\2\u0097\u0092\3\2\2\2\u0098\17\3\2\2"+ "\2\u0099\u00a4\b\t\1\2\u009a\u009b\7\21\2\2\u009b\u00a1\b\t\1\2\u009c"+ "\u009d\7\26\2\2\u009d\u009e\7\21\2\2\u009e\u00a0\b\t\1\2\u009f\u009c\3"+ "\2\2\2\u00a0\u00a3\3\2\2\2\u00a1\u009f\3\2\2\2\u00a1\u00a2\3\2\2\2\u00a2"+ "\u00a5\3\2\2\2\u00a3\u00a1\3\2\2\2\u00a4\u009a\3\2\2\2\u00a4\u00a5\3\2"+ "\2\2\u00a5\21\3\2\2\2\16,;>KS]jm\u0088\u0097\u00a1\u00a4"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
35,491
33.830226
457
java
FOADA
FOADA-master/old/src/parser/PA/ANTLR4/PAParserANTLR4BaseListener.java
// Generated from PAParserANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.PA.ANTLR4; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.TerminalNode; /** * This class provides an empty implementation of {@link PAParserANTLR4Listener}, * which can be extended to create a listener which only needs to handle a subset * of the available methods. */ public class PAParserANTLR4BaseListener implements PAParserANTLR4Listener { /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAutomaton(PAParserANTLR4.AutomatonContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAutomaton(PAParserANTLR4.AutomatonContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterFinal_list(PAParserANTLR4.Final_listContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitFinal_list(PAParserANTLR4.Final_listContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterExpression(PAParserANTLR4.ExpressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitExpression(PAParserANTLR4.ExpressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterOr_expression(PAParserANTLR4.Or_expressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitOr_expression(PAParserANTLR4.Or_expressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAnd_expression(PAParserANTLR4.And_expressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAnd_expression(PAParserANTLR4.And_expressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterBasic_expression(PAParserANTLR4.Basic_expressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitBasic_expression(PAParserANTLR4.Basic_expressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEq_expression(PAParserANTLR4.Eq_expressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEq_expression(PAParserANTLR4.Eq_expressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterArgument_list(PAParserANTLR4.Argument_listContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitArgument_list(PAParserANTLR4.Argument_listContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
4,608
28.170886
92
java
FOADA
FOADA-master/old/src/parser/PA/ANTLR4/PAParserANTLR4Listener.java
// Generated from PAParserANTLR4.g4 by ANTLR 4.7.1 /* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.PA.ANTLR4; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link PAParserANTLR4}. */ public interface PAParserANTLR4Listener extends ParseTreeListener { /** * Enter a parse tree produced by {@link PAParserANTLR4#automaton}. * @param ctx the parse tree */ void enterAutomaton(PAParserANTLR4.AutomatonContext ctx); /** * Exit a parse tree produced by {@link PAParserANTLR4#automaton}. * @param ctx the parse tree */ void exitAutomaton(PAParserANTLR4.AutomatonContext ctx); /** * Enter a parse tree produced by {@link PAParserANTLR4#final_list}. * @param ctx the parse tree */ void enterFinal_list(PAParserANTLR4.Final_listContext ctx); /** * Exit a parse tree produced by {@link PAParserANTLR4#final_list}. * @param ctx the parse tree */ void exitFinal_list(PAParserANTLR4.Final_listContext ctx); /** * Enter a parse tree produced by {@link PAParserANTLR4#expression}. * @param ctx the parse tree */ void enterExpression(PAParserANTLR4.ExpressionContext ctx); /** * Exit a parse tree produced by {@link PAParserANTLR4#expression}. * @param ctx the parse tree */ void exitExpression(PAParserANTLR4.ExpressionContext ctx); /** * Enter a parse tree produced by {@link PAParserANTLR4#or_expression}. * @param ctx the parse tree */ void enterOr_expression(PAParserANTLR4.Or_expressionContext ctx); /** * Exit a parse tree produced by {@link PAParserANTLR4#or_expression}. * @param ctx the parse tree */ void exitOr_expression(PAParserANTLR4.Or_expressionContext ctx); /** * Enter a parse tree produced by {@link PAParserANTLR4#and_expression}. * @param ctx the parse tree */ void enterAnd_expression(PAParserANTLR4.And_expressionContext ctx); /** * Exit a parse tree produced by {@link PAParserANTLR4#and_expression}. * @param ctx the parse tree */ void exitAnd_expression(PAParserANTLR4.And_expressionContext ctx); /** * Enter a parse tree produced by {@link PAParserANTLR4#basic_expression}. * @param ctx the parse tree */ void enterBasic_expression(PAParserANTLR4.Basic_expressionContext ctx); /** * Exit a parse tree produced by {@link PAParserANTLR4#basic_expression}. * @param ctx the parse tree */ void exitBasic_expression(PAParserANTLR4.Basic_expressionContext ctx); /** * Enter a parse tree produced by {@link PAParserANTLR4#eq_expression}. * @param ctx the parse tree */ void enterEq_expression(PAParserANTLR4.Eq_expressionContext ctx); /** * Exit a parse tree produced by {@link PAParserANTLR4#eq_expression}. * @param ctx the parse tree */ void exitEq_expression(PAParserANTLR4.Eq_expressionContext ctx); /** * Enter a parse tree produced by {@link PAParserANTLR4#argument_list}. * @param ctx the parse tree */ void enterArgument_list(PAParserANTLR4.Argument_listContext ctx); /** * Exit a parse tree produced by {@link PAParserANTLR4#argument_list}. * @param ctx the parse tree */ void exitArgument_list(PAParserANTLR4.Argument_listContext ctx); }
3,963
33.77193
82
java
FOADA
FOADA-master/old/src/structure/Automaton.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package structure; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment; import org.sosy_lab.java_smt.api.Model.ValueAssignment; import org.sosy_lab.java_smt.api.SolverException; import exception.FOADAException; import exception.InterpolatingProverEnvironmentException; import structure.FOADAExpression.ExpressionCategory; import structure.FOADAExpression.ExpressionType; import utility.Console; import utility.Impact; import utility.Console.ConsoleType; import utility.JavaSMTConfig; public class Automaton { /** * initial state */ public FOADAExpression initial; /** * set of names of final states */ public List<String> namesOfFinalStates; /** * map (name of predicate + event symbol : transition) */ public Map<String, FOADATransition> transitions; /** rename map (original name : new name) */ public Map<String, String> renameMap; /** set of names of predicates */ public List<String> namesOfPredicates; /** set of events */ public List<String> events; /** number of variables */ public int nbOfVariables; /** default constructor * @throws FOADAException */ public Automaton() throws FOADAException { initial = null; namesOfFinalStates = new ArrayList<String>(); transitions = new LinkedHashMap<String, FOADATransition>(); renameMap = new LinkedHashMap<String, String>(); namesOfPredicates = new ArrayList<String>(); events = new ArrayList<String>(); nbOfVariables = 0; utility.JavaSMTConfig.initJavaSMT(); } public Automaton intersects(Automaton automaton) throws FOADAException { Automaton newOne = new Automaton(); List<String> newNamesOfPredicatesForB = new ArrayList<String>(); FOADAExpression newInitialForB = automaton.initial.copy(); List<String> newNamesOfFinalStatesForB = new ArrayList<String>(); for(int i = automaton.namesOfPredicates.size() - 1; i >= 0; i--) { int newNumber = i + namesOfPredicates.size(); newNamesOfPredicatesForB.add("q" + newNumber + "c"); newInitialForB.substitute("q" + i + "c", "q" + newNumber + "c"); for(int j = 0; j < automaton.namesOfFinalStates.size(); j++) { if(automaton.namesOfFinalStates.get(j).equals("q" + i + "c")) { newNamesOfFinalStatesForB.add("q" + newNumber + "c"); } } } Map<String, String> newRenameMapForB = new LinkedHashMap<String, String>(); for(Map.Entry<String, String> entry : automaton.renameMap.entrySet()) { String original = entry.getKey(); String newName = entry.getValue(); if(newName.charAt(0) == 'q') { original = original + "_B"; int newNumber = Integer.parseInt(newName.substring(1).substring(0, newName.length() - 2)) + namesOfPredicates.size(); newName = "q" + newNumber + "c"; newRenameMapForB.put(original, newName); } } Map<String, String> eventRenameMapForB = new LinkedHashMap<String, String>(); List<String> eventsForB = new ArrayList<String>(); for(Map.Entry<String, String> entry : automaton.renameMap.entrySet()) { if(entry.getValue().charAt(0) == 'e') { if(!renameMap.containsKey(entry.getKey())) { int newNumber = events.size() + eventRenameMapForB.size(); eventRenameMapForB.put(entry.getKey(), "e" + newNumber + "c"); newRenameMapForB.put(entry.getKey(), "e" + newNumber + "c"); eventsForB.add("e" + newNumber + "c"); } } } newOne.renameMap = new LinkedHashMap<String, String>(); newOne.renameMap.putAll(renameMap); newOne.renameMap.putAll(newRenameMapForB); Map<String, FOADATransition> newTransitionsForB = new LinkedHashMap<String, FOADATransition>(); for(FOADATransition transition : automaton.transitions.values()) { // rename predicates in transitions FOADAExpression left = transition.left.copy(); FOADAExpression right = transition.right.copy(); String event = transition.event; for(Map.Entry<String, String> entry : automaton.renameMap.entrySet()) { if(entry.getValue().equals(event)) { event = entry.getKey(); } } List<FOADAExpression> inputVariables = transition.inputVariables; for(int i = automaton.namesOfPredicates.size() - 1; i >= 0; i--) { int newNumber = i + namesOfPredicates.size(); left.substitute("q" + i + "c", "q" + newNumber + "c"); right.substitute("q" + i + "c", "q" + newNumber + "c"); } FOADATransition newTransition = new FOADATransition(); newTransition.left = left; newTransition.event = newOne.renameMap.get(event); newTransition.inputVariables = inputVariables; newTransition.right = right; newTransitionsForB.put(left.name + "+" + newTransition.event, newTransition); } newOne.initial = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.And, initial, newInitialForB); newOne.namesOfPredicates = new ArrayList<String>(); newOne.namesOfPredicates.addAll(namesOfPredicates); newOne.namesOfPredicates.addAll(newNamesOfPredicatesForB); newOne.namesOfFinalStates = new ArrayList<String>(); newOne.namesOfFinalStates.addAll(namesOfFinalStates); newOne.namesOfFinalStates.addAll(newNamesOfFinalStatesForB); newOne.events = new ArrayList<String>(); newOne.events.addAll(events); newOne.events.addAll(eventsForB); newOne.nbOfVariables = nbOfVariables; newOne.transitions = new LinkedHashMap<String, FOADATransition>(); newOne.transitions.putAll(transitions); newOne.transitions.putAll(newTransitionsForB); return newOne; } public Automaton complements() throws FOADAException { Automaton newOne = new Automaton(); newOne.initial = initial.copy(); newOne.namesOfFinalStates = new ArrayList<String>(); newOne.namesOfFinalStates.addAll(namesOfPredicates); newOne.namesOfFinalStates.removeAll(namesOfFinalStates); newOne.transitions = new LinkedHashMap<String, FOADATransition>(); for(Entry<String, FOADATransition> transitionEntry : transitions.entrySet()) { newOne.transitions.put(transitionEntry.getKey(), transitionEntry.getValue().copy()); } for(FOADATransition t : newOne.transitions.values()) { t.right.negate(); } Map<String, FOADAExpression> predicatesNameArguments = new LinkedHashMap<String, FOADAExpression>(); for(FOADATransition transition : transitions.values()) { FOADAExpression predicateWithArguments = transition.left; String nameOfPredicate = transition.left.name; if(!predicatesNameArguments.containsKey(nameOfPredicate)) { predicatesNameArguments.put(nameOfPredicate, predicateWithArguments); } } List<FOADAExpression> inputVariables = transitions.values().iterator().next().inputVariables; for(String predicate : namesOfPredicates) { FOADAExpression left = predicatesNameArguments.get(predicate); for(String event : events) { if(!transitions.containsKey(predicate + "+" + event)) { FOADATransition transition = new FOADATransition(); transition.left = left.copy(); transition.event = event; transition.inputVariables = inputVariables; transition.right = new FOADAExpression(true); newOne.transitions.put(predicate + "+" + event, transition); } } } newOne.renameMap = new LinkedHashMap<String, String>(); newOne.renameMap.putAll(renameMap); newOne.namesOfPredicates = new ArrayList<String>(); newOne.namesOfPredicates.addAll(namesOfPredicates); newOne.events = new ArrayList<String>(); newOne.events.addAll(events); newOne.nbOfVariables = nbOfVariables; return newOne; } public boolean isIncluded(Automaton B, utility.TreeSearch.Mode searchMode, utility.Impact.Mode transitionMode) throws FOADAException { Automaton complementOfB = B.complements(); Automaton AIntersectsComplementOfB = intersects(complementOfB); return AIntersectsComplementOfB.isEmpty(searchMode, transitionMode); } public boolean isEmpty(utility.TreeSearch.Mode searchMode, utility.Impact.Mode transitionMode) throws FOADAException { /*System.out.println(renameMap); System.out.println("Predicates : " + namesOfPredicates); System.out.println("Initial : " + initial); System.out.println("Final : " + namesOfFinalStates); System.out.println("Events : " + events); for(Entry<String, FOADATransition> entry : transitions.entrySet()) { System.out.println(entry.getKey() + " ### " + entry.getValue()); }*/ long beginTime = System.currentTimeMillis(); int nbOfNodesVisited = 0; int nbOfNodesCreated = 0; // start with the initial state // create initial node FOADAConfiguration initialNode = new FOADAConfiguration(nbOfNodesCreated++, (BooleanFormula)initial.toJavaSMTFormula(JavaSMTConfig.fmgr), null, null); // initialize the set of all valid Nodes Set<FOADAConfiguration> allValidNodes = new HashSet<FOADAConfiguration>(); // initialize the work list List<FOADAConfiguration> workList = new ArrayList<FOADAConfiguration>(); // add the initial node into the work list workList.add(initialNode); // start working with the work list while(!workList.isEmpty()) { // pick a node -> the current node FOADAConfiguration currentNode = null; if(searchMode == utility.TreeSearch.Mode.BFS) { currentNode = workList.get(0); workList.remove(0); } else { currentNode = workList.get(workList.size() - 1); workList.remove(workList.size() - 1); } nbOfNodesVisited++; allValidNodes.add(currentNode); /** TODO **/ //System.out.println(currentNode); // calculate the path from the initial node to the current node List<String> pathFromInitToCurrent = new ArrayList<String>(); // loop to find the path FOADAConfiguration c = currentNode; while(c.father != null) { pathFromInitToCurrent.add(0, c.fatherSymbol); c = c.father; } /** TODO **/ //System.out.println(pathFromInitToCurrent); // determine whether the current node is accepting // create a list of JavaSMT expressions (blocks) for interpolation List<BooleanFormula> blocks = new ArrayList<BooleanFormula>(); // create a time-stamped initial state FOADAExpression timeStampedInitial = initial.copy(); timeStampedInitial.addTimeStamps(0); // add the JavaSMT expression of the timed-stamped initial state into list of blocks blocks.add((BooleanFormula)timeStampedInitial.toJavaSMTFormula(JavaSMTConfig.fmgr)); // create a set of all the un-time-stamped predicates in the current block // or // create a set of all the occurrences of predicates in the current block Set<FOADAExpression> predicatesInCurrentBlock = null; Set<FOADAExpression> predicatesOccurrencesInCurrentBlock = null; // get the names of all the predicates in the initial state // or // get all the occurrences of predicates in the initial state if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { predicatesInCurrentBlock = new HashSet<FOADAExpression>(); Set<FOADAExpression> predicatesOccurrencesInUnTimeStampedCurrentBlock = initial.copy().findPredicatesOccurrences(); for(FOADAExpression o : predicatesOccurrencesInUnTimeStampedCurrentBlock) { for(int i = 0; i < o.subData.size(); i++) { o.subData.get(i).name = "a" + i + "c"; o.subData.get(i).category = ExpressionCategory.Function; o.subData.get(i).subData = new ArrayList<FOADAExpression>(); } predicatesInCurrentBlock.add(o); } } else { predicatesOccurrencesInCurrentBlock = timeStampedInitial.findPredicatesOccurrences(); } // compute next blocks int currentTimeStamp = 0; for(String a : pathFromInitToCurrent) { // create a new list of all the small parts (of conjunction) of the new block List<BooleanFormula> smallPartsOfNewBlock = new ArrayList<BooleanFormula>(); // compute the small parts of the new block if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { Set<FOADAExpression> predicatesInNewBlock = new HashSet<FOADAExpression>(); // compute one small part of the new block for(FOADAExpression predicate : predicatesInCurrentBlock) { FOADATransition transition = transitions.get(predicate.name + "+" + a); if(transition != null) { predicatesInNewBlock.addAll(transition.getPredicates()); BooleanFormula currentPartOfNewBlock = transition.getUniversallyQuantifiedImplication(currentTimeStamp); smallPartsOfNewBlock.add(currentPartOfNewBlock); } else { List<Formula> arguments = new ArrayList<Formula>(); for(FOADAExpression x : predicate.subData) { Formula argument; if(x.type == ExpressionType.Integer) { argument = JavaSMTConfig.ufmgr.declareAndCallUF(x.name, FormulaType.IntegerType); } else { argument = JavaSMTConfig.ufmgr.declareAndCallUF(x.name, FormulaType.BooleanType); } arguments.add(argument); } FOADAExpression timeStampedLeft = predicate.copy(); timeStampedLeft.addTimeStamps(currentTimeStamp); BooleanFormula leftPartOfImplication = (BooleanFormula)timeStampedLeft.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula rightPartOfImplication = JavaSMTConfig.bmgr.makeBoolean(false); BooleanFormula implication = JavaSMTConfig.bmgr.implication(leftPartOfImplication, rightPartOfImplication); if(arguments.isEmpty()) { smallPartsOfNewBlock.add(implication); } else { BooleanFormula universallyQuantifiedImplication = JavaSMTConfig.qmgr.forall(arguments, implication); smallPartsOfNewBlock.add(universallyQuantifiedImplication); } } } if(smallPartsOfNewBlock.isEmpty()) { blocks.add(JavaSMTConfig.bmgr.makeBoolean(true)); } else { blocks.add(JavaSMTConfig.bmgr.and(smallPartsOfNewBlock)); } predicatesInCurrentBlock = predicatesInNewBlock; } else { Set<FOADAExpression> predicatesOccurrencesInNewBlock = new HashSet<FOADAExpression>(); // compute one small part of the new block for(FOADAExpression occurrence : predicatesOccurrencesInCurrentBlock) { FOADAExpression left = occurrence; FOADATransition transition = transitions.get(left.name.substring(0, left.name.indexOf("_")) + "+" + a); if(transition != null) { predicatesOccurrencesInNewBlock.addAll(transition.getPredicatesOccurrences(currentTimeStamp, left)); BooleanFormula currentPartOfNewBlock = transition.getImplicationWithOccurrences(currentTimeStamp, left); smallPartsOfNewBlock.add(currentPartOfNewBlock); } else { BooleanFormula currentPartOfNewBlock = JavaSMTConfig.bmgr.implication((BooleanFormula)left.toJavaSMTFormula(JavaSMTConfig.fmgr), JavaSMTConfig.bmgr.makeBoolean(false)); smallPartsOfNewBlock.add(currentPartOfNewBlock); } } if(smallPartsOfNewBlock.isEmpty()) { blocks.add(JavaSMTConfig.bmgr.makeBoolean(true)); } else { blocks.add(JavaSMTConfig.bmgr.and(smallPartsOfNewBlock)); } predicatesOccurrencesInCurrentBlock = predicatesOccurrencesInNewBlock; } currentTimeStamp++; } // compute the final conjunction (last block) List<BooleanFormula> finalConjunction = new ArrayList<BooleanFormula>(); if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { for(FOADAExpression predicate : predicatesInCurrentBlock) { List<Formula> arguments = new ArrayList<Formula>(); for(FOADAExpression a : predicate.subData) { Formula argument; if(a.type == ExpressionType.Integer) { argument = JavaSMTConfig.ufmgr.declareAndCallUF(a.name, FormulaType.IntegerType); } else { argument = JavaSMTConfig.ufmgr.declareAndCallUF(a.name, FormulaType.BooleanType); } arguments.add(argument); } FOADAExpression timeStampedLeft = predicate.copy(); timeStampedLeft.addTimeStamps(currentTimeStamp); BooleanFormula leftPartOfImplication = (BooleanFormula)timeStampedLeft.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula rightPartOfImplication; if(namesOfFinalStates.contains(predicate.name)) { rightPartOfImplication = JavaSMTConfig.bmgr.makeBoolean(true); } else { rightPartOfImplication = JavaSMTConfig.bmgr.makeBoolean(false); } BooleanFormula implication = JavaSMTConfig.bmgr.implication(leftPartOfImplication, rightPartOfImplication); if(arguments.isEmpty()) { finalConjunction.add(implication); } else { BooleanFormula universallyQuantifiedImplication = JavaSMTConfig.qmgr.forall(arguments, implication); finalConjunction.add(universallyQuantifiedImplication); } } } else { for(FOADAExpression occurrence : predicatesOccurrencesInCurrentBlock) { FOADAExpression left = occurrence; // implies true if is final state if(namesOfFinalStates.contains(left.name.substring(0, left.name.indexOf("_")))) { BooleanFormula right = JavaSMTConfig.bmgr.makeBoolean(true); BooleanFormula implication = JavaSMTConfig.bmgr.implication((BooleanFormula)left.toJavaSMTFormula(JavaSMTConfig.fmgr), right); finalConjunction.add(implication); } // implies false if is not final state else { BooleanFormula right = JavaSMTConfig.bmgr.makeBoolean(false); BooleanFormula implication = JavaSMTConfig.bmgr.implication((BooleanFormula)left.toJavaSMTFormula(JavaSMTConfig.fmgr), right); finalConjunction.add(implication); } } } // add the last block into the list of blocks if(finalConjunction.isEmpty()) { blocks.add(JavaSMTConfig.bmgr.makeBoolean(true)); } else { blocks.add(JavaSMTConfig.bmgr.and(finalConjunction)); } /** TODO **/ /*System.out.println("Blocks:"); for(BooleanFormula b : blocks) { System.out.println(b); }*/ // check if the conjunction of all blocks is satisfiable or compute the interpolants // create prover environment for interpolation @SuppressWarnings("rawtypes") InterpolatingProverEnvironment prover = JavaSMTConfig.solverContext.newProverEnvironmentWithInterpolation(); // create a new list for sets of objects received when pushing different partitions into the prover List<Set<Object>> listPartitions = new ArrayList<Set<Object>>(); // each block is a partition for(BooleanFormula f : blocks) { // create a set for objects received when pushing different partitions into the prover Set<Object> Partition = new HashSet<Object>(); // push the partition (block) into the prover and add the received object into the set Partition.add(prover.push(f)); // add the set into the list listPartitions.add(Partition); } // check whether the conjunction of all blocks is unsatisfiable try { // compute the interpolants if it is not satisfiable if(prover.isUnsat()) { @SuppressWarnings("unchecked") // compute the interpolants (with time-stamps) List<BooleanFormula> interpolantsWithTimeStamps = prover.getSeqInterpolants(listPartitions); List<BooleanFormula> interpolants = new ArrayList<BooleanFormula>(); // remove the time-stamps from the interpolants for(BooleanFormula f : interpolantsWithTimeStamps) { interpolants.add(JavaSMTConfig.removeTimeStamp(f)); } // refine the nodes along the path // starting from the root node FOADAConfiguration currentNodeAlongPath = initialNode; int step = 0; // loop check the path boolean oneNodeIsClosed = false; while(true) { // get the corresponding interpolant according to the current step BooleanFormula interpolant = interpolants.get(step); // check the validity of the implication: current -> interpolant boolean implicationIsValid = JavaSMTConfig.checkImplication(currentNodeAlongPath.expression, interpolant); // if the implication if not valid if(!implicationIsValid) { // refine the node by making a conjunction currentNodeAlongPath.expression = JavaSMTConfig.bmgr.and(currentNodeAlongPath.expression, interpolant); /** TODO **/ //System.out.println("\t#" + currentNodeAlongPath.number + " refined : " + currentNodeAlongPath.expression); // remove all the covered relations of the current node along path currentNodeAlongPath.removeCoveredRelations(workList); // close the current node along path if(!oneNodeIsClosed) { oneNodeIsClosed = Impact.close(currentNodeAlongPath, workList, allValidNodes); } if(currentNodeAlongPath.expression.toString().equals("false")) { workList.remove(currentNodeAlongPath); allValidNodes.remove(currentNodeAlongPath); } } // if finish looping the path if(step >= pathFromInitToCurrent.size()) { break; } // if not finish looping the path else { // refresh the current node along path int indexOfSuccessor = currentNodeAlongPath.successorSymbolIndexMap.get(pathFromInitToCurrent.get(step)); currentNodeAlongPath = currentNodeAlongPath.successors.get(indexOfSuccessor); // refresh the current step step++; } } } // print out the model and return false if it is satisfiable else { System.out.println("------------------------------"); long endTime = System.currentTimeMillis(); if(pathFromInitToCurrent.size() == 0) { System.out.println("empty trace"); } else { Object[][] variablesAssignments = new Object[pathFromInitToCurrent.size()][nbOfVariables]; for(Object a : prover.getModelAssignments()) { String expressionString = ((ValueAssignment)a).getKey().toString(); if(expressionString.charAt(0) == 'v') { int lastIndexOfUnderscore = expressionString.lastIndexOf('_'); int variableStep = Integer.valueOf(expressionString.substring(lastIndexOfUnderscore + 1)); if(variableStep > 0) { int variableIndex = Integer.valueOf(expressionString.substring(1, lastIndexOfUnderscore - 1)); variablesAssignments[variableStep - 1][variableIndex] = ((ValueAssignment)a).getValue(); } } } for(int i1 = 0; i1 < pathFromInitToCurrent.size(); i1++) { String newNameEvent = pathFromInitToCurrent.get(i1); String oldNameEvent = null; for(Entry<String, String> e : renameMap.entrySet()) { if(e.getValue().equals(newNameEvent)) { oldNameEvent = e.getKey(); break; } } System.out.print(oldNameEvent + " \t::::: DATA ::::: { "); for(int i2 = 0; i2 < nbOfVariables; i2++) { System.out.print(variablesAssignments[i1][i2] == null ? "any " : variablesAssignments[i1][i2] + " "); } System.out.println('}'); } } System.out.println("------------------------------"); Console.printInfo(ConsoleType.FOADA, "Nodes Created : " + nbOfNodesCreated); Console.printInfo(ConsoleType.FOADA, "Nodes Visited : " + nbOfNodesVisited); Console.printInfo(ConsoleType.FOADA, "Time Used : " + (endTime - beginTime) + " ms"); return false; } } catch (SolverException e) { throw new InterpolatingProverEnvironmentException(e); } catch (InterruptedException e) { throw new InterpolatingProverEnvironmentException(e); } // expand the current node if it is not covered // check if the current node is covered, if not then expand it if(currentNode.successors.isEmpty() && !currentNode.isCovered()) { for(String e : events) { FOADAConfiguration newNode = new FOADAConfiguration(nbOfNodesCreated++, JavaSMTConfig.bmgr.makeBoolean(true), currentNode, e); currentNode.addSuccessor(e, newNode); workList.add(newNode); } } } System.out.println("------------------------------"); long endTime = System.currentTimeMillis(); Console.printInfo(ConsoleType.FOADA, "Nodes Created : " + nbOfNodesCreated); Console.printInfo(ConsoleType.FOADA, "Nodes Visited : " + nbOfNodesVisited); Console.printInfo(ConsoleType.FOADA, "Time Used : " + (endTime - beginTime) + " ms"); return true; } }
25,103
41.621392
175
java
FOADA
FOADA-master/old/src/structure/FOADAConfiguration.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package structure; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.sosy_lab.java_smt.api.BooleanFormula; import exception.FOADAException; import utility.Impact; public class FOADAConfiguration { /** configuration number */ public int number; /** expression in the configuration */ public BooleanFormula expression; /** father node */ public FOADAConfiguration father; /** father symbol */ public String fatherSymbol; /** successors */ public List<FOADAConfiguration> successors; /** map of symbol leading to successor to successor's index */ public Map<String, Integer> successorSymbolIndexMap; /** set of nodes covering this */ public Set<FOADAConfiguration> coveringNodes; /** set of nodes that are covered by this */ public Set<FOADAConfiguration> coveredNodes; /** default constructor * @param expression given expression in the configuration * @param father given father node of the current configuration node * @param fatherSymbol the symbol with which father nodes comes to here */ public FOADAConfiguration(int number, BooleanFormula expression, FOADAConfiguration father, String fatherSymbol) { this.number = number; this.expression = expression; this.father = father; this.fatherSymbol = fatherSymbol; successors = new ArrayList<FOADAConfiguration>(); successorSymbolIndexMap = new HashMap<String, Integer>(); coveringNodes = new HashSet<FOADAConfiguration>(); coveredNodes = new HashSet<FOADAConfiguration>(); } /** copy constructor */ public FOADAConfiguration(FOADAConfiguration configuration) { number = configuration.number; expression = configuration.expression; father = configuration.father; fatherSymbol = configuration.fatherSymbol; successors = new ArrayList<FOADAConfiguration>(); for(FOADAConfiguration c : configuration.successors) { successors.add(c.copy()); } successorSymbolIndexMap = new HashMap<String, Integer>(); successorSymbolIndexMap.putAll(configuration.successorSymbolIndexMap); coveringNodes = new HashSet<FOADAConfiguration>(); for(FOADAConfiguration c : configuration.coveringNodes) { coveringNodes.add(c.copy()); } coveredNodes = new HashSet<FOADAConfiguration>(); for(FOADAConfiguration c : configuration.coveredNodes) { coveredNodes.add(c.copy()); } } /** deep copy */ public FOADAConfiguration copy() { FOADAConfiguration copy = new FOADAConfiguration(this); return copy; } /** add successor * @param symbol the symbol leading to the successor * @param successor the successor to be added */ public void addSuccessor(String symbol, FOADAConfiguration successor) { successors.add(successor); successorSymbolIndexMap.put(symbol, successors.size() - 1); } /** check whether the current configuration is a successor of another configuration * @param another the target configuration */ public boolean isSuccessorOf(FOADAConfiguration another) { boolean isSuccessor = false; for(FOADAConfiguration current = this; current != null; current = current.father) { if(current.number == another.number) { isSuccessor = true; break; } } return isSuccessor; } /** remove all the covered relations */ public void removeCoveredRelations(List<FOADAConfiguration> workList) throws FOADAException { for(FOADAConfiguration covered : coveredNodes) { covered.coveringNodes.remove(this); Impact.reEnable(covered, workList); } coveredNodes.clear(); } /** remove all the covered relations of this and its successors */ public void removeRecursivelyCoveredRelations(List<FOADAConfiguration> workList) throws FOADAException { removeCoveredRelations(workList); for(FOADAConfiguration successor : successors) { successor.removeRecursivelyCoveredRelations(workList); } } /** check if this is covered (or one of its ancestor is covered) */ public boolean isCovered() { if(!coveringNodes.isEmpty()) { return true; } else if(father == null){ return false; } else { return father.isCovered(); } } @Override public String toString() { return "#" + number + ' ' + expression; } }
5,093
26.095745
113
java
FOADA
FOADA-master/old/src/structure/FOADAExpression.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package structure; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; public class FOADAExpression { public enum ExpressionType { Integer, Boolean }; public enum ExpressionCategory { Constant, Function, Exists, Forall, Not, And, Or, Equals, Distinct, Plus, Minus, Times, Slash, GT, LT, GEQ, LEQ } // data // ------------------------------ /** type of the expression */ public ExpressionType type; /** category of the expression */ public ExpressionCategory category; /** name */ public String name; /** data for "Boolean constant" */ public boolean bValue; /** data for "Integer constant" */ public int iValue; /** data for "composite structure" */ public List<FOADAExpression> subData; // constructors // ------------------------------ /** constructor for "Boolean constant" */ public FOADAExpression(boolean constant) { type = ExpressionType.Boolean; category = ExpressionCategory.Constant; bValue = constant; // data not used name = null; iValue = 0; subData = null; } /** constructor for "integer constant" */ public FOADAExpression(int constant) { type = ExpressionType.Integer; category = ExpressionCategory.Constant; iValue = constant; // data not used name = null; bValue = true; subData = null; } /** constructor for "unknown-type function" */ public FOADAExpression(String name) { type = null; this.name = name; category = ExpressionCategory.Function; subData = new ArrayList<FOADAExpression>(); // data not used bValue = true; iValue = 0; } /** constructor for "function" */ public FOADAExpression(String name, ExpressionType type, FOADAExpression... arguments) { this.type = type; this.name = name; category = ExpressionCategory.Function; subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : arguments) { subData.add(e.copy()); } // data not used bValue = true; iValue = 0; } /** constructor for "function" */ public FOADAExpression(String name, ExpressionType type, List<FOADAExpression> arguments) { this.type = type; this.name = name; category = ExpressionCategory.Function; subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : arguments) { subData.add(e.copy()); } // data not used bValue = true; iValue = 0; } public void setType(ExpressionType type) { this.type = type; switch(category) { case Not: subData.get(0).setType(ExpressionType.Boolean); break; case And: case Or: for(FOADAExpression e : subData) { e.setType(ExpressionType.Boolean);; } break; case Equals: case Distinct: if(subData.get(0).type != null) { subData.get(0).setType(subData.get(0).type); subData.get(1).setType(subData.get(0).type); } else { subData.get(0).setType(subData.get(1).type); subData.get(1).setType(subData.get(1).type); } break; case Plus: case Minus: case Times: case Slash: case GT: case LT: case GEQ: case LEQ: subData.get(0).setType(ExpressionType.Integer); subData.get(1).setType(ExpressionType.Integer); break; default: break; } } /** constructor for "non-function composite structure" */ public FOADAExpression(ExpressionType type, ExpressionCategory category, FOADAExpression... subExpressions) { this.category = category; subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : subExpressions) { subData.add(e.copy()); } // data not used name = null; bValue = true; iValue = 0; setType(type); } /** constructor for "non-function composite structure" */ public FOADAExpression(ExpressionType type, ExpressionCategory category, List<FOADAExpression> subExpressions) { this.type = type; this.category = category; subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : subExpressions) { subData.add(e.copy()); } // data not used name = null; bValue = true; iValue = 0; } /** copy constructor */ public FOADAExpression(FOADAExpression expression) { type = expression.type; category = expression.category; name = expression.name; bValue = expression.bValue; iValue = expression.iValue; if(expression.subData == null) { subData = null; } else { subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : expression.subData) { subData.add(e.copy()); } } } // utilities /** (only for ADA) add recursively arguments to all the predicates in the expression * @param nbOfVariables number of arguments to be added */ public void addArguments(int nbOfVariables) { if(type == ExpressionType.Boolean && category == ExpressionCategory.Function) { for(int i = 0; i < nbOfVariables; i++) { FOADAExpression argument = new FOADAExpression("v" + i + 'c', ExpressionType.Integer); subData.add(argument); } } if(subData != null) { for(FOADAExpression subexpression : subData) { subexpression.addArguments(nbOfVariables); } } } /** (only for ADA) add recursively 0 as arguments to all the predicates in the initial state * @param nbOfVariables number of arguments to be added */ public void addInitArguments(int nbOfVariables) { if(type == ExpressionType.Boolean && category == ExpressionCategory.Function) { for(int i = 0; i < nbOfVariables; i++) { FOADAExpression argument = new FOADAExpression(0); subData.add(argument); } } if(subData != null) { for(FOADAExpression subexpression : subData) { subexpression.addInitArguments(nbOfVariables); } } } /** (only for ADA) finish recursively the types */ public void finishTypes() { if(type == null && category == ExpressionCategory.Function) { if(name.charAt(0) == 'q') { type = ExpressionType.Boolean; } else { type = ExpressionType.Integer; } } if(subData != null) { for(FOADAExpression subexpression : subData) { subexpression.finishTypes(); } } } public void negate() { switch(category) { case Constant: if(type == ExpressionType.Boolean) { if(bValue == false) { bValue = true; } else { bValue = false; } } break; case Function: for(FOADAExpression e : subData) { e.negate(); } break; case Exists: category = ExpressionCategory.Forall; subData.get(subData.size() - 1).negate(); break; case Forall: category = ExpressionCategory.Exists; subData.get(subData.size() - 1).negate(); break; case Not: FOADAExpression expression = new FOADAExpression(subData.get(0)); type = expression.type; category = expression.category; name = expression.name; bValue = expression.bValue; iValue = expression.iValue; if(expression.subData == null) { subData = null; } else { subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : expression.subData) { subData.add(e.copy()); } } break; case And: category = ExpressionCategory.Or; for(FOADAExpression e : subData) { e.negate(); } break; case Or: category = ExpressionCategory.And; for(FOADAExpression e : subData) { e.negate(); } break; case Equals: category = ExpressionCategory.Distinct; break; case Distinct: category = ExpressionCategory.Equals; break; case Plus: break; case Minus: break; case Times: break; case Slash: break; case GT: category = ExpressionCategory.LEQ; break; case LT: category = ExpressionCategory.GEQ; break; case GEQ: category = ExpressionCategory.LT; break; case LEQ: category = ExpressionCategory.GT; break; } } public Set<FOADAExpression> findPredicatesOccurrences(){ Set<FOADAExpression> result = new HashSet<FOADAExpression>(); switch(category) { case Constant: break; case Function: if(name.charAt(0) == 'q') { result.add(this.copy()); } for(FOADAExpression e : subData) { result.addAll(e.findPredicatesOccurrences()); } break; case Exists: result.addAll(subData.get(subData.size() - 1).findPredicatesOccurrences()); break; case Forall: result.addAll(subData.get(subData.size() - 1).findPredicatesOccurrences()); break; case Not: result.addAll(subData.get(0).findPredicatesOccurrences()); break; case And: for(FOADAExpression e : subData) { result.addAll(e.findPredicatesOccurrences()); } break; case Or: for(FOADAExpression e : subData) { result.addAll(e.findPredicatesOccurrences()); } break; case Equals: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case Distinct: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case Plus: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case Minus: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case Times: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case Slash: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case GT: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case LT: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case GEQ: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case LEQ: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; } return result; } public void addTimeStamps(int timeStamp) { switch(category) { case Constant: break; case Function: if(name.charAt(0) == 'v' || name.charAt(0) == 'q') { name = name + '_' + timeStamp; } for(FOADAExpression e : subData) { e.addTimeStamps(timeStamp); } break; case Exists: subData.get(subData.size() - 1).addTimeStamps(timeStamp); break; case Forall: subData.get(subData.size() - 1).addTimeStamps(timeStamp); break; case Not: subData.get(0).addTimeStamps(timeStamp); break; case And: for(FOADAExpression e : subData) { e.addTimeStamps(timeStamp); } break; case Or: for(FOADAExpression e : subData) { e.addTimeStamps(timeStamp); } break; case Equals: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case Distinct: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case Plus: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case Minus: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case Times: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case Slash: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case GT: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case LT: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case GEQ: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case LEQ: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; } } /** replace a part of the expression * @param from the part to be replaced * @param to used to replace the part */ public void substitute(String from, String to) { switch(category) { case Constant: break; case Function: if(name.equals(from)) { name = to; } for(FOADAExpression e : subData) { e.substitute(from, to); } break; case Exists: subData.get(subData.size() - 1).substitute(from, to); break; case Forall: subData.get(subData.size() - 1).substitute(from, to); break; case Not: subData.get(0).substitute(from, to); break; case And: for(FOADAExpression e : subData) { e.substitute(from, to); } break; case Or: for(FOADAExpression e : subData) { e.substitute(from, to); } break; case Equals: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Distinct: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Plus: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Minus: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Times: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Slash: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case GT: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case LT: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case GEQ: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case LEQ: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; } } /** replace a part of the expression * @param from the part to be replaced * @param to used to replace the part */ public void substitue(FOADAExpression from, FOADAExpression to) { switch(category) { case Constant: break; case Function: if(equals(from)) { type = to.type; category = to.category; name = to.name; bValue = to.bValue; iValue = to.iValue; if(to.subData == null) { subData = null; } else { subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : to.subData) { subData.add(e.copy()); } } } else { for(FOADAExpression e : subData) { e.substitue(from, to); } } break; case Exists: subData.get(subData.size() - 1).substitue(from, to); break; case Forall: subData.get(subData.size() - 1).substitue(from, to); break; case Not: subData.get(subData.size() - 1).substitue(from, to); break; case And: for(FOADAExpression e : subData) { e.substitue(from, to); } break; case Or: for(FOADAExpression e : subData) { e.substitue(from, to); } break; case Equals: subData.get(0).substitue(from, to); subData.get(1).substitue(from, to); break; case Distinct: subData.get(0).substitue(from, to); subData.get(1).substitue(from, to); break; case Plus: subData.get(0).substitue(from, to); subData.get(1).substitue(from, to); break; case Minus: subData.get(0).substitue(from, to); subData.get(1).substitue(from, to); break; case Times: subData.get(0).substitue(from, to); subData.get(1).substitue(from, to); break; case Slash: subData.get(0).substitue(from, to); subData.get(1).substitue(from, to); break; case GT: subData.get(0).substitue(from, to); subData.get(1).substitue(from, to); break; case LT: subData.get(0).substitue(from, to); subData.get(1).substitue(from, to); break; case GEQ: subData.get(0).substitue(from, to); subData.get(1).substitue(from, to); break; case LEQ: subData.get(0).substitue(from, to); subData.get(1).substitue(from, to); break; } } /** deep copy */ public FOADAExpression copy() { FOADAExpression copy = new FOADAExpression(this); return copy; } /** to JavaSMT Formula * @param fmgr corresponding JavaSMT FormulaManager */ public Formula toJavaSMTFormula(FormulaManager fmgr) { switch(category) { case Constant: if(type == ExpressionType.Integer) { return fmgr.getIntegerFormulaManager().makeNumber(iValue); } else { return fmgr.getBooleanFormulaManager().makeBoolean(bValue); } case Function: List<Formula> argumentsIntoJavaSMT = new ArrayList<Formula>(); for(FOADAExpression e : subData) { argumentsIntoJavaSMT.add(e.toJavaSMTFormula(fmgr)); } if(type == ExpressionType.Integer) { return fmgr.getUFManager().declareAndCallUF(name, FormulaType.IntegerType, argumentsIntoJavaSMT); } else { return fmgr.getUFManager().declareAndCallUF(name, FormulaType.BooleanType, argumentsIntoJavaSMT); } case Exists: List<Formula> quantifiedVariables1 = new ArrayList<Formula>(); for(int i = 0; i < subData.size() - 1; i++) { quantifiedVariables1.add(subData.get(i).toJavaSMTFormula(fmgr)); } return fmgr.getQuantifiedFormulaManager().exists(quantifiedVariables1, (BooleanFormula)subData.get(subData.size() - 1).toJavaSMTFormula(fmgr)); case Forall: List<Formula> quantifiedVariables2 = new ArrayList<Formula>(); for(int i = 0; i < subData.size() - 1; i++) { quantifiedVariables2.add(subData.get(i).toJavaSMTFormula(fmgr)); } return fmgr.getQuantifiedFormulaManager().forall(quantifiedVariables2, (BooleanFormula)subData.get(subData.size() - 1).toJavaSMTFormula(fmgr)); case Not: return fmgr.getBooleanFormulaManager().not((BooleanFormula)subData.get(0).toJavaSMTFormula(fmgr)); case And: List<BooleanFormula> subDataIntoJavaSMT1 = new ArrayList<BooleanFormula>(); for(FOADAExpression e : subData) { subDataIntoJavaSMT1.add((BooleanFormula)e.toJavaSMTFormula(fmgr)); } return fmgr.getBooleanFormulaManager().and(subDataIntoJavaSMT1); case Or: List<BooleanFormula> subDataIntoJavaSMT2 = new ArrayList<BooleanFormula>(); for(FOADAExpression e : subData) { subDataIntoJavaSMT2.add((BooleanFormula)e.toJavaSMTFormula(fmgr)); } return fmgr.getBooleanFormulaManager().or(subDataIntoJavaSMT2); case Equals: if(subData.get(0).type == ExpressionType.Integer) { return fmgr.getIntegerFormulaManager().equal((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); } else { return fmgr.getBooleanFormulaManager().equivalence((BooleanFormula)subData.get(0).toJavaSMTFormula(fmgr), (BooleanFormula)subData.get(1).toJavaSMTFormula(fmgr)); } case Distinct: if(subData.get(0).type == ExpressionType.Integer) { return fmgr.getBooleanFormulaManager().not(fmgr.getIntegerFormulaManager().equal((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr))); } else { return fmgr.getBooleanFormulaManager().xor((BooleanFormula)subData.get(0).toJavaSMTFormula(fmgr), (BooleanFormula)subData.get(1).toJavaSMTFormula(fmgr)); } case Plus: return fmgr.getIntegerFormulaManager().add((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case Minus: return fmgr.getIntegerFormulaManager().subtract((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case Times: return fmgr.getIntegerFormulaManager().multiply((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case Slash: return fmgr.getIntegerFormulaManager().divide((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case GT: return fmgr.getIntegerFormulaManager().greaterThan((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case LT: return fmgr.getIntegerFormulaManager().lessThan((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case GEQ: return fmgr.getIntegerFormulaManager().greaterOrEquals((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case LEQ: return fmgr.getIntegerFormulaManager().lessOrEquals((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); /* never reach here */ default: return null; } } @Override public String toString() { String resultString = ""; switch(category) { case Constant: if(type == ExpressionType.Integer) { return Integer.toString(iValue); } else { return Boolean.toString(bValue); } case Function: resultString = resultString + name + '('; for(FOADAExpression e : subData) { resultString = resultString + e.toString() + ','; } if(subData.size() == 0) { resultString = resultString + ' '; } resultString = resultString.substring(0, resultString.length() - 1) + ')'; return resultString; case Exists: resultString = resultString + "exists "; for(int i = 0; i < subData.size() - 1; i++) { resultString = resultString + subData.get(i).toString() + ' '; } resultString = resultString + ". " + subData.get(subData.size() - 1).toString(); return resultString; case Forall: resultString = resultString + "forall "; for(int i = 0; i < subData.size() - 1; i++) { resultString = resultString + subData.get(i).toString() + ' '; } resultString = resultString + ". " + subData.get(subData.size() - 1).toString(); return resultString; case Not: resultString = resultString + "!(" + subData.get(0).toString() + ')'; return resultString; case And: for(int i = 0; i < subData.size(); i++) { ExpressionCategory subCategory = subData.get(i).category; boolean needPar; if(subCategory == ExpressionCategory.Or || subCategory == ExpressionCategory.Exists || subCategory == ExpressionCategory.Forall) { needPar = true; } else { needPar = false; } if(needPar) { resultString = resultString + '('; } resultString = resultString + subData.get(i).toString(); if(needPar) { resultString = resultString + ')'; } resultString = resultString + " /\\ "; } resultString = resultString.substring(0, resultString.length() - 4); return resultString; case Or: for(int i = 0; i < subData.size(); i++) { ExpressionCategory subCategory = subData.get(i).category; boolean needPar; if(subCategory == ExpressionCategory.Exists || subCategory == ExpressionCategory.Forall) { needPar = true; } else { needPar = false; } if(needPar) { resultString = resultString + '('; } resultString = resultString + subData.get(i).toString(); if(needPar) { resultString = resultString + ')'; } resultString = resultString + " \\/ "; } resultString = resultString.substring(0, resultString.length() - 4); return resultString; case Equals: resultString = subData.get(0).toString() + " = " + subData.get(1).toString(); return resultString; case Distinct: resultString = subData.get(0).toString() + " != " + subData.get(1).toString(); return resultString; case Plus: resultString = subData.get(0).toString() + " + " + subData.get(1).toString(); return resultString; case Minus: resultString = subData.get(0).toString() + " - " + subData.get(1).toString(); return resultString; case Times: resultString = subData.get(0).toString() + " * " + subData.get(1).toString(); return resultString; case Slash: resultString = subData.get(0).toString() + " / " + subData.get(1).toString(); return resultString; case GT: resultString = subData.get(0).toString() + " > " + subData.get(1).toString(); return resultString; case LT: resultString = subData.get(0).toString() + " < " + subData.get(1).toString(); return resultString; case GEQ: resultString = subData.get(0).toString() + " >= " + subData.get(1).toString(); return resultString; case LEQ: resultString = subData.get(0).toString() + " <= " + subData.get(1).toString(); return resultString; /* never reach here */ default: return ""; } } @Override public boolean equals(Object obj) { return toString().equals(obj.toString()); } @Override public int hashCode() { return toString().hashCode(); } }
26,325
30.794686
199
java
FOADA
FOADA-master/old/src/structure/FOADATransition.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package structure; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import structure.FOADAExpression.ExpressionCategory; import structure.FOADAExpression.ExpressionType; import utility.JavaSMTConfig; public class FOADATransition { public FOADAExpression left; public String event; public List<FOADAExpression> inputVariables; public FOADAExpression right; public FOADATransition(String nameOfPredicate, List<String> argumentsNames, List<FOADAExpression.ExpressionType> argumentsTypes, String event, List<String> inputVarNames, List<FOADAExpression.ExpressionType> inputVarTypes, FOADAExpression post) { List<FOADAExpression> arguments = new ArrayList<FOADAExpression>(); for(int i = 0; i < argumentsNames.size(); i++) { FOADAExpression argument = new FOADAExpression(argumentsNames.get(i), argumentsTypes.get(i)); arguments.add(argument); } left = new FOADAExpression(nameOfPredicate, ExpressionType.Boolean, arguments); this.event = event; inputVariables = new ArrayList<FOADAExpression>(); for(int i = 0; i < inputVarNames.size(); i++) { FOADAExpression inputVar = new FOADAExpression(inputVarNames.get(i), inputVarTypes.get(i)); inputVariables.add(inputVar); } right = post.copy(); } public FOADATransition() { left = null; event = null; inputVariables = null; right = null; } public Set<FOADAExpression> getPredicates() { Set<FOADAExpression> result = new HashSet<FOADAExpression>(); Set<FOADAExpression> predicatesWithChangedArguments = right.findPredicatesOccurrences(); for(FOADAExpression o : predicatesWithChangedArguments) { for(int i = 0; i < o.subData.size(); i++) { o.subData.get(i).name = "a" + i + "c"; o.subData.get(i).category = ExpressionCategory.Function; o.subData.get(i).subData = new ArrayList<FOADAExpression>(); } result.add(o); } return result; } public Set<FOADAExpression> getPredicatesOccurrences(int currentTimeStamp, FOADAExpression occurenceOfLeft) { FOADAExpression rightAccordingToOccurrenceOfLeft = right.copy(); rightAccordingToOccurrenceOfLeft.addTimeStamps(currentTimeStamp + 1); for(int i = 0; i < occurenceOfLeft.subData.size(); i++) { rightAccordingToOccurrenceOfLeft.substitue(left.subData.get(i), occurenceOfLeft.subData.get(i)); } return rightAccordingToOccurrenceOfLeft.findPredicatesOccurrences(); } public BooleanFormula getImplicationWithOccurrences(int currentTimeStamp, FOADAExpression occurenceOfLeft) { FOADAExpression rightAccordingToOccurrenceOfLeft = right.copy(); rightAccordingToOccurrenceOfLeft.addTimeStamps(currentTimeStamp + 1); for(int i = 0; i < occurenceOfLeft.subData.size(); i++) { rightAccordingToOccurrenceOfLeft.substitue(left.subData.get(i), occurenceOfLeft.subData.get(i)); } BooleanFormula leftPartOfImplication = (BooleanFormula)occurenceOfLeft.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula rightPartOfImplication = (BooleanFormula)rightAccordingToOccurrenceOfLeft.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula implication = JavaSMTConfig.bmgr.implication(leftPartOfImplication, rightPartOfImplication); return implication; } public BooleanFormula getUniversallyQuantifiedImplication(int currentTimeStamp) { List<Formula> arguments = new ArrayList<Formula>(); for(FOADAExpression a : left.subData) { Formula argument; if(a.type == ExpressionType.Integer) { argument = JavaSMTConfig.ufmgr.declareAndCallUF(a.name, FormulaType.IntegerType); } else { argument = JavaSMTConfig.ufmgr.declareAndCallUF(a.name, FormulaType.BooleanType); } arguments.add(argument); } FOADAExpression timeStampedLeft = left.copy(); timeStampedLeft.addTimeStamps(currentTimeStamp); FOADAExpression timeStampedRight = right.copy(); timeStampedRight.addTimeStamps(currentTimeStamp + 1); BooleanFormula leftPartOfImplication = (BooleanFormula)timeStampedLeft.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula rightPartOfImplication = (BooleanFormula)timeStampedRight.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula implication = JavaSMTConfig.bmgr.implication(leftPartOfImplication, rightPartOfImplication); if(arguments.isEmpty()) { return implication; } else { BooleanFormula universallyQuantifiedImplication = JavaSMTConfig.qmgr.forall(arguments, implication); return universallyQuantifiedImplication; } } public FOADATransition copy() { FOADATransition copy = new FOADATransition(); copy.left = left.copy(); copy.event = event; copy.inputVariables = new ArrayList<FOADAExpression>(); for(FOADAExpression inputVariable : inputVariables) { copy.inputVariables.add(inputVariable.copy()); } copy.right = right.copy(); return copy; } @Override public String toString() { String result = left.toString(); result = result + " + " + event + " : "; for(FOADAExpression i : inputVariables) { result = result + i.toString() + " "; } result = result + "---> "; result = result + right.toString(); return result; } }
6,080
34.561404
128
java
FOADA
FOADA-master/old/src/utility/Console.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; public class Console { // Reset public static final String RESET = "\033[0m"; // Text Reset // Regular Colors public static final String BLACK = "\033[0;30m"; // BLACK public static final String RED = "\033[0;31m"; // RED public static final String GREEN = "\033[0;32m"; // GREEN public static final String YELLOW = "\033[0;33m"; // YELLOW public static final String BLUE = "\033[0;34m"; // BLUE public static final String PURPLE = "\033[0;35m"; // PURPLE public static final String CYAN = "\033[0;36m"; // CYAN public static final String WHITE = "\033[0;37m"; // WHITE // Bold public static final String BLACK_BOLD = "\033[1;30m"; // BLACK public static final String RED_BOLD = "\033[1;31m"; // RED public static final String GREEN_BOLD = "\033[1;32m"; // GREEN public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW public static final String BLUE_BOLD = "\033[1;34m"; // BLUE public static final String PURPLE_BOLD = "\033[1;35m"; // PURPLE public static final String CYAN_BOLD = "\033[1;36m"; // CYAN public static final String WHITE_BOLD = "\033[1;37m"; // WHITE // Underline public static final String BLACK_UNDERLINED = "\033[4;30m"; // BLACK public static final String RED_UNDERLINED = "\033[4;31m"; // RED public static final String GREEN_UNDERLINED = "\033[4;32m"; // GREEN public static final String YELLOW_UNDERLINED = "\033[4;33m"; // YELLOW public static final String BLUE_UNDERLINED = "\033[4;34m"; // BLUE public static final String PURPLE_UNDERLINED = "\033[4;35m"; // PURPLE public static final String CYAN_UNDERLINED = "\033[4;36m"; // CYAN public static final String WHITE_UNDERLINED = "\033[4;37m"; // WHITE // Background public static final String BLACK_BACKGROUND = "\033[40m"; // BLACK public static final String RED_BACKGROUND = "\033[41m"; // RED public static final String GREEN_BACKGROUND = "\033[42m"; // GREEN public static final String YELLOW_BACKGROUND = "\033[43m"; // YELLOW public static final String BLUE_BACKGROUND = "\033[44m"; // BLUE public static final String PURPLE_BACKGROUND = "\033[45m"; // PURPLE public static final String CYAN_BACKGROUND = "\033[46m"; // CYAN public static final String WHITE_BACKGROUND = "\033[47m"; // WHITE // High Intensity public static final String BLACK_BRIGHT = "\033[0;90m"; // BLACK public static final String RED_BRIGHT = "\033[0;91m"; // RED public static final String GREEN_BRIGHT = "\033[0;92m"; // GREEN public static final String YELLOW_BRIGHT = "\033[0;93m"; // YELLOW public static final String BLUE_BRIGHT = "\033[0;94m"; // BLUE public static final String PURPLE_BRIGHT = "\033[0;95m"; // PURPLE public static final String CYAN_BRIGHT = "\033[0;96m"; // CYAN public static final String WHITE_BRIGHT = "\033[0;97m"; // WHITE // Bold High Intensity public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; // BLACK public static final String RED_BOLD_BRIGHT = "\033[1;91m"; // RED public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; // GREEN public static final String YELLOW_BOLD_BRIGHT = "\033[1;93m";// YELLOW public static final String BLUE_BOLD_BRIGHT = "\033[1;94m"; // BLUE public static final String PURPLE_BOLD_BRIGHT = "\033[1;95m";// PURPLE public static final String CYAN_BOLD_BRIGHT = "\033[1;96m"; // CYAN public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; // WHITE // High Intensity backgrounds public static final String BLACK_BACKGROUND_BRIGHT = "\033[100m";// BLACK public static final String RED_BACKGROUND_BRIGHT = "\033[101m";// RED public static final String GREEN_BACKGROUND_BRIGHT = "\033[102m";// GREEN public static final String YELLOW_BACKGROUND_BRIGHT = "\033[103m";// YELLOW public static final String BLUE_BACKGROUND_BRIGHT = "\033[104m";// BLUE public static final String PURPLE_BACKGROUND_BRIGHT = "\033[105m"; // PURPLE public static final String CYAN_BACKGROUND_BRIGHT = "\033[106m"; // CYAN public static final String WHITE_BACKGROUND_BRIGHT = "\033[107m"; // WHITE public enum ConsoleType {FOADA, ANTLR4, Java, JavaSMT}; public static void printInfo(ConsoleType t, String m) { System.out.print(CYAN_BRIGHT); String console = ""; switch(t) { case FOADA: console = "FOADA"; break; case ANTLR4:console = "ANTLR4"; break; case Java:console = "Java"; break; case JavaSMT:console = "JavaSMT"; break; default:console = "*"; break; } System.out.println(console + " > " + RESET + m); } public static void printError(ConsoleType t, String m) { System.out.print(RED_BRIGHT); String console = ""; switch(t) { case FOADA: console = "FOADA"; break; case ANTLR4:console = "ANTLR4"; break; case Java:console = "Java"; break; case JavaSMT:console = "JavaSMT"; break; default:console = "*"; break; } System.out.println(console + " > " + RESET + m); } // FOADA Special Console Print public static void printFOADAEndOfSession() { printInfo(ConsoleType.FOADA, "End of session.\n"); } }
6,059
42.285714
82
java
FOADA
FOADA-master/old/src/utility/ErrorListenerWithExceptions.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.misc.ParseCancellationException; public class ErrorListenerWithExceptions extends BaseErrorListener { public static final ErrorListenerWithExceptions listener = new ErrorListenerWithExceptions(); @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException { throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + msg); } }
1,509
34.952381
147
java
FOADA
FOADA-master/old/src/utility/Impact.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; import java.util.List; import java.util.Set; import exception.FOADAException; import structure.FOADAConfiguration; public abstract class Impact { public enum Mode { UniversallyQuantifyArguments, FindOccurrences }; /** add all the leaves successors of a given node into the work list if it is not covered * @param givenNode the given node * @param workList the work list of IMPACT */ public static void reEnable(FOADAConfiguration givenNode, List<FOADAConfiguration> workList) throws FOADAException { boolean givenNodeIsCovered = givenNode.isCovered(); if(givenNode.successors.isEmpty() && !givenNodeIsCovered && !workList.contains(givenNode) && !givenNode.expression.toString().equals("false")) { workList.add(0, givenNode); } if(!givenNodeIsCovered) { for(FOADAConfiguration successor : givenNode.successors) { reEnable(successor, workList); } } } public static boolean close(FOADAConfiguration node, List<FOADAConfiguration> workList, Set<FOADAConfiguration> allValidNodes) throws FOADAException { for(FOADAConfiguration targetNode : allValidNodes) { // pick a target node (which is not covered) from all nodes according to a certain order if(targetNode.number < node.number && !targetNode.isCovered()) { // if the current node along path is covered by the target node if(JavaSMTConfig.checkImplication(node.expression, targetNode.expression)) { // remove all the coverage where the node or any of its successors covers another node.removeRecursivelyCoveredRelations(workList); node.coveringNodes.add(targetNode); targetNode.coveredNodes.add(node); return true; } } } return false; } }
2,548
31.265823
127
java
FOADA
FOADA-master/old/src/utility/JavaSMTConfig.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; import org.sosy_lab.common.configuration.InvalidConfigurationException; import org.sosy_lab.java_smt.SolverContextFactory; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.ProverEnvironment; import org.sosy_lab.java_smt.api.QuantifiedFormulaManager; import org.sosy_lab.java_smt.api.SolverContext; import org.sosy_lab.java_smt.api.SolverException; import org.sosy_lab.java_smt.api.UFManager; import exception.FOADAException; import exception.ImplicationProverEnvironmentException; import exception.JavaSMTInvalidConfigurationException; public class JavaSMTConfig { public static SolverContext solverContext; public static FormulaManager fmgr; public static BooleanFormulaManager bmgr; public static QuantifiedFormulaManager qmgr; public static UFManager ufmgr; public static void initJavaSMT() throws FOADAException { try { solverContext = SolverContextFactory.createSolverContext(Solvers.Z3); fmgr = solverContext.getFormulaManager(); bmgr = fmgr.getBooleanFormulaManager(); qmgr = fmgr.getQuantifiedFormulaManager(); ufmgr = fmgr.getUFManager(); } catch(InvalidConfigurationException e) { throw new JavaSMTInvalidConfigurationException(e); } } public static BooleanFormula removeTimeStamp(BooleanFormula expression) { BooleanFormula result = expression; String resultToString = fmgr.dumpFormula(result).toString(); for(String s : fmgr.extractVariablesAndUFs(result).keySet()) { if(s.contains("_") && s.charAt(0) != 'v') { resultToString = resultToString.replace(s, s.substring(0, s.indexOf("_"))); } } result = fmgr.parse(resultToString); return result; } public static boolean checkImplication(BooleanFormula f1, BooleanFormula f2) throws FOADAException { BooleanFormula implication = bmgr.implication(f1, f2); ProverEnvironment prover = solverContext.newProverEnvironment(); BooleanFormula notImplication = bmgr.not(implication); prover.addConstraint(notImplication); boolean isUnsat; boolean implicationIsValid = false; try { isUnsat = prover.isUnsat(); if(isUnsat) { implicationIsValid = true; } else { implicationIsValid = false; } } catch (SolverException e) { throw new ImplicationProverEnvironmentException(e); } catch (InterruptedException e) { throw new ImplicationProverEnvironmentException(e); } prover.close(); return implicationIsValid; } }
3,441
30.290909
82
java
FOADA
FOADA-master/old/src/utility/Solver.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; import org.sosy_lab.java_smt.SolverContextFactory; import org.sosy_lab.java_smt.SolverContextFactory.Solvers; import utility.Console.ConsoleType; public abstract class Solver { public static void checkZ3() { try { SolverContextFactory.createSolverContext(Solvers.Z3); } catch(Exception e) { Console.printError(ConsoleType.JavaSMT, "The solver Z3 failed."); Console.printError(ConsoleType.JavaSMT, e.getMessage()); return; } Console.printInfo(ConsoleType.JavaSMT, "The solver " + Console.GREEN_BRIGHT + "Z3 succeeded" + Console.RESET + "."); } public static void checkMATHSAT5() { try { SolverContextFactory.createSolverContext(Solvers.MATHSAT5); } catch(Exception e) { Console.printError(ConsoleType.JavaSMT, "The solver MATHSAT5 failed."); Console.printError(ConsoleType.JavaSMT, e.getMessage()); return; } Console.printInfo(ConsoleType.JavaSMT, "The solver " + Console.GREEN_BRIGHT + "MATHSAT5 succeeded" + Console.RESET + "."); } public static void checkSMTINTERPOL() { try { SolverContextFactory.createSolverContext(Solvers.SMTINTERPOL); } catch(Exception e) { Console.printError(ConsoleType.JavaSMT, "The solver SMTINTERPOL failed."); Console.printError(ConsoleType.JavaSMT, e.getMessage()); return; } Console.printInfo(ConsoleType.JavaSMT, "The solver " + Console.GREEN_BRIGHT + "SMTINTERPOL succeeded" + Console.RESET + "."); } public static void checkPRINCESS() { try { SolverContextFactory.createSolverContext(Solvers.PRINCESS); } catch(Exception e) { Console.printError(ConsoleType.JavaSMT, "The solver PRINCESS failed."); Console.printError(ConsoleType.JavaSMT, e.getMessage()); return; } Console.printInfo(ConsoleType.JavaSMT, "The solver " + Console.GREEN_BRIGHT + "PRINCESS succeeded" + Console.RESET + "."); } }
2,770
31.988095
127
java
FOADA
FOADA-master/old/src/utility/TreeSearch.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; public abstract class TreeSearch { public enum Mode { BFS, DFS }; }
919
26.878788
82
java
FOADA
FOADA-master/src/app/FOADA.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package app; import java.util.ArrayList; import java.util.List; import exception.FOADAException; import exception.InputFileNotFoundException; import exception.UnknownConsoleOptionException; import parser.ParserTools; import parser.ParserTools.ParserType; import structure.Automaton; import structure.FOADAExpression.ExpressionType; import utility.Console; import utility.Console.ConsoleType; import utility.Solver; public class FOADA { // FOADA Version public static final String FOADA_version = "1.0"; /** < FOADA welcome > </br> * FOADA execution with no argument */ private static void welcome() { System.out.println("------------------------------"); System.out.print(" FOADA Version "); System.out.println(FOADA_version); System.out.println("------------------------------"); help(); } /** < FOADA help menu > </br> * FOADA execution with argument <b> -h </b> or <b> --help </b> */ private static void help() { Console.printInfo(ConsoleType.FOADA, "Showing all the options..."); // -h , --help System.out.println("-h, --help \t\t\thelp menu"); // -c , --check System.out.println("-c, --check \t\t\tsolver checking"); // -e, --empty System.out.println("-e, --empty <input> <options>\temptiness checking using BFS "); // additional options for emptiness checking System.out.println("\tadditional options:"); // -d, --dfs System.out.println("\t-d, --dfs\t\tusing DFS instead of using BFS"); // -o, --occurrences System.out.println("\t-o, --occurrences\tfinding occurrences of predicates instead of universally quantifying arguments"); // -i, --inclusion System.out.println("-i, --inclusion <input1> <input2> <options>\tinclusion checking using BFS "); // additional options for inclusion checking System.out.println("\tadditional options:"); // -d, --dfs System.out.println("\t-d, --dfs\t\tusing DFS instead of using BFS"); // -o, --occurrences System.out.println("\t-o, --occurrences\tfinding occurrences of predicates instead of universally quantifying arguments"); // -v , --version System.out.println("-v, --version \t\t\tinstalled version"); Console.printFOADAEndOfSession(); } /** < FOADA solver checking > </br> * FOADA execution with argument <b> -c </b> or <b> --check </b> */ private static void checkSolvers() { Console.printInfo(ConsoleType.FOADA, "Start checking all the solvers..."); Solver.checkSMTINTERPOL(); Solver.checkZ3(); Solver.checkMATHSAT5(); Solver.checkPRINCESS(); Console.printFOADAEndOfSession(); } /** < FOADA emptiness checking > </br> * FOADA execution with argument <b> -e </b> or <b> --empty </b> * @param filename name of the input file * @param searchMode mode of tree search: <b> BFS </b> / <b> DFS </b> * @param transitionMode mode of transition rules: <b> universally quantifier arguments </b> / <b> find occurrences </b> */ private static void checkEmpty(String filename, utility.TreeSearch.Mode searchMode, utility.Impact.Mode transitionMode) throws FOADAException { ParserType parserType = ParserTools.selectAccordingToInputFile(filename); Automaton automaton = ParserTools.buildAutomatonFromFile(filename, parserType); if(searchMode == utility.TreeSearch.Mode.BFS) { if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (BFS / Universally Quantify Arguments) ... "); } else if(transitionMode == utility.Impact.Mode.FindOccurrences) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (BFS / Find Occurrences) ... "); Console.printInfo(ConsoleType.FOADA, Console.RED_BRIGHT + "WARNING : " + Console.RESET + "This version does not work with transition quantifiers."); } } else if(searchMode == utility.TreeSearch.Mode.DFS) { if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (DFS / Universally Quantify Arguments) ... "); } else if(transitionMode == utility.Impact.Mode.FindOccurrences) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (DFS / Find Occurrences) ... "); Console.printInfo(ConsoleType.FOADA, Console.RED_BRIGHT + "WARNING : " + Console.RESET + "This version does not work with transition quantifiers."); } } if(automaton.isEmpty(searchMode, transitionMode)) { Console.printInfo(ConsoleType.FOADA, "The automaton is empty..."); } else { Console.printInfo(ConsoleType.FOADA, "The automaton is not empty..."); } Console.printFOADAEndOfSession(); } /** < FOADA inclusion checking > </br> * FOADA execution with argument <b> -i </b> or <b> --inclusion </b> * @param filename1 name of the input file 1 * @param filename2 name of the input file 2 * @param searchMode mode of tree search: <b> BFS </b> / <b> DFS </b> * @param transitionMode mode of transition rules: <b> universally quantifier arguments </b> / <b> find occurrences </b> */ private static void checkInclusion(String filename1, String filename2, utility.TreeSearch.Mode searchMode, utility.Impact.Mode transitionMode) throws FOADAException { Console.printInfo(ConsoleType.FOADA, "Building automaton 1 ... "); ParserType parser1Type = ParserTools.selectAccordingToInputFile(filename1); Automaton automaton1 = ParserTools.buildAutomatonFromFile(filename1, parser1Type); /* TODO */ /*System.out.println("Predicates: " + automaton1.namesOfPredicates); System.out.println("Initial: " + automaton1.initial); System.out.println("Final: " + automaton1.namesOfFinalStates); System.out.println("Events: " + automaton1.events); System.out.println("Nb of Variables: " + automaton1.nbOfVariables); System.out.println(automaton1.renameMap); for(Map.Entry<String, FOADATransition> xx : automaton1.transitions.entrySet()) { System.out.println(xx.getValue()); } System.out.println();*/ Console.printInfo(ConsoleType.FOADA, "Building automaton 2 ... "); ParserType parser2Type = ParserTools.selectAccordingToInputFile(filename2); Automaton automaton2 = ParserTools.buildAutomatonFromFile(filename2, parser2Type); /* TODO */ /*System.out.println("Predicates: " + automaton2.namesOfPredicates); System.out.println("Initial: " + automaton2.initial); System.out.println("Final: " + automaton2.namesOfFinalStates); System.out.println("Events: " + automaton2.events); System.out.println("Nb of Variables: " + automaton2.nbOfVariables); System.out.println(automaton2.renameMap); for(Map.Entry<String, FOADATransition> xx : automaton2.transitions.entrySet()) { System.out.println(xx.getValue()); } System.out.println();*/ Console.printInfo(ConsoleType.FOADA, "Complementing automaton 2 ... "); Automaton complementOfAutomaton2 = automaton2.complements(); /* TODO */ /*System.out.println("Predicates: " + complementOfAutomaton2.namesOfPredicates); System.out.println("Initial: " + complementOfAutomaton2.initial); System.out.println("Final: " + complementOfAutomaton2.namesOfFinalStates); System.out.println("Events: " + complementOfAutomaton2.events); System.out.println("Nb of Variables: " + complementOfAutomaton2.nbOfVariables); System.out.println(complementOfAutomaton2.renameMap); for(Map.Entry<String, FOADATransition> xx : complementOfAutomaton2.transitions.entrySet()) { System.out.println(xx.getValue()); } System.out.println();*/ Console.printInfo(ConsoleType.FOADA, "Intersecting automaton 1 with complement of automaton 2 ... "); Automaton automaton = automaton1.intersects(complementOfAutomaton2); /* TODO */ /*System.out.println("Predicates: " + automaton.namesOfPredicates); System.out.println("Initial: " + automaton.initial); System.out.println("Final: " + automaton.namesOfFinalStates); System.out.println("Events: " + automaton.events); System.out.println("Nb of Variables: " + automaton.nbOfVariables); System.out.println(automaton.renameMap); for(Map.Entry<String, FOADATransition> xx : automaton.transitions.entrySet()) { System.out.println(xx.getValue()); } System.out.println();*/ if(searchMode == utility.TreeSearch.Mode.BFS) { if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (BFS / Universally Quantify Arguments) ... "); } else if(transitionMode == utility.Impact.Mode.FindOccurrences) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (BFS / Find Occurrences) ... "); Console.printInfo(ConsoleType.FOADA, Console.RED_BRIGHT + "WARNING : " + Console.RESET + "This version does not work with transition quantifiers."); } } else if(searchMode == utility.TreeSearch.Mode.DFS) { if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (DFS / Universally Quantify Arguments) ... "); } else if(transitionMode == utility.Impact.Mode.FindOccurrences) { Console.printInfo(ConsoleType.FOADA, "Start checking emptiness (DFS / Find Occurrences) ... "); Console.printInfo(ConsoleType.FOADA, Console.RED_BRIGHT + "WARNING : " + Console.RESET + "This version does not work with transition quantifiers."); } } if(automaton.isEmpty(searchMode, transitionMode)) { Console.printInfo(ConsoleType.FOADA, "The inclusion holds..."); } else { Console.printInfo(ConsoleType.FOADA, "The inclusion does not hold..."); } Console.printFOADAEndOfSession(); } /** < FOADA installed version > </br> * FOADA execution with argument <b> -v </b> or <b> --version </b> */ private static void version() { Console.printInfo(ConsoleType.FOADA, "Version " + FOADA_version); Console.printFOADAEndOfSession(); } /** < FOADA execution > * @param args command-line arguments */ public static void main(String[] args) { try { // welcome if(args.length == 0) { //welcome(); /* *********************** */ Automaton Philo1 = ParserTools.buildAutomatonFromFile("examples/Philo1.foada", ParserType.FOADAParser); Automaton Philo2 = ParserTools.buildAutomatonFromFile("examples/Philo2.foada", ParserType.FOADAParser); Automaton Philo3 = ParserTools.buildAutomatonFromFile("examples/Philo3.foada", ParserType.FOADAParser); //Philo1.isEmpty(utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); //Philo2.isEmpty(utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); //Philo3.isEmpty(utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); Automaton coe = Philo1.intersects(Philo2, "B").intersects(Philo3, "C"); coe.isEmpty(utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); Automaton acc = ParserTools.buildAutomatonFromFile("examples/PhiloAcc.foada", ParserType.FOADAParser); acc.isEmpty(utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); // OK ! Automaton complAcc = acc.complements(); //complAcc.isEmpty(utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); Automaton coeIntersectsComplAcc = coe.intersects(complAcc, "D"); //coeIntersectsComplAcc.isEmpty(utility.TreeSearch.Mode.BFS, utility.Impact.Mode.UniversallyQuantifyArguments); //Automaton complCoeIntersectsComplAcc = coeIntersectsComplAcc.complements(); //complCoeIntersectsComplAcc.isEmpty(utility.TreeSearch.Mode.BFS, utility.Impact.Mode.UniversallyQuantifyArguments); List<String> variablesNames = new ArrayList<String>(); List<ExpressionType> variablesTypes = new ArrayList<ExpressionType>(); variablesNames.add("Nf"); variablesTypes.add(ExpressionType.Integer); variablesNames.add("Nb"); variablesTypes.add(ExpressionType.Integer); variablesNames.add("Nw"); variablesTypes.add(ExpressionType.Integer); variablesNames.add("Nh"); variablesTypes.add(ExpressionType.Integer); variablesNames.add("Ne"); variablesTypes.add(ExpressionType.Integer); Automaton qtfCoeIntersectsComplAcc = coeIntersectsComplAcc.quantifies(variablesNames, variablesTypes); //qtfCoeIntersectsComplAcc.isEmpty(utility.TreeSearch.Mode.BFS, utility.Impact.Mode.UniversallyQuantifyArguments); Automaton complQtfCoeIntersectsComplAcc = qtfCoeIntersectsComplAcc.complements(); /*if(complQtfCoeIntersectsComplAcc.isEmpty(utility.TreeSearch.Mode.BFS, utility.Impact.Mode.UniversallyQuantifyArguments)) { System.out.println("Empty"); };*/ //Automaton DL1 = ParserTools.buildAutomatonFromFile("examples/PhiloDL1.foada", ParserType.FOADAParser); //DL1.isEmpty(utility.TreeSearch.Mode.BFS, utility.Impact.Mode.UniversallyQuantifyArguments); /* *********************** */ } // help menu else if(args[0].equals("-h") || args[0].equals("--help")) { help(); } // solver checking else if(args[0].equals("-c") || args[0].equals("--check")) { checkSolvers(); } // emptiness checking else if(args[0].equals("-e") || args[0].equals("--empty")) { if(args.length < 2) { throw new InputFileNotFoundException(null); } else if(args.length == 2) { checkEmpty(args[1], utility.TreeSearch.Mode.BFS, utility.Impact.Mode.UniversallyQuantifyArguments); } else if(args.length == 3 && (args[2].equals("-d") || args[2].equals("--dfs"))) { checkEmpty(args[1], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.UniversallyQuantifyArguments); } else if(args.length == 3 && (args[2].equals("-o") || args[2].equals("--occurrences"))){ checkEmpty(args[1], utility.TreeSearch.Mode.BFS, utility.Impact.Mode.FindOccurrences); } else if(args.length == 4 && (args[2].equals("-d") || args[2].equals("--dfs")) && (args[3].equals("-o") || args[3].equals("--occurrences"))) { checkEmpty(args[1], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); } else if(args.length == 4 && (args[2].equals("-o") || args[2].equals("--occurrences")) && (args[3].equals("-d") || args[3].equals("--dfs"))) { checkEmpty(args[1], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); } } // inclusion checking else if(args[0].equals("-i") || args[0].equals("--inclusion")) { if(args.length < 3) { throw new InputFileNotFoundException(null); } else if(args.length == 3) { checkInclusion(args[1], args[2], utility.TreeSearch.Mode.BFS, utility.Impact.Mode.UniversallyQuantifyArguments); } else if(args.length == 4 && (args[3].equals("-d") || args[3].equals("--dfs"))) { checkInclusion(args[1], args[2], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.UniversallyQuantifyArguments); } else if(args.length == 4 && (args[3].equals("-o") || args[3].equals("--occurrences"))){ checkInclusion(args[1], args[2], utility.TreeSearch.Mode.BFS, utility.Impact.Mode.FindOccurrences); } else if(args.length == 5 && (args[3].equals("-d") || args[3].equals("--dfs")) && (args[4].equals("-o") || args[4].equals("--occurrences"))) { checkInclusion(args[1], args[2], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); } else if(args.length == 5 && (args[3].equals("-o") || args[3].equals("--occurrences")) && (args[4].equals("-d") || args[4].equals("--dfs"))) { checkInclusion(args[1], args[2], utility.TreeSearch.Mode.DFS, utility.Impact.Mode.FindOccurrences); } } // installed version else if(args[0].equals("-v") || args[0].equals("--version")) { version(); } // unknown option else { throw new UnknownConsoleOptionException(args[0]); } } catch(FOADAException e) { e.printErrorMessage(); Console.printFOADAEndOfSession(); } } }
16,575
45.044444
152
java
FOADA
FOADA-master/src/exception/ANTLR4ParseCancellationException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import org.antlr.v4.runtime.misc.ParseCancellationException; import utility.Console; import utility.Console.ConsoleType; @SuppressWarnings("serial") public class ANTLR4ParseCancellationException extends FOADAException { private ParseCancellationException ANTLR4Exception; public ANTLR4ParseCancellationException(ParseCancellationException ANTLR4Exception) { type = ExceptionType.ANTLR4ParseCancellation; this.ANTLR4Exception = ANTLR4Exception; } public String getInfo() { return ANTLR4Exception.getMessage(); } public void printErrorMessage() { Console.printError(ConsoleType.ANTLR4, getInfo()); } }
1,471
28.44
84
java
FOADA
FOADA-master/src/exception/FOADAException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import utility.Console; import utility.Console.*; // general structure for FOADA exception (abstract class) @SuppressWarnings("serial") public abstract class FOADAException extends Throwable { public enum ExceptionType { ANTLR4ParseCancellation, ImplicationProverEnvironment, InputFileNotFound, InputFileUnsupported, InterpolatingProverEnvironment, JavaIO, JavaSMTInvalidConfiguration, UnknownConsoleOption }; public ExceptionType type; public abstract String getInfo(); public void printErrorMessage() { Console.printError(ConsoleType.FOADA, getInfo()); } }
1,437
26.132075
82
java
FOADA
FOADA-master/src/exception/ImplicationProverEnvironmentException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import org.sosy_lab.java_smt.api.SolverException; import utility.Console; import utility.Console.ConsoleType; @SuppressWarnings("serial") public class ImplicationProverEnvironmentException extends FOADAException { private SolverException javaSMTSolverException; private InterruptedException javaInterruptedException; public ImplicationProverEnvironmentException(SolverException javaSMTSolverException) { type = ExceptionType.ImplicationProverEnvironment; this.javaSMTSolverException = javaSMTSolverException; javaInterruptedException = null; } public ImplicationProverEnvironmentException(InterruptedException javaInterruptedException) { type = ExceptionType.ImplicationProverEnvironment; this.javaInterruptedException = javaInterruptedException; javaSMTSolverException = null; } public String getInfo() { if(javaSMTSolverException == null) { return javaInterruptedException.getMessage(); } else { return javaSMTSolverException.getMessage(); } } public void printErrorMessage() { if(javaSMTSolverException == null) { Console.printError(ConsoleType.Java, getInfo()); } else { Console.printError(ConsoleType.JavaSMT, getInfo()); } } }
1,973
26.416667
91
java
FOADA
FOADA-master/src/exception/InputFileNotFoundException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; // the input file cannot be found @SuppressWarnings("serial") public class InputFileNotFoundException extends FOADAException { private String filename; public InputFileNotFoundException(String filename) { type = ExceptionType.InputFileNotFound; this.filename = filename; } public String getInfo() { if(filename == null) { return "No input file is given."; } else { return "The file < " + filename + " > cannot be found."; } } }
1,303
26.744681
82
java
FOADA
FOADA-master/src/exception/InputFileUnsupportedException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; // the input file is not supported @SuppressWarnings("serial") public class InputFileUnsupportedException extends FOADAException { private String filename; public InputFileUnsupportedException(String filename) { type = ExceptionType.InputFileUnsupported; this.filename = filename; } public String getInfo() { return "The input file \"" + filename + "\" is not supported."; } }
1,241
27.883721
82
java
FOADA
FOADA-master/src/exception/InterpolatingProverEnvironmentException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import org.sosy_lab.java_smt.api.SolverException; import utility.Console; import utility.Console.ConsoleType; @SuppressWarnings("serial") public class InterpolatingProverEnvironmentException extends FOADAException { private SolverException javaSMTSolverException; private InterruptedException javaInterruptedException; public InterpolatingProverEnvironmentException(SolverException javaSMTSolverException) { type = ExceptionType.InterpolatingProverEnvironment; this.javaSMTSolverException = javaSMTSolverException; javaInterruptedException = null; } public InterpolatingProverEnvironmentException(InterruptedException javaInterruptedException) { type = ExceptionType.InterpolatingProverEnvironment; this.javaInterruptedException = javaInterruptedException; javaSMTSolverException = null; } public String getInfo() { if(javaSMTSolverException == null) { return javaInterruptedException.getMessage(); } else { return javaSMTSolverException.getMessage(); } } public void printErrorMessage() { if(javaSMTSolverException == null) { Console.printError(ConsoleType.Java, getInfo()); } else { Console.printError(ConsoleType.JavaSMT, getInfo()); } } }
2,056
27.569444
94
java
FOADA
FOADA-master/src/exception/JavaIOException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import java.io.IOException; import utility.Console; import utility.Console.ConsoleType; @SuppressWarnings("serial") public class JavaIOException extends FOADAException { private IOException javaIOException; public JavaIOException(IOException javaIOException) { type = ExceptionType.JavaIO; this.javaIOException = javaIOException; } public String getInfo() { return javaIOException.getMessage(); } public void printErrorMessage() { Console.printError(ConsoleType.Java, getInfo()); } }
1,355
26.12
82
java
FOADA
FOADA-master/src/exception/JavaSMTInvalidConfigurationException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; import org.sosy_lab.common.configuration.InvalidConfigurationException; import utility.Console; import utility.Console.ConsoleType; //invalid configuration when create JavaSMT solver context @SuppressWarnings("serial") public class JavaSMTInvalidConfigurationException extends FOADAException { private InvalidConfigurationException javaSMTInvalidConfigurationException; public JavaSMTInvalidConfigurationException(InvalidConfigurationException javaSMTInvalidConfigurationException) { type = ExceptionType.JavaSMTInvalidConfiguration; this.javaSMTInvalidConfigurationException = javaSMTInvalidConfigurationException; } public String getInfo() { return javaSMTInvalidConfigurationException.getMessage(); } public void printErrorMessage() { Console.printError(ConsoleType.JavaSMT, getInfo()); } }
1,667
30.471698
112
java
FOADA
FOADA-master/src/exception/UndefinedVariableException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; //a variable in the transition is undefined @SuppressWarnings("serial") public class UndefinedVariableException extends FOADAException { private String variable; public UndefinedVariableException(String variable) { type = ExceptionType.UnknownConsoleOption; this.variable = variable; } public String getInfo() { return "Undefined variable < " + variable + " >."; } }
1,231
27.651163
82
java
FOADA
FOADA-master/src/exception/UnknownConsoleOptionException.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package exception; // the given console option is unknown @SuppressWarnings("serial") public class UnknownConsoleOptionException extends FOADAException { private String option; public UnknownConsoleOptionException(String option) { type = ExceptionType.UnknownConsoleOption; this.option = option; } public String getInfo() { return "Unknown option < " + option + " >."; } }
1,218
27.348837
82
java
FOADA
FOADA-master/src/parser/ParserTools.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.Parser; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.misc.ParseCancellationException; import exception.ANTLR4ParseCancellationException; import exception.FOADAException; import exception.InputFileNotFoundException; import exception.InputFileUnsupportedException; import exception.JavaIOException; import parser.FOADA.ANTLR4.FOADALexerANTLR4; import parser.FOADA.ANTLR4.FOADAParserANTLR4; import structure.Automaton; import utility.Console; import utility.Console.ConsoleType; // general structure for Parser (abstract class) @SuppressWarnings("deprecation") public abstract class ParserTools { public enum ParserType { FOADAParser }; public static ParserType selectAccordingToInputFile(String filename) throws FOADAException { int strLength = filename.length(); if(strLength >= 6 && filename.substring(strLength - 6, strLength).equals(".foada")) { Console.printInfo(ConsoleType.FOADA, "Type of the input file is < " + Console.YELLOW_BRIGHT + "*.foada" + Console.RESET + " >."); return ParserType.FOADAParser; } else { throw new InputFileUnsupportedException(filename); } } public static Automaton buildAutomatonFromFile(String filename, ParserType parserType) throws FOADAException { try { InputStream istream = new FileInputStream(filename); //System.out.println(istream); Console.printInfo(ConsoleType.ANTLR4, "Parsing and checking the syntax in the input..."); Lexer lexer = null; Parser parser = null; CommonTokenStream tokens = null; Automaton result = null; switch(parserType) { case FOADAParser: lexer = new FOADALexerANTLR4(new ANTLRInputStream(istream)); lexer.removeErrorListeners(); lexer.addErrorListener(utility.ErrorListenerWithExceptions.listener); tokens = new CommonTokenStream(lexer); parser = new FOADAParserANTLR4(tokens); parser.removeErrorListeners(); parser.addErrorListener(utility.ErrorListenerWithExceptions.listener); istream.close(); result = ((FOADAParserANTLR4)parser).automaton().jData; break; default: lexer = null; parser = null; break; } Console.printInfo(ConsoleType.ANTLR4, "Syntax checking succeeded..."); return result; } catch(ParseCancellationException e) { throw new ANTLR4ParseCancellationException(e); } catch(FileNotFoundException e) { throw new InputFileNotFoundException(filename); } catch(IOException e) { throw new JavaIOException(e); } } }
3,730
33.546296
132
java
FOADA
FOADA-master/src/parser/FOADA/FOADAParserFunctions.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.FOADA; import java.util.List; import exception.FOADAException; import structure.Automaton; import structure.FOADAExpression; import structure.FOADATransition; public abstract class FOADAParserFunctions { public static void addPredicate(Automaton automaton, String nameOfPredicate) { String newName = "q" + automaton.namesOfPredicates.size() + "c"; automaton.renameMap.put(nameOfPredicate, newName); automaton.namesOfPredicates.add(newName); } public static void addEvent(Automaton automaton, String nameOfEvent) { String newName = "e" + automaton.events.size() + "c"; automaton.renameMap.put(nameOfEvent, newName); automaton.events.add(newName); } public static void setInitial(Automaton automaton, FOADAExpression initial) { for(String original : automaton.renameMap.keySet()) { initial.substitute(original, automaton.renameMap.get(original)); } automaton.initial = initial; } public static void addFinal(Automaton automaton, String nameOfPredicate) { automaton.namesOfFinalStates.add(automaton.renameMap.get(nameOfPredicate)); } public static void addTransition(Automaton automaton, String nameOfPredicate, List<String> argumentsNames, List<FOADAExpression.ExpressionType> argumentsTypes, String event, List<String> inputVarNames, List<FOADAExpression.ExpressionType> inputVarTypes, FOADAExpression post) throws FOADAException { post.finishTypes(automaton, argumentsNames, argumentsTypes, inputVarNames, inputVarTypes); for(int i = 0; i < inputVarNames.size(); i++) { String original = inputVarNames.get(i); if(automaton.renameMap.containsKey(original)) { inputVarNames.set(i, automaton.renameMap.get(original)); } else { String newName = "v" + automaton.nbOfVariables + "c"; automaton.renameMap.put(original, newName); automaton.nbOfVariables = automaton.nbOfVariables + 1; inputVarNames.set(i, newName); } } for(String original : automaton.renameMap.keySet()) { post.substitute(original, automaton.renameMap.get(original)); } int nbRenamedArguments = 0; for(int i = 0; i < argumentsNames.size(); i++) { String original = argumentsNames.get(i); String newName = "a" + nbRenamedArguments + "c"; post.substitute(original, newName); nbRenamedArguments++; argumentsNames.set(i, newName); } FOADATransition transition = new FOADATransition(automaton.renameMap.get(nameOfPredicate), argumentsNames, argumentsTypes, automaton.renameMap.get(event), inputVarNames, inputVarTypes, post); automaton.transitions.put(automaton.renameMap.get(nameOfPredicate) + "+" + automaton.renameMap.get(event), transition); } }
3,542
34.43
193
java
FOADA
FOADA-master/src/parser/FOADA/ANTLR4/FOADALexerANTLR4.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.FOADA.ANTLR4; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class FOADALexerANTLR4 extends Lexer { static { RuntimeMetaData.checkVersion("4.7.1", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int PRED=1, EVENT=2, INITIAL=3, FINAL=4, TRANS=5, TRUE=6, FALSE=7, NOT=8, AND=9, OR=10, DISTINCT=11, INT=12, BOOL=13, ITE=14, ID=15, INTEGER=16, LP=17, RP=18, PLUS=19, MINUS=20, TIMES=21, SLASH=22, GT=23, LT=24, GEQ=25, LEQ=26, EQUALS=27, WS=28, COMMENT=29; public static String[] channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }; public static String[] modeNames = { "DEFAULT_MODE" }; public static final String[] ruleNames = { "PRED", "EVENT", "INITIAL", "FINAL", "TRANS", "TRUE", "FALSE", "NOT", "AND", "OR", "DISTINCT", "INT", "BOOL", "ITE", "LETTER", "DIGIT", "ID", "INTEGER", "LP", "RP", "PLUS", "MINUS", "TIMES", "SLASH", "GT", "LT", "GEQ", "LEQ", "EQUALS", "WS", "COMMENT" }; private static final String[] _LITERAL_NAMES = { null, "'pred'", "'event'", "'initial'", "'final'", "'trans'", "'true'", "'false'", "'not'", "'and'", "'or'", "'distinct'", "'Int'", "'Bool'", "'ite'", null, null, "'('", "')'", "'+'", "'-'", "'*'", "'/'", "'>'", "'<'", "'>='", "'<='", "'='" }; private static final String[] _SYMBOLIC_NAMES = { null, "PRED", "EVENT", "INITIAL", "FINAL", "TRANS", "TRUE", "FALSE", "NOT", "AND", "OR", "DISTINCT", "INT", "BOOL", "ITE", "ID", "INTEGER", "LP", "RP", "PLUS", "MINUS", "TIMES", "SLASH", "GT", "LT", "GEQ", "LEQ", "EQUALS", "WS", "COMMENT" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public FOADALexerANTLR4(CharStream input) { super(input); _interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } @Override public String getGrammarFileName() { return "FOADALexerANTLR4.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } @Override public void action(RuleContext _localctx, int ruleIndex, int actionIndex) { switch (ruleIndex) { case 29: WS_action((RuleContext)_localctx, actionIndex); break; case 30: COMMENT_action((RuleContext)_localctx, actionIndex); break; } } private void WS_action(RuleContext _localctx, int actionIndex) { switch (actionIndex) { case 0: skip(); break; } } private void COMMENT_action(RuleContext _localctx, int actionIndex) { switch (actionIndex) { case 1: skip(); break; } } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\37\u00ca\b\1\4\2"+ "\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4"+ "\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22"+ "\t\22\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31"+ "\t\31\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\4 \t"+ " \3\2\3\2\3\2\3\2\3\2\3\3\3\3\3\3\3\3\3\3\3\3\3\4\3\4\3\4\3\4\3\4\3\4"+ "\3\4\3\4\3\5\3\5\3\5\3\5\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3\7\3"+ "\7\3\7\3\b\3\b\3\b\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\13\3"+ "\13\3\13\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\r\3\r\3\r\3\r\3\16\3\16"+ "\3\16\3\16\3\16\3\17\3\17\3\17\3\17\3\20\3\20\3\21\3\21\3\22\3\22\5\22"+ "\u0093\n\22\3\22\3\22\3\22\7\22\u0098\n\22\f\22\16\22\u009b\13\22\3\23"+ "\3\23\3\23\7\23\u00a0\n\23\f\23\16\23\u00a3\13\23\5\23\u00a5\n\23\3\24"+ "\3\24\3\25\3\25\3\26\3\26\3\27\3\27\3\30\3\30\3\31\3\31\3\32\3\32\3\33"+ "\3\33\3\34\3\34\3\34\3\35\3\35\3\35\3\36\3\36\3\37\3\37\3\37\3 \3 \7 "+ "\u00c4\n \f \16 \u00c7\13 \3 \3 \2\2!\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21"+ "\n\23\13\25\f\27\r\31\16\33\17\35\20\37\2!\2#\21%\22\'\23)\24+\25-\26"+ "/\27\61\30\63\31\65\32\67\339\34;\35=\36?\37\3\2\6\4\2C\\c|\4\2&&aa\5"+ "\2\13\f\17\17\"\"\3\2\f\f\2\u00ce\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2"+ "\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3"+ "\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2"+ "\2\2#\3\2\2\2\2%\3\2\2\2\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2"+ "\2/\3\2\2\2\2\61\3\2\2\2\2\63\3\2\2\2\2\65\3\2\2\2\2\67\3\2\2\2\29\3\2"+ "\2\2\2;\3\2\2\2\2=\3\2\2\2\2?\3\2\2\2\3A\3\2\2\2\5F\3\2\2\2\7L\3\2\2\2"+ "\tT\3\2\2\2\13Z\3\2\2\2\r`\3\2\2\2\17e\3\2\2\2\21k\3\2\2\2\23o\3\2\2\2"+ "\25s\3\2\2\2\27v\3\2\2\2\31\177\3\2\2\2\33\u0083\3\2\2\2\35\u0088\3\2"+ "\2\2\37\u008c\3\2\2\2!\u008e\3\2\2\2#\u0092\3\2\2\2%\u00a4\3\2\2\2\'\u00a6"+ "\3\2\2\2)\u00a8\3\2\2\2+\u00aa\3\2\2\2-\u00ac\3\2\2\2/\u00ae\3\2\2\2\61"+ "\u00b0\3\2\2\2\63\u00b2\3\2\2\2\65\u00b4\3\2\2\2\67\u00b6\3\2\2\29\u00b9"+ "\3\2\2\2;\u00bc\3\2\2\2=\u00be\3\2\2\2?\u00c1\3\2\2\2AB\7r\2\2BC\7t\2"+ "\2CD\7g\2\2DE\7f\2\2E\4\3\2\2\2FG\7g\2\2GH\7x\2\2HI\7g\2\2IJ\7p\2\2JK"+ "\7v\2\2K\6\3\2\2\2LM\7k\2\2MN\7p\2\2NO\7k\2\2OP\7v\2\2PQ\7k\2\2QR\7c\2"+ "\2RS\7n\2\2S\b\3\2\2\2TU\7h\2\2UV\7k\2\2VW\7p\2\2WX\7c\2\2XY\7n\2\2Y\n"+ "\3\2\2\2Z[\7v\2\2[\\\7t\2\2\\]\7c\2\2]^\7p\2\2^_\7u\2\2_\f\3\2\2\2`a\7"+ "v\2\2ab\7t\2\2bc\7w\2\2cd\7g\2\2d\16\3\2\2\2ef\7h\2\2fg\7c\2\2gh\7n\2"+ "\2hi\7u\2\2ij\7g\2\2j\20\3\2\2\2kl\7p\2\2lm\7q\2\2mn\7v\2\2n\22\3\2\2"+ "\2op\7c\2\2pq\7p\2\2qr\7f\2\2r\24\3\2\2\2st\7q\2\2tu\7t\2\2u\26\3\2\2"+ "\2vw\7f\2\2wx\7k\2\2xy\7u\2\2yz\7v\2\2z{\7k\2\2{|\7p\2\2|}\7e\2\2}~\7"+ "v\2\2~\30\3\2\2\2\177\u0080\7K\2\2\u0080\u0081\7p\2\2\u0081\u0082\7v\2"+ "\2\u0082\32\3\2\2\2\u0083\u0084\7D\2\2\u0084\u0085\7q\2\2\u0085\u0086"+ "\7q\2\2\u0086\u0087\7n\2\2\u0087\34\3\2\2\2\u0088\u0089\7k\2\2\u0089\u008a"+ "\7v\2\2\u008a\u008b\7g\2\2\u008b\36\3\2\2\2\u008c\u008d\t\2\2\2\u008d"+ " \3\2\2\2\u008e\u008f\4\62;\2\u008f\"\3\2\2\2\u0090\u0093\5\37\20\2\u0091"+ "\u0093\t\3\2\2\u0092\u0090\3\2\2\2\u0092\u0091\3\2\2\2\u0093\u0099\3\2"+ "\2\2\u0094\u0098\5\37\20\2\u0095\u0098\5!\21\2\u0096\u0098\t\3\2\2\u0097"+ "\u0094\3\2\2\2\u0097\u0095\3\2\2\2\u0097\u0096\3\2\2\2\u0098\u009b\3\2"+ "\2\2\u0099\u0097\3\2\2\2\u0099\u009a\3\2\2\2\u009a$\3\2\2\2\u009b\u0099"+ "\3\2\2\2\u009c\u00a5\7\62\2\2\u009d\u00a1\4\63;\2\u009e\u00a0\5!\21\2"+ "\u009f\u009e\3\2\2\2\u00a0\u00a3\3\2\2\2\u00a1\u009f\3\2\2\2\u00a1\u00a2"+ "\3\2\2\2\u00a2\u00a5\3\2\2\2\u00a3\u00a1\3\2\2\2\u00a4\u009c\3\2\2\2\u00a4"+ "\u009d\3\2\2\2\u00a5&\3\2\2\2\u00a6\u00a7\7*\2\2\u00a7(\3\2\2\2\u00a8"+ "\u00a9\7+\2\2\u00a9*\3\2\2\2\u00aa\u00ab\7-\2\2\u00ab,\3\2\2\2\u00ac\u00ad"+ "\7/\2\2\u00ad.\3\2\2\2\u00ae\u00af\7,\2\2\u00af\60\3\2\2\2\u00b0\u00b1"+ "\7\61\2\2\u00b1\62\3\2\2\2\u00b2\u00b3\7@\2\2\u00b3\64\3\2\2\2\u00b4\u00b5"+ "\7>\2\2\u00b5\66\3\2\2\2\u00b6\u00b7\7@\2\2\u00b7\u00b8\7?\2\2\u00b88"+ "\3\2\2\2\u00b9\u00ba\7>\2\2\u00ba\u00bb\7?\2\2\u00bb:\3\2\2\2\u00bc\u00bd"+ "\7?\2\2\u00bd<\3\2\2\2\u00be\u00bf\t\4\2\2\u00bf\u00c0\b\37\2\2\u00c0"+ ">\3\2\2\2\u00c1\u00c5\7=\2\2\u00c2\u00c4\n\5\2\2\u00c3\u00c2\3\2\2\2\u00c4"+ "\u00c7\3\2\2\2\u00c5\u00c3\3\2\2\2\u00c5\u00c6\3\2\2\2\u00c6\u00c8\3\2"+ "\2\2\u00c7\u00c5\3\2\2\2\u00c8\u00c9\b \3\2\u00c9@\3\2\2\2\t\2\u0092\u0097"+ "\u0099\u00a1\u00a4\u00c5\4\3\37\2\3 \3"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
9,508
41.262222
97
java
FOADA
FOADA-master/src/parser/FOADA/ANTLR4/FOADAParserANTLR4.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.FOADA.ANTLR4; import exception.FOADAException; import structure.Automaton; import structure.FOADAExpression; import structure.FOADAExpression.ExpressionCategory; import structure.FOADAExpression.ExpressionType; import java.util.List; import java.util.Iterator; import java.util.ArrayList; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.misc.*; import org.antlr.v4.runtime.tree.*; import java.util.List; import java.util.Iterator; import java.util.ArrayList; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class FOADAParserANTLR4 extends Parser { static { RuntimeMetaData.checkVersion("4.7.1", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int PRED=1, EVENT=2, INITIAL=3, FINAL=4, TRANS=5, TRUE=6, FALSE=7, NOT=8, AND=9, OR=10, DISTINCT=11, INT=12, BOOL=13, ITE=14, ID=15, INTEGER=16, LP=17, RP=18, PLUS=19, MINUS=20, TIMES=21, SLASH=22, GT=23, LT=24, GEQ=25, LEQ=26, EQUALS=27, WS=28, COMMENT=29; public static final int RULE_automaton = 0, RULE_type = 1, RULE_expression = 2; public static final String[] ruleNames = { "automaton", "type", "expression" }; private static final String[] _LITERAL_NAMES = { null, "'pred'", "'event'", "'initial'", "'final'", "'trans'", "'true'", "'false'", "'not'", "'and'", "'or'", "'distinct'", "'Int'", "'Bool'", "'ite'", null, null, "'('", "')'", "'+'", "'-'", "'*'", "'/'", "'>'", "'<'", "'>='", "'<='", "'='" }; private static final String[] _SYMBOLIC_NAMES = { null, "PRED", "EVENT", "INITIAL", "FINAL", "TRANS", "TRUE", "FALSE", "NOT", "AND", "OR", "DISTINCT", "INT", "BOOL", "ITE", "ID", "INTEGER", "LP", "RP", "PLUS", "MINUS", "TIMES", "SLASH", "GT", "LT", "GEQ", "LEQ", "EQUALS", "WS", "COMMENT" }; public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } @Override public String getGrammarFileName() { return "FOADAParserANTLR4.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public ATN getATN() { return _ATN; } public FOADAParserANTLR4(TokenStream input) { super(input); _interp = new ParserATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } public static class AutomatonContext extends ParserRuleContext { public Automaton jData; public Token nameOfPredicate; public Token nameOfEvent; public ExpressionContext init; public Token nameOfFinal; public Token argumentName; public TypeContext argumentType; public Token event; public Token inputVarName; public TypeContext inputVarType; public ExpressionContext post; public List<TerminalNode> LP() { return getTokens(FOADAParserANTLR4.LP); } public TerminalNode LP(int i) { return getToken(FOADAParserANTLR4.LP, i); } public TerminalNode PRED() { return getToken(FOADAParserANTLR4.PRED, 0); } public List<TerminalNode> RP() { return getTokens(FOADAParserANTLR4.RP); } public TerminalNode RP(int i) { return getToken(FOADAParserANTLR4.RP, i); } public TerminalNode EVENT() { return getToken(FOADAParserANTLR4.EVENT, 0); } public TerminalNode INITIAL() { return getToken(FOADAParserANTLR4.INITIAL, 0); } public TerminalNode FINAL() { return getToken(FOADAParserANTLR4.FINAL, 0); } public List<ExpressionContext> expression() { return getRuleContexts(ExpressionContext.class); } public ExpressionContext expression(int i) { return getRuleContext(ExpressionContext.class,i); } public List<TerminalNode> TRANS() { return getTokens(FOADAParserANTLR4.TRANS); } public TerminalNode TRANS(int i) { return getToken(FOADAParserANTLR4.TRANS, i); } public List<TerminalNode> ID() { return getTokens(FOADAParserANTLR4.ID); } public TerminalNode ID(int i) { return getToken(FOADAParserANTLR4.ID, i); } public List<TypeContext> type() { return getRuleContexts(TypeContext.class); } public TypeContext type(int i) { return getRuleContext(TypeContext.class,i); } public AutomatonContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_automaton; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).enterAutomaton(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).exitAutomaton(this); } } public final AutomatonContext automaton() throws RecognitionException, FOADAException { AutomatonContext _localctx = new AutomatonContext(_ctx, getState()); enterRule(_localctx, 0, RULE_automaton); int _la; try { enterOuterAlt(_localctx, 1); { ((AutomatonContext)_localctx).jData = new Automaton(); setState(7); match(LP); setState(8); match(PRED); setState(9); match(LP); setState(14); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(10); ((AutomatonContext)_localctx).nameOfPredicate = match(ID); parser.FOADA.FOADAParserFunctions.addPredicate(_localctx.jData, (((AutomatonContext)_localctx).nameOfPredicate!=null?((AutomatonContext)_localctx).nameOfPredicate.getText():null)); } } setState(16); _errHandler.sync(this); _la = _input.LA(1); } setState(17); match(RP); setState(18); match(RP); setState(19); match(LP); setState(20); match(EVENT); setState(21); match(LP); setState(26); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(22); ((AutomatonContext)_localctx).nameOfEvent = match(ID); parser.FOADA.FOADAParserFunctions.addEvent(_localctx.jData, (((AutomatonContext)_localctx).nameOfEvent!=null?((AutomatonContext)_localctx).nameOfEvent.getText():null)); } } setState(28); _errHandler.sync(this); _la = _input.LA(1); } setState(29); match(RP); setState(30); match(RP); setState(31); match(LP); setState(32); match(INITIAL); setState(33); ((AutomatonContext)_localctx).init = expression(); setState(34); match(RP); parser.FOADA.FOADAParserFunctions.setInitial(_localctx.jData, ((AutomatonContext)_localctx).init.jData); setState(36); match(LP); setState(37); match(FINAL); setState(38); match(LP); setState(43); _errHandler.sync(this); _la = _input.LA(1); while (_la==ID) { { { setState(39); ((AutomatonContext)_localctx).nameOfFinal = match(ID); parser.FOADA.FOADAParserFunctions.addFinal(_localctx.jData, (((AutomatonContext)_localctx).nameOfFinal!=null?((AutomatonContext)_localctx).nameOfFinal.getText():null)); } } setState(45); _errHandler.sync(this); _la = _input.LA(1); } setState(46); match(RP); setState(47); match(RP); setState(90); _errHandler.sync(this); _la = _input.LA(1); while (_la==LP) { { { setState(48); match(LP); setState(49); match(TRANS); setState(50); match(LP); setState(51); ((AutomatonContext)_localctx).nameOfPredicate = match(ID); setState(52); match(LP); List<String> argumentsNames = new ArrayList<String>(); List<FOADAExpression.ExpressionType> argumentsTypes = new ArrayList<FOADAExpression.ExpressionType>(); setState(62); _errHandler.sync(this); _la = _input.LA(1); while (_la==LP) { { { setState(54); match(LP); setState(55); ((AutomatonContext)_localctx).argumentName = match(ID); setState(56); ((AutomatonContext)_localctx).argumentType = type(); setState(57); match(RP); argumentsNames.add((((AutomatonContext)_localctx).argumentName!=null?((AutomatonContext)_localctx).argumentName.getText():null)); argumentsTypes.add(((AutomatonContext)_localctx).argumentType.jData); } } setState(64); _errHandler.sync(this); _la = _input.LA(1); } setState(65); match(RP); setState(66); match(RP); setState(67); match(LP); setState(68); ((AutomatonContext)_localctx).event = match(ID); setState(69); match(LP); List<String> inputVarNames = new ArrayList<String>(); List<FOADAExpression.ExpressionType> inputVarTypes = new ArrayList<FOADAExpression.ExpressionType>(); setState(79); _errHandler.sync(this); _la = _input.LA(1); while (_la==LP) { { { setState(71); match(LP); setState(72); ((AutomatonContext)_localctx).inputVarName = match(ID); setState(73); ((AutomatonContext)_localctx).inputVarType = type(); setState(74); match(RP); inputVarNames.add((((AutomatonContext)_localctx).inputVarName!=null?((AutomatonContext)_localctx).inputVarName.getText():null)); inputVarTypes.add(((AutomatonContext)_localctx).inputVarType.jData); } } setState(81); _errHandler.sync(this); _la = _input.LA(1); } setState(82); match(RP); setState(83); match(RP); setState(84); ((AutomatonContext)_localctx).post = expression(); parser.FOADA.FOADAParserFunctions.addTransition(_localctx.jData, (((AutomatonContext)_localctx).nameOfPredicate!=null?((AutomatonContext)_localctx).nameOfPredicate.getText():null), argumentsNames, argumentsTypes, (((AutomatonContext)_localctx).event!=null?((AutomatonContext)_localctx).event.getText():null), inputVarNames, inputVarTypes, ((AutomatonContext)_localctx).post.jData); setState(86); match(RP); } } setState(92); _errHandler.sync(this); _la = _input.LA(1); } } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class TypeContext extends ParserRuleContext { public FOADAExpression.ExpressionType jData; public TerminalNode INT() { return getToken(FOADAParserANTLR4.INT, 0); } public TerminalNode BOOL() { return getToken(FOADAParserANTLR4.BOOL, 0); } public TypeContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_type; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).enterType(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).exitType(this); } } public final TypeContext type() throws RecognitionException { TypeContext _localctx = new TypeContext(_ctx, getState()); enterRule(_localctx, 2, RULE_type); try { setState(97); _errHandler.sync(this); switch (_input.LA(1)) { case INT: enterOuterAlt(_localctx, 1); { setState(93); match(INT); ((TypeContext)_localctx).jData = FOADAExpression.ExpressionType.Integer; } break; case BOOL: enterOuterAlt(_localctx, 2); { setState(95); match(BOOL); ((TypeContext)_localctx).jData = FOADAExpression.ExpressionType.Boolean; } break; default: throw new NoViableAltException(this); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static class ExpressionContext extends ParserRuleContext { public FOADAExpression jData; public ExpressionContext c; public ExpressionContext e1; public ExpressionContext e2; public Token INTEGER; public ExpressionContext e; public Token i; public TerminalNode LP() { return getToken(FOADAParserANTLR4.LP, 0); } public TerminalNode ITE() { return getToken(FOADAParserANTLR4.ITE, 0); } public TerminalNode RP() { return getToken(FOADAParserANTLR4.RP, 0); } public List<ExpressionContext> expression() { return getRuleContexts(ExpressionContext.class); } public ExpressionContext expression(int i) { return getRuleContext(ExpressionContext.class,i); } public TerminalNode MINUS() { return getToken(FOADAParserANTLR4.MINUS, 0); } public TerminalNode INTEGER() { return getToken(FOADAParserANTLR4.INTEGER, 0); } public TerminalNode TRUE() { return getToken(FOADAParserANTLR4.TRUE, 0); } public TerminalNode FALSE() { return getToken(FOADAParserANTLR4.FALSE, 0); } public TerminalNode NOT() { return getToken(FOADAParserANTLR4.NOT, 0); } public TerminalNode AND() { return getToken(FOADAParserANTLR4.AND, 0); } public TerminalNode OR() { return getToken(FOADAParserANTLR4.OR, 0); } public TerminalNode GT() { return getToken(FOADAParserANTLR4.GT, 0); } public TerminalNode LT() { return getToken(FOADAParserANTLR4.LT, 0); } public TerminalNode GEQ() { return getToken(FOADAParserANTLR4.GEQ, 0); } public TerminalNode LEQ() { return getToken(FOADAParserANTLR4.LEQ, 0); } public TerminalNode EQUALS() { return getToken(FOADAParserANTLR4.EQUALS, 0); } public TerminalNode DISTINCT() { return getToken(FOADAParserANTLR4.DISTINCT, 0); } public TerminalNode ID() { return getToken(FOADAParserANTLR4.ID, 0); } public TerminalNode PLUS() { return getToken(FOADAParserANTLR4.PLUS, 0); } public TerminalNode TIMES() { return getToken(FOADAParserANTLR4.TIMES, 0); } public TerminalNode SLASH() { return getToken(FOADAParserANTLR4.SLASH, 0); } public ExpressionContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_expression; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).enterExpression(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof FOADAParserANTLR4Listener ) ((FOADAParserANTLR4Listener)listener).exitExpression(this); } } public final ExpressionContext expression() throws RecognitionException { ExpressionContext _localctx = new ExpressionContext(_ctx, getState()); enterRule(_localctx, 4, RULE_expression); int _la; try { setState(239); _errHandler.sync(this); switch ( getInterpreter().adaptivePredict(_input,11,_ctx) ) { case 1: enterOuterAlt(_localctx, 1); { setState(99); match(LP); setState(100); match(ITE); setState(101); ((ExpressionContext)_localctx).c = expression(); setState(102); ((ExpressionContext)_localctx).e1 = expression(); setState(103); ((ExpressionContext)_localctx).e2 = expression(); setState(104); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(null, ExpressionCategory.ITE, ((ExpressionContext)_localctx).c.jData, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 2: enterOuterAlt(_localctx, 2); { setState(107); match(MINUS); setState(108); ((ExpressionContext)_localctx).INTEGER = match(INTEGER); ((ExpressionContext)_localctx).jData = new FOADAExpression(Integer.parseInt("-" + (((ExpressionContext)_localctx).INTEGER!=null?((ExpressionContext)_localctx).INTEGER.getText():null))); } break; case 3: enterOuterAlt(_localctx, 3); { setState(110); ((ExpressionContext)_localctx).INTEGER = match(INTEGER); ((ExpressionContext)_localctx).jData = new FOADAExpression(Integer.parseInt((((ExpressionContext)_localctx).INTEGER!=null?((ExpressionContext)_localctx).INTEGER.getText():null))); } break; case 4: enterOuterAlt(_localctx, 4); { setState(112); match(TRUE); ((ExpressionContext)_localctx).jData = new FOADAExpression(true); } break; case 5: enterOuterAlt(_localctx, 5); { setState(114); match(FALSE); ((ExpressionContext)_localctx).jData = new FOADAExpression(false); } break; case 6: enterOuterAlt(_localctx, 6); { setState(116); match(LP); setState(117); match(NOT); setState(118); ((ExpressionContext)_localctx).e = expression(); setState(119); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Not, ((ExpressionContext)_localctx).e.jData); } break; case 7: enterOuterAlt(_localctx, 7); { setState(122); match(LP); setState(123); match(AND); setState(124); ((ExpressionContext)_localctx).e1 = expression(); ((ExpressionContext)_localctx).jData = ((ExpressionContext)_localctx).e1.jData; setState(129); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(126); ((ExpressionContext)_localctx).e2 = expression(); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.And, _localctx.jData, ((ExpressionContext)_localctx).e2.jData); } } setState(131); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TRUE) | (1L << FALSE) | (1L << ID) | (1L << INTEGER) | (1L << LP) | (1L << MINUS))) != 0) ); setState(133); match(RP); } break; case 8: enterOuterAlt(_localctx, 8); { setState(135); match(LP); setState(136); match(OR); setState(137); ((ExpressionContext)_localctx).e1 = expression(); ((ExpressionContext)_localctx).jData = ((ExpressionContext)_localctx).e1.jData; setState(142); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(139); ((ExpressionContext)_localctx).e2 = expression(); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Or, _localctx.jData, ((ExpressionContext)_localctx).e2.jData); } } setState(144); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TRUE) | (1L << FALSE) | (1L << ID) | (1L << INTEGER) | (1L << LP) | (1L << MINUS))) != 0) ); setState(146); match(RP); } break; case 9: enterOuterAlt(_localctx, 9); { setState(148); match(LP); setState(149); match(GT); setState(150); ((ExpressionContext)_localctx).e1 = expression(); setState(151); ((ExpressionContext)_localctx).e2 = expression(); setState(152); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.GT, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 10: enterOuterAlt(_localctx, 10); { setState(155); match(LP); setState(156); match(LT); setState(157); ((ExpressionContext)_localctx).e1 = expression(); setState(158); ((ExpressionContext)_localctx).e2 = expression(); setState(159); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.LT, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 11: enterOuterAlt(_localctx, 11); { setState(162); match(LP); setState(163); match(GEQ); setState(164); ((ExpressionContext)_localctx).e1 = expression(); setState(165); ((ExpressionContext)_localctx).e2 = expression(); setState(166); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.GEQ, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 12: enterOuterAlt(_localctx, 12); { setState(169); match(LP); setState(170); match(LEQ); setState(171); ((ExpressionContext)_localctx).e1 = expression(); setState(172); ((ExpressionContext)_localctx).e2 = expression(); setState(173); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.LEQ, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 13: enterOuterAlt(_localctx, 13); { setState(176); match(LP); setState(177); match(EQUALS); setState(178); ((ExpressionContext)_localctx).e1 = expression(); setState(179); ((ExpressionContext)_localctx).e2 = expression(); setState(180); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Equals, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 14: enterOuterAlt(_localctx, 14); { setState(183); match(LP); setState(184); match(DISTINCT); setState(185); ((ExpressionContext)_localctx).e1 = expression(); setState(186); ((ExpressionContext)_localctx).e2 = expression(); setState(187); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Distinct, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 15: enterOuterAlt(_localctx, 15); { setState(190); ((ExpressionContext)_localctx).i = match(ID); ((ExpressionContext)_localctx).jData = new FOADAExpression((((ExpressionContext)_localctx).i!=null?((ExpressionContext)_localctx).i.getText():null)); } break; case 16: enterOuterAlt(_localctx, 16); { setState(192); match(LP); setState(193); match(PLUS); setState(194); ((ExpressionContext)_localctx).e1 = expression(); ((ExpressionContext)_localctx).jData = ((ExpressionContext)_localctx).e1.jData; setState(199); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(196); ((ExpressionContext)_localctx).e2 = expression(); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Plus, _localctx.jData, ((ExpressionContext)_localctx).e2.jData); } } setState(201); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TRUE) | (1L << FALSE) | (1L << ID) | (1L << INTEGER) | (1L << LP) | (1L << MINUS))) != 0) ); setState(203); match(RP); } break; case 17: enterOuterAlt(_localctx, 17); { setState(205); match(LP); setState(206); match(TIMES); setState(207); ((ExpressionContext)_localctx).e1 = expression(); setState(208); ((ExpressionContext)_localctx).e2 = expression(); setState(209); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Times, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 18: enterOuterAlt(_localctx, 18); { setState(212); match(LP); setState(213); match(MINUS); setState(214); ((ExpressionContext)_localctx).e1 = expression(); setState(215); ((ExpressionContext)_localctx).e2 = expression(); setState(216); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Minus, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 19: enterOuterAlt(_localctx, 19); { setState(219); match(LP); setState(220); match(SLASH); setState(221); ((ExpressionContext)_localctx).e1 = expression(); setState(222); ((ExpressionContext)_localctx).e2 = expression(); setState(223); match(RP); ((ExpressionContext)_localctx).jData = new FOADAExpression(ExpressionType.Integer, ExpressionCategory.Slash, ((ExpressionContext)_localctx).e1.jData, ((ExpressionContext)_localctx).e2.jData); } break; case 20: enterOuterAlt(_localctx, 20); { setState(226); match(LP); setState(227); ((ExpressionContext)_localctx).i = match(ID); List<FOADAExpression> arguments = new ArrayList<FOADAExpression>(); setState(232); _errHandler.sync(this); _la = _input.LA(1); do { { { setState(229); ((ExpressionContext)_localctx).e = expression(); arguments.add(((ExpressionContext)_localctx).e.jData); } } setState(234); _errHandler.sync(this); _la = _input.LA(1); } while ( (((_la) & ~0x3f) == 0 && ((1L << _la) & ((1L << TRUE) | (1L << FALSE) | (1L << ID) | (1L << INTEGER) | (1L << LP) | (1L << MINUS))) != 0) ); ((ExpressionContext)_localctx).jData = new FOADAExpression((((ExpressionContext)_localctx).i!=null?((ExpressionContext)_localctx).i.getText():null), ExpressionType.Boolean, arguments); setState(237); match(RP); } break; } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\3\37\u00f4\4\2\t\2"+ "\4\3\t\3\4\4\t\4\3\2\3\2\3\2\3\2\3\2\3\2\7\2\17\n\2\f\2\16\2\22\13\2\3"+ "\2\3\2\3\2\3\2\3\2\3\2\3\2\7\2\33\n\2\f\2\16\2\36\13\2\3\2\3\2\3\2\3\2"+ "\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\7\2,\n\2\f\2\16\2/\13\2\3\2\3\2\3\2\3"+ "\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\7\2?\n\2\f\2\16\2B\13\2\3\2"+ "\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\3\2\7\2P\n\2\f\2\16\2S\13\2\3"+ "\2\3\2\3\2\3\2\3\2\3\2\7\2[\n\2\f\2\16\2^\13\2\3\3\3\3\3\3\3\3\5\3d\n"+ "\3\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4"+ "\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\6\4\u0084\n\4\r\4"+ "\16\4\u0085\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\6\4\u0091\n\4\r\4\16\4"+ "\u0092\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4"+ "\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3"+ "\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4"+ "\3\4\3\4\6\4\u00ca\n\4\r\4\16\4\u00cb\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4"+ "\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3\4\3"+ "\4\3\4\3\4\3\4\6\4\u00eb\n\4\r\4\16\4\u00ec\3\4\3\4\3\4\5\4\u00f2\n\4"+ "\3\4\2\2\5\2\4\6\2\2\2\u010e\2\b\3\2\2\2\4c\3\2\2\2\6\u00f1\3\2\2\2\b"+ "\t\b\2\1\2\t\n\7\23\2\2\n\13\7\3\2\2\13\20\7\23\2\2\f\r\7\21\2\2\r\17"+ "\b\2\1\2\16\f\3\2\2\2\17\22\3\2\2\2\20\16\3\2\2\2\20\21\3\2\2\2\21\23"+ "\3\2\2\2\22\20\3\2\2\2\23\24\7\24\2\2\24\25\7\24\2\2\25\26\7\23\2\2\26"+ "\27\7\4\2\2\27\34\7\23\2\2\30\31\7\21\2\2\31\33\b\2\1\2\32\30\3\2\2\2"+ "\33\36\3\2\2\2\34\32\3\2\2\2\34\35\3\2\2\2\35\37\3\2\2\2\36\34\3\2\2\2"+ "\37 \7\24\2\2 !\7\24\2\2!\"\7\23\2\2\"#\7\5\2\2#$\5\6\4\2$%\7\24\2\2%"+ "&\b\2\1\2&\'\7\23\2\2\'(\7\6\2\2(-\7\23\2\2)*\7\21\2\2*,\b\2\1\2+)\3\2"+ "\2\2,/\3\2\2\2-+\3\2\2\2-.\3\2\2\2.\60\3\2\2\2/-\3\2\2\2\60\61\7\24\2"+ "\2\61\\\7\24\2\2\62\63\7\23\2\2\63\64\7\7\2\2\64\65\7\23\2\2\65\66\7\21"+ "\2\2\66\67\7\23\2\2\67@\b\2\1\289\7\23\2\29:\7\21\2\2:;\5\4\3\2;<\7\24"+ "\2\2<=\b\2\1\2=?\3\2\2\2>8\3\2\2\2?B\3\2\2\2@>\3\2\2\2@A\3\2\2\2AC\3\2"+ "\2\2B@\3\2\2\2CD\7\24\2\2DE\7\24\2\2EF\7\23\2\2FG\7\21\2\2GH\7\23\2\2"+ "HQ\b\2\1\2IJ\7\23\2\2JK\7\21\2\2KL\5\4\3\2LM\7\24\2\2MN\b\2\1\2NP\3\2"+ "\2\2OI\3\2\2\2PS\3\2\2\2QO\3\2\2\2QR\3\2\2\2RT\3\2\2\2SQ\3\2\2\2TU\7\24"+ "\2\2UV\7\24\2\2VW\5\6\4\2WX\b\2\1\2XY\7\24\2\2Y[\3\2\2\2Z\62\3\2\2\2["+ "^\3\2\2\2\\Z\3\2\2\2\\]\3\2\2\2]\3\3\2\2\2^\\\3\2\2\2_`\7\16\2\2`d\b\3"+ "\1\2ab\7\17\2\2bd\b\3\1\2c_\3\2\2\2ca\3\2\2\2d\5\3\2\2\2ef\7\23\2\2fg"+ "\7\20\2\2gh\5\6\4\2hi\5\6\4\2ij\5\6\4\2jk\7\24\2\2kl\b\4\1\2l\u00f2\3"+ "\2\2\2mn\7\26\2\2no\7\22\2\2o\u00f2\b\4\1\2pq\7\22\2\2q\u00f2\b\4\1\2"+ "rs\7\b\2\2s\u00f2\b\4\1\2tu\7\t\2\2u\u00f2\b\4\1\2vw\7\23\2\2wx\7\n\2"+ "\2xy\5\6\4\2yz\7\24\2\2z{\b\4\1\2{\u00f2\3\2\2\2|}\7\23\2\2}~\7\13\2\2"+ "~\177\5\6\4\2\177\u0083\b\4\1\2\u0080\u0081\5\6\4\2\u0081\u0082\b\4\1"+ "\2\u0082\u0084\3\2\2\2\u0083\u0080\3\2\2\2\u0084\u0085\3\2\2\2\u0085\u0083"+ "\3\2\2\2\u0085\u0086\3\2\2\2\u0086\u0087\3\2\2\2\u0087\u0088\7\24\2\2"+ "\u0088\u00f2\3\2\2\2\u0089\u008a\7\23\2\2\u008a\u008b\7\f\2\2\u008b\u008c"+ "\5\6\4\2\u008c\u0090\b\4\1\2\u008d\u008e\5\6\4\2\u008e\u008f\b\4\1\2\u008f"+ "\u0091\3\2\2\2\u0090\u008d\3\2\2\2\u0091\u0092\3\2\2\2\u0092\u0090\3\2"+ "\2\2\u0092\u0093\3\2\2\2\u0093\u0094\3\2\2\2\u0094\u0095\7\24\2\2\u0095"+ "\u00f2\3\2\2\2\u0096\u0097\7\23\2\2\u0097\u0098\7\31\2\2\u0098\u0099\5"+ "\6\4\2\u0099\u009a\5\6\4\2\u009a\u009b\7\24\2\2\u009b\u009c\b\4\1\2\u009c"+ "\u00f2\3\2\2\2\u009d\u009e\7\23\2\2\u009e\u009f\7\32\2\2\u009f\u00a0\5"+ "\6\4\2\u00a0\u00a1\5\6\4\2\u00a1\u00a2\7\24\2\2\u00a2\u00a3\b\4\1\2\u00a3"+ "\u00f2\3\2\2\2\u00a4\u00a5\7\23\2\2\u00a5\u00a6\7\33\2\2\u00a6\u00a7\5"+ "\6\4\2\u00a7\u00a8\5\6\4\2\u00a8\u00a9\7\24\2\2\u00a9\u00aa\b\4\1\2\u00aa"+ "\u00f2\3\2\2\2\u00ab\u00ac\7\23\2\2\u00ac\u00ad\7\34\2\2\u00ad\u00ae\5"+ "\6\4\2\u00ae\u00af\5\6\4\2\u00af\u00b0\7\24\2\2\u00b0\u00b1\b\4\1\2\u00b1"+ "\u00f2\3\2\2\2\u00b2\u00b3\7\23\2\2\u00b3\u00b4\7\35\2\2\u00b4\u00b5\5"+ "\6\4\2\u00b5\u00b6\5\6\4\2\u00b6\u00b7\7\24\2\2\u00b7\u00b8\b\4\1\2\u00b8"+ "\u00f2\3\2\2\2\u00b9\u00ba\7\23\2\2\u00ba\u00bb\7\r\2\2\u00bb\u00bc\5"+ "\6\4\2\u00bc\u00bd\5\6\4\2\u00bd\u00be\7\24\2\2\u00be\u00bf\b\4\1\2\u00bf"+ "\u00f2\3\2\2\2\u00c0\u00c1\7\21\2\2\u00c1\u00f2\b\4\1\2\u00c2\u00c3\7"+ "\23\2\2\u00c3\u00c4\7\25\2\2\u00c4\u00c5\5\6\4\2\u00c5\u00c9\b\4\1\2\u00c6"+ "\u00c7\5\6\4\2\u00c7\u00c8\b\4\1\2\u00c8\u00ca\3\2\2\2\u00c9\u00c6\3\2"+ "\2\2\u00ca\u00cb\3\2\2\2\u00cb\u00c9\3\2\2\2\u00cb\u00cc\3\2\2\2\u00cc"+ "\u00cd\3\2\2\2\u00cd\u00ce\7\24\2\2\u00ce\u00f2\3\2\2\2\u00cf\u00d0\7"+ "\23\2\2\u00d0\u00d1\7\27\2\2\u00d1\u00d2\5\6\4\2\u00d2\u00d3\5\6\4\2\u00d3"+ "\u00d4\7\24\2\2\u00d4\u00d5\b\4\1\2\u00d5\u00f2\3\2\2\2\u00d6\u00d7\7"+ "\23\2\2\u00d7\u00d8\7\26\2\2\u00d8\u00d9\5\6\4\2\u00d9\u00da\5\6\4\2\u00da"+ "\u00db\7\24\2\2\u00db\u00dc\b\4\1\2\u00dc\u00f2\3\2\2\2\u00dd\u00de\7"+ "\23\2\2\u00de\u00df\7\30\2\2\u00df\u00e0\5\6\4\2\u00e0\u00e1\5\6\4\2\u00e1"+ "\u00e2\7\24\2\2\u00e2\u00e3\b\4\1\2\u00e3\u00f2\3\2\2\2\u00e4\u00e5\7"+ "\23\2\2\u00e5\u00e6\7\21\2\2\u00e6\u00ea\b\4\1\2\u00e7\u00e8\5\6\4\2\u00e8"+ "\u00e9\b\4\1\2\u00e9\u00eb\3\2\2\2\u00ea\u00e7\3\2\2\2\u00eb\u00ec\3\2"+ "\2\2\u00ec\u00ea\3\2\2\2\u00ec\u00ed\3\2\2\2\u00ed\u00ee\3\2\2\2\u00ee"+ "\u00ef\b\4\1\2\u00ef\u00f0\7\24\2\2\u00f0\u00f2\3\2\2\2\u00f1e\3\2\2\2"+ "\u00f1m\3\2\2\2\u00f1p\3\2\2\2\u00f1r\3\2\2\2\u00f1t\3\2\2\2\u00f1v\3"+ "\2\2\2\u00f1|\3\2\2\2\u00f1\u0089\3\2\2\2\u00f1\u0096\3\2\2\2\u00f1\u009d"+ "\3\2\2\2\u00f1\u00a4\3\2\2\2\u00f1\u00ab\3\2\2\2\u00f1\u00b2\3\2\2\2\u00f1"+ "\u00b9\3\2\2\2\u00f1\u00c0\3\2\2\2\u00f1\u00c2\3\2\2\2\u00f1\u00cf\3\2"+ "\2\2\u00f1\u00d6\3\2\2\2\u00f1\u00dd\3\2\2\2\u00f1\u00e4\3\2\2\2\u00f2"+ "\7\3\2\2\2\16\20\34-@Q\\c\u0085\u0092\u00cb\u00ec\u00f1"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
33,621
32.859013
388
java
FOADA
FOADA-master/src/parser/FOADA/ANTLR4/FOADAParserANTLR4BaseListener.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.FOADA.ANTLR4; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.TerminalNode; /** * This class provides an empty implementation of {@link FOADAParserANTLR4Listener}, * which can be extended to create a listener which only needs to handle a subset * of the available methods. */ public class FOADAParserANTLR4BaseListener implements FOADAParserANTLR4Listener { /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterAutomaton(FOADAParserANTLR4.AutomatonContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitAutomaton(FOADAParserANTLR4.AutomatonContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterType(FOADAParserANTLR4.TypeContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitType(FOADAParserANTLR4.TypeContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterExpression(FOADAParserANTLR4.ExpressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitExpression(FOADAParserANTLR4.ExpressionContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
2,841
28.604167
84
java
FOADA
FOADA-master/src/parser/FOADA/ANTLR4/FOADAParserANTLR4Listener.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package parser.FOADA.ANTLR4; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link FOADAParserANTLR4}. */ public interface FOADAParserANTLR4Listener extends ParseTreeListener { /** * Enter a parse tree produced by {@link FOADAParserANTLR4#automaton}. * @param ctx the parse tree */ void enterAutomaton(FOADAParserANTLR4.AutomatonContext ctx); /** * Exit a parse tree produced by {@link FOADAParserANTLR4#automaton}. * @param ctx the parse tree */ void exitAutomaton(FOADAParserANTLR4.AutomatonContext ctx); /** * Enter a parse tree produced by {@link FOADAParserANTLR4#type}. * @param ctx the parse tree */ void enterType(FOADAParserANTLR4.TypeContext ctx); /** * Exit a parse tree produced by {@link FOADAParserANTLR4#type}. * @param ctx the parse tree */ void exitType(FOADAParserANTLR4.TypeContext ctx); /** * Enter a parse tree produced by {@link FOADAParserANTLR4#expression}. * @param ctx the parse tree */ void enterExpression(FOADAParserANTLR4.ExpressionContext ctx); /** * Exit a parse tree produced by {@link FOADAParserANTLR4#expression}. * @param ctx the parse tree */ void exitExpression(FOADAParserANTLR4.ExpressionContext ctx); }
2,106
32.983871
82
java
FOADA
FOADA-master/src/structure/Automaton.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package structure; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.InterpolatingProverEnvironment; import org.sosy_lab.java_smt.api.Model.ValueAssignment; import org.sosy_lab.java_smt.api.SolverException; import exception.FOADAException; import exception.InterpolatingProverEnvironmentException; import structure.FOADAExpression.ExpressionCategory; import structure.FOADAExpression.ExpressionType; import utility.Console; import utility.Impact; import utility.Console.ConsoleType; import utility.JavaSMTConfig; public class Automaton { /** * initial state */ public FOADAExpression initial; /** * set of names of final states */ public List<String> namesOfFinalStates; /** * map (name of predicate + event symbol : transition) */ public Map<String, FOADATransition> transitions; /** rename map (original name : new name) */ public Map<String, String> renameMap; /** set of names of predicates */ public List<String> namesOfPredicates; /** set of events */ public List<String> events; /** number of input variables */ public int nbOfVariables; /** default constructor * @throws FOADAException */ public Automaton() throws FOADAException { initial = null; namesOfFinalStates = new ArrayList<String>(); transitions = new LinkedHashMap<String, FOADATransition>(); renameMap = new LinkedHashMap<String, String>(); namesOfPredicates = new ArrayList<String>(); events = new ArrayList<String>(); nbOfVariables = 0; } public Automaton quantifies(List<String> variablesNames, List<ExpressionType> variablesTypes) throws FOADAException { Automaton newOne = new Automaton(); // initial state newOne.initial = initial; // final states newOne.namesOfFinalStates = new ArrayList<String>(); newOne.namesOfFinalStates.addAll(namesOfFinalStates); // rename map newOne.renameMap = new LinkedHashMap<String, String>(); newOne.renameMap.putAll(renameMap); for(String nameOfQuantifiedInputVariable : variablesNames) { newOne.renameMap.remove(nameOfQuantifiedInputVariable); } // predicates (states) newOne.namesOfPredicates = new ArrayList<String>(); newOne.namesOfPredicates.addAll(namesOfPredicates); // event symbols newOne.events = new ArrayList<String>(); newOne.events.addAll(events); // transitions List<String> originalNamesAfterRenamingOfQuantifiedVariables = new ArrayList<String>(); List<String> newNamesOfQuantifiedVariables = new ArrayList<String>(); List<FOADAExpression> quantifiedVariables = new ArrayList<FOADAExpression>(); for(int i = 0; i < variablesNames.size(); i++) { String nameAfterRenamingOfQuantifiedVariable = renameMap.get(variablesNames.get(i)); originalNamesAfterRenamingOfQuantifiedVariables.add(nameAfterRenamingOfQuantifiedVariable); String newNameOfQuantifiedVariable = "i" + i; newNamesOfQuantifiedVariables.add(newNameOfQuantifiedVariable); FOADAExpression quantifiedVariable = new FOADAExpression(newNameOfQuantifiedVariable, variablesTypes.get(i)); quantifiedVariables.add(quantifiedVariable); } Boolean renameMapIsUpdated = false; newOne.transitions = new LinkedHashMap<String, FOADATransition>(); for(Entry<String, FOADATransition> entry : this.transitions.entrySet()) { FOADATransition transition = new FOADATransition(); transition.left = entry.getValue().left.copy(); transition.event = entry.getValue().event; transition.inputVariables = new ArrayList<FOADAExpression>(); List<String> originalNamesAfterRenamingOfInputVariables = new ArrayList<String>(); List<String> newNamesOfInputVariables = new ArrayList<String>(); int orderOfInputVariable = 0; for(FOADAExpression expression : entry.getValue().inputVariables) { Boolean needToBeQuantified = false; for(String nameOfVariable : variablesNames) { if(expression.name.equals(renameMap.get(nameOfVariable))) { needToBeQuantified = true; break; } } if(!needToBeQuantified) { originalNamesAfterRenamingOfInputVariables.add(expression.name); String newNameOfInputVariable = "v" + orderOfInputVariable + "c"; orderOfInputVariable++; newNamesOfInputVariables.add(newNameOfInputVariable); transition.inputVariables.add(new FOADAExpression(newNameOfInputVariable, expression.type)); } } transition.right = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.Exists, quantifiedVariables); transition.right.subData.add(entry.getValue().right.copy()); for(int i = 0; i < newNamesOfQuantifiedVariables.size(); i++) { transition.right.substitute(originalNamesAfterRenamingOfQuantifiedVariables.get(i), newNamesOfQuantifiedVariables.get(i)); } for(int i = 0; i < newNamesOfInputVariables.size(); i++) { transition.right.substitute(originalNamesAfterRenamingOfInputVariables.get(i), newNamesOfInputVariables.get(i)); if(!renameMapIsUpdated) { for(Entry<String, String> entry2 : newOne.renameMap.entrySet()) { if(entry2.getValue().equals(originalNamesAfterRenamingOfInputVariables.get(i))) { entry2.setValue(newNamesOfInputVariables.get(i)); } } } } renameMapIsUpdated = true; newOne.transitions.put(entry.getKey(), transition); } // number of input variables //newOne.nbOfVariables = nbOfVariables; newOne.nbOfVariables = nbOfVariables - variablesNames.size(); //System.out.println(newOne.nbOfVariables); return newOne; } public Automaton intersects(Automaton automaton, String renameChar) throws FOADAException { Automaton newOne = new Automaton(); List<String> newNamesOfPredicatesForB = new ArrayList<String>(); FOADAExpression newInitialForB = automaton.initial.copy(); List<String> newNamesOfFinalStatesForB = new ArrayList<String>(); for(int i = automaton.namesOfPredicates.size() - 1; i >= 0; i--) { int newNumber = i + namesOfPredicates.size(); newNamesOfPredicatesForB.add("q" + newNumber + "c"); newInitialForB.substitute("q" + i + "c", "q" + newNumber + "c"); for(int j = 0; j < automaton.namesOfFinalStates.size(); j++) { if(automaton.namesOfFinalStates.get(j).equals("q" + i + "c")) { newNamesOfFinalStatesForB.add("q" + newNumber + "c"); } } } Map<String, String> newRenameMapForB = new LinkedHashMap<String, String>(); for(Map.Entry<String, String> entry : automaton.renameMap.entrySet()) { String original = entry.getKey(); String newName = entry.getValue(); if(newName.charAt(0) == 'q') { original = original + "_" + renameChar; int newNumber = Integer.parseInt(newName.substring(1).substring(0, newName.length() - 2)) + namesOfPredicates.size(); newName = "q" + newNumber + "c"; newRenameMapForB.put(original, newName); } } Map<String, String> eventRenameMapForB = new LinkedHashMap<String, String>(); List<String> eventsForB = new ArrayList<String>(); for(Map.Entry<String, String> entry : automaton.renameMap.entrySet()) { if(entry.getValue().charAt(0) == 'e') { if(!renameMap.containsKey(entry.getKey())) { int newNumber = events.size() + eventRenameMapForB.size(); eventRenameMapForB.put(entry.getKey(), "e" + newNumber + "c"); newRenameMapForB.put(entry.getKey(), "e" + newNumber + "c"); eventsForB.add("e" + newNumber + "c"); } } } newOne.renameMap = new LinkedHashMap<String, String>(); newOne.renameMap.putAll(renameMap); newOne.renameMap.putAll(newRenameMapForB); Map<String, FOADATransition> newTransitionsForB = new LinkedHashMap<String, FOADATransition>(); for(FOADATransition transition : automaton.transitions.values()) { // rename predicates in transitions FOADAExpression left = transition.left.copy(); FOADAExpression right = transition.right.copy(); String event = transition.event; for(Map.Entry<String, String> entry : automaton.renameMap.entrySet()) { if(entry.getValue().equals(event)) { event = entry.getKey(); } } List<FOADAExpression> inputVariables = transition.inputVariables; for(int i = automaton.namesOfPredicates.size() - 1; i >= 0; i--) { int newNumber = i + namesOfPredicates.size(); left.substitute("q" + i + "c", "q" + newNumber + "c"); right.substitute("q" + i + "c", "q" + newNumber + "c"); } FOADATransition newTransition = new FOADATransition(); newTransition.left = left; newTransition.event = newOne.renameMap.get(event); newTransition.inputVariables = inputVariables; newTransition.right = right; newTransitionsForB.put(left.name + "+" + newTransition.event, newTransition); } newOne.initial = new FOADAExpression(ExpressionType.Boolean, ExpressionCategory.And, initial, newInitialForB); newOne.namesOfPredicates = new ArrayList<String>(); newOne.namesOfPredicates.addAll(namesOfPredicates); newOne.namesOfPredicates.addAll(newNamesOfPredicatesForB); newOne.namesOfFinalStates = new ArrayList<String>(); newOne.namesOfFinalStates.addAll(namesOfFinalStates); newOne.namesOfFinalStates.addAll(newNamesOfFinalStatesForB); newOne.events = new ArrayList<String>(); newOne.events.addAll(events); newOne.events.addAll(eventsForB); newOne.nbOfVariables = nbOfVariables; newOne.transitions = new LinkedHashMap<String, FOADATransition>(); newOne.transitions.putAll(transitions); newOne.transitions.putAll(newTransitionsForB); return newOne; } public Automaton intersects(Automaton automaton) throws FOADAException { return intersects(automaton, "B"); } public Automaton complements() throws FOADAException { Automaton newOne = new Automaton(); newOne.initial = initial.copy(); newOne.namesOfFinalStates = new ArrayList<String>(); newOne.namesOfFinalStates.addAll(namesOfPredicates); newOne.namesOfFinalStates.removeAll(namesOfFinalStates); newOne.transitions = new LinkedHashMap<String, FOADATransition>(); for(Entry<String, FOADATransition> transitionEntry : transitions.entrySet()) { newOne.transitions.put(transitionEntry.getKey(), transitionEntry.getValue().copy()); } for(FOADATransition t : newOne.transitions.values()) { t.right.negate(); } Map<String, FOADAExpression> predicatesNameArguments = new LinkedHashMap<String, FOADAExpression>(); for(FOADATransition transition : transitions.values()) { FOADAExpression predicateWithArguments = transition.left; String nameOfPredicate = transition.left.name; if(!predicatesNameArguments.containsKey(nameOfPredicate)) { predicatesNameArguments.put(nameOfPredicate, predicateWithArguments); } } List<FOADAExpression> inputVariables = transitions.values().iterator().next().inputVariables; for(String predicate : namesOfPredicates) { FOADAExpression left = predicatesNameArguments.get(predicate); for(String event : events) { if(!transitions.containsKey(predicate + "+" + event)) { FOADATransition transition = new FOADATransition(); if(left != null) { transition.left = left.copy(); } else { transition.left = new FOADAExpression(predicate, ExpressionType.Boolean); } transition.event = event; transition.inputVariables = inputVariables; transition.right = new FOADAExpression(true); newOne.transitions.put(predicate + "+" + event, transition); } } } newOne.renameMap = new LinkedHashMap<String, String>(); newOne.renameMap.putAll(renameMap); newOne.namesOfPredicates = new ArrayList<String>(); newOne.namesOfPredicates.addAll(namesOfPredicates); newOne.events = new ArrayList<String>(); newOne.events.addAll(events); newOne.nbOfVariables = nbOfVariables; return newOne; } public boolean isIncluded(Automaton B, utility.TreeSearch.Mode searchMode, utility.Impact.Mode transitionMode) throws FOADAException { Automaton complementOfB = B.complements(); Automaton AIntersectsComplementOfB = intersects(complementOfB); return AIntersectsComplementOfB.isEmpty(searchMode, transitionMode); } public boolean isEmpty(utility.TreeSearch.Mode searchMode, utility.Impact.Mode transitionMode) throws FOADAException { utility.JavaSMTConfig.initJavaSMT(); System.out.println(renameMap); System.out.println("Predicates : " + namesOfPredicates); System.out.println("Initial : " + initial); System.out.println("Final : " + namesOfFinalStates); System.out.println("Events : " + events); for(Entry<String, FOADATransition> entry : transitions.entrySet()) { System.out.println(entry.getKey() + " ### " + entry.getValue()); } long beginTime = System.currentTimeMillis(); int nbOfNodesVisited = 0; int nbOfNodesCreated = 0; // start with the initial state // create initial node FOADAConfiguration initialNode = new FOADAConfiguration(nbOfNodesCreated++, (BooleanFormula)initial.toJavaSMTFormula(JavaSMTConfig.fmgr), null, null); // initialize the set of all valid Nodes Set<FOADAConfiguration> allValidNodes = new HashSet<FOADAConfiguration>(); // initialize the work list List<FOADAConfiguration> workList = new ArrayList<FOADAConfiguration>(); // add the initial node into the work list workList.add(initialNode); // start working with the work list while(!workList.isEmpty()) { // pick a node -> the current node FOADAConfiguration currentNode = null; if(searchMode == utility.TreeSearch.Mode.BFS) { currentNode = workList.get(0); workList.remove(0); } else { currentNode = workList.get(workList.size() - 1); workList.remove(workList.size() - 1); } nbOfNodesVisited++; allValidNodes.add(currentNode); /** TODO **/ //System.out.println(currentNode); // calculate the path from the initial node to the current node List<String> pathFromInitToCurrent = new ArrayList<String>(); // loop to find the path FOADAConfiguration c = currentNode; while(c.father != null) { pathFromInitToCurrent.add(0, c.fatherSymbol); c = c.father; } /** TODO **/ //System.out.println(pathFromInitToCurrent); // determine whether the current node is accepting // create a list of JavaSMT expressions (blocks) for interpolation List<BooleanFormula> blocks = new ArrayList<BooleanFormula>(); // create a time-stamped initial state FOADAExpression timeStampedInitial = initial.copy(); timeStampedInitial.addTimeStamps(0); // add the JavaSMT expression of the timed-stamped initial state into list of blocks blocks.add((BooleanFormula)timeStampedInitial.toJavaSMTFormula(JavaSMTConfig.fmgr)); // create a set of all the un-time-stamped predicates in the current block // or // create a set of all the occurrences of predicates in the current block Set<FOADAExpression> predicatesInCurrentBlock = null; Set<FOADAExpression> predicatesOccurrencesInCurrentBlock = null; // get the names of all the predicates in the initial state // or // get all the occurrences of predicates in the initial state if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { predicatesInCurrentBlock = new HashSet<FOADAExpression>(); Set<FOADAExpression> predicatesOccurrencesInUnTimeStampedCurrentBlock = initial.copy().findPredicatesOccurrences(); for(FOADAExpression o : predicatesOccurrencesInUnTimeStampedCurrentBlock) { for(int i = 0; i < o.subData.size(); i++) { o.subData.get(i).name = "a" + i + "c"; o.subData.get(i).category = ExpressionCategory.Function; o.subData.get(i).subData = new ArrayList<FOADAExpression>(); } predicatesInCurrentBlock.add(o); } } else { predicatesOccurrencesInCurrentBlock = timeStampedInitial.findPredicatesOccurrences(); } // compute next blocks int currentTimeStamp = 0; for(String a : pathFromInitToCurrent) { // create a new list of all the small parts (of conjunction) of the new block List<BooleanFormula> smallPartsOfNewBlock = new ArrayList<BooleanFormula>(); // compute the small parts of the new block if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { Set<FOADAExpression> predicatesInNewBlock = new HashSet<FOADAExpression>(); // compute one small part of the new block for(FOADAExpression predicate : predicatesInCurrentBlock) { FOADATransition transition = transitions.get(predicate.name + "+" + a); if(transition != null) { predicatesInNewBlock.addAll(transition.getPredicates()); BooleanFormula currentPartOfNewBlock = transition.getUniversallyQuantifiedImplication(currentTimeStamp); smallPartsOfNewBlock.add(currentPartOfNewBlock); } else { List<Formula> arguments = new ArrayList<Formula>(); for(FOADAExpression x : predicate.subData) { Formula argument; if(x.type == ExpressionType.Integer) { argument = JavaSMTConfig.ufmgr.declareAndCallUF(x.name, FormulaType.IntegerType); } else { argument = JavaSMTConfig.ufmgr.declareAndCallUF(x.name, FormulaType.BooleanType); } arguments.add(argument); } FOADAExpression timeStampedLeft = predicate.copy(); timeStampedLeft.addTimeStamps(currentTimeStamp); BooleanFormula leftPartOfImplication = (BooleanFormula)timeStampedLeft.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula rightPartOfImplication = JavaSMTConfig.bmgr.makeBoolean(false); BooleanFormula implication = JavaSMTConfig.bmgr.implication(leftPartOfImplication, rightPartOfImplication); if(arguments.isEmpty()) { smallPartsOfNewBlock.add(implication); } else { BooleanFormula universallyQuantifiedImplication = JavaSMTConfig.qmgr.forall(arguments, implication); smallPartsOfNewBlock.add(universallyQuantifiedImplication); } } } if(smallPartsOfNewBlock.isEmpty()) { blocks.add(JavaSMTConfig.bmgr.makeBoolean(true)); } else { blocks.add(JavaSMTConfig.bmgr.and(smallPartsOfNewBlock)); } predicatesInCurrentBlock = predicatesInNewBlock; } else { Set<FOADAExpression> predicatesOccurrencesInNewBlock = new HashSet<FOADAExpression>(); // compute one small part of the new block for(FOADAExpression occurrence : predicatesOccurrencesInCurrentBlock) { FOADAExpression left = occurrence; FOADATransition transition = transitions.get(left.name.substring(0, left.name.indexOf("_")) + "+" + a); if(transition != null) { predicatesOccurrencesInNewBlock.addAll(transition.getPredicatesOccurrences(currentTimeStamp, left)); BooleanFormula currentPartOfNewBlock = transition.getImplicationWithOccurrences(currentTimeStamp, left); smallPartsOfNewBlock.add(currentPartOfNewBlock); } else { BooleanFormula currentPartOfNewBlock = JavaSMTConfig.bmgr.implication((BooleanFormula)left.toJavaSMTFormula(JavaSMTConfig.fmgr), JavaSMTConfig.bmgr.makeBoolean(false)); smallPartsOfNewBlock.add(currentPartOfNewBlock); } } if(smallPartsOfNewBlock.isEmpty()) { blocks.add(JavaSMTConfig.bmgr.makeBoolean(true)); } else { blocks.add(JavaSMTConfig.bmgr.and(smallPartsOfNewBlock)); } predicatesOccurrencesInCurrentBlock = predicatesOccurrencesInNewBlock; } currentTimeStamp++; } // compute the final conjunction (last block) List<BooleanFormula> finalConjunction = new ArrayList<BooleanFormula>(); if(transitionMode == utility.Impact.Mode.UniversallyQuantifyArguments) { for(FOADAExpression predicate : predicatesInCurrentBlock) { List<Formula> arguments = new ArrayList<Formula>(); for(FOADAExpression a : predicate.subData) { Formula argument; if(a.type == ExpressionType.Integer) { argument = JavaSMTConfig.ufmgr.declareAndCallUF(a.name, FormulaType.IntegerType); } else { argument = JavaSMTConfig.ufmgr.declareAndCallUF(a.name, FormulaType.BooleanType); } arguments.add(argument); } FOADAExpression timeStampedLeft = predicate.copy(); timeStampedLeft.addTimeStamps(currentTimeStamp); BooleanFormula leftPartOfImplication = (BooleanFormula)timeStampedLeft.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula rightPartOfImplication; if(namesOfFinalStates.contains(predicate.name)) { rightPartOfImplication = JavaSMTConfig.bmgr.makeBoolean(true); } else { rightPartOfImplication = JavaSMTConfig.bmgr.makeBoolean(false); } BooleanFormula implication = JavaSMTConfig.bmgr.implication(leftPartOfImplication, rightPartOfImplication); if(arguments.isEmpty()) { finalConjunction.add(implication); } else { BooleanFormula universallyQuantifiedImplication = JavaSMTConfig.qmgr.forall(arguments, implication); finalConjunction.add(universallyQuantifiedImplication); } } } else { for(FOADAExpression occurrence : predicatesOccurrencesInCurrentBlock) { FOADAExpression left = occurrence; // implies true if is final state if(namesOfFinalStates.contains(left.name.substring(0, left.name.indexOf("_")))) { BooleanFormula right = JavaSMTConfig.bmgr.makeBoolean(true); BooleanFormula implication = JavaSMTConfig.bmgr.implication((BooleanFormula)left.toJavaSMTFormula(JavaSMTConfig.fmgr), right); finalConjunction.add(implication); } // implies false if is not final state else { BooleanFormula right = JavaSMTConfig.bmgr.makeBoolean(false); BooleanFormula implication = JavaSMTConfig.bmgr.implication((BooleanFormula)left.toJavaSMTFormula(JavaSMTConfig.fmgr), right); finalConjunction.add(implication); } } } // add the last block into the list of blocks if(finalConjunction.isEmpty()) { blocks.add(JavaSMTConfig.bmgr.makeBoolean(true)); } else { blocks.add(JavaSMTConfig.bmgr.and(finalConjunction)); } /** TODO **/ /*System.out.println("Blocks:"); for(BooleanFormula b : blocks) { System.out.println(b); }*/ // check if the conjunction of all blocks is satisfiable or compute the interpolants // create prover environment for interpolation @SuppressWarnings("rawtypes") InterpolatingProverEnvironment prover = JavaSMTConfig.solverContext.newProverEnvironmentWithInterpolation(); // create a new list for sets of objects received when pushing different partitions into the prover List<Set<Object>> listPartitions = new ArrayList<Set<Object>>(); // each block is a partition for(BooleanFormula f : blocks) { // create a set for objects received when pushing different partitions into the prover Set<Object> Partition = new HashSet<Object>(); // push the partition (block) into the prover and add the received object into the set Partition.add(prover.push(f)); // add the set into the list listPartitions.add(Partition); } // check whether the conjunction of all blocks is unsatisfiable try { // compute the interpolants if it is not satisfiable if(prover.isUnsat()) { @SuppressWarnings("unchecked") // compute the interpolants (with time-stamps) List<BooleanFormula> interpolantsWithTimeStamps = prover.getSeqInterpolants(listPartitions); List<BooleanFormula> interpolants = new ArrayList<BooleanFormula>(); // remove the time-stamps from the interpolants for(BooleanFormula f : interpolantsWithTimeStamps) { interpolants.add(JavaSMTConfig.removeTimeStamp(f)); } // refine the nodes along the path // starting from the root node FOADAConfiguration currentNodeAlongPath = initialNode; int step = 0; // loop check the path boolean oneNodeIsClosed = false; while(true) { // get the corresponding interpolant according to the current step BooleanFormula interpolant = interpolants.get(step); // check the validity of the implication: current -> interpolant boolean implicationIsValid = JavaSMTConfig.checkImplication(currentNodeAlongPath.expression, interpolant); // if the implication if not valid if(!implicationIsValid) { // refine the node by making a conjunction currentNodeAlongPath.expression = JavaSMTConfig.bmgr.and(currentNodeAlongPath.expression, interpolant); /** TODO **/ //System.out.println("\t#" + currentNodeAlongPath.number + " refined : " + currentNodeAlongPath.expression); // remove all the covered relations of the current node along path currentNodeAlongPath.removeCoveredRelations(workList); // close the current node along path if(!oneNodeIsClosed) { oneNodeIsClosed = Impact.close(currentNodeAlongPath, workList, allValidNodes); } if(currentNodeAlongPath.expression.toString().equals("false")) { workList.remove(currentNodeAlongPath); allValidNodes.remove(currentNodeAlongPath); } } // if finish looping the path if(step >= pathFromInitToCurrent.size()) { break; } // if not finish looping the path else { // refresh the current node along path int indexOfSuccessor = currentNodeAlongPath.successorSymbolIndexMap.get(pathFromInitToCurrent.get(step)); currentNodeAlongPath = currentNodeAlongPath.successors.get(indexOfSuccessor); // refresh the current step step++; } } } // print out the model and return false if it is satisfiable else { System.out.println("------------------------------"); long endTime = System.currentTimeMillis(); if(pathFromInitToCurrent.size() == 0) { System.out.println("empty trace"); } else { Object[][] variablesAssignments = new Object[pathFromInitToCurrent.size()][nbOfVariables]; for(Object a : prover.getModelAssignments()) { /* TODO */ //System.out.println((ValueAssignment)a); String expressionString = ((ValueAssignment)a).getKey().toString(); if(expressionString.charAt(0) == 'v') { int lastIndexOfUnderscore = expressionString.lastIndexOf('_'); int variableStep = Integer.valueOf(expressionString.substring(lastIndexOfUnderscore + 1)); if(variableStep > 0) { int variableIndex = Integer.valueOf(expressionString.substring(1, lastIndexOfUnderscore - 1)); variablesAssignments[variableStep - 1][variableIndex] = ((ValueAssignment)a).getValue(); } } } for(int i1 = 0; i1 < pathFromInitToCurrent.size(); i1++) { String newNameEvent = pathFromInitToCurrent.get(i1); String oldNameEvent = null; for(Entry<String, String> e : renameMap.entrySet()) { if(e.getValue().equals(newNameEvent)) { oldNameEvent = e.getKey(); break; } } System.out.print(oldNameEvent + " \t::::: DATA ::::: { "); for(int i2 = 0; i2 < nbOfVariables; i2++) { System.out.print(variablesAssignments[i1][i2] == null ? "any " : variablesAssignments[i1][i2] + " "); } System.out.println('}'); } } System.out.println("------------------------------"); Console.printInfo(ConsoleType.FOADA, "Nodes Created : " + nbOfNodesCreated); Console.printInfo(ConsoleType.FOADA, "Nodes Visited : " + nbOfNodesVisited); Console.printInfo(ConsoleType.FOADA, "Time Used : " + (endTime - beginTime) + " ms"); return false; } } catch (SolverException e) { throw new InterpolatingProverEnvironmentException(e); } catch (InterruptedException e) { throw new InterpolatingProverEnvironmentException(e); } // expand the current node if it is not covered // check if the current node is covered, if not then expand it if(currentNode.successors.isEmpty() && !currentNode.isCovered()) { for(String e : events) { FOADAConfiguration newNode = new FOADAConfiguration(nbOfNodesCreated++, JavaSMTConfig.bmgr.makeBoolean(true), currentNode, e); currentNode.addSuccessor(e, newNode); workList.add(newNode); } } } System.out.println("------------------------------"); long endTime = System.currentTimeMillis(); Console.printInfo(ConsoleType.FOADA, "Nodes Created : " + nbOfNodesCreated); Console.printInfo(ConsoleType.FOADA, "Nodes Visited : " + nbOfNodesVisited); Console.printInfo(ConsoleType.FOADA, "Time Used : " + (endTime - beginTime) + " ms"); return true; } }
29,386
41.90073
175
java
FOADA
FOADA-master/src/structure/FOADAConfiguration.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package structure; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.sosy_lab.java_smt.api.BooleanFormula; import exception.FOADAException; import utility.Impact; public class FOADAConfiguration { /** configuration number */ public int number; /** expression in the configuration */ public BooleanFormula expression; /** father node */ public FOADAConfiguration father; /** father symbol */ public String fatherSymbol; /** successors */ public List<FOADAConfiguration> successors; /** map of symbol leading to successor to successor's index */ public Map<String, Integer> successorSymbolIndexMap; /** set of nodes covering this */ public Set<FOADAConfiguration> coveringNodes; /** set of nodes that are covered by this */ public Set<FOADAConfiguration> coveredNodes; /** default constructor * @param expression given expression in the configuration * @param father given father node of the current configuration node * @param fatherSymbol the symbol with which father nodes comes to here */ public FOADAConfiguration(int number, BooleanFormula expression, FOADAConfiguration father, String fatherSymbol) { this.number = number; this.expression = expression; this.father = father; this.fatherSymbol = fatherSymbol; successors = new ArrayList<FOADAConfiguration>(); successorSymbolIndexMap = new HashMap<String, Integer>(); coveringNodes = new HashSet<FOADAConfiguration>(); coveredNodes = new HashSet<FOADAConfiguration>(); } /** copy constructor */ public FOADAConfiguration(FOADAConfiguration configuration) { number = configuration.number; expression = configuration.expression; father = configuration.father; fatherSymbol = configuration.fatherSymbol; successors = new ArrayList<FOADAConfiguration>(); for(FOADAConfiguration c : configuration.successors) { successors.add(c.copy()); } successorSymbolIndexMap = new HashMap<String, Integer>(); successorSymbolIndexMap.putAll(configuration.successorSymbolIndexMap); coveringNodes = new HashSet<FOADAConfiguration>(); for(FOADAConfiguration c : configuration.coveringNodes) { coveringNodes.add(c.copy()); } coveredNodes = new HashSet<FOADAConfiguration>(); for(FOADAConfiguration c : configuration.coveredNodes) { coveredNodes.add(c.copy()); } } /** deep copy */ public FOADAConfiguration copy() { FOADAConfiguration copy = new FOADAConfiguration(this); return copy; } /** add successor * @param symbol the symbol leading to the successor * @param successor the successor to be added */ public void addSuccessor(String symbol, FOADAConfiguration successor) { successors.add(successor); successorSymbolIndexMap.put(symbol, successors.size() - 1); } /** check whether the current configuration is a successor of another configuration * @param another the target configuration */ public boolean isSuccessorOf(FOADAConfiguration another) { boolean isSuccessor = false; for(FOADAConfiguration current = this; current != null; current = current.father) { if(current.number == another.number) { isSuccessor = true; break; } } return isSuccessor; } /** remove all the covered relations */ public void removeCoveredRelations(List<FOADAConfiguration> workList) throws FOADAException { for(FOADAConfiguration covered : coveredNodes) { covered.coveringNodes.remove(this); Impact.reEnable(covered, workList); } coveredNodes.clear(); } /** remove all the covered relations of this and its successors */ public void removeRecursivelyCoveredRelations(List<FOADAConfiguration> workList) throws FOADAException { removeCoveredRelations(workList); for(FOADAConfiguration successor : successors) { successor.removeRecursivelyCoveredRelations(workList); } } /** check if this is covered (or one of its ancestor is covered) */ public boolean isCovered() { if(!coveringNodes.isEmpty()) { return true; } else if(father == null){ return false; } else { return father.isCovered(); } } @Override public String toString() { return "#" + number + ' ' + expression; } }
5,093
26.095745
113
java
FOADA
FOADA-master/src/structure/FOADAExpression.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package structure; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaManager; import org.sosy_lab.java_smt.api.FormulaType; import org.sosy_lab.java_smt.api.NumeralFormula.IntegerFormula; import exception.FOADAException; import exception.UndefinedVariableException; public class FOADAExpression { public enum ExpressionType { Integer, Boolean }; public enum ExpressionCategory { ITE, Constant, Function, Exists, Forall, Not, And, Or, Equals, Distinct, Plus, Minus, Times, Slash, GT, LT, GEQ, LEQ } // data // ------------------------------ /** type of the expression */ public ExpressionType type; /** category of the expression */ public ExpressionCategory category; /** name */ public String name; /** data for "Boolean constant" */ public boolean bValue; /** data for "Integer constant" */ public int iValue; /** data for "composite structure" */ public List<FOADAExpression> subData; // constructors // ------------------------------ /** constructor for "Boolean constant" */ public FOADAExpression(boolean constant) { type = ExpressionType.Boolean; category = ExpressionCategory.Constant; bValue = constant; // data not used name = null; iValue = 0; subData = null; } /** constructor for "integer constant" */ public FOADAExpression(int constant) { type = ExpressionType.Integer; category = ExpressionCategory.Constant; iValue = constant; // data not used name = null; bValue = true; subData = null; } /** constructor for "unknown-type function" */ public FOADAExpression(String name) { type = null; this.name = name; category = ExpressionCategory.Function; subData = new ArrayList<FOADAExpression>(); // data not used bValue = true; iValue = 0; } /** constructor for "function" */ public FOADAExpression(String name, ExpressionType type, FOADAExpression... arguments) { this.type = type; this.name = name; category = ExpressionCategory.Function; subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : arguments) { subData.add(e.copy()); } // data not used bValue = true; iValue = 0; } /** constructor for "function" */ public FOADAExpression(String name, ExpressionType type, List<FOADAExpression> arguments) { this.type = type; this.name = name; category = ExpressionCategory.Function; subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : arguments) { subData.add(e.copy()); } // data not used bValue = true; iValue = 0; } /** finish recursively the types according to the information from arguments and input variables */ public void finishTypes(Automaton automaton, List<String> argumentsNames, List<FOADAExpression.ExpressionType> argumentsTypes, List<String> inputVarNames, List<FOADAExpression.ExpressionType> inputVarTypes) throws FOADAException { if(subData != null) { for(FOADAExpression e : subData) { e.finishTypes(automaton, argumentsNames, argumentsTypes, inputVarNames, inputVarTypes); } } if(type == null && category == ExpressionCategory.Function) { Boolean alreadySet = false; for(String nameOfPredicate : automaton.namesOfPredicates) { String newName = automaton.renameMap.get(name); if(newName != null && newName.equals(nameOfPredicate)) { type = ExpressionType.Boolean; alreadySet = true; break; } } if(!alreadySet) { for(int i = 0; i < argumentsNames.size(); i++ ) { if(name.equals(argumentsNames.get(i))) { type = argumentsTypes.get(i); alreadySet = true; break; } } } if(!alreadySet) { for(int i = 0; i < inputVarNames.size(); i++) { if(name.equals(inputVarNames.get(i))) { type = inputVarTypes.get(i); alreadySet = true; break; } } } } else if(category == ExpressionCategory.ITE) { type = subData.get(1).type; } if(type == null) { throw new UndefinedVariableException(name); } } /** constructor for "non-function composite structure" */ public FOADAExpression(ExpressionType type, ExpressionCategory category, FOADAExpression... subExpressions) { this.type = type; this.category = category; subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : subExpressions) { subData.add(e.copy()); } // data not used name = null; bValue = true; iValue = 0; } /** constructor for "non-function composite structure" */ public FOADAExpression(ExpressionType type, ExpressionCategory category, List<FOADAExpression> subExpressions) { this.type = type; this.category = category; subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : subExpressions) { subData.add(e.copy()); } // data not used name = null; bValue = true; iValue = 0; } /** copy constructor */ public FOADAExpression(FOADAExpression expression) { type = expression.type; category = expression.category; name = expression.name; bValue = expression.bValue; iValue = expression.iValue; if(expression.subData == null) { subData = null; } else { subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : expression.subData) { subData.add(e.copy()); } } } // utilities public void negate() { switch(category) { case ITE: break; case Constant: if(type == ExpressionType.Boolean) { if(bValue == false) { bValue = true; } else { bValue = false; } } break; case Function: for(FOADAExpression e : subData) { e.negate(); } break; case Exists: category = ExpressionCategory.Forall; subData.get(subData.size() - 1).negate(); break; case Forall: category = ExpressionCategory.Exists; subData.get(subData.size() - 1).negate(); break; case Not: FOADAExpression expression = new FOADAExpression(subData.get(0)); type = expression.type; category = expression.category; name = expression.name; bValue = expression.bValue; iValue = expression.iValue; if(expression.subData == null) { subData = null; } else { subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : expression.subData) { subData.add(e.copy()); } } break; case And: category = ExpressionCategory.Or; for(FOADAExpression e : subData) { e.negate(); } break; case Or: category = ExpressionCategory.And; for(FOADAExpression e : subData) { e.negate(); } break; case Equals: category = ExpressionCategory.Distinct; break; case Distinct: category = ExpressionCategory.Equals; break; case Plus: break; case Minus: break; case Times: break; case Slash: break; case GT: category = ExpressionCategory.LEQ; break; case LT: category = ExpressionCategory.GEQ; break; case GEQ: category = ExpressionCategory.LT; break; case LEQ: category = ExpressionCategory.GT; break; } } public Set<FOADAExpression> findPredicatesOccurrences(){ Set<FOADAExpression> result = new HashSet<FOADAExpression>(); switch(category) { case ITE: result.addAll(subData.get(1).findPredicatesOccurrences()); result.addAll(subData.get(2).findPredicatesOccurrences()); break; case Constant: break; case Function: if(name.charAt(0) == 'q') { result.add(this.copy()); } for(FOADAExpression e : subData) { result.addAll(e.findPredicatesOccurrences()); } break; case Exists: result.addAll(subData.get(subData.size() - 1).findPredicatesOccurrences()); break; case Forall: result.addAll(subData.get(subData.size() - 1).findPredicatesOccurrences()); break; case Not: result.addAll(subData.get(0).findPredicatesOccurrences()); break; case And: for(FOADAExpression e : subData) { result.addAll(e.findPredicatesOccurrences()); } break; case Or: for(FOADAExpression e : subData) { result.addAll(e.findPredicatesOccurrences()); } break; case Equals: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case Distinct: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case Plus: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case Minus: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case Times: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case Slash: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case GT: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case LT: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case GEQ: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; case LEQ: result.addAll(subData.get(0).findPredicatesOccurrences()); result.addAll(subData.get(1).findPredicatesOccurrences()); break; } return result; } public void addTimeStamps(int timeStamp) { switch(category) { case ITE: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); subData.get(2).addTimeStamps(timeStamp); break; case Constant: break; case Function: if(name.charAt(0) == 'v' || name.charAt(0) == 'q') { name = name + '_' + timeStamp; } for(FOADAExpression e : subData) { e.addTimeStamps(timeStamp); } break; case Exists: subData.get(subData.size() - 1).addTimeStamps(timeStamp); break; case Forall: subData.get(subData.size() - 1).addTimeStamps(timeStamp); break; case Not: subData.get(0).addTimeStamps(timeStamp); break; case And: for(FOADAExpression e : subData) { e.addTimeStamps(timeStamp); } break; case Or: for(FOADAExpression e : subData) { e.addTimeStamps(timeStamp); } break; case Equals: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case Distinct: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case Plus: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case Minus: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case Times: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case Slash: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case GT: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case LT: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case GEQ: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; case LEQ: subData.get(0).addTimeStamps(timeStamp); subData.get(1).addTimeStamps(timeStamp); break; } } /** replace a part of the expression * @param from the part to be replaced * @param to used to replace the part */ public void substitute(String from, String to) { switch(category) { case ITE: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); subData.get(2).substitute(from, to); break; case Constant: break; case Function: if(name.equals(from)) { name = to; } for(FOADAExpression e : subData) { e.substitute(from, to); } break; case Exists: subData.get(subData.size() - 1).substitute(from, to); break; case Forall: subData.get(subData.size() - 1).substitute(from, to); break; case Not: subData.get(0).substitute(from, to); break; case And: for(FOADAExpression e : subData) { e.substitute(from, to); } break; case Or: for(FOADAExpression e : subData) { e.substitute(from, to); } break; case Equals: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Distinct: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Plus: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Minus: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Times: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Slash: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case GT: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case LT: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case GEQ: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case LEQ: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; } } /** replace a part of the expression * @param from the part to be replaced * @param to used to replace the part */ public void substitute(FOADAExpression from, FOADAExpression to) { switch(category) { case ITE: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); subData.get(2).substitute(from, to); break; case Constant: break; case Function: if(equals(from)) { type = to.type; category = to.category; name = to.name; bValue = to.bValue; iValue = to.iValue; if(to.subData == null) { subData = null; } else { subData = new ArrayList<FOADAExpression>(); for(FOADAExpression e : to.subData) { subData.add(e.copy()); } } } else { for(FOADAExpression e : subData) { e.substitute(from, to); } } break; case Exists: subData.get(subData.size() - 1).substitute(from, to); break; case Forall: subData.get(subData.size() - 1).substitute(from, to); break; case Not: subData.get(subData.size() - 1).substitute(from, to); break; case And: for(FOADAExpression e : subData) { e.substitute(from, to); } break; case Or: for(FOADAExpression e : subData) { e.substitute(from, to); } break; case Equals: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Distinct: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Plus: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Minus: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Times: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case Slash: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case GT: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case LT: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case GEQ: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; case LEQ: subData.get(0).substitute(from, to); subData.get(1).substitute(from, to); break; } } /** deep copy */ public FOADAExpression copy() { FOADAExpression copy = new FOADAExpression(this); return copy; } /** to JavaSMT Formula * @param fmgr corresponding JavaSMT FormulaManager */ public Formula toJavaSMTFormula(FormulaManager fmgr) { switch(category) { case ITE: return fmgr.getBooleanFormulaManager().ifThenElse((BooleanFormula)subData.get(0).toJavaSMTFormula(fmgr), subData.get(1).toJavaSMTFormula(fmgr), subData.get(2).toJavaSMTFormula(fmgr)); case Constant: if(type == ExpressionType.Integer) { return fmgr.getIntegerFormulaManager().makeNumber(iValue); } else { return fmgr.getBooleanFormulaManager().makeBoolean(bValue); } case Function: List<Formula> argumentsIntoJavaSMT = new ArrayList<Formula>(); for(FOADAExpression e : subData) { argumentsIntoJavaSMT.add(e.toJavaSMTFormula(fmgr)); } if(type == ExpressionType.Integer) { return fmgr.getUFManager().declareAndCallUF(name, FormulaType.IntegerType, argumentsIntoJavaSMT); } else { return fmgr.getUFManager().declareAndCallUF(name, FormulaType.BooleanType, argumentsIntoJavaSMT); } case Exists: List<Formula> quantifiedVariables1 = new ArrayList<Formula>(); for(int i = 0; i < subData.size() - 1; i++) { quantifiedVariables1.add(subData.get(i).toJavaSMTFormula(fmgr)); } return fmgr.getQuantifiedFormulaManager().exists(quantifiedVariables1, (BooleanFormula)subData.get(subData.size() - 1).toJavaSMTFormula(fmgr)); case Forall: List<Formula> quantifiedVariables2 = new ArrayList<Formula>(); for(int i = 0; i < subData.size() - 1; i++) { quantifiedVariables2.add(subData.get(i).toJavaSMTFormula(fmgr)); } return fmgr.getQuantifiedFormulaManager().forall(quantifiedVariables2, (BooleanFormula)subData.get(subData.size() - 1).toJavaSMTFormula(fmgr)); case Not: return fmgr.getBooleanFormulaManager().not((BooleanFormula)subData.get(0).toJavaSMTFormula(fmgr)); case And: List<BooleanFormula> subDataIntoJavaSMT1 = new ArrayList<BooleanFormula>(); for(FOADAExpression e : subData) { subDataIntoJavaSMT1.add((BooleanFormula)e.toJavaSMTFormula(fmgr)); } return fmgr.getBooleanFormulaManager().and(subDataIntoJavaSMT1); case Or: List<BooleanFormula> subDataIntoJavaSMT2 = new ArrayList<BooleanFormula>(); for(FOADAExpression e : subData) { subDataIntoJavaSMT2.add((BooleanFormula)e.toJavaSMTFormula(fmgr)); } return fmgr.getBooleanFormulaManager().or(subDataIntoJavaSMT2); case Equals: if(subData.get(0).type == ExpressionType.Integer) { return fmgr.getIntegerFormulaManager().equal((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); } else { return fmgr.getBooleanFormulaManager().equivalence((BooleanFormula)subData.get(0).toJavaSMTFormula(fmgr), (BooleanFormula)subData.get(1).toJavaSMTFormula(fmgr)); } case Distinct: if(subData.get(0).type == ExpressionType.Integer) { return fmgr.getBooleanFormulaManager().not(fmgr.getIntegerFormulaManager().equal((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr))); } else { return fmgr.getBooleanFormulaManager().xor((BooleanFormula)subData.get(0).toJavaSMTFormula(fmgr), (BooleanFormula)subData.get(1).toJavaSMTFormula(fmgr)); } case Plus: return fmgr.getIntegerFormulaManager().add((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case Minus: return fmgr.getIntegerFormulaManager().subtract((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case Times: return fmgr.getIntegerFormulaManager().multiply((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case Slash: return fmgr.getIntegerFormulaManager().divide((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case GT: return fmgr.getIntegerFormulaManager().greaterThan((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case LT: return fmgr.getIntegerFormulaManager().lessThan((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case GEQ: return fmgr.getIntegerFormulaManager().greaterOrEquals((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); case LEQ: return fmgr.getIntegerFormulaManager().lessOrEquals((IntegerFormula)subData.get(0).toJavaSMTFormula(fmgr), (IntegerFormula)subData.get(1).toJavaSMTFormula(fmgr)); /* never reach here */ default: return null; } } @Override public String toString() { String resultString = ""; switch(category) { case ITE: return "(" + subData.get(0).toString() + " ? " + subData.get(1).toString() + " : " + subData.get(2).toString() + ")"; case Constant: if(type == ExpressionType.Integer) { return Integer.toString(iValue); } else { return Boolean.toString(bValue); } case Function: resultString = resultString + name + '('; for(FOADAExpression e : subData) { resultString = resultString + e.toString() + ','; } if(subData.size() == 0) { resultString = resultString + ' '; } resultString = resultString.substring(0, resultString.length() - 1) + ')'; return resultString; case Exists: resultString = resultString + "exists "; for(int i = 0; i < subData.size() - 1; i++) { resultString = resultString + subData.get(i).toString() + ' '; } resultString = resultString + ". " + subData.get(subData.size() - 1).toString(); return resultString; case Forall: resultString = resultString + "forall "; for(int i = 0; i < subData.size() - 1; i++) { resultString = resultString + subData.get(i).toString() + ' '; } resultString = resultString + ". " + subData.get(subData.size() - 1).toString(); return resultString; case Not: resultString = resultString + "!(" + subData.get(0).toString() + ')'; return resultString; case And: for(int i = 0; i < subData.size(); i++) { ExpressionCategory subCategory = subData.get(i).category; boolean needPar; if(subCategory == ExpressionCategory.Or || subCategory == ExpressionCategory.Exists || subCategory == ExpressionCategory.Forall) { needPar = true; } else { needPar = false; } if(needPar) { resultString = resultString + '('; } resultString = resultString + subData.get(i).toString(); if(needPar) { resultString = resultString + ')'; } resultString = resultString + " /\\ "; } resultString = resultString.substring(0, resultString.length() - 4); return resultString; case Or: for(int i = 0; i < subData.size(); i++) { ExpressionCategory subCategory = subData.get(i).category; boolean needPar; if(subCategory == ExpressionCategory.Exists || subCategory == ExpressionCategory.Forall) { needPar = true; } else { needPar = false; } if(needPar) { resultString = resultString + '('; } resultString = resultString + subData.get(i).toString(); if(needPar) { resultString = resultString + ')'; } resultString = resultString + " \\/ "; } resultString = resultString.substring(0, resultString.length() - 4); return resultString; case Equals: resultString = subData.get(0).toString() + " = " + subData.get(1).toString(); return resultString; case Distinct: resultString = subData.get(0).toString() + " != " + subData.get(1).toString(); return resultString; case Plus: resultString = subData.get(0).toString() + " + " + subData.get(1).toString(); return resultString; case Minus: resultString = subData.get(0).toString() + " - " + subData.get(1).toString(); return resultString; case Times: resultString = subData.get(0).toString() + " * " + subData.get(1).toString(); return resultString; case Slash: resultString = subData.get(0).toString() + " / " + subData.get(1).toString(); return resultString; case GT: resultString = subData.get(0).toString() + " > " + subData.get(1).toString(); return resultString; case LT: resultString = subData.get(0).toString() + " < " + subData.get(1).toString(); return resultString; case GEQ: resultString = subData.get(0).toString() + " >= " + subData.get(1).toString(); return resultString; case LEQ: resultString = subData.get(0).toString() + " <= " + subData.get(1).toString(); return resultString; /* never reach here */ default: return ""; } } @Override public boolean equals(Object obj) { return toString().equals(obj.toString()); } @Override public int hashCode() { return toString().hashCode(); } }
26,435
31.799007
207
java
FOADA
FOADA-master/src/structure/FOADATransition.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package structure; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.Formula; import org.sosy_lab.java_smt.api.FormulaType; import structure.FOADAExpression.ExpressionCategory; import structure.FOADAExpression.ExpressionType; import utility.JavaSMTConfig; public class FOADATransition { public FOADAExpression left; public String event; public List<FOADAExpression> inputVariables; public FOADAExpression right; public FOADATransition(String nameOfPredicate, List<String> argumentsNames, List<FOADAExpression.ExpressionType> argumentsTypes, String event, List<String> inputVarNames, List<FOADAExpression.ExpressionType> inputVarTypes, FOADAExpression post) { List<FOADAExpression> arguments = new ArrayList<FOADAExpression>(); for(int i = 0; i < argumentsNames.size(); i++) { FOADAExpression argument = new FOADAExpression(argumentsNames.get(i), argumentsTypes.get(i)); arguments.add(argument); } left = new FOADAExpression(nameOfPredicate, ExpressionType.Boolean, arguments); this.event = event; inputVariables = new ArrayList<FOADAExpression>(); for(int i = 0; i < inputVarNames.size(); i++) { FOADAExpression inputVar = new FOADAExpression(inputVarNames.get(i), inputVarTypes.get(i)); inputVariables.add(inputVar); } right = post.copy(); } public FOADATransition() { left = null; event = null; inputVariables = null; right = null; } public Set<FOADAExpression> getPredicates() { Set<FOADAExpression> result = new HashSet<FOADAExpression>(); Set<FOADAExpression> predicatesWithChangedArguments = right.findPredicatesOccurrences(); for(FOADAExpression o : predicatesWithChangedArguments) { for(int i = 0; i < o.subData.size(); i++) { o.subData.get(i).name = "a" + i + "c"; o.subData.get(i).category = ExpressionCategory.Function; o.subData.get(i).subData = new ArrayList<FOADAExpression>(); } result.add(o); } return result; } public Set<FOADAExpression> getPredicatesOccurrences(int currentTimeStamp, FOADAExpression occurenceOfLeft) { FOADAExpression rightAccordingToOccurrenceOfLeft = right.copy(); rightAccordingToOccurrenceOfLeft.addTimeStamps(currentTimeStamp + 1); for(int i = 0; i < occurenceOfLeft.subData.size(); i++) { rightAccordingToOccurrenceOfLeft.substitute(left.subData.get(i), occurenceOfLeft.subData.get(i)); } return rightAccordingToOccurrenceOfLeft.findPredicatesOccurrences(); } public BooleanFormula getImplicationWithOccurrences(int currentTimeStamp, FOADAExpression occurenceOfLeft) { FOADAExpression rightAccordingToOccurrenceOfLeft = right.copy(); rightAccordingToOccurrenceOfLeft.addTimeStamps(currentTimeStamp + 1); for(int i = 0; i < occurenceOfLeft.subData.size(); i++) { rightAccordingToOccurrenceOfLeft.substitute(left.subData.get(i), occurenceOfLeft.subData.get(i)); } BooleanFormula leftPartOfImplication = (BooleanFormula)occurenceOfLeft.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula rightPartOfImplication = (BooleanFormula)rightAccordingToOccurrenceOfLeft.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula implication = JavaSMTConfig.bmgr.implication(leftPartOfImplication, rightPartOfImplication); return implication; } public BooleanFormula getUniversallyQuantifiedImplication(int currentTimeStamp) { List<Formula> arguments = new ArrayList<Formula>(); for(FOADAExpression a : left.subData) { Formula argument; if(a.type == ExpressionType.Integer) { argument = JavaSMTConfig.ufmgr.declareAndCallUF(a.name, FormulaType.IntegerType); } else { argument = JavaSMTConfig.ufmgr.declareAndCallUF(a.name, FormulaType.BooleanType); } arguments.add(argument); } FOADAExpression timeStampedLeft = left.copy(); timeStampedLeft.addTimeStamps(currentTimeStamp); FOADAExpression timeStampedRight = right.copy(); timeStampedRight.addTimeStamps(currentTimeStamp + 1); BooleanFormula leftPartOfImplication = (BooleanFormula)timeStampedLeft.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula rightPartOfImplication = (BooleanFormula)timeStampedRight.toJavaSMTFormula(JavaSMTConfig.fmgr); BooleanFormula implication = JavaSMTConfig.bmgr.implication(leftPartOfImplication, rightPartOfImplication); if(arguments.isEmpty()) { return implication; } else { BooleanFormula universallyQuantifiedImplication = JavaSMTConfig.qmgr.forall(arguments, implication); return universallyQuantifiedImplication; } } public FOADATransition copy() { FOADATransition copy = new FOADATransition(); copy.left = left.copy(); copy.event = event; copy.inputVariables = new ArrayList<FOADAExpression>(); for(FOADAExpression inputVariable : inputVariables) { copy.inputVariables.add(inputVariable.copy()); } copy.right = right.copy(); return copy; } @Override public String toString() { String result = left.toString(); result = result + " + " + event + " : "; for(FOADAExpression i : inputVariables) { result = result + i.toString() + " "; } result = result + "---> "; result = result + right.toString(); return result; } }
6,082
34.573099
128
java
FOADA
FOADA-master/src/utility/Console.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; public class Console { // Reset public static final String RESET = "\033[0m"; // Text Reset // Regular Colors public static final String BLACK = "\033[0;30m"; // BLACK public static final String RED = "\033[0;31m"; // RED public static final String GREEN = "\033[0;32m"; // GREEN public static final String YELLOW = "\033[0;33m"; // YELLOW public static final String BLUE = "\033[0;34m"; // BLUE public static final String PURPLE = "\033[0;35m"; // PURPLE public static final String CYAN = "\033[0;36m"; // CYAN public static final String WHITE = "\033[0;37m"; // WHITE // Bold public static final String BLACK_BOLD = "\033[1;30m"; // BLACK public static final String RED_BOLD = "\033[1;31m"; // RED public static final String GREEN_BOLD = "\033[1;32m"; // GREEN public static final String YELLOW_BOLD = "\033[1;33m"; // YELLOW public static final String BLUE_BOLD = "\033[1;34m"; // BLUE public static final String PURPLE_BOLD = "\033[1;35m"; // PURPLE public static final String CYAN_BOLD = "\033[1;36m"; // CYAN public static final String WHITE_BOLD = "\033[1;37m"; // WHITE // Underline public static final String BLACK_UNDERLINED = "\033[4;30m"; // BLACK public static final String RED_UNDERLINED = "\033[4;31m"; // RED public static final String GREEN_UNDERLINED = "\033[4;32m"; // GREEN public static final String YELLOW_UNDERLINED = "\033[4;33m"; // YELLOW public static final String BLUE_UNDERLINED = "\033[4;34m"; // BLUE public static final String PURPLE_UNDERLINED = "\033[4;35m"; // PURPLE public static final String CYAN_UNDERLINED = "\033[4;36m"; // CYAN public static final String WHITE_UNDERLINED = "\033[4;37m"; // WHITE // Background public static final String BLACK_BACKGROUND = "\033[40m"; // BLACK public static final String RED_BACKGROUND = "\033[41m"; // RED public static final String GREEN_BACKGROUND = "\033[42m"; // GREEN public static final String YELLOW_BACKGROUND = "\033[43m"; // YELLOW public static final String BLUE_BACKGROUND = "\033[44m"; // BLUE public static final String PURPLE_BACKGROUND = "\033[45m"; // PURPLE public static final String CYAN_BACKGROUND = "\033[46m"; // CYAN public static final String WHITE_BACKGROUND = "\033[47m"; // WHITE // High Intensity public static final String BLACK_BRIGHT = "\033[0;90m"; // BLACK public static final String RED_BRIGHT = "\033[0;91m"; // RED public static final String GREEN_BRIGHT = "\033[0;92m"; // GREEN public static final String YELLOW_BRIGHT = "\033[0;93m"; // YELLOW public static final String BLUE_BRIGHT = "\033[0;94m"; // BLUE public static final String PURPLE_BRIGHT = "\033[0;95m"; // PURPLE public static final String CYAN_BRIGHT = "\033[0;96m"; // CYAN public static final String WHITE_BRIGHT = "\033[0;97m"; // WHITE // Bold High Intensity public static final String BLACK_BOLD_BRIGHT = "\033[1;90m"; // BLACK public static final String RED_BOLD_BRIGHT = "\033[1;91m"; // RED public static final String GREEN_BOLD_BRIGHT = "\033[1;92m"; // GREEN public static final String YELLOW_BOLD_BRIGHT = "\033[1;93m";// YELLOW public static final String BLUE_BOLD_BRIGHT = "\033[1;94m"; // BLUE public static final String PURPLE_BOLD_BRIGHT = "\033[1;95m";// PURPLE public static final String CYAN_BOLD_BRIGHT = "\033[1;96m"; // CYAN public static final String WHITE_BOLD_BRIGHT = "\033[1;97m"; // WHITE // High Intensity backgrounds public static final String BLACK_BACKGROUND_BRIGHT = "\033[100m";// BLACK public static final String RED_BACKGROUND_BRIGHT = "\033[101m";// RED public static final String GREEN_BACKGROUND_BRIGHT = "\033[102m";// GREEN public static final String YELLOW_BACKGROUND_BRIGHT = "\033[103m";// YELLOW public static final String BLUE_BACKGROUND_BRIGHT = "\033[104m";// BLUE public static final String PURPLE_BACKGROUND_BRIGHT = "\033[105m"; // PURPLE public static final String CYAN_BACKGROUND_BRIGHT = "\033[106m"; // CYAN public static final String WHITE_BACKGROUND_BRIGHT = "\033[107m"; // WHITE public enum ConsoleType {FOADA, ANTLR4, Java, JavaSMT}; public static void printInfo(ConsoleType t, String m) { System.out.print(CYAN_BRIGHT); String console = ""; switch(t) { case FOADA: console = "FOADA"; break; case ANTLR4:console = "ANTLR4"; break; case Java:console = "Java"; break; case JavaSMT:console = "JavaSMT"; break; default:console = "*"; break; } System.out.println(console + " > " + RESET + m); } public static void printError(ConsoleType t, String m) { System.out.print(RED_BRIGHT); String console = ""; switch(t) { case FOADA: console = "FOADA"; break; case ANTLR4:console = "ANTLR4"; break; case Java:console = "Java"; break; case JavaSMT:console = "JavaSMT"; break; default:console = "*"; break; } System.out.println(console + " > " + RESET + m); } // FOADA Special Console Print public static void printFOADAEndOfSession() { printInfo(ConsoleType.FOADA, "End of session.\n"); } }
6,059
42.285714
82
java
FOADA
FOADA-master/src/utility/ErrorListenerWithExceptions.java
/* FOADA Copyright (C) 2018 Xiao XU & Radu IOSIF This file is part of FOADA. FOADA is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. If you have any questions, please contact Xiao XU <[email protected]>. */ package utility; import org.antlr.v4.runtime.BaseErrorListener; import org.antlr.v4.runtime.RecognitionException; import org.antlr.v4.runtime.Recognizer; import org.antlr.v4.runtime.misc.ParseCancellationException; public class ErrorListenerWithExceptions extends BaseErrorListener { public static final ErrorListenerWithExceptions listener = new ErrorListenerWithExceptions(); @Override public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) throws ParseCancellationException { throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + msg); } }
1,509
34.952381
147
java