@Override public void endElement(String uri, String localName, String qName) throws SAXException { addElementErrors(); FxNode node = nodeStack.pop(); i(node).endsAt(contentLocator.getEndOffset()).endContent(contentLocator.getElementOffset()); if (node instanceof PropertySetter) { PropertySetter s = (PropertySetter) node; if (s.isImplicit()) { // actually the outer element ends node = nodeStack.pop(); // copy the offset information i(node).endsAt(contentLocator.getEndOffset()).endContent(contentLocator.getElementOffset()); } } String tn = node.getSourceName(); if (!tn.equals(localName)) { throw new IllegalStateException(); } // special hack for parent nodes, which are implicit property setters: FxNode parentNode = nodeStack.peek(); if (parentNode instanceof PropertySetter) { PropertySetter ps = (PropertySetter) parentNode; if (ps.isImplicit() && ps.getContent() == null) { i(ps).endsAt(contentLocator.getEndOffset()).endContent(contentLocator.getEndOffset()); } } if (!nodeStack.isEmpty() && nodeStack.peek().getKind() == Kind.Instance) { current = (FxInstance) nodeStack.peek(); } else { current = null; } }
@Override public void meet(ValueConstant node) throws RuntimeException { String val = node.getValue().stringValue(); switch (optypes.peek()) { case STRING: case URI: builder.append("'").append(val).append("'"); break; case INT: builder.append(Integer.parseInt(val)); break; case DECIMAL: case DOUBLE: builder.append(Double.parseDouble(val)); break; case BOOL: builder.append(Boolean.parseBoolean(val)); break; case DATE: builder.append("'").append(sqlDateFormat.format(DateUtils.parseDate(val))).append("'"); break; // in this case we should return a node ID and also need to make sure it actually exists case TERM: case NODE: KiWiNode n = parent.getConverter().convert(node.getValue()); builder.append(n.getId()); break; default: throw new IllegalArgumentException("unsupported value type: " + optypes.peek()); } }
public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || k == 0) { return new int[0]; } int n = nums.length; int[] res = new int[n - k + 1]; Deque<Integer> dq = new ArrayDeque<>(); int pointer = 0; for (int i = 0; i < n; i++) { while (!dq.isEmpty() && dq.peek() < i - k + 1) { dq.poll(); } while (!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) { dq.pollLast(); } dq.offer(i); if (i >= k - 1) { res[pointer++] = nums[dq.peek()]; } } return res; }
@Override public void visitNode(Tree tree) { if (isClassTree(tree)) { classes++; classTrees.push((ClassTree) tree); } if (tree.is(Tree.Kind.NEW_CLASS) && ((NewClassTree) tree).classBody() != null) { classes--; } if (tree.is(Tree.Kind.METHOD, Tree.Kind.CONSTRUCTOR) && classTrees.peek().simpleName() != null) { // don't count methods in anonymous classes. MethodTree methodTree = (MethodTree) tree; if (separateAccessorsFromMethods && AccessorsUtils.isAccessor(classTrees.peek(), methodTree)) { accessors++; } else { methods++; int methodComplexity = context.getMethodComplexityNodes(classTrees.peek(), methodTree).size(); methodComplexityDistribution.add(methodComplexity); complexityInMethods += methodComplexity; } } }
@SuppressWarnings("unchecked") private void processNextNode() { if (stateStack.isEmpty()) { nextEvent = null; return; } currentItr = stateStack.peek(); if (currentItr.hasNext()) { Object o = currentItr.next(); if (inMap()) { Entry<String, HValue> entry = (Entry<String, HValue>) o; key = entry.getKey(); value = entry.getValue(); } else { key = null; value = HValue.initFromObject(o); } nextEvent = Types.getEventTypeForType(value.getType()); if (!value.getType().isScalar()) { stateStack.push(new IteratorWithType(value)); } } else { IteratorWithType iter = stateStack.pop(); key = null; value = iter.getValue(); nextEvent = (iter.getType() == Type.MAP) ? EventType.END_MAP : EventType.END_ARRAY; currentItr = stateStack.isEmpty() ? null : stateStack.peek(); } }
/** Returns the current scope's root. */ public Node getScopeRoot() { if (scopeRoots.isEmpty()) { return scopes.peek().getRootNode(); } else { return scopeRoots.peek(); } }
/** * Remove a Security Manager and restore the Security Manager it replaced. This handles the case * where another Security Manager was set in place of this one to insure the previous security * manager is not replaced prematurely. * * @param sm Security Manager to remove */ public void removeSecurityManager(SecurityManager sm) { if (sm == null) { throw new IllegalArgumentException("SecurityManager is required"); } synchronized (stack) { if (stack.peek() == null) { throw new IllegalStateException("empty stack"); } if (sm.equals(stack.peek().sm)) { // If sm was the last SecurityManager to be registered restore an older // one by finding the last contiguous element which has been released // and restore the Security Manager that one replaced SecurityManager smToRestore = stack.pop().original; while (stack.peek() != null && stack.peek().released == true) { smToRestore = stack.pop().original; } restore(smToRestore); } else { // If another Security Manager has been registered since we were called // mark ourself as being released so when the more recent ones are removed // our original is restored properly for (StackElement e : stack) { if (e.sm.equals(sm)) { e.released = true; } } } } }
// Append the line mapping entries. void traverse(MappingVisitor v) throws IOException { // The mapping list is ordered as a pre-order traversal. The mapping // positions give us enough information to rebuild the stack and this // allows the building of the source map in O(n) time. Deque<Mapping> stack = new ArrayDeque<>(); for (Mapping m : mappings) { // Find the closest ancestor of the current mapping: // An overlapping mapping is an ancestor of the current mapping, any // non-overlapping mappings are siblings (or cousins) and must be // closed in the reverse order of when they encountered. while (!stack.isEmpty() && !isOverlapped(stack.peek(), m)) { Mapping previous = stack.pop(); maybeVisit(v, previous); } // Any gaps between the current line position and the start of the // current mapping belong to the parent. Mapping parent = stack.peek(); maybeVisitParent(v, parent, m); stack.push(m); } // There are no more children to be had, simply close the remaining // mappings in the reverse order of when they encountered. while (!stack.isEmpty()) { Mapping m = stack.pop(); maybeVisit(v, m); } }
@Override public void endField(String field, int index) { if (DEBUG) if (!fields.peek().equals(index)) throw new IllegalStateException( "opening " + fields.peek() + " but closing " + index + " (" + field + ")"); fields.pop(); }
@Override public void leaveNode(AstNode astNode) { if (isInClass && classStack.peek().isInConstructor && astNode.is(FlexGrammar.FUNCTION_DEF)) { classStack.peek().isInConstructor = false; } else if (isInClass && astNode.is(FlexGrammar.CLASS_DEF)) { classStack.pop(); isInClass = classStack.isEmpty() ? false : true; } }
private void extractIMethod(IMethod method, boolean annotationElement) { try { StringBuilder fqnBuilder = new StringBuilder(fqnStack.peek()); if (method.isConstructor()) { fqnBuilder.append('.').append("<init>"); } else { fqnBuilder.append('.').append(method.getElementName()); } fqnBuilder.append('('); boolean first = true; for (String param : method.getParameterTypes()) { if (first) { first = false; } else { fqnBuilder.append(','); } String sig = typeSignatureToFqn(param); fqnBuilder.append(sig); } fqnBuilder.append(')'); String fqn = fqnBuilder.toString(); // Write the entity if (annotationElement) { entityWriter.writeAnnotationElement(fqn, method.getFlags(), path); } else if (method.isConstructor()) { entityWriter.writeConstructor(fqn, method.getFlags(), path); } else { entityWriter.writeMethod(fqn, method.getFlags(), path); } // Write the inside relation relationWriter.writeInside(fqn, fqnStack.peek(), path); // Write the returns relation relationWriter.writeReturns(fqn, typeSignatureToFqn(method.getReturnType()), path); // Write the receives relation String[] paramTypes = method.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { localVariableWriter.writeClassParameter( "arg" + i, typeSignatureToFqn(paramTypes[i]), fqn, i, path); // relationWriter.writeReceives(fqn, typeSignatureToFqn(paramTypes[i]), "arg" + i, // i); } int pos = 0; for (ITypeParameter param : method.getTypeParameters()) { relationWriter.writeParametrizedBy(fqn, getTypeParam(param), pos++, path); } } catch (JavaModelException e) { logger.log(Level.SEVERE, "Error in extracting class file", e); } }
private Node getCfgRoot() { if (cfgRoots.isEmpty()) { Scope currScope = scopes.peek(); while (currScope.isBlockScope()) { currScope = currScope.getParent(); } return currScope.getRootNode(); } else { return cfgRoots.peek(); } }
public CircularImportProblem( ConfigurationClass attemptedImport, Deque<ConfigurationClass> importStack) { super( String.format( "A circular @Import has been detected: " + "Illegal attempt by @Configuration class '%s' to import class '%s' as '%s' is " + "already present in the current import stack %s", importStack.peek().getSimpleName(), attemptedImport.getSimpleName(), attemptedImport.getSimpleName(), importStack), new Location(importStack.peek().getResource(), attemptedImport.getMetadata())); }
@Override public void characters(char[] data, int start, int len) { String d = new String(data, start, len).trim(); if (d.isEmpty()) { return; } String parent = parentNames.peek(); if (parent == null) { return; } if (parent.equals(qName)) { parentNames.pop(); parent = parentNames.peek(); } if (qName.equals("Label")) { key = d; value = null; } else if (qName.equals("Value")) { value = d; } else { key = parent + " " + qName; value = d; } if (key != null && value != null) { addGlobalMeta(key, value); if (key.equals("Stage X") || ("StagePosition".equals(parent) && key.equals("X"))) { final Double number = Double.valueOf(value); stageX = new Length(number, UNITS.REFERENCEFRAME); } else if (key.equals("Stage Y") || ("StagePosition".equals(parent) && key.equals("Y"))) { final Double number = Double.valueOf(value); stageY = new Length(number, UNITS.REFERENCEFRAME); } else if (key.equals("Stage Z") || ("StagePosition".equals(parent) && key.equals("Z"))) { final Double number = Double.valueOf(value); stageZ = new Length(number, UNITS.REFERENCEFRAME); } else if (key.equals("Microscope")) { microscopeModel = value; } else if (key.equals("User")) { userName = value; } else if (key.equals("Magnification")) { magnification = new Double(value); } // physical sizes stored in meters, but usually too small to be used without converting else if (key.endsWith("X") && "PixelSize".equals(parent)) { sizeX = new Double(value) * 1000000; } else if (key.endsWith("Y") && "PixelSize".equals(parent)) { sizeY = new Double(value) * 1000000; } } }
@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"); } } }
private String getClassKey(String className) { String key = className; if (StringUtils.isNotEmpty(currentPackage)) { key = currentPackage + "/" + className; } if ("".equals(className) || (parent.peek() != null && parent.peek().is(Tree.Kind.METHOD))) { // inner class declared within method int count = anonymousInnerClassCounter.pop() + 1; key = currentClassKey.peek() + "$" + count + className; anonymousInnerClassCounter.push(count); } else if (currentClassKey.peek() != null) { key = currentClassKey.peek() + "$" + className; } return key; }
/** * Rename or remove labels. * * @param node The label node. * @param parent The parent of the label node. */ private void visitLabel(Node node, Node parent) { Node nameNode = node.getFirstChild(); Preconditions.checkState(nameNode != null); String name = nameNode.getString(); LabelInfo li = getLabelInfo(name); // This is a label... if (li.referenced || !removeUnused) { String newName = getNameForId(li.id); if (!name.equals(newName)) { // ... and it is used, give it the short name. nameNode.setString(newName); compiler.reportCodeChange(); } } else { // ... and it is not referenced, just remove it. Node newChild = node.getLastChild(); node.removeChild(newChild); parent.replaceChild(node, newChild); if (newChild.isBlock()) { NodeUtil.tryMergeBlock(newChild); } compiler.reportCodeChange(); } // Remove the label from the current stack of labels. namespaceStack.peek().renameMap.remove(name); }
/** * Conjuncts the given {@link Connectable} with the current one. This method will be called * whenever an expression or condition was created. To build the {@link Conjunction} object it * will use the conjunction type stored during the {@link #conjunct(Type)} visit call. * * @param newElement the element to conjunct with the current one */ protected void conjunctNew(Connectable newElement) { if (copy == null) { // the copy process has just begun copy = newElement; } else { if (conjunctionType != null) { // if the conjunct(Type) method was already called we can conjunct the current // element with the new one current.setConjunction(conjunctionType, newElement); conjunctionType = null; } else { // the conjunct(Type) method wasn't called so far so we just entered an expression // and we have to fill it's condition instead of it's conjunction which will be done // afterwards Expression lastExpression = expressionStack.peek(); if (lastExpression.equals( newElement)) { // means that an expression is the condition of an expression // don't push it back to the stack because the stack is just lastExpression = (Expression) current; } lastExpression.setCondition(newElement); } } current = newElement; }
/** * process modifiers * * @param ast ast of Modifiers */ private void processModifiers(DetailAST ast) { final ScopeState state = scopeStates.peek(); if (ast.findFirstToken(TokenTypes.LITERAL_STATIC) != null) { if (state.currentScopeState > STATE_STATIC_VARIABLE_DEF) { if (!ignoreModifiers || state.currentScopeState > STATE_INSTANCE_VARIABLE_DEF) { log(ast, MSG_STATIC); } } else { state.currentScopeState = STATE_STATIC_VARIABLE_DEF; } } else { if (state.currentScopeState > STATE_INSTANCE_VARIABLE_DEF) { log(ast, MSG_INSTANCE); } else if (state.currentScopeState == STATE_STATIC_VARIABLE_DEF) { state.declarationAccess = Scope.PUBLIC; state.currentScopeState = STATE_INSTANCE_VARIABLE_DEF; } } final Scope access = ScopeUtils.getScopeFromMods(ast); if (state.declarationAccess.compareTo(access) > 0) { if (!ignoreModifiers) { log(ast, MSG_ACCESS); } } else { state.declarationAccess = access; } }
private void refineRelevantPredicatesComputer(List<ARGState> pPath, ARGReachedSet pReached) { UnmodifiableReachedSet reached = pReached.asReachedSet(); Precision oldPrecision = reached.getPrecision(reached.getLastState()); PredicatePrecision oldPredicatePrecision = Precisions.extractPrecisionByType(oldPrecision, PredicatePrecision.class); BlockPartitioning partitioning = predicateCpa.getPartitioning(); Deque<Block> openBlocks = new ArrayDeque<>(); openBlocks.push(partitioning.getMainBlock()); for (ARGState pathElement : pPath) { CFANode currentNode = AbstractStates.extractLocation(pathElement); Integer currentNodeInstance = getPredicateState(pathElement).getAbstractionLocationsOnPath().get(currentNode); if (partitioning.isCallNode(currentNode)) { openBlocks.push(partitioning.getBlockForCallNode(currentNode)); } Collection<AbstractionPredicate> localPreds = oldPredicatePrecision.getPredicates(currentNode, currentNodeInstance); for (Block block : openBlocks) { for (AbstractionPredicate pred : localPreds) { relevantPredicatesComputer.considerPredicateAsRelevant(block, pred); } } while (openBlocks.peek().isReturnNode(currentNode)) { openBlocks.pop(); } } }
private void leaf(NonTerminal node, String name, String icon) { node.getChildren() .stream() .filter(ast -> ast instanceof Terminal) .findFirst() .ifPresent(ident -> converted.peek().addChild(new Outline(name, ident, icon))); }
@Override public void exitCallStmt(ResolveParser.CallStmtContext ctx) { VCRuleBackedStat s = null; PApply callExp = (PApply) tr.exprASTs.get(ctx.progParamExp()); OperationSymbol op = getOperation(moduleScope, callExp); if (inSimpleForm(op.getEnsures(), op.getParameters())) { // TODO: Use log instead! // gen.getCompiler().info("APPLYING EXPLICIT (SIMPLE) CALL RULE"); s = new VCCall(ctx, assertiveBlocks.peek(), EXPLICIT_CALL_APPLICATION, callExp); } else { // TODO: Use log instead! // gen.getCompiler().info("APPLYING GENERAL CALL RULE"); s = new VCCall(ctx, assertiveBlocks.peek(), GENERAL_CALL_APPLICATION, callExp); } stats.put(ctx, s); }
private void addOperator(Operator operator) { Section section = stack.peek(); Tree tree = section.unwind(operator); Tree tree1 = Tree.of(operator, tree.getRight(), Atom.NIL); Tree.forceSetRight(tree, tree1); section.push(tree1); }
@Override public void writeAttribute(String localName, String value) throws XMLStreamException { try { if (!objectQueue.isEmpty()) { if (StringUtils.equals(CmsConstants.EXPORT_AS_AN_ARRAY_INSTRUCTION, localName)) { objectQueue.peek().exportAsAnArray = BooleanUtils.isTrue(BooleanUtils.toBoolean(value)); } else { objectQueue.peek().addAttribute(localName, value); } } } catch (Exception e) { throw new XMLStreamException(e); } }
// trim unnecessary log messages. private void truncate(long handle, boolean isSP) { // MIN value means no work to do, is a startup condition if (handle == Long.MIN_VALUE) { return; } Deque<RepairLog.Item> deq = null; if (isSP) { deq = m_logSP; if (m_truncationHandle < handle) { m_truncationHandle = handle; for (TransactionCommitInterest interest : m_txnCommitInterests) { interest.transactionCommitted(m_truncationHandle); } } } else { deq = m_logMP; } RepairLog.Item item = null; while ((item = deq.peek()) != null) { if (item.canTruncate(handle)) { deq.poll(); } else { break; } } }
@Override public void characterSequence(CharSequence seq) { addElementErrors(); int length = seq.length(); FxNode node = nodeStack.peek(); FxNode addedNode = null; switch (node.getKind()) { case Event: addedNode = handleEventContent(seq); break; case Instance: addedNode = handleInstanceContent(seq); break; case Property: addedNode = handlePropertyContent(seq); break; default: addError( new ErrorMark( contentLocator.getElementOffset(), length, "unexpected-characters", ERR_unexpectedCharacters())); } if (addedNode != null) { i(addedNode).endsAt(contentLocator.getEndOffset()); } }
private Expression leaveOptimistic(final Optimistic opt) { final int pp = opt.getProgramPoint(); if (isValid(pp) && !neverOptimistic.peek().get(pp)) { return (Expression) opt.setType(compiler.getOptimisticType(opt)); } return (Expression) opt; }
@Override public void visitToken(DetailAST ast) { final int parentType = ast.getParent().getType(); switch (ast.getType()) { case TokenTypes.OBJBLOCK: scopeStates.push(new ScopeState()); break; case TokenTypes.MODIFIERS: if (parentType == TokenTypes.VARIABLE_DEF && ast.getParent().getParent().getType() == TokenTypes.OBJBLOCK) { processModifiers(ast); } break; case TokenTypes.CTOR_DEF: if (parentType == TokenTypes.OBJBLOCK) { processConstructor(ast); } break; case TokenTypes.METHOD_DEF: if (parentType == TokenTypes.OBJBLOCK) { final ScopeState state = scopeStates.peek(); // nothing can be bigger than method's state state.currentScopeState = STATE_METHOD_DEF; } break; default: break; } }
private void handleFunction(Node node) { // A block transfer control to its first child if it is not empty. Preconditions.checkState(node.getChildCount() >= 3); createEdge(node, Branch.UNCOND, computeFallThrough(node.getFirstChild().getNext().getNext())); Preconditions.checkState(exceptionHandler.peek() == node); exceptionHandler.pop(); }
@Override public EditorCell updateRoleAttributeCell( final Class attributeKind, final EditorCell cellWithRole, final SNode roleAttribute) { if (attributeKind != AttributeKind.Reference.class && myContextStack.peek().hasRoles()) { // Suppressing role attribute cell creation upon reference cells. return cellWithRole; } final EditorContext editorContext = getUpdater().getEditorContext(); editorContext.getCellFactory().pushCellContext(); editorContext .getCellFactory() .removeCellContextHints(EditorCellFactoryImpl.BASE_REFLECTIVE_EDITOR_HINT); try { return runWithExplicitEditorHints( editorContext, roleAttribute, new Computable<EditorCell>() { @Override public EditorCell compute() { return EditorManager.getInstanceFromContext(editorContext) .doCreateRoleAttributeCell( attributeKind, cellWithRole, roleAttribute, myModelModifications); } }); } finally { editorContext.getCellFactory().popCellContext(); } }