Search in sources :

Example 1 with LocationType

use of abs.frontend.typechecker.locationtypes.LocationType in project abstools by abstools.

the class LocationTypeTests method testAwaitFailRewriteOff.

@Test
public void testAwaitFailRewriteOff() {
    LocationType lt = LocationType.INFER;
    Model.doAACrewrite = false;
    Model m = assertParseOkStdLib("interface T { Unit foo(); } class C { T t = null; Unit bar() { await t!foo(); }}");
    // This line is essential to trigger the NPE!
    assertFalse(m.hasErrors());
    LocationTypeInferrerExtension ltie = new LocationTypeInferrerExtension(m);
    ltie.setDefaultType(lt);
    ltie.setLocationTypingPrecision(LocationTypingPrecision.CLASS_LOCAL_FAR);
    m.registerTypeSystemExtension(ltie);
    m.getErrors();
    SemanticConditionList e = m.typeCheck();
    Model.doAACrewrite = true;
}
Also used : LocationTypeInferrerExtension(abs.frontend.typechecker.locationtypes.infer.LocationTypeInferrerExtension) SemanticConditionList(abs.frontend.analyser.SemanticConditionList) Model(abs.frontend.ast.Model) LocationType(abs.frontend.typechecker.locationtypes.LocationType) Test(org.junit.Test) FrontendTest(abs.frontend.FrontendTest)

Example 2 with LocationType

use of abs.frontend.typechecker.locationtypes.LocationType in project abstools by abstools.

the class FileAddLocationHandler method execute.

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveMenuSelection(event);
    Object firstElement = selection.getFirstElement();
    if (firstElement instanceof IFile) {
        IFile file = (IFile) firstElement;
        IProject project = file.getProject();
        AbsNature nature = UtilityFunctions.getAbsNature(project);
        if (nature == null)
            return null;
        IPersistentPreferenceStore projectStore = nature.getProjectPreferenceStore();
        boolean locationTypecheckingEnabled = projectStore.getBoolean(Constants.LOCATION_TYPECHECK);
        if (!locationTypecheckingEnabled) {
            MessageDialog.openInformation(Display.getDefault().getActiveShell(), "Locationtypechecking", "Location type checking is disabled. Please enable for this function to work!");
            return null;
        }
        UtilityFunctions.saveEditor(file, false);
        Map<LocationTypeVariable, LocationType> locationTypeInferrerResult = nature.getLocationTypeInferrerResult();
        if (locationTypeInferrerResult != null) {
            Map<LocationTypeVariable, LocationType> filteredResults = new HashMap<LocationTypeVariable, LocationType>();
            ASTNode<?> node;
            CompilationUnit cu;
            for (Entry<LocationTypeVariable, LocationType> entry : locationTypeInferrerResult.entrySet()) {
                node = entry.getKey().getNode();
                if (node == null)
                    continue;
                cu = node.getCompilationUnit();
                if (cu == null)
                    continue;
                if (file.getLocation().toFile().getAbsolutePath().equals(cu.getFileName())) {
                    filteredResults.put(entry.getKey(), entry.getValue());
                }
            }
            InferMain inferMain = new InferMain();
            String commandId = event.getCommand().getId();
            if ("org.abs-models.abs.plugin.fileaddalllocations".equals(commandId)) {
                inferMain.setConfig(InferMain.Config.values());
            } else if ("org.abs-models.abs.plugin.fileaddclasslocations".equals(commandId)) {
                inferMain.setConfig(InferMain.Config.CLASSES);
            } else if ("org.abs-models.abs.plugin.fileaddfieldlocations".equals(commandId)) {
                inferMain.setConfig(InferMain.Config.FIELDS);
            } else if ("org.abs-models.abs.plugin.fileaddfunctionlocations".equals(commandId)) {
                inferMain.setConfig(InferMain.Config.FUNCTIONS);
            } else if ("org.abs-models.abs.plugin.fileaddinterfacelocations".equals(commandId)) {
                inferMain.setConfig(InferMain.Config.INTERFACES);
            }
            try {
                inferMain.writeInferenceResultsBack(filteredResults);
                try {
                    file.refreshLocal(IResource.DEPTH_INFINITE, null);
                } catch (CoreException e) {
                    Activator.logException(e);
                }
            } catch (IOException e) {
                MessageDialog.openError(Display.getDefault().getActiveShell(), "Error while inserting locations", "An error occurred while inserting locations!\n" + e.getLocalizedMessage());
            }
        }
    }
    return null;
}
Also used : CompilationUnit(abs.frontend.ast.CompilationUnit) IFile(org.eclipse.core.resources.IFile) InferMain(abs.frontend.typechecker.locationtypes.infer.InferMain) HashMap(java.util.HashMap) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) IOException(java.io.IOException) IProject(org.eclipse.core.resources.IProject) IPersistentPreferenceStore(org.eclipse.jface.preference.IPersistentPreferenceStore) LocationTypeVariable(abs.frontend.typechecker.locationtypes.infer.LocationTypeVariable) CoreException(org.eclipse.core.runtime.CoreException) LocationType(abs.frontend.typechecker.locationtypes.LocationType) AbsNature(org.absmodels.abs.plugin.builder.AbsNature)

Example 3 with LocationType

use of abs.frontend.typechecker.locationtypes.LocationType in project abstools by abstools.

the class SatGenerator method generate.

public Map<LocationTypeVariable, LocationType> generate() {
    long startNanos = System.nanoTime();
    Map<LocationTypeVariable, LocationType> tvl = new HashMap<>();
    for (Constraint c : constraints) {
        if (enableDebug)
            System.out.println(c);
        List<List<Integer>> gen = c.generateSat(e);
        output.addAll(gen);
        c.variables(vars);
    }
    long genNanos = System.nanoTime();
    if (enableStats) {
        System.out.println("Constraint generation time: " + (genNanos - startNanos) / 1000000);
    }
    StringBuilder weights = new StringBuilder();
    int countNiceConstraints = 0;
    for (LocationTypeVariable tv : vars) {
        if (tv.getNode() != null) {
            countNiceConstraints++;
            weights.append(Constraint.NICE_TO_HAVE);
            weights.append(" ");
            weights.append(e.get(tv, LocationType.NEAR));
            weights.append(" ");
            weights.append(e.get(tv, LocationType.FAR));
            weights.append(" ");
            for (LocationType lt : tv.parametricFarTypes()) {
                weights.append(e.get(tv, lt));
                weights.append(" ");
            }
            weights.append("0\n");
        }
    }
    StringBuilder sb = new StringBuilder();
    int nbclauses = output.size() + countNiceConstraints;
    int nbvars = e.current;
    addInitLine(sb, nbclauses, nbvars);
    // update should_have
    int newShouldHave = countNiceConstraints * Constraint.NICE_TO_HAVE + 1;
    for (List<Integer> line : output) {
        if (line.get(0).equals(Constraint.SHOULD_HAVE)) {
            line.set(0, newShouldHave);
        }
    }
    // System.out.println("SHOULD_HAVE value: "+ newShouldHave);
    try {
        for (List<Integer> line : output) {
            for (Integer i : line) {
                sb.append(i);
                sb.append(" ");
            }
            sb.append("0\n");
        }
    } catch (Exception e) {
        System.out.println(sb.length());
        throw e;
    }
    sb.append(weights);
    if (enableStats) {
        System.out.println("Number of variables: " + nbvars);
        System.out.println("Number of clauses: " + nbclauses);
    }
    // System.out.println(sb);
    // instance().defaultSolver();
    IPBSolver solver = org.sat4j.maxsat.SolverFactory.newDefault();
    // IPBSolver solver = org.sat4j.pb.SolverFactory.newBoth();
    // System.exit(0);
    WeightedMaxSatDecorator wmsd = new WeightedMaxSatDecorator(solver);
    WDimacsReader reader = new WDimacsReader(wmsd);
    try {
        InputStream is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
        IProblem problem = reader.parseInstance(is);
        long parseNanos = System.nanoTime();
        if (enableStats) {
            System.out.println("Parsing time: " + (parseNanos - genNanos) / 1000000);
        }
        if (enableStats) {
            System.gc();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            System.gc();
        }
        OptToPBSATAdapter opt = new OptToPBSATAdapter(wmsd);
        opt.setVerbose(false);
        // opt.setTimeoutMs(10000);
        // parseNanos = System.nanoTime();
        // opt.setTimeout(arg0)
        parseNanos = System.nanoTime();
        if (opt.isSatisfiable()) {
            int[] model = opt.model();
            long solveNanos = System.nanoTime();
            if (enableStats) {
                System.out.println("Solving time: " + (solveNanos - parseNanos) / 1000000);
                System.out.println("Total time: " + (solveNanos - startNanos) / 1000000);
            }
            // System.out.println(Arrays.toString(model));
            for (int i : model) {
                if (i > 0) /*&& i <= nbvars*/
                {
                    TypedVar tv = e.vars().get(i - 1);
                    // System.out.println(tv.v + " : " + tv.t);
                    tvl.put(tv.v, tv.t);
                }
            }
            if (enableDebug)
                System.out.println("Solution: " + tvl);
            if (enableStats) {
                int fars = 0;
                int sws = 0;
                int nears = 0;
                int paramfars = 0;
                for (Entry<LocationTypeVariable, LocationType> e : tvl.entrySet()) {
                    if (e.getKey().getNode() != null) {
                        LocationType t = e.getValue();
                        if (t.isFar())
                            fars++;
                        if (t.isParametricFar())
                            paramfars++;
                        if (t.isNear())
                            nears++;
                        if (t.isSomewhere())
                            sws++;
                    }
                }
                System.out.println("Fars: " + fars);
                System.out.println("Somewheres: " + sws);
                System.out.println("Nears: " + nears);
                System.out.println("Parametric Fars: " + paramfars);
                System.out.println("Total: " + (fars + sws + nears + paramfars));
            }
        } else {
            return null;
        }
        return tvl;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ContradictionException e) {
    // TODO Auto-generated catch block
    // e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}
Also used : IPBSolver(org.sat4j.pb.IPBSolver) WDimacsReader(org.sat4j.maxsat.reader.WDimacsReader) HashMap(java.util.HashMap) ContradictionException(org.sat4j.specs.ContradictionException) FileNotFoundException(java.io.FileNotFoundException) ParseFormatException(org.sat4j.reader.ParseFormatException) SemanticConditionList(abs.frontend.analyser.SemanticConditionList) ArrayList(java.util.ArrayList) List(java.util.List) TimeoutException(org.sat4j.specs.TimeoutException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) WeightedMaxSatDecorator(org.sat4j.maxsat.WeightedMaxSatDecorator) IProblem(org.sat4j.specs.IProblem) ContradictionException(org.sat4j.specs.ContradictionException) IOException(java.io.IOException) ParseFormatException(org.sat4j.reader.ParseFormatException) FileNotFoundException(java.io.FileNotFoundException) TimeoutException(org.sat4j.specs.TimeoutException) ByteArrayInputStream(java.io.ByteArrayInputStream) OptToPBSATAdapter(org.sat4j.pb.OptToPBSATAdapter) LocationType(abs.frontend.typechecker.locationtypes.LocationType)

Example 4 with LocationType

use of abs.frontend.typechecker.locationtypes.LocationType in project abstools by abstools.

the class IncrementalModelBuilder method typeCheckModel.

public synchronized SemanticConditionList typeCheckModel(IProgressMonitor monitor, boolean locationTypeChecking, String defaultloctype, String locationTypePrecision, boolean checkProducts) throws NoModelException, TypecheckInternalException {
    if (model == null)
        throw new NoModelException();
    if (model.hasParserErrors())
        // don't typecheck if the model has parsererrors
        return new SemanticConditionList();
    // throw new TypecheckInternalException(new Exception("Model has parser errors!"));
    // model.flushCache();
    flushAll(model);
    model.getTypeExt().clearTypeSystemExtensions();
    if (locationTypeChecking) {
        LocationType defaultLocType = LocationType.createFromName(defaultloctype);
        LocationTypeInferrerExtension ltie = new LocationTypeInferrerExtension(model);
        this.ltie = ltie;
        ltie.setDefaultType(defaultLocType);
        ltie.setLocationTypingPrecision(LocationTypingPrecision.valueOf(locationTypePrecision));
        model.registerTypeSystemExtension(ltie);
    }
    try {
        SemanticConditionList semerrors = model.getErrors();
        /* Don't typecheck with semerrors, it might trip up. */
        if (!semerrors.containsErrors())
            semerrors = model.typeCheck();
        /* Check products for errors.
			 * Only the first error is reported (if any), on the product AST-node.
			 * TODO: May be time-consuming for large projects, hence the checkProducts-switch.
			 *       Also could use a timer to switch off if it becomes excessive.
			 * TODO: Use Eclipse's nested markers to show ALL contained errors?
			 * TODO: The outline could indicate the broken product as well.
			 */
        if (!semerrors.containsErrors() && checkProducts) {
            // arbitrary value
            monitor = new SubProgressMonitor(monitor, 10);
            monitor.beginTask("Checking products", model.getProductDecls().size());
            for (ProductDecl p : model.getProductDecls()) {
                monitor.subTask("Checking " + p.getName());
                Model m2 = model.treeCopyNoTransform();
                m2.flushTreeCache();
                try {
                    m2.flattenForProduct(p);
                    SemanticConditionList p_errs = m2.typeCheck();
                    if (p_errs.containsErrors()) {
                        // Only show first error, on product
                        semerrors.add(new SemanticError(p, ErrorMessage.ERROR_IN_PRODUCT, p.getName(), p_errs.getFirstError().getMessage()));
                    }
                } catch (WrongProgramArgumentException e) {
                    semerrors.add(new SemanticError(p, ErrorMessage.ERROR_IN_PRODUCT, p.getName(), e.getMessage()));
                } catch (DeltaModellingException e) {
                    /* We we have a better location for error reporting? */
                    final ASTNode<?> loc;
                    if (e instanceof DeltaModellingWithNodeException)
                        loc = ((DeltaModellingWithNodeException) e).getNode();
                    else
                        loc = p;
                    if (e.getDelta() == null)
                        semerrors.add(new SemanticError(loc, ErrorMessage.ERROR_IN_PRODUCT, p.getName(), e.getMessage()));
                    else
                        semerrors.add(new SemanticError(loc, ErrorMessage.ERROR_IN_PRODUCT_WITH_DELTA, p.getName(), e.getDelta().getName(), e.getMessage()));
                }
            }
            monitor.done();
        }
        return semerrors;
    } catch (TypeCheckerException e) {
        return new SemanticConditionList(e);
    } catch (RuntimeException e) {
        throw new TypecheckInternalException(e);
    }
}
Also used : ProductDecl(abs.frontend.ast.ProductDecl) WrongProgramArgumentException(abs.common.WrongProgramArgumentException) DeltaModellingWithNodeException(abs.frontend.delta.DeltaModellingWithNodeException) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor) LocationTypeInferrerExtension(abs.frontend.typechecker.locationtypes.infer.LocationTypeInferrerExtension) TypeCheckerException(abs.frontend.typechecker.TypeCheckerException) SemanticConditionList(abs.frontend.analyser.SemanticConditionList) SemanticError(abs.frontend.analyser.SemanticError) Model(abs.frontend.ast.Model) ASTNode(abs.frontend.ast.ASTNode) LocationType(abs.frontend.typechecker.locationtypes.LocationType) DeltaModellingException(abs.frontend.delta.DeltaModellingException)

Example 5 with LocationType

use of abs.frontend.typechecker.locationtypes.LocationType in project abstools by abstools.

the class LocationTypeTests method testAwaitFail.

@Test
public void testAwaitFail() {
    LocationType lt = LocationType.INFER;
    Model m = assertParseOkStdLib("interface T { Unit foo(); } class C { T t = null; Unit bar() { await t!foo(); }}");
    // This line is essential to trigger the NPE!
    assertFalse(m.hasErrors());
    LocationTypeInferrerExtension ltie = new LocationTypeInferrerExtension(m);
    ltie.setDefaultType(lt);
    ltie.setLocationTypingPrecision(LocationTypingPrecision.CLASS_LOCAL_FAR);
    m.registerTypeSystemExtension(ltie);
    m.getErrors();
    SemanticConditionList e = m.typeCheck();
}
Also used : LocationTypeInferrerExtension(abs.frontend.typechecker.locationtypes.infer.LocationTypeInferrerExtension) SemanticConditionList(abs.frontend.analyser.SemanticConditionList) Model(abs.frontend.ast.Model) LocationType(abs.frontend.typechecker.locationtypes.LocationType) Test(org.junit.Test) FrontendTest(abs.frontend.FrontendTest)

Aggregations

LocationType (abs.frontend.typechecker.locationtypes.LocationType)13 SemanticConditionList (abs.frontend.analyser.SemanticConditionList)6 LocationTypeInferrerExtension (abs.frontend.typechecker.locationtypes.infer.LocationTypeInferrerExtension)6 Model (abs.frontend.ast.Model)5 FrontendTest (abs.frontend.FrontendTest)3 LocationTypeVariable (abs.frontend.typechecker.locationtypes.infer.LocationTypeVariable)3 IOException (java.io.IOException)3 IPersistentPreferenceStore (org.eclipse.jface.preference.IPersistentPreferenceStore)3 Test (org.junit.Test)3 ClassDecl (abs.frontend.ast.ClassDecl)2 InferMain (abs.frontend.typechecker.locationtypes.infer.InferMain)2 HashMap (java.util.HashMap)2 AbsNature (org.absmodels.abs.plugin.builder.AbsNature)2 IProject (org.eclipse.core.resources.IProject)2 CoreException (org.eclipse.core.runtime.CoreException)2 IStructuredSelection (org.eclipse.jface.viewers.IStructuredSelection)2 WrongProgramArgumentException (abs.common.WrongProgramArgumentException)1 HasCogs (abs.frontend.analyser.HasCogs)1 SemanticError (abs.frontend.analyser.SemanticError)1 ASTNode (abs.frontend.ast.ASTNode)1