com.concurnas.runtime.Pair

Here are the examples of the java api com.concurnas.runtime.Pair taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

82 Examples 7

19 Source : BytecodeTests.java
with MIT License
from Concurnas

public static MockFileLoader produceLoader(String srcdir, String inputFile, String code) {
    ArrayList<Pair<String, String>> fnameAndCodes = extractToModules(inputFile, code);
    MockFileLoader mockLoader = new MockFileLoader(srcdir);
    for (Pair<String, String> fnameData : fnameAndCodes) {
        mockLoader.addFile(srcdir + FileLoader.pathSeparatorChar + fnameData.getA(), fnameData.getB());
    }
    return mockLoader;
}

19 Source : OffHeapEncoder.java
with MIT License
from Concurnas

private void malloc(Object myclreplaced, int size) {
    allocated = true;
    // test = new byte[this.putSoFar];
    Pair<ByteBuffer, Long> bbandAddress = mallocprovider.malloc(size);
    buffer = bbandAddress.getA();
    // buffer.position();
    mallocAddress = bbandAddress.getB();
    // System.err.println("got mallocprovider: " + mallocprovider);
    // System.err.println("got mallocprovider buffer: " + buffer);
    // System.err.println("got mallocAddress: " + mallocAddress);
    // buffer = ByteBuffer.allocate(this.putSoFar);
    putSoFar = 0;
}

19 Source : Utils.java
with MIT License
from Concurnas

private static Pair<FuncType, Pair<NamedType, TypeAndLocation>> getFuncTypeForAnonLambdareplacedign(ScopeAndTypeChecker satc, Type potential) {
    // see if we are mapping to a functype or a Single abstract method
    if (potential instanceof FuncType) {
        return new Pair<FuncType, Pair<NamedType, TypeAndLocation>>((FuncType) potential, null);
    } else if (potential instanceof NamedType) {
        NamedType asNamed = (NamedType) potential;
        if (asNamed.isInterface()) {
            List<Pair<String, TypeAndLocation>> methods = asNamed.getAllLocallyDefinedMethods(satc, true, false);
            if (methods.size() == 1) {
                Pair<String, TypeAndLocation> inst = methods.get(0);
                FuncType ft = (FuncType) inst.getB().getType();
                if (!ft.signatureExpectedToChange) {
                    return new Pair<FuncType, Pair<NamedType, TypeAndLocation>>(ft, new Pair<NamedType, TypeAndLocation>(asNamed, inst.getB()));
                }
            }
        }
    }
    return null;
}

19 Source : Utils.java
with MIT License
from Concurnas

public static Pair<List<Pair<String, Boolean>>, List<Pair<String, Boolean>>> filterNullInferMap(List<HashMap<Pair<String, Boolean>, NullStatus>> inferedNullinBlocks) {
    HashMap<Pair<String, Boolean>, NullStatus> base = inferedNullinBlocks.remove(0);
    List<Pair<String, Boolean>> nonnull = new ArrayList<Pair<String, Boolean>>();
    List<Pair<String, Boolean>> nullable = new ArrayList<Pair<String, Boolean>>();
    for (Pair<String, Boolean> key : base.keySet()) {
        NullStatus ns = base.get(key);
        Set<NullStatus> nss = new HashSet<NullStatus>();
        nss.add(ns);
        for (HashMap<Pair<String, Boolean>, NullStatus> inst : inferedNullinBlocks) {
            nss.add(inst.get(key));
        }
        List<Pair<String, Boolean>> addTo = (nss.size() > 1 || nss.contains(NullStatus.NULLABLE)) ? nullable : nonnull;
        addTo.add(key);
    }
    return new Pair<List<Pair<String, Boolean>>, List<Pair<String, Boolean>>>(nonnull, nullable);
}

19 Source : ConstantFolding.java
with MIT License
from Concurnas

@Override
public Object visit(Annotation annotation) {
    super.visit(annotation);
    if (annotation.singleArg != null) {
        // .accept(this);
        Object got = checkAnnotationArgument(annotation.singleArg);
        if (null == got) {
            // doesnt resolved to a constant expression
            PrintSourceVisitor psv = new PrintSourceVisitor();
            annotation.singleArg.accept(psv);
            this.raiseError(annotation.singleArg.getLine(), annotation.singleArg.getColumn(), String.format("Argument preplaceded to annotation must resolve to constant at compilation time. This does not: %s", psv));
        }
    } else if (annotation.manyArgs != null && !annotation.manyArgs.isEmpty()) {
        for (Pair<String, Expression> kv : annotation.manyArgs) {
            String key = kv.getA();
            Expression v = kv.getB();
            Object value = checkAnnotationArgument(v);
            if (value == null) {
                PrintSourceVisitor psv = new PrintSourceVisitor();
                v.accept(psv);
                this.raiseError(annotation.getLine(), annotation.getColumn(), String.format("Argument preplaceded to annotation must resolve to constant at compilation time. This does not: %s = %s", key, psv));
            }
        }
    }
    return annotation.setFoldedConstant(annotation);
}

19 Source : AbstractVisitor.java
with MIT License
from Concurnas

@Override
public Object visit(AnonLambdaDef anonLambdaDef) {
    anonLambdaDef.body.accept(this);
    ArrayList<Pair<String, Type>> inputs = anonLambdaDef.getInputs();
    int sz = inputs.size();
    for (int n = 0; n < sz; n++) {
        Pair<String, Type> inst = inputs.get(n);
        Type tt = inst.getB();
        if (tt != null) {
            tt.accept(this);
        }
    }
    if (null != anonLambdaDef.retType) {
        anonLambdaDef.retType.accept(this);
    }
    return null;
}

19 Source : AbstractVisitor.java
with MIT License
from Concurnas

protected void processArrayElements(ArrayRefLevelElementsHolder elements) {
    for (Pair<Boolean, ArrayList<ArrayRefElement>> levels : elements.getAll()) {
        ArrayList<ArrayRefElement> brackset = levels.getB();
        for (int n = 0; n < brackset.size(); n++) {
            brackset.get(n).accept(this);
        }
    }
}

19 Source : AbstractVisitor.java
with MIT License
from Concurnas

@Override
public Object visit(FuncInvokeArgs funcInvokeArgs) {
    // lastLineVisited=funcInvokeArgs.getLine();
    /*List<Expression> args = funcInvokeArgs.getArgumentsWNPs();
		if(args == null) {
			args = funcInvokeArgs.asnames;
		}*/
    for (Expression e : funcInvokeArgs.asnames) {
        if (null != e) {
            e.accept(this);
        }
    }
    for (Pair<String, Object> thing : funcInvokeArgs.nameMap) {
        ((Expression) thing.getB()).accept(this);
    }
    return null;
}

19 Source : AbstractVisitor.java
with MIT License
from Concurnas

@Override
public Object visit(FuncRefArgs funcRefArgs) {
    // lastLineVisited=funcRefArgs.getLine();
    for (Object item : funcRefArgs.exprOrTypeArgsList) {
        if (item instanceof Expression) {
            ((Expression) item).accept(this);
        } else if (item instanceof Type) {
            ((Type) item).accept(this);
        }
    }
    for (Pair<String, Object> thing : funcRefArgs.nameMap) {
        Object item = thing.getB();
        if (item instanceof Expression) {
            ((Expression) item).accept(this);
        } else if (item instanceof Type) {
            ((Type) item).accept(this);
        }
    }
    return null;
}

19 Source : LabelAllocator.java
with MIT License
from Concurnas

/*@Override
	public Object visit(WithBlock withBlock) {
		return super.visit(withBlock);//TODO when with impl later
	}
	*/
private void allocateLabelsPriorToInsertedFinalCode(PreEntryCode retStmt) {
    Stack<Pair<Label, Block>> finCodes = retStmt.getLinesToVisitOnEntry();
    if (!finCodes.isEmpty()) {
        Label labelAfterInsertedCode = new Label();
        // the label to conitue on from is the next which is non null after this one unless you get to the end in which case revert to  labelAfterInsertedCode
        int fcSize = finCodes.size();
        for (int n = 0; n < fcSize; n++) {
            Pair<Label, Block> level = finCodes.get(n);
            if (level.getA() != null) {
                Label nextLabel = labelAfterInsertedCode;
                int m = n + 1;
                while (m <= fcSize - 1) {
                    if (finCodes.get(m).getA() != null) {
                        nextLabel = finCodes.get(m).getA();
                        break;
                    }
                    m++;
                }
                labelNeedingConsumption.push(new Pair<Label, Label>(null, nextLabel));
                this.visit(level.getB());
                labelNeedingConsumption.pop();
            }
        }
        retStmt.setLabelToVisitJustBeforeReturnOpCode(labelAfterInsertedCode);
    }
}

19 Source : LabelAllocator.java
with MIT License
from Concurnas

private void consumeLabelIfAny(Node nd) {
    if (!(nd instanceof ClreplacedDef || nd instanceof FuncDefI)) {
        if (!labelNeedingConsumption.isEmpty() && null != labelNeedingConsumption.peek().getB()) {
            Pair<Label, Label> startEnd = labelNeedingConsumption.pop();
            Label lowes = startEnd.getB();
            nd.setLabelOnEntry(lowes);
            labelNeedingConsumption.push(new Pair<Label, Label>(startEnd.getA(), null));
        }
    }
}

19 Source : LabelAllocator.java
with MIT License
from Concurnas

private void overriteNextLabelToContinueOnFromBranch(Label with) {
    Pair<Label, Label> whileStartEnd = labelNeedingConsumption.pop();
    labelNeedingConsumption.push(new Pair<Label, Label>(whileStartEnd.getA(), with));
}

19 Source : LabelAllocator.java
with MIT License
from Concurnas

private Label getNextLabelToContinueFrom(Label startOfLoop) {
    Label found = null;
    if (this.isLastLineInBlock) {
        // pop from stack
        int sz = labelNeedingConsumption.size() - 2;
        while (sz >= 0) {
            // from end to start
            Pair<Label, Label> whileStartEnd = labelNeedingConsumption.get(sz);
            Label blkStart = whileStartEnd.getA();
            Label blkEnd = whileStartEnd.getB();
            // goto start if in while loop, otherwise not
            found = blkStart != null ? blkStart : blkEnd;
            if (null != found) {
                break;
            }
            sz--;
        }
    }
    if (null == found) {
        found = new Label();
        labelNeedingConsumption.pop();
        labelNeedingConsumption.push(new Pair<Label, Label>(startOfLoop, found));
    }
    return found;
}

19 Source : LabelAllocator.java
with MIT License
from Concurnas

private void overriteNextLabelToContinueOnFrom(Label with) {
    Pair<Label, Label> whileStartEnd = labelNeedingConsumption.pop();
    labelNeedingConsumption.push(new Pair<Label, Label>(with, whileStartEnd.getB()));
}

19 Source : ClassDefJava.java
with MIT License
from Concurnas

@Override
public Annotations getAnnotations() {
    if (anotscache == null) {
        ArrayList<Annotation> annotations = new ArrayList<Annotation>();
        java.lang.annotation.Annotation[] xxx = this.cls.getAnnotations();
        for (java.lang.annotation.Annotation an : xxx) {
            Clreplaced<?> cls = an.annotationType();
            ArrayList<Pair<String, Expression>> args = new ArrayList<Pair<String, Expression>>();
            for (Method mx : cls.getDeclaredMethods()) {
                try {
                    Object what = mx.invoke(an, null);
                    VarNull dummy = new VarNull();
                    dummy.setFoldedConstant(what);
                    Pair<String, Expression> item = new Pair<String, Expression>(mx.getName(), dummy);
                    args.add(item);
                }// meh
                 catch (Throwable e) {
                }
            }
            Annotation anot = new Annotation(0, 0, cls.getCanonicalName(), null, args, new ArrayList<String>());
            anot.setTaggedType(new NamedType(0, 0, new ClreplacedDefJava(cls)));
            annotations.add(anot);
        }
        anotscache = new Annotations(0, 0, annotations);
    }
    return anotscache;
}

19 Source : ClassDef.java
with MIT License
from Concurnas

private void setGenericList(ArrayList<Pair<String, NamedType>> clreplacedGenricList) {
    // TODO: add upper bound restriuctions clreplaced A[X extends List] etc -> A[X <: List]
    this.clreplacedGenricList = new ArrayList<GenericType>(clreplacedGenricList.size());
    int n = 0;
    for (Pair<String, NamedType> nameandType : clreplacedGenricList) {
        String name = nameandType.getA();
        GenericType gen = new GenericType(this.getLine(), this.getColumn(), name, n++);
        this.clreplacedGenricList.add(gen);
        NamedType upperBound = nameandType.getB();
        if (null != upperBound) {
            gen.upperBound = upperBound;
            gen.setNullStatus(upperBound.getNullStatus());
        }
        nameToGenericMap.put(name, gen);
    }
}

19 Source : ArrayRefLevelElementsHolder.java
with MIT License
from Concurnas

public void prepend(ArrayList<ArrayRefElement> item) {
    Pair<Boolean, ArrayList<ArrayRefElement>> itemx = new Pair<Boolean, ArrayList<ArrayRefElement>>(false, item);
    items.add(0, itemx);
}

19 Source : ArrayRefLevelElementsHolder.java
with MIT License
from Concurnas

public void add(boolean isNullSafe, ArrayList<ArrayRefElement> item) {
    Pair<Boolean, ArrayList<ArrayRefElement>> itemx = new Pair<Boolean, ArrayList<ArrayRefElement>>(isNullSafe, item);
    items.add(itemx);
}

19 Source : Annotation.java
with MIT License
from Concurnas

public ArrayList<Thruple<String, Expression, Type>> getArguments() {
    ArrayList<Thruple<String, Expression, Type>> args = new ArrayList<Thruple<String, Expression, Type>>();
    if (this.singleArg != null) {
        args.add(new Thruple<String, Expression, Type>(this.singleArgFeildName, this.singleArg, this.keyToType.get(this.singleArgFeildName)));
    } else if (this.manyArgs != null && !this.manyArgs.isEmpty()) {
        for (Pair<String, Expression> ma : this.manyArgs) {
            args.add(new Thruple<String, Expression, Type>(ma.getA(), ma.getB(), this.keyToType.get(ma.getA())));
        }
    // args = this.manyArgs;//:null;
    }
    return args;
}

18 Source : ConcSemanticsTests.java
with MIT License
from Concurnas

@Test
public void simpleValidClreplacedRequestImplicitClreplaced() throws IOException {
    String code = "def main() void => System.err.println('hey')";
    Pair<ConccTestMockFileLoader, CLProviderToIMM> mAndP = createMFL("/work", "/work/hg", "MyFirstClreplaced", code);
    // implicit clreplaced ref
    Conc concc = new Conc("/work/hg/MyFirstClreplaced", mAndP.getA(), mAndP.getB());
    TestCase.replacedertNull(concc.validateConcInstance(concc.getConcInstance()).validationErrs);
}

18 Source : ConcSemanticsTests.java
with MIT License
from Concurnas

@Test
public void simpleValidClreplacedRequest() throws Exception {
    String code = "def main() void => System.err.println('hey')";
    Pair<ConccTestMockFileLoader, CLProviderToIMM> mAndP = createMFL("/work", "/work/hg", "MyFirstClreplaced", code);
    // ok
    Conc concc = new Conc("/work/hg/MyFirstClreplaced.clreplaced", mAndP.getA(), mAndP.getB());
    TestCase.replacedertNull(concc.validateConcInstance(concc.getConcInstance()).validationErrs);
}

18 Source : REPL.java
with MIT License
from Concurnas

private static String processNewFuncsDefined(List<Pair<REPLTopLevelComponent, Boolean>> newfuncs) {
    StringBuilder sb = new StringBuilder();
    for (Pair<REPLTopLevelComponent, Boolean> itemx : newfuncs) {
        REPLTopLevelComponent comp = itemx.getA();
        boolean isNew = itemx.getB();
        String formattedName = formatTopLevelElement(comp);
        if (null != formattedName) {
            sb.append("|  ");
            if (isNew) {
                sb.append("created ");
                comp.setSupressErrors(true);
            } else {
                sb.append("redefined ");
            }
            if (comp instanceof FuncDef) {
                FuncDef funcDef = (FuncDef) comp;
                if (funcDef.extFunOn == null) {
                    sb.append("function ");
                } else {
                    sb.append("extension function ");
                    sb.append(funcDef.extFunOn.toString());
                    sb.append('.');
                }
            }
            sb.append(formattedName);
            sb.append('\n');
        }
    }
    return sb.toString().trim();
}

18 Source : OffHeapMalloc.java
with MIT License
from Concurnas

private void closeCreatedFiles(ArrayList<Pair<File, FileChannel>> cfss) {
    if (this.path != null && cfss != null && !cfss.isEmpty()) {
        for (Pair<File, FileChannel> fu : cfss) {
            FileChannel fc = fu.getB();
            try {
                fc.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        for (Pair<File, FileChannel> fu : cfss) {
            File ff = fu.getA();
            if (this.cleanOnClose && ff.exists()) {
                try {
                    Files.delete(ff.toPath());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

18 Source : REPLDepGraphManager.java
with MIT License
from Concurnas

public Object visit(REPLTopLevelComponent comp) {
    if (isTopLevelItem && comp.isNewComponent()) {
        boolean prevIsTop = isTopLevelItem;
        HashSet<String> prevCDeps = currentDependencies;
        isTopLevelItem = false;
        currentDependencies = new HashSet<String>();
        HashSet<Type> typeDependencies = null;
        if (comp instanceof ClreplacedDef || comp instanceof ObjectProvider) {
            HashSet<Type> prevCTDeps = currentTypeDependencies;
            currentTypeDependencies = new HashSet<Type>();
            visitSuperREPLGraphComp(comp);
            typeDependencies = currentTypeDependencies;
            currentTypeDependencies = prevCTDeps;
        } else {
            visitSuperREPLGraphComp(comp);
        }
        if (!currentDependencies.isEmpty()) {
            for (String dep : currentDependencies) {
                HashSet<REPLTopLevelComponent> deps = depMap.get(dep);
                if (deps == null) {
                    deps = new HashSet<REPLTopLevelComponent>();
                    depMap.put(dep, deps);
                }
                deps.add(comp);
            }
        }
        {
            Type tt = comp.getFuncType();
            tt = tt == null ? null : tt.getTaggedType();
            for (String fname : comp.getNames()) {
                HashSet<Pair<Type, HashSet<Type>>> typesForTopLe = topLevelNames.get(fname);
                if (null == typesForTopLe) {
                    typesForTopLe = new HashSet<Pair<Type, HashSet<Type>>>();
                    topLevelNames.put(fname, typesForTopLe);
                }
                // double call to validate whether the type returned is valid or not (e.g. on typedefs or namedTypes)
                Pair<Type, HashSet<Type>> typeAndDependantTypes = new Pair<Type, HashSet<Type>>(tt, typeDependencies);
                typesForTopLe.add(typeAndDependantTypes);
            }
        }
        isTopLevelItem = prevIsTop;
        currentDependencies = prevCDeps;
        this.replState.topLevelItemsToSkip.add(new REPLComponentWrapper(comp));
    } else {
        visitSuperREPLGraphComp(comp);
    }
    return null;
}

18 Source : FieldAccessRepointer.java
with MIT License
from Concurnas

private DotOperator handlePrefixPostFix(Expression expr, replacedignStyleEnum operator, boolean ispostfix, int line, int col) {
    DotOperator rereplacedignTo = null;
    if (expr instanceof DotOperator && !isLastElementArrayRef((DotOperator) expr) && ((DotOperator) expr).getElements(this).size() > 1) {
        // JPT: refactor this nasty copy paste job
        // cls.x[0] = 99; -> cls.getX()[0] = 99; - note that we avoid this case and revert to getter logic, not setter
        DotOperator doreplacedigne = (DotOperator) expr;
        Expression rhsExpression = new VarInt(line, col, 1);
        Type clreplacedofar = processDotOp(doreplacedigne, false);
        ArrayList<Expression> elements = doreplacedigne.getElements(this);
        ArrayList<Boolean> isDirectAccess = doreplacedigne.getIsDirectAccess(this);
        int idxLastE = elements.size() - 1;
        Expression laste = elements.get(idxLastE);
        Expression preve = elements.get(idxLastE - 1);
        boolean lastdirectacc = isDirectAccess.get(isDirectAccess.size() - 1);
        ClreplacedDef clsDottedOn = isEligableForRewrite(lastdirectacc, laste, preve, clreplacedofar, true);
        if (null != clsDottedOn) {
            // e.g. obj.x += 69 -> obj.SYN-getXSetX(PLUS, PREFIX, 69)//note prefix avoids unecisary dup operation
            Pair<Type, String> getter = getGetterSetter(clsDottedOn, laste, true);
            if (null != getter) {
                Pair<Type, String> setter = getGetterSetter(clsDottedOn, laste, false);
                if (null != setter) {
                    laste = gennerateRepointGetSet(laste, getter.getB(), setter.getB(), rhsExpression, operator, ispostfix);
                    elements.set(idxLastE, laste);
                    rereplacedignTo = doreplacedigne;
                }
            }
        }
        laste.accept(this);
    } else {
        // do nothing
        expr.accept(this);
    }
    return rereplacedignTo;
}

18 Source : FieldAccessRepointer.java
with MIT License
from Concurnas

private ClreplacedDef isEligableForRewrite(Boolean directAccess, Expression e, Expression prevE, Type typeSoFar, boolean isGetter) {
    if (!directAccess && !(prevE instanceof RefSuper) && repointableRhs(e)) {
        Type tt = e.getTaggedType();
        if (tt instanceof ModuleType) {
            Type pgt = TypeCheckUtils.getRefType(prevE.getTaggedType());
            if (pgt instanceof NamedType) {
                ClreplacedDef cd = ((NamedType) pgt).getSetClreplacedDef();
                Pair<Type, String> typeAndFuncName = getGetterSetter(cd, e, isGetter, false);
                return typeAndFuncName == null ? null : cd;
            }
            return null;
        }
        if (e instanceof RefName) {
            RefName refName = (RefName) e;
            if (null != refName.resolvesTo) {
                Location loc = refName.resolvesTo.getLocation();
                if (loc instanceof LocationClreplacedField) {
                    LocationClreplacedField aslcf = (LocationClreplacedField) loc;
                    Type owner = aslcf.ownerType;
                    if (owner != null && owner instanceof NamedType) {
                        ClreplacedDef set = ((NamedType) owner).getSetClreplacedDef();
                        if (set != null) {
                            if (!this.currentClreplacedDef.isEmpty()) {
                                ClreplacedDef cd = this.currentClreplacedDef.peek();
                                if (cd.equals(set)) {
                                    // if potentially calling a this or implicit this reference to own 'get/set' function, we wish to avoid inf loop
                                    Expression preceeding = elementPreceededBy.get(e);
                                    if (preceeding == null || preceeding instanceof RefSuper || preceeding instanceof RefThis) {
                                        // abort else we end up, in inf loop
                                        return null;
                                    }
                                }
                            }
                            return set;
                        }
                    }
                }
            }
        }
        ClreplacedDef clsDottedOn = extractClreplacedDottedOn(typeSoFar);
        if (null != clsDottedOn) {
            if (!(typeSoFar.hasArrayLevels() && e instanceof RefName && ((RefName) e).name.equals("length"))) {
                // exception: ar = [1,2,3]; ar.length <- we dont want to remap this
                if (typeSoFar instanceof NamedType && TypeCheckUtils.isTypedActor(ersup, (NamedType) typeSoFar)) {
                    NamedType rootActorType = TypeCheckUtils.extractRootActor((NamedType) typeSoFar);
                    return extractClreplacedDottedOn(rootActorType.getGenTypes().get(0));
                }
                return clsDottedOn;
            }
        }
    }
    return null;
}

18 Source : FieldAccessRepointer.java
with MIT License
from Concurnas

@Override
public DotOperator visit(replacedignExisting replacedignExisting) {
    Expression replacedignee = replacedignExisting.replacedignee;
    DotOperator rereplacedignTo = null;
    if (replacedignee instanceof DotOperator && !isLastElementArrayRef((DotOperator) replacedignee) && ((DotOperator) replacedignee).getElements(this).size() > 1) {
        // obj[2].x = 8 -> obj[2].setX(8)
        // cls.x[0] = 99; -> cls.getX()[0] = 99; - note that we avoid this case and revert to getter logic, not setter
        DotOperator doreplacedigne = (DotOperator) replacedignee;
        ArrayList<Expression> elements = doreplacedigne.getElements(this);
        ArrayList<Boolean> isDirectAccess = doreplacedigne.getIsDirectAccess(this);
        Expression rhsExpression = replacedignExisting.expr;
        Type clreplacedofar = processDotOp(doreplacedigne, false);
        int idxLastE = elements.size() - 1;
        Expression laste = elements.get(idxLastE);
        Expression preve = elements.get(idxLastE - 1);
        boolean lastdirectacc = isDirectAccess.get(isDirectAccess.size() - 1);
        ClreplacedDef clsDottedOn = isEligableForRewrite(lastdirectacc, laste, preve, clreplacedofar, false);
        if (null != clsDottedOn) {
            if (replacedignExisting.eq.isEquals()) {
                boolean forcedRef = replacedignExisting.refCnt > 0;
                Type rhsType = rhsExpression.getTaggedType();
                boolean rhsLockedRef = TypeCheckUtils.hasRefLevelsAndIsLocked(rhsType);
                boolean setterArgExpectRef = forcedRef || rhsLockedRef;
                // setter
                Pair<Type, String> typeAndFuncName = getGetterSetter(clsDottedOn, laste, false, setterArgExpectRef);
                if (null != typeAndFuncName) {
                    // Uh ok
                    if (setterArgExpectRef && !rhsLockedRef) {
                        if (!TypeCheckUtils.hasRefLevels(rhsType)) {
                            // e.g. a.z := d. transform to: a.setZ(d!) [where d is not already a ref]
                            // rhsExpression = new AsyncInvoke(rhsExpression.getLine(), rhsExpression.getColumn(), rhsExpression);
                            // mc.x := "newRef2" -> mc.setX("newRef2" as Object:) where x is of type Object:
                            rhsExpression = new CastExpression(rhsExpression.getLine(), rhsExpression.getColumn(), replacedignExisting.getTaggedType(), rhsExpression);
                        } else {
                            // e.g. a.z := d. transform to: a.setZ((d):) [where d is a ref already]
                            rhsExpression = new AsyncRefRef(rhsExpression.getLine(), rhsExpression.getColumn(), rhsExpression, replacedignExisting.refCnt);
                        }
                    }
                    Type origonalRhsType = TypeCheckUtils.hasRefLevels(rhsType) ? replacedignExisting.getTaggedType() : null;
                    // because this: mc.x := "newRef2"! //where x is ~x Object: of a mcClreplaced -  should blow up! (else it gets set via setX(Object) resutling in double ref, probably not what u want!
                    laste = gennerateRepointSet(laste, typeAndFuncName.getB(), rhsExpression, origonalRhsType);
                    elements.set(idxLastE, laste);
                    rereplacedignTo = doreplacedigne;
                }
            } else {
                // translate into a new GetSetOperation:
                // e.g. obj.x += 69 -> obj.SYN-getXSetX(PLUS, PREFIX, 69)//note prefix avoids unecisary dup operation
                Pair<Type, String> getter = getGetterSetter(clsDottedOn, laste, true);
                if (null != getter) {
                    Pair<Type, String> setter = getGetterSetter(clsDottedOn, laste, false);
                    if (null != setter) {
                        laste = gennerateRepointGetSet(laste, getter.getB(), setter.getB(), rhsExpression, replacedignExisting.eq, false);
                        elements.set(idxLastE, laste);
                        rereplacedignTo = doreplacedigne;
                    }
                }
            }
        }
        laste.accept(this);
    } else {
        replacedignee.accept(this);
        if (null != replacedignExisting.expr) {
            replacedignExisting.expr.accept(this);
        }
    }
    return rereplacedignTo;
}

18 Source : FieldAccessRepointer.java
with MIT License
from Concurnas

private Type processDotOp(DotOperator dotOperator, Boolean processLast) {
    ArrayList<Type> typesSoFar = new ArrayList<Type>();
    ArrayList<Expression> elements = dotOperator.getElements(this);
    for (Expression e : elements) {
        typesSoFar.add(e.getTaggedType());
    }
    Expression head = dotOperator.getHead(this);
    head.accept(this);
    Expression preceeding = head;
    Type typeSoFar = head.getTaggedType();
    for (int n = 1; n < elements.size(); n++) {
        if (processLast || n != elements.size() - 1) {
            boolean directAccess = dotOperator.getIsDirectAccess(this).get(n - 1);
            Expression e = elements.get(n);
            ClreplacedDef clsDottedOn = isEligableForRewrite(directAccess, e, elements.get(n - 1), typeSoFar, true);
            if (null != clsDottedOn) {
                Pair<Type, String> typeAndFuncName = getGetterSetter(clsDottedOn, e, true);
                if (null != typeAndFuncName) {
                    e = gennerateRepointGet(e, typeAndFuncName.getB());
                    elements.set(n, e);
                }
            }
            elementPreceededBy.put(e, preceeding);
            e.accept(this);
            elementPreceededBy.remove(e);
            preceeding = e;
            // on fail revert to prev tagged types and carry on as if
            // nothing happened
            // replacedume no type change
            typeSoFar = typesSoFar.get(n);
        }
    }
    return typeSoFar;
}

18 Source : LambdaDef.java
with MIT License
from Concurnas

public clreplaced LambdaDef extends FuncDefI implements HasExtraCapturedVars, HasAnnotations, AnonLambdaDefOrLambdaDef {

    public FuncParams params = new FuncParams(0, 0);

    public Type returnType;

    public Block body;

    public FuncRef fakeFuncRef;

    public String methodName;

    private FuncParams extraCapturedLocalVars;

    private final boolean shouldInferFuncType;

    // MHA
    public Pair<String, String> lamDets;

    public Boolean forceNestFuncRepoint = null;

    public Annotations annotations;

    @Override
    public void setAnnotations(Annotations annotations) {
        this.annotations = annotations;
    }

    @Override
    public Annotations getAnnotations() {
        return annotations;
    }

    public boolean isFinal() {
        return false;
    }

    @Override
    public Node copyTypeSpecific() {
        LambdaDef lam = new LambdaDef(super.line, super.column, (Annotations) (annotations == null ? null : annotations.copy()), (FuncParams) params.copy(), body == null ? null : (Block) body.copy(), returnType == null ? null : (Type) returnType.copy(), (ArrayList<Pair<String, NamedType>>) Utils.cloneArrayList(methodGenricList));
        lam.extraCapturedLocalVars = this.extraCapturedLocalVars;
        lam.lamDets = lamDets;
        lam.methodName = methodName;
        lam.fakeFuncRef = fakeFuncRef == null ? null : (FuncRef) fakeFuncRef.copy();
        lam.forceNestFuncRepoint = forceNestFuncRepoint;
        lam.preceedingExpression = preceedingExpression == null ? null : (Expression) preceedingExpression.copy();
        lam.ignore = ignore;
        lam.implementSAM = implementSAM;
        lam.omitAnonLambdaSources = omitAnonLambdaSources;
        lam.isInjected = isInjected;
        lam.origSource = origSource;
        lam.supressTypeBoxing = supressTypeBoxing;
        return lam;
    }

    private Expression preceedingExpression;

    public boolean ignore;

    public Pair<NamedType, TypeAndLocation> implementSAM;

    public boolean omitAnonLambdaSources = false;

    public String origSource = null;

    private boolean supressTypeBoxing = false;

    public void setSupressTypeBoxing(boolean supressTypeBoxing) {
        this.supressTypeBoxing = supressTypeBoxing;
    }

    public boolean getSupressTypeBoxing() {
        return supressTypeBoxing || this.implementSAM != null || this.fakeFuncRef != null;
    }

    @Override
    public void setPreceedingExpression(Expression expr) {
        this.preceedingExpression = expr;
    }

    @Override
    public Expression getPreceedingExpression() {
        return preceedingExpression;
    }

    public LambdaDef(int line, int col, Annotations annotations, FuncParams params, Block body, Type t, ArrayList<Pair<String, NamedType>> methodGenricList) {
        super(line, col, false);
        this.annotations = annotations;
        if (null != params) {
            this.params = params;
        }
        this.returnType = t;
        this.body = body;
        if (null != this.body) {
            this.body.isMethodBlock = true;
        }
        /*if(null != returnType){
			returnType.setInOutGenModifier(InoutGenericModifier.OUT);
		}*/
        shouldInferFuncType = returnType == null;
        super.methodGenricList = methodGenricList;
    }

    public void setShouldBePresevedOnStack(boolean should) {
        super.setShouldBePresevedOnStack(should);
        if (this.body != null) {
            this.body.setShouldBePresevedOnStack(should);
        }
    }

    public AccessModifier getAccessModifier() {
        return AccessModifier.PUBLIC;
    }

    public FuncType getFunctType() {
        ArrayList<Type> inputs = new ArrayList<Type>();
        if (params != null) {
            for (FuncParam p : params.params) {
                inputs.add(p.getTaggedType());
            }
        }
        FuncType ft = new FuncType(0, 0, inputs, returnType);
        ft.origonatingFuncDef = FuncDef.build(returnType, params);
        return ft;
    }

    public FuncType getFunctTypeIncExtraArgs() {
        ArrayList<Type> inputs = new ArrayList<Type>();
        if (params != null) {
            for (FuncParam p : params.params) {
                inputs.add(p.getTaggedType());
            }
        }
        FuncType ret = new FuncType(0, 0, inputs, returnType);
        ArrayList<GenericType> gens = new ArrayList<GenericType>();
        for (Pair<String, NamedType> ss : this.methodGenricList) {
            String name = ss.getA();
            NamedType nt = ss.getB();
            GenericType gt = new GenericType(name, 0);
            if (nt != null) {
                gt.upperBound = nt;
                gt.setNullStatus(nt.getNullStatus());
            }
            gens.add(gt);
        }
        ret.setLocalGenerics(gens);
        return ret;
    }

    @Override
    public Object accept(Visitor visitor) {
        visitor.setLastLineVisited(super.getLine());
        return visitor.visit(this);
    }

    @Override
    public Type getRetuType() {
        return returnType;
    }

    @Override
    public FuncParams getParams() {
        FuncParams pars = new FuncParams(0, 0);
        for (FuncParams p : new FuncParams[] { params, extraCapturedLocalVars }) {
            if (p != null) {
                for (FuncParam pa : p.params) {
                    pars.add(pa);
                }
            }
        }
        // return  this.params;
        return pars;
    }

    @Override
    public Type getReturnType() {
        return this.returnType;
    }

    @Override
    public String getMethodName() {
        return methodName;
    }

    @Override
    public Block getBody() {
        return this.body;
    }

    public boolean isAbstract() {
        return false;
    }

    public void setAbstract(boolean asbtr) {
    }

    @Override
    public void setMethodName(String replace) {
        this.methodName = replace;
    }

    @Override
    public boolean IsAutoGennerated() {
        return false;
    }

    @Override
    public FuncParams getExtraCapturedLocalVars() {
        return this.extraCapturedLocalVars;
    }

    @Override
    public void setExtraCapturedLocalVars(FuncParams extraCapturedLocalVars) {
        this.extraCapturedLocalVars = extraCapturedLocalVars;
    }

    @Override
    public String toString() {
        return String.format("lambda %s(%s) %s : %s -> %s", this.methodName, this.params, this.returnType, this.getLine(), this.lamDets);
    }

    @Override
    public boolean getShouldInferFuncType() {
        return shouldInferFuncType;
    }
}

18 Source : ClassDefJava.java
with MIT License
from Concurnas

@Override
public ArrayList<Sixple<String, Type, Boolean, AccessModifier, Boolean, String>> getAllFieldsDefined() {
    ArrayList<Sixple<String, Type, Boolean, AccessModifier, Boolean, String>> ret = new ArrayList<Sixple<String, Type, Boolean, AccessModifier, Boolean, String>>();
    if (this.isTrait) {
        Annotations annots = this.getAnnotations();
        if (null != annots) {
            Annotation annot = annots.getAnnotation("com.concurnas.lang.Trait");
            if (null != annot) {
                for (Pair<String, Expression> inst : annot.manyArgs) {
                    if (inst.getA().equals("traitFields")) {
                        Object traitFields = inst.getB().getFoldedConstant();
                        if (traitFields instanceof TraitField[]) {
                            for (TraitField tf : (TraitField[]) traitFields) {
                                String fname = tf.fieldName();
                                boolean isAbastract = tf.isAbstract();
                                Type tt = TraitFieldEncoderDecoder.decode(tf.fieldType());
                                AccessModifier am = AccessModifier.getAccessModifier(tf.accessModifier());
                                ret.add(new Sixple<String, Type, Boolean, AccessModifier, Boolean, String>(fname, tt, isAbastract, am, false, null));
                            }
                            return ret;
                        }
                    }
                }
            }
        }
    }
    ArrayList<Fiveple<String, Type, Boolean, String, AccessModifier>> allfields = CompiledClreplacedUtils.getAllFields(cls, nameToGenericMap);
    allfields.forEach(a -> ret.add(new Sixple<String, Type, Boolean, AccessModifier, Boolean, String>(a.getA(), a.getB(), false, a.getE(), a.getC(), a.getD())));
    return ret;
}

18 Source : ClassDef.java
with MIT License
from Concurnas

public List<Fiveple<String, ClreplacedDef, Type, Boolean, AccessModifier>> getTraitFields(Map<Type, Type> superGenToChildGenBinding) {
    HashMap<Pair<String, Type>, Thruple<Boolean, AccessModifier, ClreplacedDef>> retx = new HashMap<Pair<String, Type>, Thruple<Boolean, AccessModifier, ClreplacedDef>>();
    for (Sevenple<String, Type, Boolean, AccessModifier, ClreplacedDef, Boolean, String> inst : getAllFields(true)) {
        // list order: supertype, trait then own type, so ok to write over
        Type tt = inst.getB();
        Type mapped = GenericTypeUtils.mapFuncTypeGenericsToOtherGenerics(tt, superGenToChildGenBinding, false);
        retx.put(new Pair<String, Type>(inst.getA(), mapped), new Thruple<Boolean, AccessModifier, ClreplacedDef>(inst.getC(), inst.getD(), inst.getE()));
    }
    List<Fiveple<String, ClreplacedDef, Type, Boolean, AccessModifier>> ret = new ArrayList<Fiveple<String, ClreplacedDef, Type, Boolean, AccessModifier>>();
    for (Pair<String, Type> item : retx.keySet()) {
        Thruple<Boolean, AccessModifier, ClreplacedDef> pair = retx.get(item);
        ret.add(new Fiveple<String, ClreplacedDef, Type, Boolean, AccessModifier>(item.getA(), pair.getC(), item.getB(), pair.getA(), pair.getB()));
    }
    return ret;
}

18 Source : ClassDef.java
with MIT License
from Concurnas

/**
 * @param includeInterfaces - include 'ordinary' java interfaces, i.e. not traits. Which go via the java method invokation approach of superclreplaced first
 */
public ArrayList<NamedType> getTraitsAsNamedType(int line, int col, boolean includeInterfaces) {
    ArrayList<NamedType> ret = new ArrayList<NamedType>();
    ArrayList<Pair<ClreplacedDef, List<Type>>> ifaces = this.getTraitsMapGens(includeInterfaces);
    if (null != ifaces) {
        for (Pair<ClreplacedDef, List<Type>> entry : ifaces) {
            ret.add(fullyQualifiedGens(line, col, entry.getA(), entry.getB()));
        }
    }
    Collections.reverse(ret);
    return ret;
}

18 Source : ClassDef.java
with MIT License
from Concurnas

public List<Pair<String, TypeAndLocation>> getAbstractMethods(Map<Type, Type> superGenToChildGenBinding) {
    List<Pair<String, TypeAndLocation>> ret = new ArrayList<Pair<String, TypeAndLocation>>();
    for (Pair<String, TypeAndLocation> can : getAllLocallyDefinedMethods()) {
        TypeAndLocation tandL = can.getB();
        FuncType fun = (FuncType) tandL.getType();
        if (fun.isAbstarct()) {
            // map generics properly
            FuncType mapped = (FuncType) GenericTypeUtils.mapFuncTypeGenericsToOtherGenerics(fun, superGenToChildGenBinding, false);
            ret.add(new Pair<String, TypeAndLocation>(can.getA(), new TypeAndLocation(mapped, tandL.getLocation())));
        }
    }
    // also we add the ones from the parent
    if (null != this.resolvedSuperType) {
        // filter out with the stuff that gets qualified
        List<Pair<String, TypeAndLocation>> parent = this.resolvedSuperType.getAbstractMethods(this.superclreplacedTypeToClsGeneric);
        for (Pair<String, TypeAndLocation> pk : parent) {
            // JPT: replace with hashmap
            TypeAndLocation pkTandA = pk.getB();
            FuncType pk2 = (FuncType) GenericTypeUtils.mapFuncTypeGenericsToOtherGenerics((FuncType) pkTandA.getType(), superGenToChildGenBinding, false);
            Pair<String, TypeAndLocation> cando = new Pair<String, TypeAndLocation>(pk.getA(), new TypeAndLocation(pk2, pkTandA.getLocation()));
            if (!ret.contains(cando)) {
                ret.add(cando);
            }
        }
    }
    return ret;
}

18 Source : AsyncBlock.java
with MIT License
from Concurnas

public clreplaced AsyncBlock extends Block implements HasExtraCapturedVars {

    // TOOD: rename to block?
    public Block body;

    public Expression executor;

    private FuncParams extraCapturedLocalVars = new FuncParams(0, 0);

    private boolean isAsync = true;

    public String methodName;

    public FuncRef fakeFuncRef;

    public boolean noReturn = false;

    public LambdaDef fakeLambdaDef;

    // the replaced will have the
    public replacedignExisting thereplacedToStoreRefIn;

    public Pair<String, String> lamDets;

    public AsyncBlock(int line, int col, Block b) {
        this(line, col, b, false, null);
    }

    public AsyncBlock(int line, int col, Block b, Expression executor) {
        this(line, col, b, false, executor);
    }

    public AsyncBlock(int line, int col, Block b, boolean isAsync) {
        this(line, col, b, isAsync, null);
    }

    public AsyncBlock(int line, int col, Block b, boolean isAsync, Expression executor) {
        super(line, col);
        this.body = b;
        this.body.isAsyncBody = true;
        this.isAsync = isAsync;
        this.executor = executor;
    }

    @Override
    public Object accept(Visitor visitor) {
        visitor.setLastLineVisited(super.getLine());
        return visitor.visit(this);
    }

    @Override
    public Node copyTypeSpecific() {
        AsyncBlock ret = new AsyncBlock(super.line, super.column, (Block) body.copy(), isAsync, executor == null ? null : (Expression) executor.copy());
        ret.methodName = methodName;
        ret.fakeFuncRef = null == fakeFuncRef ? null : (FuncRef) fakeFuncRef.copy();
        ret.noReturn = noReturn;
        ret.fakeLambdaDef = null == fakeLambdaDef ? null : (LambdaDef) fakeLambdaDef.copy();
        ret.thereplacedToStoreRefIn = null == thereplacedToStoreRefIn ? null : (replacedignExisting) thereplacedToStoreRefIn.copy();
        ret.extraCapturedLocalVars = null == extraCapturedLocalVars ? null : (FuncParams) extraCapturedLocalVars.copy();
        ret.lamDets = lamDets;
        return ret;
    }

    /*//////////////////////////////
	 * 
	 * this is special because we need to make copies of all variables et al refernced when we enter the scopeframe to make everything unchangable.
		ScopeFrame
		Ordered
				
		/*
		int x = 9;
		{
			x = x+8; //this is not allowed
			but we hack it to
			int Scope1$x = 8; //this does work...
		}!
		*/
    public void setAsync(boolean isAsync) {
    // this.isAsync = isAsync;
    // now replacedume all is async...
    // TODO: fix me along with parser so it can do
    // {asd();a;} vs, {asd();a;}!
    }

    public void setShouldBePresevedOnStack(boolean should) {
        super.setShouldBePresevedOnStack(should);
        this.body.setShouldBePresevedOnStack(should);
    }

    public boolean getShouldBePresevedOnStack() {
        return super.getShouldBePresevedOnStack();
    }

    @Override
    public FuncParams getExtraCapturedLocalVars() {
        return this.extraCapturedLocalVars;
    }

    @Override
    public void setExtraCapturedLocalVars(FuncParams extraCapturedLocalVars) {
        this.extraCapturedLocalVars = extraCapturedLocalVars;
    }

    @Override
    public String toString() {
        return "" + this.getLine() + " -> " + this.lamDets;
    }
    /*public boolean isPermissableToGoOnRHSOfADot(Node preceededBy)
	{
		return true;
	}*/
}

18 Source : ArrayRefLevelElementsHolder.java
with MIT License
from Concurnas

public ArrayList<ArrayRefElement> flatten() {
    ArrayList<ArrayRefElement> ret = new ArrayList<ArrayRefElement>();
    for (Pair<Boolean, ArrayList<ArrayRefElement>> inst : items) {
        ret.addAll(inst.getB());
    }
    return ret;
}

18 Source : ArrayRef.java
with MIT License
from Concurnas

public ArrayList<Pair<Boolean, ArrayRefElement>> getFlatALEWithNullSafe() {
    ArrayList<Pair<Boolean, ArrayRefElement>> ret = new ArrayList<Pair<Boolean, ArrayRefElement>>();
    for (Pair<Boolean, ArrayList<ArrayRefElement>> levelx : arrayLevelElements.getAll()) {
        boolean nullSafe = levelx.getA();
        for (ArrayRefElement level : levelx.getB()) {
            ret.add(new Pair<Boolean, ArrayRefElement>(nullSafe, level));
            nullSafe = false;
        }
    }
    return ret;
}

18 Source : ArrayRef.java
with MIT License
from Concurnas

public ArrayList<ArrayRefElement> getFlatALE() {
    ArrayList<ArrayRefElement> ret = new ArrayList<ArrayRefElement>();
    for (Pair<Boolean, ArrayList<ArrayRefElement>> levelx : arrayLevelElements.getAll()) {
        ArrayList<ArrayRefElement> level = levelx.getB();
        ret.addAll(level);
    }
    return ret;
}

17 Source : REPL.java
with MIT License
from Concurnas

private void trackNewDefaultMethods(Block blk, List<REPLComponentWrapper> newTopLevelItemsDeclared) {
    for (LineHolder lh : blk.lines) {
        Line lin = lh.l;
        if (lin instanceof FuncDef) {
            FuncDef fd = (FuncDef) lin;
            if (fd.isAutoGennerated) {
                if (fd.params.params.stream().anyMatch(a -> a.name.contains("$defaultNull") && ScopeAndTypeChecker.const_defaultParamUncre.equals(a.type))) {
                    Type tt = fd.getFuncType().getErasedFuncTypeNoRet();
                    String name = fd.getName();
                    Pair<String, Type> key = new Pair<String, Type>(name, tt);
                    persistedTopLevelElementSet.put(key, fd);
                    newTopLevelItemsDeclared.add(new REPLComponentWrapper(fd));
                }
            }
        }
    }
}

17 Source : OffHeapMap.java
with MIT License
from Concurnas

// private long metaMap_vidToCount;
/*
	 * protected region: 
	 * nextvid 					 -> 8
	 * mainBuckets 				 -> 2^16 = 65536
	 * clreplacedToVid 				 -> 2^14 = 16384
	 * vidtoClreplaced 				 -> 2^14 = 16384
	 * vidToCount 				 -> 2^14 = 16384
	 */
protected void postStart() {
    // mapBase = offHeapStorage.getLong(OffHeapMalloc.SIGNATURE);//
    createLocks();
    long protectedRegion = getProtectedRegionAddress();
    if (0 == protectedRegion) {
        int totalprotectedsize = 8 + CONCURRENCY_LEVEL * 8 + (META_CONCURRENCY_LEVEL * 8 * 3);
        Pair<ByteBuffer, Long> basePointerbbl = offHeapStorage.malloc(totalprotectedsize);
        ByteBuffer basePointerbb = basePointerbbl.getA();
        offHeapStorage.setProtectedRegionAndSize(basePointerbb.position(), totalprotectedsize);
        long protectedAddress = basePointerbbl.getB();
        meta_nextvid_address = protectedAddress;
        mainMapEntriesBase = protectedAddress + 8;
        metaMap_clreplacedToVid = protectedAddress + 8 + (CONCURRENCY_LEVEL * 8);
        metaMap_vidtoClreplaced = protectedAddress + 8 + (CONCURRENCY_LEVEL * 8) + (META_CONCURRENCY_LEVEL * 8);
        // metaMap_vidToCount = protectedAddress+8 + (CONCURRENCY_LEVEL*8) + (META_CONCURRENCY_LEVEL*8*2);
        // put the nextvid in first
        basePointerbb.putLong(VidConstants.startVid);
        // allocate all in one go, exclude the nextvid
        basePointerbb.put(new byte[(totalprotectedsize - 1) / 8]);
    } else {
        // reload...
        // nextVid = this.offHeapStorage.getLong(protectedRegion);
        mainMapEntriesBase = protectedRegion + 8;
        metaMap_clreplacedToVid = protectedRegion + 8 + (CONCURRENCY_LEVEL * 8);
        metaMap_vidtoClreplaced = protectedRegion + 8 + (CONCURRENCY_LEVEL * 8) + (META_CONCURRENCY_LEVEL * 8);
        // metaMap_vidToCount = protectedRegion+8 + (CONCURRENCY_LEVEL*8) + (META_CONCURRENCY_LEVEL*8*2);
        // initialize item count and vid count
        long count = 0;
        for (int n = 0; n < CONCURRENCY_LEVEL; n++) {
            // note: we dont do locking here as concurrent access cannot occur prior to initialization
            long currentPtr = mainMapEntriesBase + (n * 8);
            long nextEntry = offHeapStorage.getLong(currentPtr);
            if (nextEntry != 0) {
                currentPtr = nextEntry;
            }
            while (nextEntry != 0) {
                nextEntry = offHeapStorage.getLong(currentPtr);
                // nexPnter[long] | keyhash[int] | keySize[int] | key | pnterToValue ....
                int ksize = offHeapStorage.getInt(currentPtr + 8 + 4);
                long valueAddress = offHeapStorage.getLong(currentPtr + 8 + 4 + 4 + ksize);
                HashMap<Long, Long> vidToCountUsed = this.valueDecoder.getVids(valueAddress);
                this.registerVidUsage(vidToCountUsed);
                count++;
                currentPtr = nextEntry;
            }
        }
        this.count = count;
    }
}

17 Source : Profiler.java
with MIT License
from Concurnas

public void printEvents() {
    int longest = events.stream().map(a -> a.getA().length()).max(Comparator.naturalOrder()).get();
    String fmtString = "%-" + longest + "s";
    for (Pair<String, Double> strAndDur : events) {
        String padded = String.format(fmtString, strAndDur.getA());
        String fmtrh = String.format("%11s", String.format("%.3fsec", strAndDur.getB()));
        System.out.println(String.format("%s%s", padded, fmtrh));
    }
}

17 Source : LabelAllocator.java
with MIT License
from Concurnas

// private boolean alreadyCreatedNewLayer = false;
@Override
public Object visit(Block block) {
    ArrayList<LineHolder> lines = block.lines;
    int sz = lines.size();
    if (permitTaggingOfImmediateUse && block.getShouldBePresevedOnStackAndImmediatlyUsed() && block.getIfReturnsExpectImmediateUse() && block.isolated) {
        // System.err.println(String.format("igi: %s - %s", block.getLine(), block.isolated));
        tagLastThingInBlockWithImmediateUse(block);
    }
    if (!block.isEmpty()) {
        labelNeedingConsumption.push(new Pair<Label, Label>(null, null));
        for (int n = 0; n < sz; n++) {
            boolean isLast = n == sz - 1;
            boolean prev = isLastLineInBlock;
            if (isLast) {
                isLastLineInBlock = block.isolated ? prev : true;
            } else {
                isLastLineInBlock = isLast;
            }
            LineHolder lh = lines.get(n);
            // if(!ignoreConsume){
            // ignoreConsume=true;
            consumeLabelIfAny((Node) lh.l);
            // }
            super.visit(lh);
            isLastLineInBlock = prev;
        }
        Label unallocated = labelNeedingConsumption.pop().getB();
        if (null != unallocated) {
            // carry on up chain to next block
            if (!block.isMethodBlock) {
                // if it's a method block then it will have been consumed already by the return statement
                // unless its a constructor which always has implicit returns
                if (labelNeedingConsumption.isEmpty()) {
                    // oh noes no chain tag main blcok
                    // System.err.println("allocate before ret of top level block: " + unallocated);
                    block.mustVisitLabelBeforeRet = unallocated;
                } else {
                    Pair<Label, Label> ab = labelNeedingConsumption.pop();
                    labelNeedingConsumption.push(new Pair<Label, Label>(ab.getA(), unallocated));
                }
            } else if (block.isConstructor) {
                block.mustVisitLabelBeforeRet = unallocated;
            }
        }
    }
    return null;
}

17 Source : FinallyBlockCodeCopier.java
with MIT License
from Concurnas

private Stack<Pair<Label, Block>> performDeepClone(Stack<Pair<Label, Block>> input) {
    Stack<Pair<Label, Block>> output = new Stack<Pair<Label, Block>>();
    for (Pair<Label, Block> i : input) {
        output.push(new Pair<Label, Block>(i.getA() == null ? null : new Label(), i.getB() == null ? null : (Block) i.getB().copy()));
    }
    return output;
}

17 Source : New.java
with MIT License
from Concurnas

public clreplaced New extends ConstructorInvoke implements CanBeInternallyVectorized {

    // think this can be only named..
    public Type typeee;

    public FuncInvokeArgs args;

    public FuncType constType;

    public String defaultActorName;

    public String defaultActorNameFull;

    public NamedType actingOn;

    public HashMap<Integer, Integer> genericInputsToQualifingArgsAtRuntime = new HashMap<Integer, Integer>();

    public Pair<String, Integer> enumItemNameAndIndex;

    public boolean explicitNewKeywordUsed;

    public FuncType actorOfClreplacedRef;

    public Fourple<ArrayList<Pair<Boolean, NullStatus>>, ArrayList<Integer>, Integer, Type> vectroizedDegreeAndArgs;

    private Block vectorizedRedirect = null;

    private boolean hasErrored = false;

    // public boolean preventActorRedirect = false;
    public New(int line, int col, Type typeee2, FuncInvokeArgs args, boolean explicitNewKeywordUsed) {
        super(line, col);
        this.typeee = typeee2;
        this.args = args;
        this.explicitNewKeywordUsed = explicitNewKeywordUsed;
    }

    @Override
    public Object accept(Visitor visitor) {
        visitor.setLastLineVisited(super.getLine());
        if (null != vectorizedRedirect) {
            if (!(visitor instanceof VectorizedRedirector)) {
                return vectorizedRedirect.accept(visitor);
            }
        }
        if (null != astRedirect && !(visitor instanceof ScopeAndTypeChecker)) {
            return astRedirect.accept(visitor);
        }
        return visitor.visit(this);
    }

    @Override
    public Node copyTypeSpecific() {
        New ret = new New(super.getLine(), super.getColumn(), (Type) typeee.copy(), args == null ? null : (FuncInvokeArgs) args.copy(), explicitNewKeywordUsed);
        ret.constType = constType;
        // ret.isActor=isActor;
        ret.defaultActorName = defaultActorName;
        ret.defaultActorNameFull = defaultActorNameFull;
        // no copy needed
        ret.actingOn = actingOn;
        ret.genericInputsToQualifingArgsAtRuntime = new HashMap<Integer, Integer>(genericInputsToQualifingArgsAtRuntime);
        ret.enumItemNameAndIndex = null != enumItemNameAndIndex ? new Pair<String, Integer>(enumItemNameAndIndex.getA(), enumItemNameAndIndex.getB()) : null;
        // ret.preceedingExpression = preceedingExpression==null?null:(Expression)preceedingExpression.copy();
        ret.astRedirect = astRedirect == null ? null : (Node) astRedirect.copy();
        ret.actorOfClreplacedRef = actorOfClreplacedRef == null ? null : (FuncType) actorOfClreplacedRef.copy();
        ret.newOpOverloaded = newOpOverloaded == null ? null : (FuncInvoke) newOpOverloaded.copy();
        ret.newOpOverloadedNeedsCast = newOpOverloadedNeedsCast;
        ret.vectorizedRedirect = vectorizedRedirect == null ? null : (Block) vectorizedRedirect.copy();
        // ret.preventActorRedirect = preventActorRedirect;
        return ret;
    }

    private Expression preceedingExpression;

    public Node astRedirect;

    public FuncInvoke newOpOverloaded;

    public boolean newOpOverloadedNeedsCast = false;

    public boolean calledInFuncRef = false;

    @Override
    public void setPreceedingExpression(Expression expr) {
        this.preceedingExpression = expr;
    }

    @Override
    public Expression getPreceedingExpression() {
        return preceedingExpression;
    }

    @Override
    public boolean hasVectorizedRedirect() {
        return this.vectorizedRedirect != null;
    }

    @Override
    public void setVectorizedRedirect(Node vectRedirect) {
        this.vectorizedRedirect = (Block) vectRedirect;
    }

    @Override
    public boolean hasErroredAlready() {
        return hasErrored;
    }

    @Override
    public void setHasErroredAlready(boolean hasError) {
        this.hasErrored = hasError;
    }
    /*public void setShouldBePresevedOnStack(boolean should)
	{
		super.setShouldBePresevedOnStack(should);
	}*/
}

17 Source : FuncRefArgs.java
with MIT License
from Concurnas

@Override
public Node copyTypeSpecific() {
    FuncRefArgs ret = new FuncRefArgs(line, column);
    ret.exprOrTypeArgsList = (List<Object>) Utils.cloneArrayList(exprOrTypeArgsList);
    for (Pair<String, Object> name : nameMap) {
        ret.addName(name.getA(), (Expression) (((Expression) name.getB()).copy()));
    }
    return ret;
}

17 Source : Block.java
with MIT License
from Concurnas

public void overwriteLineHolder(Pair<String, FuncType> key, LineHolder newlh) {
    Pair<String, FuncType> keyNoRet = new Pair<String, FuncType>(key.getA(), key.getB().copyIgnoreReturnType());
    LineHolder oldLH = prependedStuff.get(key);
    if (null == oldLH) {
        if (!prependedStuff.isEmpty()) {
            // recalculate hashcodes incase they have changed
            prependedStuff = new HashMap<Pair<String, FuncType>, LineHolder>(prependedStuff);
            oldLH = prependedStuff.get(key);
        }
    }
    if (null == oldLH) {
        oldLH = prependedStuff.get(keyNoRet);
    }
    if (null != oldLH) {
        this.replaceLineHolder(oldLH, newlh);
    } else {
        this.prepend(newlh);
    }
    prependedStuff.put(key, newlh);
    prependedStuff.put(keyNoRet, newlh);
}

17 Source : ArrayRefLevelElementsHolder.java
with MIT License
from Concurnas

public ArrayRefElement getLastArrayRefElement() {
    Pair<Boolean, ArrayList<ArrayRefElement>> lastEsx = items.get(items.size() - 1);
    ArrayList<ArrayRefElement> lastEs = lastEsx.getB();
    return lastEs.get(lastEs.size() - 1);
}

17 Source : ArrayRef.java
with MIT License
from Concurnas

public void setlhsOfreplacedignment(Expression rhsOnreplacedignmentType, replacedignStyleEnum eq) {
    for (Pair<Boolean, ArrayList<ArrayRefElement>> levelx : arrayLevelElements.getAll()) {
        ArrayList<ArrayRefElement> level = levelx.getB();
        for (ArrayRefElement are : level) {
            are.rhsOfreplacedigmentType = rhsOnreplacedignmentType;
            are.rhsOfreplacedigmentEQ = eq;
        }
    }
}

16 Source : BytecodeTests.java
with MIT License
from Concurnas

private void testBigLoadFiles(String intputFile, String compareTo, boolean newSchedulerEveryRun) throws Throwable {
    boolean showProgress = StartUtils.isRunningInEclipse();
    ShowProgress sp = null;
    if (intputFile.endsWith("*") && showProgress) {
        intputFile = intputFile.substring(0, intputFile.length() - 1);
        // create progress monitor thread:
        sp = new ShowProgress();
        sp.go();
    }
    checkExists(intputFile);
    checkExists(compareTo);
    String data = FileUtils.readFile(intputFile);
    String dataE = FileUtils.readFile(compareTo);
    String[] intputs = data.split("~~~~~");
    StringBuilder result = new StringBuilder();
    replacedertEquals(intputs.length, dataE.split("~~~~~").length);
    ConcurnasClreplacedLoader masterLoader = new ConcurnasClreplacedLoader(ClreplacedPathUtils.getSystemClreplacedPathAsPaths(), ClreplacedPathUtils.getInstallationPath());
    SchedulClsAndObj shh = newSchedulerEveryRun ? null : makeSchedulClsAndObj(masterLoader);
    for (int n = 0; n < intputs.length; n++) {
        if (newSchedulerEveryRun) {
            shh = makeSchedulClsAndObj(masterLoader);
        }
        Pair<String, String> testnameAndCode = splitTestNameAndCode(intputs[n]);
        String testname = testnameAndCode.getA();
        if (sp != null) {
            sp.latestProg = testname;
        }
        String code = testnameAndCode.getB();
        String output = null;
        double comTime = 0;
        double exeTime = 0;
        double totTime = System.currentTimeMillis();
        MainLoop mainLoop = null;
        try {
            replacedertNotNull(testname);
            ArrayList<String> linesToFind = foundLines(testnameAndCode.getB(), "\n");
            String niceTestName = Utils.getMiniTestFileName(testname);
            String inputFileName = niceTestName + ".conc";
            // MockFileLoader mockLoader = new MockFileLoader();
            // mockLoader.addFile(SrcDir + FileLoader.pathSeparatorChar + inputFileName, code);
            MockFileLoader mockLoader = produceLoader(inputFileName, code);
            MockFileWriter mfw = new MockFileWriter();
            mainLoop = new MainLoop(SrcDir, mockLoader, true, false, mfw, false);
            long comTimeStart = System.currentTimeMillis();
            // TODO: convert to multi input version
            ArrayList<ErrorHolder> errs = mainLoop.compileFiles(mockLoader.getAllFiles()).messages;
            comTime = (System.currentTimeMillis() - comTimeStart) / 1000.;
            output = replacedertNoPreBytecodeErrors(errs, false, code.contains("//#Ignore WARN"));
            if (null == output) {
                boolean hasNop = false;
                for (String name : mfw.nametoCode.keySet()) {
                    // fix nopper
                    hasNop |= BytecodePrettyPrinter.print(mfw.nametoCode.get(name), false).contains("NOP");
                }
                if (hasNop) {
                    output = "NOP detected in bytecode";
                } else {
                    InMemoryClreplacedLoader myClreplacedLoader = new InMemoryClreplacedLoader();
                    myClreplacedLoader.loadClreplacedes(mfw.nametoCode);
                    long tick = System.currentTimeMillis();
                    output = executeClreplaced(myClreplacedLoader, null, niceTestName, false, linesToFind, shh);
                    exeTime = (System.currentTimeMillis() - tick) / 1000.;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
            output = e.getMessage();
            if (showProgress) {
                System.out.println(String.format("Compilation fail on test %s of %s in %s: %s", n, intputs.length, intputFile, testname));
            }
        } finally {
            if (mainLoop != null) {
                mainLoop.stop();
            }
        }
        result.append("//##" + testname + "\n" + output + "\n\n");
        if (n != intputs.length - 1) {
            result.append("~~~~~\n");
        }
        if (showProgress) {
            totTime = (System.currentTimeMillis() - totTime) / 1000.;
            double overhead = totTime - (comTime + exeTime);
            System.out.println(String.format("Complete so far: %6.2f%% - % 3d of % 3d [c: %.3f e: %.3f t:%.3f o:%.3f] in %s: %s", ((n + 1) / (double) intputs.length) * 100, n + 1, intputs.length, comTime, exeTime, totTime, overhead, intputFile, testname));
        }
        if (newSchedulerEveryRun) {
            Clreplaced<?> schedulerCls = shh.schedulerCls;
            Object shceduler = shh.shceduler;
            getMethod(schedulerCls, "terminate", 0).invoke(shceduler, new Object[] {});
        // System.gc();
        }
    }
    if (!newSchedulerEveryRun) {
        Clreplaced<?> schedulerCls = shh.schedulerCls;
        Object shceduler = shh.shceduler;
        getMethod(schedulerCls, "terminate", 0).invoke(shceduler, new Object[] {});
    }
    if (sp != null) {
        sp.stop();
    }
    replacedertEquals(dataE.trim(), result.toString().trim());
}

16 Source : StaticLambdaClassesFinder.java
with MIT License
from Concurnas

private void findClinitRoots(ClreplacedNode checkme, String mNameAndSig, HashSet<String> curVisit, LinkedList<String> toProcess) {
    if (curVisit.contains(checkme.myName)) {
        // skip to avoid inf cycles
        return;
    }
    curVisit.add(checkme.myName);
    HashSet<Pair<ClreplacedNode, String>> callers = checkme.callersOfMethod.get(mNameAndSig);
    if (null != callers) {
        for (Pair<ClreplacedNode, String> caller : callers) {
            if (caller.getB().equals("<clinit>()V")) {
                String cname = caller.getA().myName;
                if (!clreplacedesWithAffectedClinit.contains(cname)) {
                    clreplacedesWithAffectedClinit.add(cname);
                    toProcess.add(cname);
                }
            } else {
                // normal method, follow this set...
                ClreplacedNode dep = caller.getA();
                HashSet<Pair<ClreplacedNode, String>> callersOfThisMethod = dep.callersOfMethod.get(caller.getB());
                if (null != callersOfThisMethod) {
                    for (Pair<ClreplacedNode, String> acaller : callersOfThisMethod) {
                        findClinitRoots(acaller.getA(), acaller.getB(), curVisit, toProcess);
                    }
                }
            }
        }
    }
}

16 Source : StaticLambdaClassesFinder.java
with MIT License
from Concurnas

private void follow(String inst, HashSet<String> curVisit) {
    if (curVisit.contains(inst)) {
        // skip to avoid inf cycles
        return;
    }
    curVisit.add(inst);
    ClreplacedNode cnDeps = clreplacedNodes.get(inst);
    for (Pair<ClreplacedNode, Boolean> dependorAndIsClinit : cnDeps.nodesDependingOnMyStaticFields) {
        String depName = dependorAndIsClinit.getA().myName;
        if (staticLamExclusions.contains(depName)) {
            break;
        }
        if (dependorAndIsClinit.getB()) {
            // its called by a <clinit>
            clreplacedesWithAffectedClinit.add(depName);
        }
        follow(depName, curVisit);
    }
// curVisit.remove(inst);
}

See More Examples