@Override public void accept(Visitor visitor) { a.accept(visitor); b.accept(visitor); visitor.visit(this); }
private Rvalue compileImpl(IntermediateCompiler ic, Scope scope, CType leftType, CType rightType) throws SyntaxException { // Compile operands. Rvalue rhs = right.compileWithConversion(ic, scope, rightType); Lvalue lhs = left.compileAsLvalue(ic, scope, false); // Load LHS to register. Rvalue lhsVal = new Rvalue(new VirtualRegister()); ic.emit("load", lhsVal.getRegister(), "0", lhs.getRegister()); lhsVal = left.getType(scope).compileConversion(ic, scope, lhsVal, leftType); // Compile the binary operator. String binOp = operator.binaryOperator; Rvalue retVal; if (leftType.isPointer()) { // Scale integer operand if necessary. int leftIncrSize = left.getType(scope).decay().getIncrementSize(); if (leftIncrSize > 1) ic.emit("mul", rhs.getRegister(), "=" + leftIncrSize); ic.emit(operator.mnemonic, lhsVal.getRegister(), rhs.getRegister()); retVal = lhsVal; } else if (operator.type == BinaryExpression.Type.BITWISE) retVal = leftType.compileBinaryBitwiseOperator(ic, scope, lhsVal, rhs, binOp); else if (operator.type == BinaryExpression.Type.SHIFT) retVal = leftType.compileBinaryShiftOperator(ic, scope, lhsVal, rhs, binOp); else // if (operator.type == BinaryExpression.Type.ARITHMETIC) retVal = leftType.compileBinaryArithmeticOperator(ic, scope, lhsVal, rhs, binOp); // Convert to the original type of the left operand. retVal = leftType.compileConversion(ic, scope, retVal, left.getType(scope)); // Assign result back to lvalue. ic.emit("store", retVal.getRegister(), "0", lhs.getRegister()); return retVal; }
/** * @param scalar * @return true if the scalar is defines as $GLOBALS call */ private static boolean checkGLOBALS(Scalar scalar) { final String stringValue = scalar.getStringValue(); if (scalar.getScalarType() != Scalar.TYPE_STRING || stringValue.length() < 3) { return false; } final char charAtZero = stringValue.charAt(0); final char charAtEnd = stringValue.charAt(stringValue.length() - 1); if (!detectString(charAtZero) || !detectString(charAtEnd)) { return false; } if (scalar.getParent().getType() == ASTNode.ARRAY_ACCESS) { ArrayAccess arrayAccess = (ArrayAccess) scalar.getParent(); final Expression variableName = arrayAccess.getName(); if (variableName.getType() == ASTNode.VARIABLE) { Variable var = (Variable) variableName; if (var.isDollared() && var.getName() instanceof Identifier) { final Identifier id = (Identifier) var.getName(); return id.getName().equals("_GLOBALS") // $NON-NLS-1$ || id.getName().equals("GLOBALS"); // $NON-NLS-1$ } } } return false; }
public Expression expressionAt(int line, int column) { for (int i = 0; i < expressions.length; i++) { Expression expression = expressions[i]; if (expression.isAt(line, column)) return expression; } return null; }
private Expression getCompileTimeConstantExpression() { // Must be static constant if (!isStatic() || !isFinal()) { return null; } IType type = getFeatureType(); // Must be either primitive, String, or Enum constant if (type != JavaTypes.STRING() && !type.isPrimitive() && !type.isEnum()) { return null; } // // Field must be initialized directly // if (getOwnersType().isDeclarationsCompiled()) { getOwnersType().isValid(); // barf } for (VarStatement varStmt : getOwnersType().getParseInfo().getStaticFields().values()) { // barf if (varStmt.getIdentifierName().toString().equals(getName())) { Expression initiazerExpr = varStmt.getAsExpression(); if (initiazerExpr != null) { return varStmt.isEnumConstant() || initiazerExpr.isCompileTimeConstant() ? initiazerExpr : null; } } } return null; }
/** @see jaskell.compiler.JaskellVisitor#visit(QualifiedVariable) */ public Object visit(QualifiedVariable a) { Module mod = null; Iterator it = a.getPath().iterator(); while (it.hasNext()) { String mname = (String) it.next(); if (mod != null) mod = (Module) mod.lookup(mname); else mod = (Module) Module.getToplevels().get(mname); } /* module found */ if (mod != null) { Expression def = mod.lookup(a.getName()); if (def == null) throw new CompilerException("Unknown variable " + a.getName()); Type t = def.getType(); if (t == null) t = (Type) def.visit(this); /* as it is the case for variable, we assume * that a defined symbol may be overloaded (only for primitive types) * so we return a type variable and defers choice of * symbol to a later stage */ a.setType(t); return t; } throw new CompilerException("Unable to find module needed for variable " + a.getName()); }
/** * Advances to the next available value. * * <p> * * @return true if a next value is available upon exit * @throws HsqlException if a database access error occurs */ boolean next() throws HsqlException { nonJoinIsNull = false; isCurrentOuter = false; currentNode = filterIndex.next(currentNode); while (currentNode != null) { currentData = currentNode.getData(); currentRow = currentNode.getRow(); if (!(eEnd == null || eEnd.test(null))) { break; } if (eAnd == null || eAnd.test(null)) { return true; } currentNode = filterIndex.next(currentNode); } currentData = emptyData; currentRow = null; return false; }
/** Typing rules: see XSLT Reference by M. Kay page 345. */ public Type typeCheck(SymbolTable stable) throws TypeCheckError { final Type tleft = _left.typeCheck(stable); final Type tright = _right.typeCheck(stable); if (tleft.isSimple() && tright.isSimple()) { if (tleft != tright) { if (tleft instanceof BooleanType) { _right = new CastExpr(_right, Type.Boolean); } else if (tright instanceof BooleanType) { _left = new CastExpr(_left, Type.Boolean); } else if (tleft instanceof NumberType || tright instanceof NumberType) { _left = new CastExpr(_left, Type.Real); _right = new CastExpr(_right, Type.Real); } else { // both compared as strings _left = new CastExpr(_left, Type.String); _right = new CastExpr(_right, Type.String); } } } else if (tleft instanceof ReferenceType) { _right = new CastExpr(_right, Type.Reference); } else if (tright instanceof ReferenceType) { _left = new CastExpr(_left, Type.Reference); } // the following 2 cases optimize @attr|.|.. = 'string' else if (tleft instanceof NodeType && tright == Type.String) { _left = new CastExpr(_left, Type.String); } else if (tleft == Type.String && tright instanceof NodeType) { _right = new CastExpr(_right, Type.String); } // optimize node/node else if (tleft instanceof NodeType && tright instanceof NodeType) { _left = new CastExpr(_left, Type.String); _right = new CastExpr(_right, Type.String); } else if (tleft instanceof NodeType && tright instanceof NodeSetType) { // compare(Node, NodeSet) will be invoked } else if (tleft instanceof NodeSetType && tright instanceof NodeType) { swapArguments(); // for compare(Node, NodeSet) } else { // At least one argument is of type node, node-set or result-tree // Promote an expression of type node to node-set if (tleft instanceof NodeType) { _left = new CastExpr(_left, Type.NodeSet); } if (tright instanceof NodeType) { _right = new CastExpr(_right, Type.NodeSet); } // If one arg is a node-set then make it the left one if (tleft.isSimple() || tleft instanceof ResultTreeType && tright instanceof NodeSetType) { swapArguments(); } // Promote integers to doubles to have fewer compares if (_right.getType() instanceof IntType) { _right = new CastExpr(_right, Type.Real); } } return _type = Type.Boolean; }
public void translateDesynthesized(ClassGenerator classGen, MethodGenerator methodGen) { final Type tleft = _left.getType(); final InstructionList il = methodGen.getInstructionList(); if (tleft instanceof BooleanType) { _left.translate(classGen, methodGen); _right.translate(classGen, methodGen); _falseList.add( il.append( _op == Operators.EQ ? (BranchInstruction) new IF_ICMPNE(null) : (BranchInstruction) new IF_ICMPEQ(null))); } else if (tleft instanceof NumberType) { _left.translate(classGen, methodGen); _right.translate(classGen, methodGen); if (tleft instanceof RealType) { il.append(DCMPG); _falseList.add( il.append( _op == Operators.EQ ? (BranchInstruction) new IFNE(null) : (BranchInstruction) new IFEQ(null))); } else { _falseList.add( il.append( _op == Operators.EQ ? (BranchInstruction) new IF_ICMPNE(null) : (BranchInstruction) new IF_ICMPEQ(null))); } } else { translate(classGen, methodGen); desynthesize(classGen, methodGen); } }
/** SIMPLE_COLUMN expressions can be of different Java types */ public boolean equals(Expression other) { if (other == this) { return true; } if (other == null) { return false; } if (opType != other.opType) { return false; } switch (opType) { case OpTypes.SIMPLE_COLUMN: return this.columnIndex == other.columnIndex; case OpTypes.COALESCE: return nodes == other.nodes; case OpTypes.VARIABLE: case OpTypes.PARAMETER: case OpTypes.COLUMN: return column == other.getColumn() && rangeVariable == other.getRangeVariable(); default: return false; } }
public void visitAndExpr(OpAnd and) { if (predicates > 0) { Expression parent = and.getParent(); if (!(parent instanceof PathExpr)) { LOG.warn("Parent expression of boolean operator is not a PathExpr: " + parent); return; } PathExpr path; Predicate predicate; if (parent instanceof Predicate) { predicate = (Predicate) parent; path = predicate; } else { path = (PathExpr) parent; parent = path.getParent(); if (!(parent instanceof Predicate) || path.getLength() > 1) { LOG.warn( "Boolean operator is not a top-level expression in the predicate: " + parent.getClass().getName()); return; } predicate = (Predicate) parent; } if (LOG.isTraceEnabled()) LOG.trace("Rewriting boolean expression: " + ExpressionDumper.dump(and)); hasOptimized = true; LocationStep step = (LocationStep) predicate.getParent(); Predicate newPred = new Predicate(context); newPred.add(and.getRight()); step.insertPredicate(predicate, newPred); path.replaceExpression(and, and.getLeft()); } }
static void checkColumnsResolved(HsqlList set) { if (set != null && !set.isEmpty()) { StringBuffer sb = new StringBuffer(); Expression e = (Expression) set.get(0); if (e instanceof ExpressionColumn) { ExpressionColumn c = (ExpressionColumn) e; if (c.schema != null) { sb.append(c.schema + '.'); } if (c.tableName != null) { sb.append(c.tableName + '.'); } throw Error.error(ErrorCode.X_42501, sb.toString() + c.getColumnName()); } else { OrderedHashSet newSet = new OrderedHashSet(); e.collectAllExpressions( newSet, Expression.columnExpressionSet, Expression.emptyExpressionSet); // throw with column name checkColumnsResolved(newSet); // throw anyway if not found throw Error.error(ErrorCode.X_42501); } } }
private Expression operationWithConstantValue( BinaryExpression binExp, java.lang.Class expectedClass, Expression constantExp, boolean constantOnLeft, boolean operationWithSideEffect) { Expression exp; if (operationWithSideEffect) { MethodAccess call = new MethodAccess(); call.expression = new This(); exp = call; } else { exp = new IdExpression(); } exp.type = constantExp.type; if (constantOnLeft) { binExp.right = exp; binExp.left = constantExp; } else { binExp.left = exp; binExp.right = constantExp; } if (null == expectedClass) expectedClass = MethodAccess.class; return expressionSimplificationTester(binExp, expectedClass, constantExp.type, 0, false); }
@Override public void accept(IRVisitor visitor) { for (Expression e : expressions) { e.accept(visitor); } visitor.visit(this); }
/** * Parses the characters backwards until it hits the beginning of the current expression. Returns * a stack of expression segments, which are parts of the expression separated by a dot. * * @param chars a reverse character iterator * @return a stack of segments. */ private static Expression getExpression(PeekingIterator<Character> chars) { Expression expression = new Expression(); Segment currentSegment = new Segment(); expression.push(currentSegment); while (chars.hasNext()) { char ch = chars.peek(); if (currentSegment.isDefinitelyInvalid()) { break; } // If our segment is valid (has evenly closed blocks and quotes), and we've hit a valid // delimiter (a delimiter character or a space separating two alphanumeric chars), finish // parsing the expression. if ((DELIMITERS.apply(ch) || currentSegment.delimitedBySpace(ch)) && currentSegment.isValid()) { return expression; } // Check for segment breaks in the expression (periods separating valid segments). chars.next(); if (ch == '.' && currentSegment.isValid()) { currentSegment = new Segment(); expression.push(currentSegment); } else { currentSegment.prependText(ch); } } return expression; }
@Test public void trueConstant() throws EvaluationException { Expression e = new ConstantExpression(true); assertEquals(Boolean.TRUE, e.evaluate(topLevel)); e = new ConstantExpression(Boolean.TRUE); assertEquals(Boolean.TRUE, e.evaluate(topLevel)); }
public static boolean visit( Like obj, BooleanJunction<BooleanJunction> junction, QueryBuilder queryBuilder) throws TranslatorException { LogManager.logTrace(LogConstants.CTX_CONNECTOR, "Parsing LIKE criteria."); // $NON-NLS-1$ Expression lhs = obj.getLeftExpression(); Expression rhs = obj.getRightExpression(); Column c = null; Expression literalExp = null; if (lhs instanceof ColumnReference) { c = ((ColumnReference) lhs).getMetadataObject(); literalExp = rhs; } else { c = ((ColumnReference) rhs).getMetadataObject(); literalExp = lhs; } String value = null; if (literalExp instanceof Literal) { value = (String) escapeReservedChars(((Literal) literalExp).getValue()); createLikeQuery( c, value.replaceAll("%", ""), junction, queryBuilder); // "*" //$NON-NLS-1$ //$NON-NLS-2$ } else { final String msg = ObjectPlugin.Util.getString( "LuceneSearch.Unsupported_expression", //$NON-NLS-1$ new Object[] {literalExp.toString(), "LIKE"}); // $NON-NLS-1$ throw new TranslatorException(msg); } return true; }
@Test public void falseConstant() throws EvaluationException { Expression e = new ConstantExpression(false); assertEquals(Boolean.FALSE, e.evaluate(topLevel)); e = new ConstantExpression(Boolean.FALSE); assertEquals(Boolean.FALSE, e.evaluate(topLevel)); }
/** * Chooses certain query conditions and assigns a copy of them to this filter. The original * condition is set to Expression.TRUE once assigned. * * @param condition * @throws HsqlException */ void setConditions(Expression condition) throws HsqlException { setCondition(condition); if (filterIndex == null) { filterIndex = filterTable.getPrimaryIndex(); } if (filterIndex.getVisibleColumns() == 1 || eStart == null || eAnd == null || eStart.exprType != Expression.EQUAL) { return; } boolean[] check = filterTable.getNewColumnCheckList(); Expression[] expr = new Expression[check.length]; int colindex = eStart.getArg().getColumnNr(); check[colindex] = true; expr[colindex] = eStart.getArg2(); eAnd.getEquiJoinColumns(this, check, expr); if (ArrayUtil.containsAllTrueElements(check, filterIndex.colCheck)) { isMultiFindFirst = true; findFirstExpressions = expr; } }
private ConstantValue evaluateLogicalExpr( Expression lhs, Expression rhs, Type resultType, LogicalBinaryOperation operation) { // Evaluate the first subexpression final ConstantValue valueLhs = lhs.accept(this, null); // Get the factory for the result type final ConstantType resultConstantType = typeFactory.newConstantType(resultType); checkArgument( resultConstantType.getType() == ConstantType.Type.SIGNED_INTEGER, "result of logical AND or logical OR expression has not a signed integer type"); final boolean resultValue; /* Determine the result - we use the fact the Java '&&' and '||' operators are evaluated lazily. */ switch (operation) { case LOGICAL_AND: resultValue = valueLhs.logicalValue() && rhs.accept(this, null).logicalValue(); break; case LOGICAL_OR: resultValue = valueLhs.logicalValue() || rhs.accept(this, null).logicalValue(); break; default: throw new RuntimeException("unexpected logical binary operation '" + operation + "'"); } return UnsignedIntegerConstantValue.getLogicalValue(resultValue).castTo(resultConstantType); }
/* * INTERNAL: * If this query key represents a foreign reference answer the * base expression -> foreign reference join criteria. */ public Expression mappingCriteria() { Expression selectionCriteria; // First look for a query key, then a mapping if (getQueryKeyOrNull() == null) { if ((getMapping() == null) || (!getMapping().isForeignReferenceMapping())) { return null; } else { // The join criteria is now twisted by the mappings. selectionCriteria = ((ForeignReferenceMapping) getMapping()).getJoinCriteria(this); } } else { if (!getQueryKeyOrNull().isForeignReferenceQueryKey()) { return null; } else { selectionCriteria = ((ForeignReferenceQueryKey) getQueryKeyOrNull()).getJoinCriteria(); selectionCriteria = getBaseExpression().twist(selectionCriteria, this); } } if (shouldUseOuterJoin() && getSession().getPlatform().shouldPrintOuterJoinInWhereClause()) { selectionCriteria = selectionCriteria.convertToUseOuterJoin(); } return selectionCriteria; }
/** * Translate the code required for getting the node for which the QName, local-name or namespace * URI should be extracted. */ public void translate(ClassGenerator classGen, MethodGenerator methodGen) { final ConstantPoolGen cpg = classGen.getConstantPool(); final InstructionList il = methodGen.getInstructionList(); il.append(methodGen.loadDOM()); // Function was called with no parameters if (argumentCount() == 0) { il.append(methodGen.loadContextNode()); } // Function was called with node parameter else if (_paramType == Type.Node) { _param.translate(classGen, methodGen); } else if (_paramType == Type.Reference) { _param.translate(classGen, methodGen); il.append( new INVOKESTATIC( cpg.addMethodref( BASIS_LIBRARY_CLASS, "referenceToNodeSet", "(" + OBJECT_SIG + ")" + NODE_ITERATOR_SIG))); il.append(methodGen.nextNode()); } // Function was called with node-set parameter else { _param.translate(classGen, methodGen); _param.startIterator(classGen, methodGen); il.append(methodGen.nextNode()); } }
@Override public Object doCompileTimeEvaluation() { Expression expr = getCompileTimeConstantExpression(); return expr instanceof INewExpression ? getName() // Enum constant field name : expr.evaluate(); }
/** * Die Methode führt die Kontextanalyse für diesen Ausdruck durch. * * @param declarations Die an dieser Stelle gültigen Deklarationen. * @return Dieser Ausdruck. * @throws CompileException Während der Kontextanylyse wurde ein Fehler gefunden. */ Expression contextAnalysis(Declarations declarations) throws CompileException { leftOperand = leftOperand.contextAnalysis(declarations); // Dereferenzieren. Außerdem könnte man einen Ausdruck wie z.B. 5.print // schreiben, wenn Integer Methoden hätte. leftOperand = leftOperand.box(declarations); /** BEGIN Aufgabe (i): Vererbung */ rightOperand.dynamicBind = leftOperand.bindsDynamically(); /** END Aufgabe (i) */ // Der rechte Operand hat einen Deklarationsraum, der sich aus dem // Ergebnistyp des linken Operanden ergibt. /** BEGIN Bonus Aufgabe 5: Zugriffsscutz */ // rightOperand.contextAnalysisForMember(leftOperand.type.declarations); rightOperand.contextAnalysisForMember(leftOperand.type.declarations, declarations.currentClass); /** END Bonus Aufgabe 5 */ /** BEGIN Aufgabe (f): Methoden Parameter */ rightOperand.contextAnalysisForParameters(declarations); /** END Aufgabe (f) */ // Der Typ dieses Ausdrucks ist immer der des rechten Operanden. type = rightOperand.type; lValue = rightOperand.lValue; return this; }
private Rvalue compileSimpleAssignment(IntermediateCompiler ic, Scope scope) throws SyntaxException { Rvalue rhs = right.compileWithConversion(ic, scope, left.getType(scope).decay()); Lvalue lhs = left.compileAsLvalue(ic, scope, false); ic.emit("store", rhs.getRegister(), "0", lhs.getRegister()); return rhs; }
private void writeMapDotProperty( final Expression receiver, final String methodName, final MethodVisitor mv, final boolean safe) { receiver.visit(controller.getAcg()); // load receiver Label exit = new Label(); if (safe) { Label doGet = new Label(); mv.visitJumpInsn(IFNONNULL, doGet); controller.getOperandStack().remove(1); mv.visitInsn(ACONST_NULL); mv.visitJumpInsn(GOTO, exit); mv.visitLabel(doGet); receiver.visit(controller.getAcg()); } mv.visitLdcInsn(methodName); // load property name mv.visitMethodInsn( INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;", true); if (safe) { mv.visitLabel(exit); } controller.getOperandStack().replace(OBJECT_TYPE); }
private void implementInvoke() { BlockExpression block = getBlock(); IParsedElement body = block.getBody(); DynamicFunctionSymbol value; if (body instanceof Expression) { Expression expression = (Expression) body; ReturnStatement syntheticReturnStatement = new ReturnStatement(); syntheticReturnStatement.setValue(expression); syntheticReturnStatement.initLocation( expression.getLocation().getOffset(), expression.getLocation().getLength(), expression.getLineNum(), expression.getColumn(), expression.getLocation().getScriptPartId()); value = new DynamicFunctionSymbol( null, INVOKE_METHOD_NAME, convertToObjectSignature(block), convertToObjectSymbols(block), syntheticReturnStatement); } else { value = new DynamicFunctionSymbol( null, INVOKE_METHOD_NAME, convertToObjectSignature(block), convertToObjectSymbols(block), (IStatement) body); } value.setClassMember(true); value.setPublic(true); value.setFinal(true); getParseInfo().addMemberFunction(value); }
@Override public void makeSingleArgumentCall( final Expression receiver, final String message, final Expression arguments) { TypeChooser typeChooser = controller.getTypeChooser(); ClassNode classNode = controller.getClassNode(); ClassNode rType = typeChooser.resolveType(receiver, classNode); ClassNode aType = typeChooser.resolveType(arguments, classNode); if (trySubscript(receiver, message, arguments, rType, aType)) { return; } // new try with flow type instead of declaration type rType = receiver.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE); if (rType != null && trySubscript(receiver, message, arguments, rType, aType)) { return; } // todo: more cases throw new GroovyBugError( "At line " + receiver.getLineNumber() + " column " + receiver.getColumnNumber() + "\n" + "On receiver: " + receiver.getText() + " with message: " + message + " and arguments: " + arguments.getText() + "\n" + "This method should not have been called. Please try to create a simple example reproducing this error and file" + "a bug report at http://jira.codehaus.org/browse/GROOVY"); }
@Override public Expression optimize(Session session) { if (columnResolver == null) { Schema schema = session .getDatabase() .findSchema(tableAlias == null ? session.getCurrentSchemaName() : tableAlias); if (schema != null) { Constant constant = schema.findConstant(columnName); if (constant != null) { return (Expression) constant.getValue(); } } // 处理在where和having中出现别名的情况,如: // SELECT id AS A FROM mytable where A>=0 // SELECT id/3 AS A, COUNT(*) FROM mytable GROUP BY A HAVING A>=0 if (select != null) { for (Expression e : select.getExpressions()) { if (database.equalsIdentifiers(columnName, e.getAlias())) return e.getNonAliasExpression().optimize(session); } } String name = columnName; if (tableAlias != null) { name = tableAlias + "." + name; if (schemaName != null) { name = schemaName + "." + name; } } throw DbException.get(ErrorCode.COLUMN_NOT_FOUND_1, name); } return (Expression) columnResolver.optimize(this, column); }
public void updateAggregate(Session session) { for (Expression e : args) { if (e != null) { e.updateAggregate(session); } } }