@Override public void meet(FunctionCall fc) throws RuntimeException { // special optimizations for frequent cases with variables if ((XMLSchema.DOUBLE.toString().equals(fc.getURI()) || XMLSchema.FLOAT.toString().equals(fc.getURI())) && fc.getArgs().size() == 1) { optypes.push(ValueType.DOUBLE); fc.getArgs().get(0).visit(this); optypes.pop(); } else if ((XMLSchema.INTEGER.toString().equals(fc.getURI()) || XMLSchema.INT.toString().equals(fc.getURI())) && fc.getArgs().size() == 1) { optypes.push(ValueType.INT); fc.getArgs().get(0).visit(this); optypes.pop(); } else if (XMLSchema.BOOLEAN.toString().equals(fc.getURI()) && fc.getArgs().size() == 1) { optypes.push(ValueType.BOOL); fc.getArgs().get(0).visit(this); optypes.pop(); } else if (XMLSchema.DATE.toString().equals(fc.getURI()) && fc.getArgs().size() == 1) { optypes.push(ValueType.DATE); fc.getArgs().get(0).visit(this); optypes.pop(); } else { String fnUri = fc.getURI(); String[] args = new String[fc.getArgs().size()]; NativeFunction nf = functionRegistry.get(fnUri); if (nf != null && nf.isSupported(parent.getDialect())) { for (int i = 0; i < args.length; i++) { args[i] = new ValueExpressionEvaluator(fc.getArgs().get(i), parent, nf.getArgumentType(i)) .build(); } if (optypes.peek() != nf.getReturnType()) { builder.append(castExpression(nf.getNative(parent.getDialect(), args), optypes.peek())); } else { builder.append(nf.getNative(parent.getDialect(), args)); } } else { throw new IllegalArgumentException( "the function " + fnUri + " is not supported by the SQL translation"); } } }
@Override public void exitOperationProcedureDecl(ResolveParser.OperationProcedureDeclContext ctx) { Scope s = symtab.getScope(ctx); VCAssertiveBlockBuilder block = assertiveBlocks.pop(); List<ProgParameterSymbol> paramSyms = s.getSymbolsOfType(ProgParameterSymbol.class); PExp corrFnExpEnsures = perParameterCorrFnExpSubstitute( paramSyms, tr.getMathExpASTFor( g, ctx.ensuresClause())); // postcondition[params 1..i <-- corr_fn_exp] corrFnExpEnsures = corrFnExpEnsures.withVCInfo(ctx.getStart(), "Ensures clause of " + ctx.name.getText()); Token loc = ctx.ensuresClause() != null ? ctx.ensuresClause().getStart() : ctx.getStart(); List<PExp> paramConsequents = new ArrayList<>(); Utils.apply(paramSyms, paramConsequents, this::extractConsequentsFromParameter); // add verification statements to the assertive context/block block.stats(Utils.collect(VCRuleBackedStat.class, ctx.stmt(), stats)); // add any additional confirms from the parameters, etc for (ProgParameterSymbol p : paramSyms) { confirmParameterConsequentsForBlock(block, p); // modfies 'block' with additional confims! } // TODO: Tomorrow look at the verification statements in the assertive context for // int_do_nothing, then block.finalConfirm(corrFnExpEnsures); outputFile.addAssertiveBlock(block.build()); }
@Override public void meet(Count node) throws RuntimeException { builder.append("COUNT("); if (node.isDistinct()) { builder.append("DISTINCT "); } if (node.getArg() == null) { // this is a weird special case where we need to expand to all variables selected in the query // wrapped // by the group; we cannot simply use "*" because the concept of variables is a different one // in SQL, // so instead we construct an ARRAY of the bindings of all variables List<String> countVariables = new ArrayList<>(); for (SQLVariable v : parent.getVariables().values()) { if (v.getProjectionType() == ValueType.NONE) { Preconditions.checkState( v.getExpressions().size() > 0, "no expressions available for variable"); countVariables.add(v.getExpressions().get(0)); } } builder.append("ARRAY["); Joiner.on(',').appendTo(builder, countVariables); builder.append("]"); } else { optypes.push(ValueType.NODE); node.getArg().visit(this); optypes.pop(); } builder.append(")"); }
@Override public void meet(If node) throws RuntimeException { builder.append("CASE WHEN "); optypes.push(ValueType.BOOL); node.getCondition().visit(this); optypes.pop(); optypes.push(new OPTypeFinder(node).coerce()); builder.append(" THEN "); node.getResult().visit(this); builder.append(" ELSE "); node.getAlternative().visit(this); builder.append(" END"); optypes.pop(); }
@Override public void meet(MathExpr expr) throws RuntimeException { ValueType ot = new OPTypeFinder(expr).coerce(); if (ot == ValueType.STRING) { if (expr.getOperator() == MathExpr.MathOp.PLUS) { builder.append( functionRegistry .get(FN.CONCAT.stringValue()) .getNative( parent.getDialect(), new ValueExpressionEvaluator(expr.getLeftArg(), parent, ot).build(), new ValueExpressionEvaluator(expr.getRightArg(), parent, ot).build())); } else { throw new IllegalArgumentException( "operation " + expr.getOperator() + " is not supported on strings"); } } else { if (ot == ValueType.NODE || ot == ValueType.TERM) { ot = ValueType.DOUBLE; } optypes.push(ot); expr.getLeftArg().visit(this); builder.append(getSQLOperator(expr.getOperator())); expr.getRightArg().visit(this); optypes.pop(); } }
@Override public void meet(Sum node) throws RuntimeException { builder.append("SUM("); optypes.push(ValueType.DOUBLE); node.getArg().visit(this); optypes.pop(); builder.append(")"); }
/* * stack contains all ancestors of the node, stack.peek() is its parent. */ private void mutateUp(@NotNull final Deque<ChildReferenceTransient> stack, MutableNode node) { while (!stack.isEmpty()) { final ChildReferenceTransient parent = stack.pop(); final MutableNode mutableParent = parent.mutate(this); mutableParent.setChild(parent.firstByte, node); node = mutableParent; } }
@Override public void meet(Compare cmp) throws RuntimeException { optypes.push(new OPTypeFinder(cmp).coerce()); cmp.getLeftArg().visit(this); builder.append(getSQLOperator(cmp.getOperator())); cmp.getRightArg().visit(this); optypes.pop(); }
public void performIncludes(ModuleChain inclusionPoint, Deque<DynamicObject> moduleAncestors) { while (!moduleAncestors.isEmpty()) { DynamicObject mod = moduleAncestors.pop(); assert RubyGuards.isRubyModule(mod); inclusionPoint.insertAfter(mod); Layouts.MODULE.getFields(mod).addDependent(rubyModuleObject); } }
@Override public void meet(SameTerm cmp) throws RuntimeException { // covered by value binding in variables optypes.push(ValueType.TERM); cmp.getLeftArg().visit(this); builder.append(" = "); cmp.getRightArg().visit(this); optypes.pop(); }
public int execute(String input) { Deque<Integer> stack = new ArrayDeque<>(); for (String s : input.split("\\s")) { Operator operator = opetators.get(s); if (operator != null) { Integer num1 = stack.pop(); Integer num2 = stack.pop(); stack.push(operator.execute(num1, num2)); } else { stack.push(Integer.valueOf(s)); } } return stack.pop(); }
public static QuantileDigest deserialize(DataInput input) { try { double maxError = input.readDouble(); double alpha = input.readDouble(); QuantileDigest result = new QuantileDigest(maxError, alpha); result.landmarkInSeconds = input.readLong(); result.min = input.readLong(); result.max = input.readLong(); result.totalNodeCount = input.readInt(); Deque<Node> stack = new ArrayDeque<>(); for (int i = 0; i < result.totalNodeCount; i++) { int flags = input.readByte(); Node node = deserializeNode(input); if ((flags & Flags.HAS_RIGHT) != 0) { node.right = stack.pop(); } if ((flags & Flags.HAS_LEFT) != 0) { node.left = stack.pop(); } stack.push(node); result.weightedCount += node.weightedCount; if (node.weightedCount >= ZERO_WEIGHT_THRESHOLD) { result.nonZeroNodeCount++; } } if (!stack.isEmpty()) { Preconditions.checkArgument( stack.size() == 1, "Tree is corrupted. Expected a single root node"); result.root = stack.pop(); } return result; } catch (IOException e) { throw Throwables.propagate(e); } }
@Override public boolean add(@NotNull final ByteIterable key, @NotNull final ByteIterable value) { final ByteIterator it = key.iterator(); NodeBase node = root; MutableNode mutableNode = null; final Deque<ChildReferenceTransient> stack = new ArrayDeque<>(); while (true) { final NodeBase.MatchResult matchResult = node.matchesKeySequence(it); final int matchingLength = matchResult.matchingLength; if (matchingLength < 0) { final MutableNode prefix = node.getMutableCopy(this).splitKey(-matchingLength - 1, matchResult.keyByte); if (matchResult.hasNext) { prefix.hang(matchResult.nextByte, it).setValue(value); } else { prefix.setValue(value); } if (stack.isEmpty()) { root = new MutableRoot(prefix, root.sourceAddress); } else { final ChildReferenceTransient parent = stack.pop(); mutableNode = parent.mutate(this); mutableNode.setChild(parent.firstByte, prefix); } break; } if (!it.hasNext()) { if (node.hasValue()) { return false; } mutableNode = node.getMutableCopy(this); mutableNode.setValue(value); break; } final byte nextByte = it.next(); final NodeBase child = node.getChild(this, nextByte); if (child == null) { mutableNode = node.getMutableCopy(this); if (mutableNode.hasChildren() || mutableNode.hasKey() || mutableNode.hasValue()) { mutableNode.hang(nextByte, it).setValue(value); } else { mutableNode.setKeySequence(new ArrayByteIterable(nextByte, it)); mutableNode.setValue(value); } break; } stack.push(new ChildReferenceTransient(nextByte, node)); node = child; } ++size; mutateUp(stack, mutableNode); TreeCursorMutable.notifyCursors(this); return true; }
private void reverseChangeLog() throws InvalidOperationException { Deque<Operation> operations = new LinkedList<>(this.changeLog); while (!operations.isEmpty()) { Operation operation = operations.pop(); if (!TokenHook.TokenType.Word.equals(operation.tokenType)) { Operation inverse = operation.getInverse(); Collection<Operation> c = new LinkedList<>(); c.add(inverse); this.applyOperations(c, false); } } }
@Override public void meet(Bound node) throws RuntimeException { ValueExpr arg = node.getArg(); if (arg instanceof ValueConstant) { builder.append(Boolean.toString(true)); } else if (arg instanceof Var) { builder.append("("); optypes.push(ValueType.NODE); arg.visit(this); optypes.pop(); builder.append(" IS NOT NULL)"); } }
private void finishNode(InstructionImpl instruction) { final InstructionImpl popped = myProcessingStack.pop(); if (!instruction.equals(popped)) { String description = "popped: " + popped.toString() + " : " + popped.hashCode() + " , expected: " + instruction.toString() + " : " + instruction.hashCode(); error(description); } }
@Override public void meet(BNodeGenerator gen) throws RuntimeException { if (gen.getNodeIdExpr() != null) { // get value of argument and express it as string optypes.push(ValueType.STRING); gen.getNodeIdExpr().visit(this); optypes.pop(); } else { builder .append("'") .append( Long.toHexString(System.currentTimeMillis()) + Integer.toHexString(anonIdGenerator.nextInt(1000))) .append("'"); } }
// returns the single move to make given a board, depth, piecelist, heuristic // whill choose the best terminal board at the max depth, // or if none exists, the best board with no children (inevitable death) public Board.Direction nextMove(Board start, List<Integer> nextPiece) { int maxDepth = Math.min(exploreDepth, nextPiece.size()); double bestLiveScore = -1; Board.Direction bestLiveDirection = null; // cus why not? // add the first round seperately so we know which move to return for (Board.Direction d : Board.Direction.values()) { Board next = start.move(d, nextPiece.get(0)); if (next != null) { PriorityQueue<Double> pq = new PriorityQueue<Double>(); Deque<StackItem> stack = new ArrayDeque<StackItem>(); stack.push(new StackItem(next, 1, d)); // DFS while (!stack.isEmpty()) { StackItem cur = stack.pop(); // add more moves if not beyond max depth if (cur.d < maxDepth) { for (Board.Direction d2 : Board.Direction.values()) { Board next2 = cur.b.move(d2, nextPiece.get(cur.d)); if (next2 != null) { stack.push(new StackItem(next2, cur.d + 1, cur.move)); } } } // update live only at the bottom of the tree if (cur.d == maxDepth) { pq.add(heuristic.useHeuristic(cur.b)); if (pq.size() > 10) pq.poll(); } } double sum = 0; int count = 0; count = pq.size(); while (!pq.isEmpty()) sum += pq.poll(); if (count > 0 && sum / count > bestLiveScore) { bestLiveScore = sum / count; bestLiveDirection = d; } } } return bestLiveDirection; }
@Override public void meet(Like node) throws RuntimeException { if (node.isCaseSensitive()) { optypes.push(ValueType.STRING); node.getArg().visit(this); optypes.pop(); builder.append(" LIKE "); node.getPattern(); } else { builder.append( parent .getDialect() .getILike( new ValueExpressionEvaluator(node.getArg(), parent, ValueType.STRING).build(), node.getOpPattern())); } }
private int findMaxArea(int[] height) { if (height == null || height.length == 0) return 0; int[] h = Arrays.copyOf(height, height.length + 1); int maxArea = 0; Deque<Integer> stack = new LinkedList(); int k = 0; while (k < h.length) { if (stack.isEmpty() || h[stack.peek()] <= h[k]) { stack.push(k++); } else { int t = stack.pop(); int leftIndex = (stack.isEmpty()) ? -1 : stack.peek(); int rightIndex = k; int tmpArea = h[t] * (rightIndex - leftIndex - 1); maxArea = Math.max(maxArea, tmpArea); } } return maxArea; }
// 检测是否合法:合法 0,不合法 -1 public int checkValid(String s) { Deque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '(': q.push(i); break; case ')': if (q.isEmpty()) { return -1; } else { q.pop(); } break; default: break; } } return q.isEmpty() ? 0 : -1; }
private boolean deleteImpl(@NotNull final ByteIterable key) { final ByteIterator it = key.iterator(); NodeBase node = root; final Deque<ChildReferenceTransient> stack = new ArrayDeque<>(); for (; ; ) { if (node == null || node.matchesKeySequence(it).matchingLength < 0) { return false; } if (!it.hasNext()) { break; } final byte nextByte = it.next(); stack.push(new ChildReferenceTransient(nextByte, node)); node = node.getChild(this, nextByte); } if (!node.hasValue()) { return false; } --size; MutableNode mutableNode = node.getMutableCopy(this); ChildReferenceTransient parent = stack.peek(); final boolean hasChildren = mutableNode.hasChildren(); if (!hasChildren && parent != null) { stack.pop(); mutableNode = parent.mutate(this); mutableNode.removeChild(parent.firstByte); if (!mutableNode.hasValue() && mutableNode.getChildrenCount() == 1) { mutableNode.mergeWithSingleChild(this); } } else { mutableNode.setValue(null); if (!hasChildren) { mutableNode.setKeySequence(ByteIterable.EMPTY); } else if (mutableNode.getChildrenCount() == 1) { mutableNode.mergeWithSingleChild(this); } } mutateUp(stack, mutableNode); return true; }
@Override public void exitTypeRepresentationDecl(ResolveParser.TypeRepresentationDeclContext ctx) { PExp constraint = g.getTrueExp(); PExp correspondence = g.getTrueExp(); if (currentTypeReprSym == null) return; correspondence = currentTypeReprSym.getCorrespondence(); if (currentTypeReprSym.getDefinition() != null) { constraint = currentTypeReprSym.getDefinition().getProgramType().getConstraint(); } VCAssertiveBlockBuilder block = assertiveBlocks.pop(); PExp newConstraint = constraint.substitute( currentTypeReprSym.exemplarAsPSymbol(), currentTypeReprSym.conceptualExemplarAsPSymbol()); newConstraint = newConstraint.withVCInfo(ctx.getStart(), "Constraint for type: " + ctx.name.getText()); block.assume(correspondence.splitIntoConjuncts()); // throw new UnsupportedOperationException("re-institute the final confirm for this dan"); block.finalConfirm(newConstraint); outputFile.addAssertiveBlock(block.build()); }
@Override public void exitTypeImplInit(ResolveParser.TypeImplInitContext ctx) { PExp typeInitEnsures = g.getTrueExp(); PExp convention = currentTypeReprSym.getConvention(); PExp correspondence = currentTypeReprSym.getCorrespondence(); if (currentTypeReprSym.getDefinition() != null) { typeInitEnsures = currentTypeReprSym.getDefinition().getProgramType().getInitializationEnsures(); } VCAssertiveBlockBuilder block = assertiveBlocks.pop(); PExp newInitEnsures = typeInitEnsures.substitute( currentTypeReprSym.exemplarAsPSymbol(), currentTypeReprSym.conceptualExemplarAsPSymbol()); // block.stats(Utils.collect(VCRuleBackedStat.class, ctx.stmt(), stats)); // block.confirm(convention); //order here is important block.assume(correspondence); throw new UnsupportedOperationException("re-institute the final confirm for this dan"); // block.finalConfirm(newInitEnsures, "Initialization-ensures clause of " + // currentTypeReprSym.getName()); // outputFile.addAssertiveBlock(block.build()); }
private void addExternalParents(EntityType entityType) { Deque<Type> superTypes = new ArrayDeque<Type>(); if (entityType.getSuperType() != null) { superTypes.push(entityType.getSuperType().getType()); } while (!superTypes.isEmpty()) { Type superType = superTypes.pop(); if (!context.allTypes.containsKey(superType.getFullName())) { TypeElement typeElement = processingEnv.getElementUtils().getTypeElement(superType.getFullName()); if (typeElement == null) { throw new IllegalStateException("Found no type for " + superType.getFullName()); } EntityType superEntityType = elementHandler.handleEntityType(typeElement); if (superEntityType.getSuperType() != null) { superTypes.push(superEntityType.getSuperType().getType()); } context.allTypes.put(superType.getFullName(), superEntityType); } } }
private List<Element> createConnectedComponent( Map<Element, ElementStatus> elementStatusMap, Element root) { List<Element> connectedComponent = new ArrayList<>(); Deque<Element> stack = new ArrayDeque<>(); stack.push(root); while (!stack.isEmpty()) { Element element = stack.pop(); if (ElementStatus.UNREACHABLE.equals(elementStatusMap.get(element))) { connectedComponent.add(element); elementStatusMap.put(element, ElementStatus.REACHABLE); if (element instanceof RuntimeVertex) { RuntimeVertex vertex = (RuntimeVertex) element; for (RuntimeEdge edge : context.getModel().getOutEdges(vertex)) { stack.push(edge); } } else if (element instanceof RuntimeEdge) { RuntimeEdge edge = (RuntimeEdge) element; stack.push(edge.getTargetVertex()); } } } return Collections.unmodifiableList(connectedComponent); }
@Override public void exitProcedureDecl(ResolveParser.ProcedureDeclContext ctx) { Scope scope = symtab.getScope(ctx); List<ProgParameterSymbol> paramSyms = scope.getSymbolsOfType(ProgParameterSymbol.class); VCAssertiveBlockBuilder block = assertiveBlocks.pop(); List<ProgParameterSymbol> formalParameters = new ArrayList<>(); try { formalParameters = scope.query(new SymbolTypeQuery<ProgParameterSymbol>(ProgParameterSymbol.class)); } catch (NoSuchModuleException | UnexpectedSymbolException e) { e.printStackTrace(); } List<PExp> corrFnExps = paramSyms .stream() .filter(p -> p.getDeclaredType() instanceof PTRepresentation) .map(p -> (PTRepresentation) p.getDeclaredType()) .map(p -> p.getReprTypeSymbol().getCorrespondence()) .collect(Collectors.toList()); PExp corrFnExpEnsures = perParameterCorrFnExpSubstitute(paramSyms, currentProcOpSym.getEnsures()) .withVCInfo(ctx.getStart(), "Ensures clause of " + ctx.name.getText()); // postcondition[params 1..i <-- corr_fn_exp] List<PExp> paramConsequents = new ArrayList<>(); Utils.apply(formalParameters, paramConsequents, this::extractConsequentsFromParameter); block .stats(Utils.collect(VCRuleBackedStat.class, ctx.stmt(), stats)) .assume(corrFnExps) .confirm(ctx, g.formConjuncts(paramConsequents)) .finalConfirm(corrFnExpEnsures); outputFile.addAssertiveBlock(block.build()); currentProcOpSym = null; }
@Override public void meet(IRIFunction fun) throws RuntimeException { if (fun.getBaseURI() != null) { String ex = new ValueExpressionEvaluator(fun.getArg(), parent, ValueType.STRING).build(); builder .append("CASE WHEN position(':' IN ") .append(ex) .append(") > 0 THEN ") .append(ex) .append(" ELSE ") .append( functionRegistry .get(FN.CONCAT.stringValue()) .getNative(parent.getDialect(), "'" + fun.getBaseURI() + "'", ex)) .append(" END "); } else { // get value of argument and express it as string optypes.push(ValueType.STRING); fun.getArg().visit(this); optypes.pop(); } }
private void dropContext() { stack.pop(); }
@Override public void meet(Str node) throws RuntimeException { optypes.push(ValueType.STRING); node.getArg().visit(this); optypes.pop(); }