在这里,我们将给大家分享关于java.beans.Expression的实例源码的知识,让您更了解java.beans.introspection的本质,同时也会涉及到如何更有效地com.facebo
在这里,我们将给大家分享关于java.beans.Expression的实例源码的知识,让您更了解java.beans.introspection的本质,同时也会涉及到如何更有效地com.facebook.presto.sql.tree.Expression的实例源码、com.intellij.lang.javascript.psi.JSBinaryExpression的实例源码、com.intellij.lang.javascript.psi.JSCallExpression的实例源码、com.intellij.lang.javascript.psi.JSCommaExpression的实例源码的内容。
本文目录一览:- java.beans.Expression的实例源码(java.beans.introspection)
- com.facebook.presto.sql.tree.Expression的实例源码
- com.intellij.lang.javascript.psi.JSBinaryExpression的实例源码
- com.intellij.lang.javascript.psi.JSCallExpression的实例源码
- com.intellij.lang.javascript.psi.JSCommaExpression的实例源码
java.beans.Expression的实例源码(java.beans.introspection)
protected Expression instantiate(Object oldInstance,Encoder out) { Class oldClass = (Class) oldInstance; // Due to the special handling of String instances in the Encoder // this Expression does not lead to further class resolutions. if (oldClass == String.class) return new Expression(oldClass,"","getClass",null); // This Expression will lead to the class resolution of String.class. if (oldClass == Class.class) return new Expression(oldClass,String.class,null); // This Expression will lead to the class resolution of Class.class. return new Expression(oldClass,Class.class,"forName",new Object[] { oldClass.getName() }); }
protected Expression instantiate(Object oldInstance,Encoder out) { Class type = oldInstance.getClass().getComponentType(); // oldInstance is expected to be an array,then // getClass().getComponentType() should lead // to its component type. assert (type != null); // Not handling primitive types in a special way here // causes that Class.forName("int") is built as an Expression // later which would cause an exception if executed. A special // handling to avoid the execution for primitive types can be // java.beans.Encoder.writeExpression() . return new Expression( oldInstance,Array.class,"newInstance",new Object[] { type,new Integer(Array.getLength(oldInstance)) }); }
protected Expression instantiate(Object oldInstance,null); // This Expression will lead to the class resolution of Class.class. return new Expression(oldClass,new Object[] { oldClass.getName() }); }
protected Expression instantiate(Object oldInstance,new Integer(Array.getLength(oldInstance)) }); }
@Override protected Expression instantiate( Object oldInstance,Encoder out ) { Class type = oldInstance.getClass(); if ( !Modifier.isPublic( type.getModifiers() ) ) throw new IllegalArgumentException( "Could not instantiate instance of non-public class: " + oldInstance ); for ( Field field : type.getFields() ) { int mod = field.getModifiers(); if ( Modifier.isPublic( mod ) && Modifier.isstatic( mod ) && Modifier.isFinal( mod ) && ( type == field.getDeclaringClass() ) ) { try { if ( oldInstance == field.get( null ) ) return new Expression( oldInstance,field,"get",new Object[]{null} ); } catch ( illegalaccessexception exception ) { throw new IllegalArgumentException( "Could not get value of the field: " + field,exception ); } } } throw new IllegalArgumentException( "Could not instantiate value: " + oldInstance ); }
@Test public void testDiamond() throws Exception { if (SourceVersion.latestSupported().ordinal() >= 7) { compile("import java.util.List; import java.util.LinkedList; public class A{ List<Integer> bar = new LinkedList<>(); }"); SymbolTable symTable = getSymbolTable(); symTable.pushScope(); SymbolType st = new SymbolType(getClassLoader().loadClass("A")); symTable.pushSymbol("a",ReferenceType.VARIABLE,st,null); FieldAccessExpr expr = (FieldAccessExpr) ASTManager.parse(Expression.class,"a.bar"); HashMap<String,Object> ctx = new HashMap<String,Object>(); expressionAnalyzer.visit(expr,ctx); SymbolType type = (SymbolType) expr.getSymbolData(); Assert.assertNotNull(type); Assert.assertEquals("java.util.List",type.getName()); Assert.assertNotNull(type.getParameterizedTypes()); Assert.assertEquals("java.lang.Integer",type.getParameterizedTypes().get(0).getName()); } }
@Test public void testTargetInference() throws Exception { compile("import java.util.Collections; " + "import java.util.List; " + "public class A { public static void processstringList(List<String> stringList) {}}"); SymbolType st = new SymbolType(getClassLoader().loadClass("A")); SymbolTable symTable = getSymbolTable(); symTable.pushScope(); symTable.pushSymbol("A",ReferenceType.TYPE,null); MethodCallExpr expr = (MethodCallExpr) ASTManager.parse(Expression.class,"A.processstringList(Collections.emptyList());"); HashMap<String,Object>(); expressionAnalyzer.visit(expr,ctx); SymbolType type = (SymbolType) expr.getSymbolData(); Assert.assertNotNull(type); Assert.assertEquals("void",type.getName()); }
@Test public void testLambdaExpressionsWithExplicitArgs() throws Exception { if (SourceVersion.latestSupported().ordinal() >= 8) { String BCode = "public interface B { public int execute(int c); } "; compile("public class A{ public void run(B b){} " + BCode + "}"); SymbolType st = new SymbolType(getClassLoader().loadClass("A")); SymbolTable symTable = getSymbolTable(); symTable.pushScope(); symTable.pushSymbol("a",null); MethodCallExpr expr = (MethodCallExpr) ASTManager.parse(Expression.class,"a.run((int d)->d+1)"); HashMap<String,ctx); SymbolType type = (SymbolType) expr.getSymbolData(); Assert.assertNotNull(type); Assert.assertEquals("A$B",type.getmethod().getParameterTypes()[0].getName()); } }
@Test public void testMethodReferencesToConstructors() throws Exception { if (SourceVersion.latestSupported().ordinal() >= 8) { compile("import java.util.HashSet; public class A{ public static void foo(B b) {} public interface B{ public Object get();}}"); SymbolTable symTable = getSymbolTable(); symTable.pushSymbol("this",new SymbolType(getClassLoader().loadClass("A")),null); MethodCallExpr expr = (MethodCallExpr) ASTManager.parse(Expression.class,"A.foo(HashSet::new)"); HashMap<String,ctx); SymbolType type = (SymbolType) expr.getSymbolData(); Assert.assertNotNull(type); Assert.assertEquals("foo",type.getmethod().getName()); MethodReferenceExpr arg1 = (MethodReferenceExpr) expr.getArgs().get(0); SymbolType methodType = (SymbolType) arg1.getReferencedMethodSymbolData(); Assert.assertNotNull(methodType); Assert.assertEquals("get",methodType.getmethod().getName()); } }
@Test public void testTargetInferenceShouldFail() throws Exception { compile("import java.util.Collections; " + "import java.util.List; " + "public class A { public static <T> void processstringList(T[] args) {}}"); SymbolType st = new SymbolType(getClassLoader().loadClass("A")); SymbolTable symTable = getSymbolTable(); symTable.pushScope(); symTable.pushSymbol("A",null); try { MethodCallExpr expr = (MethodCallExpr) ASTManager.parse(Expression.class,"A.processstringList(Collections.emptyList());"); HashMap<String,ctx); fail("should not be reached: type=" + expr.getSymbolData().getmethod()); } catch (NoSuchExpressionTypeException e) { Assert.assertTrue(e.getMessage(),e.getMessage() .contains("Ops! The method call A.processstringList(Collections.emptyList()) is not resolved")); } }
/** * The test checks the correct static method is initialized */ public void testStatic() throws Exception { SampleBean theBean = new SampleBean(); Expression expr = new Expression(SampleBean.class,"create",new Object[] { "hello",theBean }); Object result = expr.getValue(); if (result != null && result instanceof SampleBean) { SampleBean bean = (SampleBean) result; assertEquals("hello",bean.getText()); assertEquals(theBean,bean.getobject()); } else { fail("Cannot instantiate an instance of Bean class by " + "static method."); } }
@Test public void testMethodReferencesToAnArrayItem() throws Exception { if (SourceVersion.latestSupported().ordinal() >= 8) { compile("import java.util.Arrays; public class A{}"); SymbolType st = new SymbolType(String.class); st.setArrayCount(1); SymbolTable symTable = getSymbolTable(); symTable.pushScope(); symTable.pushSymbol("stringArray",null); symTable.pushSymbol("this","Arrays.sort(stringArray,String::comparetoIgnoreCase)"); HashMap<String,ctx); SymbolType type = (SymbolType) expr.getSymbolData(); Assert.assertNotNull(type); Assert.assertEquals("sort",type.getmethod().getName()); MethodReferenceExpr arg1 = (MethodReferenceExpr) expr.getArgs().get(1); SymbolType methodType = (SymbolType) arg1.getReferencedMethodSymbolData(); Assert.assertNotNull(methodType); Assert.assertEquals("compare",methodType.getmethod().getName()); } }
@Test public void testGenericmethodsExplicitTypeInvocation() throws Exception { compile("import java.util.ArrayList; import java.io.Serializable;" + " public class A { public static <T> T pick(T a1,T a2) { return a2; }}"); SymbolTable symTable = getSymbolTable(); ASTSymbolTypeResolver.getInstance().setSymbolTable(symTable); symTable.pushScope(); SymbolType st = new SymbolType(getClassLoader().loadClass("A")); symTable.pushSymbol("A",null); MethodCallExpr expr = (MethodCallExpr) ASTManager.parse(Expression.class,"A.<Serializable>pick(\"d\",new ArrayList<String>())"); HashMap<String,ctx); SymbolType type = (SymbolType) expr.getSymbolData(); Assert.assertNotNull(type); Assert.assertEquals("java.io.Serializable",type.getName()); }
public void testTargetInference2() throws Exception { compile("import java.util.Collections; " + "import java.util.List; " + "public class A { public static void processAList(List<A> stringList) {}}"); SymbolType st = new SymbolType(getClassLoader().loadClass("A")); SymbolTable symTable = getSymbolTable(); symTable.pushScope(); symTable.pushSymbol("A",null); MethodCallExpr expr = (MethodCallExpr) ASTManager.parse(Expression.class,"A.processAList(Collections.emptyList());"); HashMap<String,ctx); SymbolType type = (SymbolType) expr.getSymbolData(); Assert.assertNotNull(type); Assert.assertEquals("void",type.getName()); }
@Test public void testReferencesToInnerClasses() throws Exception { compile(true,"public class OuterClass { public class InnerClass { } }"); SymbolTable symTable = getSymbolTable(); ASTSymbolTypeResolver.getInstance().setSymbolTable(symTable); symTable.pushScope(); SymbolType st = new SymbolType(getClassLoader().loadClass("OuterClass")); symTable.pushSymbol("outerObject",null); org.walkmod.javalang.ast.expr.Expression expr = (org.walkmod.javalang.ast.expr.Expression) ASTManager .parse(Expression.class,"outerObject.new InnerClass()"); HashMap<String,Object>(); expr.accept(expressionAnalyzer,ctx); SymbolType type = (SymbolType) expr.getSymbolData(); Assert.assertNotNull(type); Assert.assertEquals("OuterClass$InnerClass",type.getName()); }
@Override protected Expression instantiate(Object oldInstance,Encoder out) { byte[] e = (byte[]) oldInstance; return new Expression(e,ByteArrayPersistenceDelegate.class,"decode",new Object[] { ByteArrayPersistenceDelegate.encode(e) }); }
/** * Creates the value of this element. * * @param type the base class * @param args the array of arguments * @return the value of this element * @throws Exception if calculation is Failed */ @Override protected final ValueObject getValueObject(Class<?> type,Object[] args) throws Exception { if (this.field != null) { return ValueObjectImpl.create(FieldElementHandler.getFieldValue(getContextBean(),this.field)); } if (this.idref != null) { return ValueObjectImpl.create(getvariable(this.idref)); } Object bean = getContextBean(); String name; if (this.index != null) { name = (args.length == 2) ? PropertyElementHandler.SETTER : PropertyElementHandler.GETTER; } else if (this.property != null) { name = (args.length == 1) ? PropertyElementHandler.SETTER : PropertyElementHandler.GETTER; if (0 < this.property.length()) { name += this.property.substring(0,1).toupperCase(ENGLISH) + this.property.substring(1); } } else { name = (this.method != null) && (0 < this.method.length()) ? this.method : "new"; // NON-NLS: the constructor marker } Expression expression = new Expression(bean,name,args); return ValueObjectImpl.create(expression.getValue()); }
/** * Creates the value of this element. * * @param type the base class * @param args the array of arguments * @return the value of this element * @throws Exception if calculation is Failed */ @Override protected final ValueObject getValueObject(Class<?> type,args); return ValueObjectImpl.create(expression.getValue()); }
public static void main(String[] args) throws Exception { Object value = new Object(); Expression expression = new Expression(value,Object.class,"new",null); if (!value.equals(expression.getValue())) throw new Error("the value is updated unexpectedly"); expression.execute(); if (value.equals(expression.getValue())) throw new Error("the value is not updated as expected"); }
@Override public void writeExpression(Expression expression) { if (this.expression == null) { this.expression = expression; } super.writeExpression(expression); }
protected void initialize(XMLEncoder encoder) { encoder.setPersistenceDelegate(Container.class,new PersistenceDelegate() { protected Expression instantiate(Object oldInstance,Encoder out) { Container container = (Container) oldInstance; Component component = container.getComponent(); return new Expression(container,component,new Object[] {component}); } }); }
protected void initialize(XMLEncoder encoder) { encoder.setPersistenceDelegate( OuterClass.InnerClass.class,new DefaultPersistenceDelegate() { protected Expression instantiate(Object oldInstance,Encoder out) { OuterClass.InnerClass inner = (OuterClass.InnerClass) oldInstance; OuterClass outer = inner.getouter(); return new Expression(inner,outer,"getInner",new Object[0]); } } ); }
protected void initialize(XMLEncoder encoder) { encoder.setPersistenceDelegate(C.class,new DefaultPersistenceDelegate() { protected Expression instantiate(Object oldInstance,Encoder out) { C c = (C) oldInstance; return new Expression(c,c.getX(),"createC",new Object[] {}); } }); }
/** * Creates the value of this element. * * @param type the base class * @param args the array of arguments * @return the value of this element * @throws Exception if calculation is Failed */ @Override protected final ValueObject getValueObject(Class<?> type,args); return ValueObjectImpl.create(expression.getValue()); }
public static void main(String[] args) throws Exception { Object value = new Object(); Expression expression = new Expression(value,null); if (!value.equals(expression.getValue())) throw new Error("the value is updated unexpectedly"); expression.execute(); if (value.equals(expression.getValue())) throw new Error("the value is not updated as expected"); }
@Override public void writeExpression(Expression expression) { if (this.expression == null) { this.expression = expression; } super.writeExpression(expression); }
protected void initialize(XMLEncoder encoder) { encoder.setPersistenceDelegate(Container.class,new Object[] {component}); } }); }
protected void initialize(XMLEncoder encoder) { encoder.setPersistenceDelegate( OuterClass.InnerClass.class,new Object[0]); } } ); }
protected void initialize(XMLEncoder encoder) { encoder.setPersistenceDelegate(C.class,new Object[] {}); } }); }
/** * Creates the value of this element. * * @param type the base class * @param args the array of arguments * @return the value of this element * @throws Exception if calculation is Failed */ @Override protected final ValueObject getValueObject(Class<?> type,args); return ValueObjectImpl.create(expression.getValue()); }
public static void main(String[] args) throws Exception { Object value = new Object(); Expression expression = new Expression(value,null); if (!value.equals(expression.getValue())) throw new Error("the value is updated unexpectedly"); expression.execute(); if (value.equals(expression.getValue())) throw new Error("the value is not updated as expected"); }
@Override public void writeExpression(Expression expression) { if (this.expression == null) { this.expression = expression; } super.writeExpression(expression); }
protected void initialize(XMLEncoder encoder) { encoder.setPersistenceDelegate(Container.class,new Object[] {component}); } }); }
protected void initialize(XMLEncoder encoder) { encoder.setPersistenceDelegate( OuterClass.InnerClass.class,new Object[0]); } } ); }
protected void initialize(XMLEncoder encoder) { encoder.setPersistenceDelegate(C.class,new Object[] {}); } }); }
@SuppressWarnings("unchecked") public static <E,R> R getmethodValue(E obj,Method method,Object... args) { R value = null; try { method.setAccessible(true); value = (R) method.invoke(obj,args); } catch (InvocationTargetException | illegalaccessexception | IllegalArgumentException e) { // e.printstacktrace(); try { if (obj != null) { Expression expr = new Expression(obj,method.getName(),args); expr.execute(); value = (R) expr.getValue(); } if (value == null) { value = (R) method.getDefaultValue(); } } catch (Exception e1) { // e1.printstacktrace(); } } return value; }
/** * Creates the value of this element. * * @param type the base class * @param args the array of arguments * @return the value of this element * @throws Exception if calculation is Failed */ @Override protected final ValueObject getValueObject(Class<?> type,args); return ValueObjectImpl.create(expression.getValue()); }
public static void main(String[] args) throws Exception { Object value = new Object(); Expression expression = new Expression(value,null); if (!value.equals(expression.getValue())) throw new Error("the value is updated unexpectedly"); expression.execute(); if (value.equals(expression.getValue())) throw new Error("the value is not updated as expected"); }
@Override public void writeExpression(Expression expression) { if (this.expression == null) { this.expression = expression; } super.writeExpression(expression); }
protected void initialize(XMLEncoder encoder) { encoder.setPersistenceDelegate(Container.class,new Object[] {component}); } }); }
com.facebook.presto.sql.tree.Expression的实例源码
protected static String processFuncSet(Formatter formatter,FunctionCall node) { StringBuilder builder = new StringBuilder(); String functionName = getFunctionName(node); int numArguments = node.getArguments().size(); builder.append(functionName).append('(').append(formatter.process(node.getArguments().get(0),null)).append( ')'); if (numArguments > 1) { builder.append(" ON "); } for (int i = 1; i < numArguments; i++) { Expression item = node.getArguments().get(i); if (i == 1) { builder.append(formatter.process(item,null)); } else { builder.append(",").append(formatter.process(item,null)); } } return builder.toString(); }
@Override protected String visitArithmeticExpression(ArithmeticExpression node,Void context) { if (node.getType().equals(ArithmeticExpression.Type.DIVIDE)) { if (_outputDivideByZeroGuard == true) { if (node.getRight() instanceof FunctionCall) { if (getFunctionName((FunctionCall) node.getRight()).equals("nullifzero")) { // bypass appending nullifzero return formatBinaryExpression(node.getType().getValue(),node.getLeft(),node.getRight()); } } else if (node.getRight() instanceof Literal) { // purely literal return formatBinaryExpression(node.getType().getValue(),node.getRight()); } List<Expression> arguments = new ArrayList<Expression>(); arguments.add(node.getRight()); FunctionCall nullifzeroFunc = new FunctionCall(new Qualifiedname("nullifzero"),arguments); return formatBinaryExpression(node.getType().getValue(),nullifzeroFunc); } else { return formatBinaryExpression(node.getType().getValue(),node.getRight()); } } else { return formatBinaryExpression(node.getType().getValue(),node.getRight()); } }
protected String joinPassExpressions(String on,List<Expression> expressions) { return Joiner.on(on).join(transform(expressions,new Function<Expression,Object>() { @Override public Object apply(Expression input) { if (input instanceof QualifiednameReference) { // 20150709: enclose vero ident in () in case association matters return '(' + process(input,null) + ')'; } else { return process(input,null); } } })); }
public static void printExpression(String sql) { println(sql.trim()); println(""); System.out.println("EXP Printing CommonTree toString..."); CommonTree tree = VerosqlParser.parseExpression(sql); println(TreePrinter.treetoString(tree)); println(""); System.out.println("EXP Printing AST toString..."); Expression expression = VerosqlParser.createExpression(tree); println(expression.toString()); println(""); System.out.println("EXP Printing Format sql toString..."); // Todo: support formatting all statement types println(FormatterFactory.getsqlFormatter().formatsql(expression)); println(""); println(repeat("=",60)); println(""); }
@Override protected Void visitValues(Values node,Integer indent) { builder.append(" VALUES "); boolean first = true; for (Expression row : node.getRows()) { builder.append("\n") .append(indentString(indent)) .append(first ? " " : ","); builder.append(formatExpression(row,parameters,indent)); first = false; } builder.append('\n'); return null; }
/** * Parses the list with values to insert and returns them as Objects */ @Override public List<Object> visitValues(Values values,QueryState state){ List<Object> result = new ArrayList<Object>(); for(Expression rowExpression : values.getRows()){ if(rowExpression instanceof Row) { Row row = (Row)rowExpression; for(Expression rowValue : row.getItems()){ if(!(rowValue instanceof Literal)) { state.addException("Unable to parse non-literal value : "+rowValue); return result; } result.add(getobject((Literal)rowValue)); } }else if (rowExpression instanceof Literal){ result.add(getobject((Literal)rowExpression)); }else { state.addException("UnkNown VALUES type "+rowExpression.getClass()+" encountered"); return null; } } return result; }
@Override public PlanNode visitSample(SampleNode node,RewriteContext<Void> context) { if (node.getSampleType() == SampleNode.Type.BERNOULLI) { PlanNode rewrittenSource = context.rewrite(node.getSource()); ComparisonExpression expression = new ComparisonExpression( ComparisonExpression.Type.LESS_THAN,new FunctionCall(Qualifiedname.of("rand"),ImmutableList.<Expression>of()),new DoubleLiteral(Double.toString(node.getSampleRatio()))); return new FilterNode(node.getId(),rewrittenSource,expression); } else if (node.getSampleType() == SampleNode.Type.POISSONIZED || node.getSampleType() == SampleNode.Type.SYstem) { return context.defaultRewrite(node); } throw new UnsupportedOperationException("not yet implemented"); }
@Test public void testFromIsNullPredicate() throws Exception { Expression originalExpression = isNull(A); ExtractionResult result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(),TRUE_LIteraL); assertEquals(result.getTupleDomain(),withColumnDomains(ImmutableMap.of(A,Domain.onlyNull(BIGINT)))); originalExpression = isNull(K); result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(),withColumnDomains(ImmutableMap.of(K,Domain.onlyNull(HYPER_LOG_LOG)))); originalExpression = not(isNull(A)); result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(),Domain.notNull(BIGINT)))); originalExpression = not(isNull(K)); result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(),Domain.notNull(HYPER_LOG_LOG)))); }
private OperatorFactory compileFilterWithNoInputColumns(Expression filter,ExpressionCompiler compiler) { filter = ExpressionTreeRewriter.rewriteWith(new SymbolToInputRewriter(ImmutableMap.<Symbol,Integer>of()),filter); IdentityHashMap<Expression,Type> expressionTypes = getExpressionTypesFromInput(TEST_SESSION,Metadata,sql_PARSER,INPUT_TYPES,ImmutableList.of(filter)); try { PageProcessor processor = compiler.compilePageProcessor(toRowExpression(filter,expressionTypes),ImmutableList.of()); return new FilterandProjectOperator.FilterandProjectOperatorFactory(0,new PlanNodeId("test"),processor,ImmutableList.<Type>of()); } catch (Throwable e) { if (e instanceof UncheckedExecutionException) { e = e.getCause(); } throw new RuntimeException("Error compiling " + filter + ": " + e.getMessage(),e); } }
public InterpretedFilterFunction( Expression predicate,Map<Symbol,Type> symbolTypes,Integer> symbolToInputMappings,Metadata Metadata,sqlParser sqlParser,Session session) { // pre-compute symbol -> input mappings and replace the corresponding nodes in the tree Expression rewritten = ExpressionTreeRewriter.rewriteWith(new SymbolToInputRewriter(symbolToInputMappings),predicate); // analyze expression so we can kNow the type of every expression in the tree ImmutableMap.Builder<Integer,Type> inputTypes = ImmutableMap.builder(); for (Map.Entry<Symbol,Integer> entry : symbolToInputMappings.entrySet()) { inputTypes.put(entry.getValue(),symbolTypes.get(entry.getKey())); } IdentityHashMap<Expression,Type> expressionTypes = getExpressionTypesFromInput(session,sqlParser,inputTypes.build(),rewritten); evaluator = ExpressionInterpreter.expressionInterpreter(rewritten,session,expressionTypes); }
@Override public PlanNode visitTableScan(TableScanNode node,RewriteContext<Void> context) { Expression originalConstraint = null; if (node.getoriginalConstraint() != null) { originalConstraint = canonicalizeExpression(node.getoriginalConstraint()); } return new TableScanNode( node.getId(),node.getTable(),node.getoutputSymbols(),node.getAssignments(),node.getLayout(),node.getCurrentConstraint(),originalConstraint); }
@Override public Void visitProject(ProjectNode node,Void context) { StringBuilder builder = new StringBuilder(); for (Map.Entry<Symbol,Expression> entry : node.getAssignments().entrySet()) { if ((entry.getValue() instanceof QualifiednameReference) && ((QualifiednameReference) entry.getValue()).getName().equals(entry.getKey().toQualifiedname())) { // skip identity assignments continue; } builder.append(format("%s := %s\\n",entry.getKey(),entry.getValue())); } printNode(node,"Project",builder.toString(),NODE_COLORS.get(NodeType.PROJECT)); return node.getSource().accept(this,context); }
private Expression rewriteExpression(Expression expression,Predicate<Symbol> symbolScope,boolean allowFullReplacement) { Iterable<Expression> subExpressions = SubExpressionExtractor.extract(expression); if (!allowFullReplacement) { subExpressions = filter(subExpressions,not(equalTo(expression))); } ImmutableMap.Builder<Expression,Expression> expressionRemap = ImmutableMap.builder(); for (Expression subExpression : subExpressions) { Expression canonical = getScopedCanonical(subExpression,symbolScope); if (canonical != null) { expressionRemap.put(subExpression,canonical); } } // Perform a naive single-pass traversal to try to rewrite non-compliant portions of the tree. Prefers to replace // larger subtrees over smaller subtrees // Todo: this rewrite can probably be made more sophisticated Expression rewritten = ExpressionTreeRewriter.rewriteWith(new ExpressionNodeInliner(expressionRemap.build()),expression); if (!symbolToExpressionPredicate(symbolScope).apply(rewritten)) { // If the rewritten is still not compliant with the symbol scope,just give up return null; } return rewritten; }
@Override protected Type visitInPredicate(InPredicate node,StackableAstVisitorContext<AnalysisContext> context) { Expression value = node.getValue(); process(value,context); Expression valueList = node.getValueList(); process(valueList,context); if (valueList instanceof InListExpression) { InListExpression inListExpression = (InListExpression) valueList; coercetoSingleType(context,"IN value and list items must be the same type: %s",ImmutableList.<Expression>builder().add(value).addAll(inListExpression.getValues()).build()); } else if (valueList instanceof SubqueryExpression) { coercetoSingleType(context,node,"value and result of subquery must be of the same type for IN expression: %s vs %s",value,valueList); } expressionTypes.put(node,BOOLEAN); return BOOLEAN; }
@Override public Boolean visitwindowFrame(WindowFrame node,Void context) { Optional<Expression> start = node.getStart().getValue(); if (start.isPresent()) { if (!process(start.get(),context)) { throw new SemanticException(MUST_BE_AGGREGATE_OR_GROUP_BY,start.get(),"Window frame start must be an aggregate expression or appear in GROUP BY clause"); } } if (node.getEnd().isPresent() && node.getEnd().get().getValue().isPresent()) { Expression endValue = node.getEnd().get().getValue().get(); if (!process(endValue,endValue,"Window frame end must be an aggregate expression or appear in GROUP BY clause"); } } return true; }
@Test public void testFromIsNotNullPredicate() throws Exception { Expression originalExpression = isNotNull(A); ExtractionResult result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(),Domain.notNull(BIGINT)))); originalExpression = isNotNull(K); result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(),Domain.notNull(HYPER_LOG_LOG)))); originalExpression = not(isNotNull(A)); result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(),Domain.onlyNull(BIGINT)))); originalExpression = not(isNotNull(K)); result = fromPredicate(originalExpression); assertEquals(result.getRemainingExpression(),Domain.onlyNull(HYPER_LOG_LOG)))); }
@Override public Void visitProject(ProjectNode node,Void context) { PlanNode source = node.getSource(); source.accept(this,context); // visit child verifyUniqueId(node); Set<Symbol> inputs = ImmutableSet.copyOf(source.getoutputSymbols()); for (Expression expression : node.getAssignments().values()) { Set<Symbol> dependencies = DependencyExtractor.extractUnique(expression); checkDependencies(inputs,dependencies,"Invalid node. Expression dependencies (%s) not in source plan output (%s)",inputs); } return null; }
protected static String processFuncatan2(Formatter formatter,FunctionCall node) { Expression x = node.getArguments().get(0); Expression y = node.getArguments().get(1); FunctionCall xx = new FunctionCall(new Qualifiedname("power"),Arrays.asList(x,new LongLiteral("2"))); FunctionCall yy = new FunctionCall(new Qualifiedname("power"),Arrays.asList(y,new LongLiteral("2"))); ArithmeticExpression xxAddyy = new ArithmeticExpression(ArithmeticExpression.Type.ADD,xx,yy); FunctionCall sqrt_xxAddyy = new FunctionCall(new Qualifiedname("sqrt"),Arrays.asList(xxAddyy)); ArithmeticExpression substract = new ArithmeticExpression(ArithmeticExpression.Type.SUBTRACT,sqrt_xxAddyy,x); ArithmeticExpression divide = new ArithmeticExpression(ArithmeticExpression.Type.DIVIDE,substract,y); FunctionCall arctan = new FunctionCall(new Qualifiedname("atan"),Arrays.asList(divide)); ArithmeticExpression multiply = new ArithmeticExpression(ArithmeticExpression.Type.MULTIPLY,new DoubleLiteral("2"),arctan); return formatter.process(multiply,null); }
protected static String processFuncNullifzero(Formatter formatter,FunctionCall node) { Expression x = node.getArguments().get(0); List<WhenClause> listWhen = new ArrayList<WhenClause>(); ComparisonExpression ce = new ComparisonExpression(ComparisonExpression.Type.EQUAL,x,new LongLiteral("0")); WhenClause wc = new WhenClause(ce,new NullLiteral()); listWhen.add(wc); SearchedCaseExpression sce = new SearchedCaseExpression(listWhen,x); return formatter.process(sce,null); }
protected static Expression processFuncLast(ComparisonExpression node) { System.out.println("Processing last()"); Expression rightNode = node.getRight(); Expression leftNode = node.getLeft(); FunctionCall last = (FunctionCall) rightNode; // # of arguments are already checked outside 1 or 2 String number = last.getArguments().get(0).toString(); String format = "DAY"; // default if (last.getArguments().size() == 2) { format = last.getArguments().get(1).toString().replaceAll("\"",""); } IntervalLiteral.Sign sign; if (number.startsWith("-")) { sign = IntervalLiteral.Sign.NEGATIVE; number = number.substring(1); } else { sign = IntervalLiteral.Sign.POSITIVE; } CurrentTime cTime = new CurrentTime(CurrentTime.Type.DATE); IntervalLiteral interval = new IntervalLiteral(number,sign,format); ArithmeticExpression arithmOp = new ArithmeticExpression(ArithmeticExpression.Type.SUBTRACT,cTime,interval); BetweenPredicate bPredicate = new BetweenPredicate(leftNode,arithmOp,cTime); return bPredicate; }
public Function<Expression,String> expressionFormatterFunction() { return new Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
@Override protected String visitArrayConstructor(ArrayConstructor node,Void context) { ImmutableList.Builder<String> valueStrings = ImmutableList.builder(); for (Expression value : node.getValues()) { valueStrings.add(sqlFormatter.formatsql(value)); } return "ARRAY[" + Joiner.on(",").join(valueStrings.build()) + "]"; }
protected String formatBinaryExpression(String operator,Expression left,Expression right) { if (operator.equals("")) { // 20150709: +VPC+ return process(left,null) + process(right,null); } else { return '(' + process(left,null) + ' ' + operator + ' ' + process(right,null) + ')'; } }
protected String joinExpressions(List<Expression> expressions) { return Joiner.on(",").join(transform(expressions,Object>() { @Override public Object apply(Expression input) { return process(input,null); } })); }
protected String joinExpressions(String on,null); } })); }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
public Function<Expression,String>() { @Override public String apply(Expression input) { return formatExpression(input); } }; }
@Override protected String visitArrayConstructor(ArrayConstructor node,StackableAstVisitorContext<Integer> indent) { ImmutableList.Builder<String> valueStrings = ImmutableList.builder(); for (Expression value : node.getValues()) { valueStrings.add(formatExpression(value,indent.getContext() + 1)); } return "ARRAY[" + Joiner.on(",").join(valueStrings.build()) + "]"; }
com.intellij.lang.javascript.psi.JSBinaryExpression的实例源码
@Nullable private static Alignment alignmentProjection(final Alignment defaultAlignment,final ASTNode parent,final ASTNode child) { if(parent.getElementType() == JSElementTypes.FOR_STATEMENT && (JSElementTypes.EXPRESSIONS.contains(child.getElementType()) || child.getElementType () == JSElementTypes.VAR_STATEMENT)) { return defaultAlignment; } else if(parent.getElementType() == JSElementTypes.ParaMETER_LIST && child.getElementType() == JSElementTypes.FORMAL_ParaMETER) { return defaultAlignment; } else if(parent.getPsi() instanceof JSBinaryExpression && JSElementTypes.EXPRESSIONS.contains(child.getElementType())) { return defaultAlignment; } else if(parent.getElementType() == JSElementTypes.CONDITIONAL_EXPRESSION && JSElementTypes.EXPRESSIONS.contains(child.getElementType())) { return defaultAlignment; } return null; }
private int countTerms(JSExpression expression) { if (expression == null) { return 0; } if (!isBoolean(expression)) { return 1; } if (expression instanceof JSBinaryExpression) { final JSBinaryExpression binaryExpression = (JSBinaryExpression) expression; final JSExpression lhs = binaryExpression.getLOperand(); final JSExpression rhs = binaryExpression.getROperand(); return countTerms(lhs) + countTerms(rhs); } else if (expression instanceof JSPrefixExpression) { final JSPrefixExpression prefixExpression = (JSPrefixExpression) expression; final JSExpression operand = prefixExpression.getExpression(); return countTerms(operand); } else if (expression instanceof JSParenthesizedExpression) { final JSParenthesizedExpression parenthesizedExpression = (JSParenthesizedExpression) expression; final JSExpression contents = parenthesizedExpression.getInnerExpression(); return countTerms(contents); } return 1; }
@Override public void visitJSBinaryExpression( @NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); final JSExpression lhs = expression.getLOperand(); if (lhs == null) { return; } final JSExpression rhs = expression.getROperand(); if (rhs == null) { return; } final IElementType tokenType = expression.getoperationSign(); if (!JSTokenTypes.EQEQ.equals(tokenType) && !JSTokenTypes.NE.equals(tokenType)) { return; } if(!mayCauseCoercion(rhs) &&!mayCauseCoercion(lhs)) { return; } registerError(expression); }
@Override public void visitJSBinaryExpression( @NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); final JSExpression rhs = expression.getROperand(); if (rhs == null) { return; } final IElementType tokenType = expression.getoperationSign(); if (!JSTokenTypes.DIV.equals(tokenType) && !JSTokenTypes.PERC.equals(tokenType)) { return; } if(!isZero(rhs)) { return; } registerError(expression); }
@Override public void visitJSBinaryExpression(@NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); if (!(expression.getROperand() != null)) { return; } if (!ComparisonUtils.isComparison(expression)) { return; } final JSExpression lhs = expression.getLOperand(); final JSExpression rhs = expression.getROperand(); if (lhs instanceof JSLiteralExpression || !(rhs instanceof JSLiteralExpression)) { return; } registerError(expression); }
@Override public void visitJSBinaryExpression(@NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); if (!(expression.getROperand() != null)) { return; } if (!ComparisonUtils.isComparison(expression)) { return; } final JSExpression lhs = expression.getLOperand(); final JSExpression rhs = expression.getROperand(); if (!(lhs instanceof JSLiteralExpression) || rhs instanceof JSLiteralExpression) { return; } registerError(expression); }
@Override public void visitJSBinaryExpression( @NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); if (!(expression.getROperand() != null)) { return; } if (!isEqualityComparison(expression)) { return; } final JSExpression lhs = expression.getLOperand(); if (!(lhs instanceof JSBinaryExpression)) { return; } if (!isEqualityComparison((JSBinaryExpression) lhs)) { return; } registerError(expression); }
private static boolean isConstantMask(JSExpression expression) { if (expression == null) { return false; } if (!(expression instanceof JSBinaryExpression)) { return false; } final JSBinaryExpression binaryExpression = (JSBinaryExpression) expression; final IElementType tokenType = binaryExpression.getoperationSign(); if (!JSTokenTypes.OR.equals(tokenType) && !JSTokenTypes.AND.equals(tokenType)) { return false; } final JSExpression rhs = binaryExpression.getROperand(); if (ExpressionUtil.isConstantExpression(rhs)) { return true; } final JSExpression lhs = binaryExpression.getLOperand(); return ExpressionUtil.isConstantExpression(lhs); }
private static boolean binaryExpressionDefinitelyRecurses( JSBinaryExpression expression,JSFunction method) { final JSExpression lhs = expression.getLOperand(); if (RecursionUtil.expressionDefinitelyRecurses(lhs,method)) { return true; } final IElementType tokenType = expression.getoperationSign(); if (tokenType.equals(JSTokenTypes.ANDAND) || tokenType.equals(JSTokenTypes.OROR)) { return false; } return RecursionUtil.expressionDefinitelyRecurses(expression.getROperand(),method); }
public static JSExpression getNegated(JSExpression condition) { if (condition instanceof JSPrefixExpression) { final JSPrefixExpression prefixExp = (JSPrefixExpression) condition; final JSExpression operand = prefixExp.getExpression(); return ParenthesesUtils.stripParentheses(operand); } else if (condition instanceof JSBinaryExpression) { final JSBinaryExpression binaryExpression = (JSBinaryExpression) condition; final IElementType sign = binaryExpression.getoperationSign(); final JSExpression lhs = binaryExpression.getLOperand(); final JSExpression rhs = binaryExpression.getROperand(); final String negatedSign = ComparisonUtils.getNegatedOperatorText(sign); final String negatedText = lhs.getText() + negatedSign + rhs.getText(); return (JSExpression) JSChangeUtil.createExpressionFromText( condition.getProject(),negatedText); } else if (condition instanceof JSParenthesizedExpression) { return getNegated(((JSParenthesizedExpression) condition).getInnerExpression()); } return condition; }
@Override protected String getTextForElement(PsiElement element) { final PsiElement parent = element.getParent(); final JSBinaryExpression binaryExpression = (JSBinaryExpression) (parent instanceof JSBinaryExpression ? parent : element); final JSExpression lhs = binaryExpression.getLOperand(); final JSExpression leftSide; if (lhs instanceof JSBinaryExpression) { leftSide = ((JSBinaryExpression) lhs).getROperand(); } else { leftSide = lhs; } final IElementType operationSign = binaryExpression.getoperationSign(); final JSExpression rhs = binaryExpression.getROperand(); assert (rhs != null); assert (leftSide != null); return this.getText(leftSide.getText(),BinaryOperatorUtils.getoperatorText(operationSign),rhs.getText()); }
@Override public String getTextForElement(PsiElement element) { final JSBinaryExpression exp = (JSBinaryExpression) element; String operatorText = null; String flippedOperatorText = null; if (exp != null) { operatorText = ComparisonUtils.getoperatorText (exp.getoperationSign()); flippedOperatorText = ComparisonUtils.getFlippedOperatorText(exp.getoperationSign()); } if (exp == null) { return this.getSuffixeddisplayName("unkNown"); } else if (operatorText.equals(flippedOperatorText)) { return this.getSuffixeddisplayName("equals",operatorText); } else { return this.getSuffixeddisplayName("not-equals",operatorText,flippedOperatorText); } }
@Override public boolean satisfiedBy(@NotNull PsiElement element) { if (!(element instanceof JSBinaryExpression)) { return false; } if (ErrorUtil.containsError(element)) { return false; } final JSBinaryExpression expression = (JSBinaryExpression) element; final IElementType sign = expression.getoperationSign(); if (!(sign.equals(JSTokenTypes.EQEQ) || sign.equals(JSTokenTypes.NE))) { return false; } final JSExpression lhs = expression.getLOperand(); final JSExpression rhs = expression.getROperand(); return (lhs != null && rhs != null && (BoolUtils.isBooleanLiteral(lhs) || BoolUtils.isBooleanLiteral(rhs))); }
@Override public String getTextForElement(PsiElement element) { final JSBinaryExpression expression = (JSBinaryExpression) element; String operatorText = ""; String negatedOperatorText = ""; if (expression != null) { final IElementType sign = expression.getoperationSign(); operatorText = ComparisonUtils.getoperatorText(sign); negatedOperatorText = ComparisonUtils.getNegatedOperatorText(sign); } if (operatorText.equals(negatedOperatorText)) { return this.getSuffixeddisplayName("equals",negatedOperatorText); } }
@Override public boolean satisfiedBy(@NotNull PsiElement element) { if (!(element instanceof JSBinaryExpression)) { return false; } if (ErrorUtil.containsError(element)) { return false; } final JSBinaryExpression expression = (JSBinaryExpression) element; final JSExpression rhs = expression.getROperand(); return (rhs != null && ComparisonUtils.isComparisonoperator((JSExpression) element)); }
@Override public void processIntention(@NotNull PsiElement element) throws IncorrectOperationException { final JSBinaryExpression expression = (JSBinaryExpression) element; final JSExpression lhs = expression.getLOperand(); final JSExpression rhs = expression.getROperand(); assert (lhs instanceof JSLiteralExpression && rhs instanceof JSLiteralExpression); final JSLiteralExpression leftLiteral = (JSLiteralExpression) lhs; final JSLiteralExpression rightLiteral = (JSLiteralExpression) rhs; String lhsText = lhs.getText(); String rhsText = rhs.getText(); final String newExpression; if (StringUtil.isSimpleQuoteStringLiteral(leftLiteral) && StringUtil.isDoubleQuoteStringLiteral(rightLiteral)) { rhsText = JSDoubletoSingleQuotedStringIntention.changeQuotes(rhsText); } else if (StringUtil.isDoubleQuoteStringLiteral(leftLiteral) && StringUtil.isSimpleQuoteStringLiteral(rightLiteral)) { rhsText = JSSingletoDoubleQuotedStringIntention.changeQuotes(rhsText); } newExpression = lhsText.substring(0,lhsText.length() - 1) + rhsText.substring(1); JSElementFactory.replaceExpression(expression,newExpression); }
@Override public boolean satisfiedBy(@NotNull PsiElement element) { if (!(element instanceof JSBinaryExpression)) { return false; } final JSBinaryExpression expression = (JSBinaryExpression) element; final IElementType sign = expression.getoperationSign(); if (!sign.equals(JSTokenTypes.PLUS)) { return false; } final JSExpression lhs = expression.getLOperand(); final JSExpression rhs = expression.getROperand(); if (!isApplicableLiteral(lhs)) { return false; } if (!isApplicableLiteral(rhs)) { return false; } return true; }
private void replaceMultiplyOrDivideWithShift(JSBinaryExpression exp) throws IncorrectOperationException { JSExpression lhs = exp.getLOperand(); JSExpression rhs = exp.getROperand(); final IElementType tokenType = exp.getoperationSign(); final String operatorString = (tokenType.equals(JSTokenTypes.MULT) ? "<<" : ">>"); if (ShiftUtils.isPowerOfTwo(lhs) && tokenType.equals(JSTokenTypes.MULT)) { JSExpression swap = lhs; lhs = rhs; rhs = swap; } final String lhsText = ParenthesesUtils.getParenthesized(lhs,ParenthesesUtils.SHIFT_PRECENDENCE); String expString = lhsText + operatorString + ShiftUtils.getLogBase2(rhs); final JSElement parent = (JSElement) exp.getParent(); if (parent != null && parent instanceof JSExpression) { if (!(parent instanceof JSParenthesizedExpression) && ParenthesesUtils.getPrecendence((JSExpression) parent) < ParenthesesUtils.SHIFT_PRECENDENCE) { expString = '(' + expString + ')'; } } JSElementFactory.replaceExpression(exp,expString); }
private void replaceShiftWithMultiplyOrDivide(JSBinaryExpression exp) throws IncorrectOperationException { final JSExpression lhs = exp.getLOperand(); final JSExpression rhs = exp.getROperand(); final IElementType tokenType = exp.getoperationSign(); final String operatorString = ((tokenType.equals(JSTokenTypes.LTLT)) ? "*" : "/"); final String lhsText = ParenthesesUtils.getParenthesized(lhs,ParenthesesUtils.MULTIPLICATIVE_PRECENDENCE); String expString = lhsText + operatorString + ShiftUtils.getExpBase2(rhs); final JSElement parent = (JSElement) exp.getParent(); if (parent != null && parent instanceof JSExpression) { if (!(parent instanceof JSParenthesizedExpression) && ParenthesesUtils.getPrecendence((JSExpression) parent) < ParenthesesUtils.MULTIPLICATIVE_PRECENDENCE) { expString = '(' + expString + ')'; } } JSElementFactory.replaceExpression(exp,expString); }
@Override public void processIntention(@NotNull PsiElement element) throws IncorrectOperationException { final JSAssignmentExpression exp = (JSAssignmentExpression) element; final JSBinaryExpression rhs = (JSBinaryExpression) exp.getROperand(); final JSExpression lhs = exp.getLOperand(); assert (rhs != null); final IElementType sign = rhs.getoperationSign(); final String operand = BinaryOperatorUtils.getoperatorText(sign); final JSExpression rhsrhs = rhs.getROperand(); assert (rhsrhs != null); JSElementFactory.replaceExpression(exp,lhs.getText() + operand + '=' + rhsrhs.getText()); }
@Override public boolean satisfiedBy(@NotNull PsiElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof JSIfStatement)) { if (element instanceof JSIfStatement) { parent = element; } else { return false; } } final JSIfStatement ifStatement = (JSIfStatement) parent; final JSExpression condition = ifStatement.getCondition(); if (condition == null || ErrorUtil.containsError(condition)) { return false; } return (condition instanceof JSBinaryExpression && ((JSBinaryExpression) condition).getoperationSign().equals(JSTokenTypes.OROR)); }
@Override public boolean satisfiedBy(@NotNull PsiElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof JSIfStatement)) { if (element instanceof JSIfStatement) { parent = element; } else { return false; } } final JSIfStatement ifStatement = (JSIfStatement) parent; final JSExpression condition = ifStatement.getCondition(); if (condition == null || ErrorUtil.containsError(condition)) { return false; } return (condition instanceof JSBinaryExpression && ((JSBinaryExpression) condition).getoperationSign().equals(JSTokenTypes.ANDAND)); }
@Override public void invoke(@NotNull Project project,@NotNull PsiFile psiFile,@Nullable("is null when called from inspection") Editor editor,@NotNull PsiElement element,@NotNull PsiElement end) throws IncorrectOperationException { // PsiElement element = descriptor.getPsiElement(); JSBinaryExpression binary = PsiTreeUtil.getParentOfType(element,JSBinaryExpression.class); JSBinaryExpression binaryClone = (JSBinaryExpression) binary.copy(); binaryClone.getLOperand().replace(binary.getLOperand().getLastChild()); ASTNode negate = JSChangeUtil.createStatementFromText(project,"!(true)"); JSParenthesizedExpression paren = PsiTreeUtil.getChildOfType(negate.getPsi().getFirstChild(),JSParenthesizedExpression.class); paren.getInnerExpression().replace(binaryClone); binary.replace(negate.getPsi()); }
public static ASTNode getoperator(PsiElement element) { PsiElement binary = PsiTreeUtil.findFirstParent(element,new Condition<PsiElement>() { @Override public boolean value(PsiElement psiElement) { return psiElement instanceof JSBinaryExpression; } }); return binary == null ? null : binary.getNode().getChildren(BINARY_OPERATIONS)[0]; }
public static boolean isNeedParenthesis(JSExpression oldExpr,JSExpression newExpr) { int priority = getExpressionPrecedence(newExpr); final PsiElement parent = oldExpr.getParent(); if(!(parent instanceof JSExpression)) { return false; } int parentPriority = getExpressionPrecedence((JSExpression) parent); if(priority < parentPriority) { return true; } if(priority == parentPriority && parent instanceof JSBinaryExpression) { final IElementType operationSign = ((JSBinaryExpression) parent).getoperationSign(); if(oldExpr != ((JSBinaryExpression) parent).getROperand()) { return false; } if(!ASSOC_OPERATIONS.contains(operationSign)) { return true; } return (((JSBinaryExpression) newExpr).getoperationSign() != operationSign); } return false; }
@Override public void delete() throws IncorrectOperationException { final PsiElement parent = getParent(); if(parent instanceof JSAssignmentExpression) { final PsiElement grandParent = parent.getParent(); if(grandParent instanceof Jsstatement) { grandParent.delete(); return; } else if(grandParent instanceof JSBinaryExpression) { ((JSBinaryExpression) grandParent).getROperand().replace(((JSAssignmentExpression) parent).getROperand()); return; } else if(grandParent instanceof JSVariable) { final JSExpression initializerExpression = ((JSVariable) grandParent).getinitializer(); initializerExpression.replace(((JSAssignmentExpression) parent).getROperand()); return; } } super.delete(); }
@Override public void visitJSAssignmentExpression(@NotNull JSAssignmentExpression assignment) { super.visitJSAssignmentExpression(assignment); final IElementType sign = assignment.getoperationSign(); if (!JSTokenTypes.EQ.equals(sign)) { return; } JSExpression lhs = assignment.getLOperand(); final JSExpression rhs = assignment.getROperand(); if (rhs == null || lhs == null) { return; } if (!(rhs instanceof JSBinaryExpression)) { return; } final JSBinaryExpression binaryRhs = (JSBinaryExpression) rhs; if (!(binaryRhs.getROperand() != null)) { return; } IElementType operationSign = binaryRhs.getoperationSign(); if (operationSign == JSTokenTypes.ANDAND || operationSign == JSTokenTypes.OROR) { return; } final JSExpression lOperand = binaryRhs.getLOperand(); if (SideEffectChecker.mayHaveSideEffects(lhs)) { return; } if(lhs instanceof JSDeFinitionExpression) { lhs = ((JSDeFinitionExpression)lhs).getExpression(); } if (!EquivalenceChecker.expressionsAreEquivalent(lhs,lOperand)) { return; } registerError(assignment); }
@Override public String buildErrorString(Object... args) { if ( args[0]instanceof JSBinaryExpression) { return inspectionJSBundle.message("pointless.boolean.error.string",calculateSimplifiedBinaryExpression((JSBinaryExpression) args[0])); } else { return inspectionJSBundle.message("pointless.boolean.error.string",calculateSimplifiedPrefixExpression((JSPrefixExpression) args[0])); } }
@Override public void visitJSBinaryExpression(@NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); if (!(expression.getROperand() != null)) { return; } final IElementType sign = expression.getoperationSign(); if (!booleanTokens.contains(sign)) { return; } final JSExpression rhs = expression.getROperand(); final JSExpression lhs = expression.getLOperand(); final boolean isPointless; if (JSTokenTypes.EQEQ.equals(sign) /*|| JSTokenTypes.EQEQEQ.equals(sign) || JSTokenTypes.NE.equals(sign) || JSTokenTypes.NEQEQ.equals(sign)*/) { isPointless = equalityExpressionIsPointless(lhs,rhs); } else if (JSTokenTypes.ANDAND.equals(sign) || JSTokenTypes.AND.equals(sign)) { isPointless = andExpressionIsPointless(lhs,rhs); } else if (JSTokenTypes.OROR.equals(sign) || JSTokenTypes.OR.equals(sign)) { isPointless = orExpressionIsPointless(lhs,rhs); } else if (JSTokenTypes.XOR.equals(sign)) { isPointless = xorExpressionIsPointless(lhs,rhs); } else { isPointless = false; } if (!isPointless) { return; } registerError(expression); }
@Override public void visitJSBinaryExpression( @NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); if (!(expression.getROperand() != null)) { return; } final IElementType sign = expression.getoperationSign(); if (!arithmeticTokens.contains(sign)) { return; } final JSExpression rhs = expression.getROperand(); final JSExpression lhs = expression.getLOperand(); if (rhs == null) { return; } final boolean isPointless; if (sign.equals(JSTokenTypes.PLUS)) { isPointless = additionExpressionIsPointless(lhs,rhs); } else if (sign.equals(JSTokenTypes.MINUS)) { isPointless = subtractionExpressionIsPointless(rhs); } else if (sign.equals(JSTokenTypes.MULT)) { isPointless = multiplyExpressionIsPointless(lhs,rhs); } else if (sign.equals(JSTokenTypes.DIV)) { isPointless = divideExpressionIsPointless(rhs); } else { isPointless = false; } if (!isPointless) { return; } registerError(expression); }
private boolean isNotEquals(JSExpression expression) { if (!(expression instanceof JSBinaryExpression)) { return false; } final JSBinaryExpression binaryExpression = (JSBinaryExpression) expression; final IElementType sign = binaryExpression.getoperationSign(); return JSTokenTypes.NE.equals(sign) ||JSTokenTypes.NEQEQ.equals(sign); }
private boolean isNotEquals(JSExpression expression) { if (!(expression instanceof JSBinaryExpression)) { return false; } final JSBinaryExpression binaryExpression = (JSBinaryExpression) expression; final IElementType sign = binaryExpression.getoperationSign(); return JSTokenTypes.NE.equals(sign) || JSTokenTypes.NEQEQ.equals(sign); }
public static boolean isComparison(@Nullable JSExpression exp) { if (!(exp instanceof JSBinaryExpression)) { return false; } final JSBinaryExpression binaryExpression = (JSBinaryExpression) exp; final IElementType sign = binaryExpression.getoperationSign(); return s_comparisonStrings.contains(sign); }
@Override protected inspectionJSFix buildFix(PsiElement location) { final JSBinaryExpression expression = (JSBinaryExpression) location; final IElementType sign = expression.getoperationSign(); if (JSTokenTypes.EQEQ == sign) { return new EqualityComparisonWithCoercionFix("==="); } else if (JSTokenTypes.NE == sign) { return new EqualityComparisonWithCoercionFix("!=="); } return null; }
@Override protected void doFix(Project project,ProblemDescriptor descriptor) throws IncorrectOperationException { final JSBinaryExpression expression = (JSBinaryExpression) descriptor.getPsiElement(); final JSExpression lhs = expression.getLOperand(); final JSExpression rhs = expression.getROperand(); replaceExpression(expression,lhs.getText() + sign + rhs.getText()); }
@Override public void visitJSBinaryExpression( @NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); if (!(expression.getROperand() != null)) { return; } final IElementType sign = expression.getoperationSign(); if (!JSTokenTypes.AND.equals(sign) && !JSTokenTypes.OR.equals(sign)) { return; } registerError(expression); }
@Override public void visitJSBinaryExpression( @NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); final IElementType tokenType = expression.getoperationSign(); if (tokenType == null || ( !tokenType.equals(JSTokenTypes.LTLT) && !tokenType.equals(JSTokenTypes.GTGT) && !tokenType.equals(JSTokenTypes.GTGTGT) )) { return; } final JSExpression rhs = expression.getROperand(); if (rhs == null) { return; } if (!ExpressionUtil.isConstantExpression(rhs)) { return; } final Object valueObject = ExpressionUtil.computeConstantExpression(rhs); if (!(valueObject instanceof Integer)) { return; } final int value = (Integer) valueObject; if (value < 0 || value > 31) { registerError(expression,value); } }
@Override public void visitJSBinaryExpression( @NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); final IElementType sign = expression.getoperationSign(); if (!bitwisetokens.contains(sign)) { return; } final JSExpression rhs = expression.getROperand(); if (rhs == null) { return; } final JSExpression lhs = expression.getLOperand(); final boolean isPointless; if (JSTokenTypes.AND.equals(sign)) { isPointless = andExpressionIsPointless(lhs,rhs); } else if (JSTokenTypes.OR.equals(sign)) { isPointless = orExpressionIsPointless(lhs,rhs ); } else if (JSTokenTypes.LTLT.equals(sign) || JSTokenTypes.GTGT.equals(sign) || JSTokenTypes.GTGTGT.equals(sign)) { isPointless = shiftExpressionIsPointless(rhs); } else { isPointless = false; } if (isPointless) { registerError(expression,expression); } }
@Override @NotNull public String buildErrorString(Object... args) { final JSBinaryExpression binaryExpression = (JSBinaryExpression) args[0]; final IElementType tokenType = binaryExpression.getoperationSign(); if (JSTokenTypes.EQEQ.equals(tokenType)) { return inspectionJSBundle.message( "incompatible.mask.operation.problem.descriptor.always.false"); } else { return inspectionJSBundle.message( "incompatible.mask.operation.problem.descriptor.always.true"); } }
@Override public void visitJSBinaryExpression( @NotNull JSBinaryExpression expression) { super.visitJSBinaryExpression(expression); final JSExpression rhs = expression.getROperand(); if (!ComparisonUtils.isEqualityComparison(expression)) { return; } final JSExpression strippedRhs = ParenthesesUtils.stripParentheses(rhs); if (strippedRhs == null) { return; } final JSExpression lhs = expression.getLOperand(); final JSExpression strippedLhs = ParenthesesUtils.stripParentheses(lhs); if (strippedLhs == null) { return; } if (isConstantMask(strippedLhs) && ExpressionUtil.isConstantExpression(strippedRhs)) { if (isIncompatibleMask((JSBinaryExpression) strippedLhs,strippedRhs)) { registerError(expression,expression); } } else if (isConstantMask(strippedRhs) && ExpressionUtil.isConstantExpression(strippedLhs)) { if (isIncompatibleMask((JSBinaryExpression) strippedRhs,strippedLhs)) { registerError(expression,expression); } } }
com.intellij.lang.javascript.psi.JSCallExpression的实例源码
@Nullable @Override public PsiElement getElementByReference(@NotNull PsiReference ref,int flags) { if (ref instanceof JSTextReference) { final PsiElement element = ref.getElement(); final JSCallExpression call = PsiTreeUtil.getParentOfType(element,JSCallExpression.class); final JSExpression expression = call != null ? call.getmethodExpression() : null; if (expression instanceof JSReferenceExpression) { JSReferenceExpression callee = (JSReferenceExpression)expression; JSExpression qualifier = callee.getQualifier(); if (qualifier != null && "component".equals(callee.getReferencedname()) && EmberIndexUtil.hasEmberJS(element.getProject())) { return element; } } } return null; }
@Override public ProblemDescriptor[] checkFile(@NotNull PsiFile file,@NotNull final inspectionManager manager,boolean isOnTheFly) { if(!isEnabled(file.getProject())) { return new ProblemDescriptor[0]; } DefineResolver resolver = new DefineResolver(); final List<ProblemDescriptor> descriptors = new ArrayList<ProblemDescriptor>(); Set<JSCallExpression> expressions = resolver.getAllImportBlocks(file); for(JSCallExpression expression : expressions) { addProblemsForBlock(expression,descriptors,file,manager); } return descriptors.toArray(new ProblemDescriptor[0]); }
public static boolean elementIsAttachPoint(PsiElement element) { /* It's hard to detect when an element is an attach point,because of the use of this inside other functions this.attachpoint that.attachpoint ideally we would parse the template file in the beginning and cache all of the attach points,maybe that's a todo item... */ if(element == null || element.getParent() == null || !(element.getParent() instanceof JSReferenceExpression)) { return false; } // we can exclude JSCallExpressions at least because you will never reference an attach point like // this.attachpoint(...) if(element.getParent().getParent() instanceof JSCallExpression) { return false; } return true; }
/** * takes an existing AMD import and updates it. Used when a module changes locations * * @param index the index of the import * @param currentModule the module that is being updated * @param quote the quote symbol to use for imports * @param path the new module's path * @param newModule the new module */ public void reimportModule(int index,PsiFile currentModule,char quote,String path,PsiFile newModule,String pluginPostfix,boolean updateReferences,PsiFile pluginResourceFile,JSCallExpression callExpression) { Definestatement definestatement = new DefineResolver().getDefinestatementItemsFromArguments(callExpression.getArguments(),callExpression); String newModuleName = newModule.getName().substring(0,newModule.getName().indexOf('.')); LinkedHashMap<String,PsiFile> results = new ImportResolver().getChoicesFromFiles(new PsiFile[] { newModule },libraries,newModuleName,currentModule,false,true); // check if the original used a relative Syntax or absolute Syntax,and prefer that String[] possibleImports = results.keySet().toArray(new String[0]); String chosenImport = chooseImportToReplaceAnImport(path,possibleImports); pluginPostfix = getUpdatedpluginResource(pluginResourceFile,pluginPostfix,currentModule); PsiElement defineLiteral = definestatement.getArguments().getExpressions()[index]; PsiElement newImport = JSUtil.createExpression(defineLiteral.getParent(),quote + chosenImport + pluginPostfix + quote); MatchResult match = new MatchResult(currentModule,index,path,quote,pluginResourceFile,callExpression); importUpdater.updateModuleReference(currentModule,match,definestatement,newImport,updateReferences); }
@Test public void testTheBasicHappyPath() { Map<String,String> propertyMap = new HashMap<String,String>(); propertyMap.put("property 1","value"); JSExpression[] arguments = new JSExpression[] { new MockJSArrayLiteralExpression(new String[] { "mixin1","mixin2"}),new MockJSObjectLiteralExpression(propertyMap) }; JSCallExpression callExpression = new MockJSCallExpression(arguments); Object[] statements = new Object[] {callExpression,null}; DeclareStatementItems result = resolver.getDeclareStatementFromParsedStatement(statements); assertEquals(2,result.getExpressionsToMixin().length); assertEquals(1,result.getmethodsToConvert().length); }
@Test public void testWhenFirstArgumentIsNull() { Map<String,"value"); JSExpression[] arguments = new JSExpression[] { BasicpsiElements.Null(),null}; DeclareStatementItems result = resolver.getDeclareStatementFromParsedStatement(statements); assertEquals(0,result.getmethodsToConvert().length); }
@Test public void classNameIsRetrieved() { Map<String,"value"); JSExpression[] arguments = new JSExpression[] { new MockJSLiteralExpression("test class"),new MockJSArrayLiteralExpression(new String[] { "define 1","define 2"}),null}; DeclareStatementItems result = resolver.getDeclareStatementFromParsedStatement(statements); assertEquals("test class",result.getClassName().getText()); }
@Test public void testWhenFirstArgumentIsAClassName() { Map<String,result.getmethodsToConvert().length); }
@Test public void testWhenMixinArrayIsNull() { Map<String,new MockJSLiteralExpression("null"),null}; DeclareStatementItems result = resolver.getDeclareStatementFromParsedStatement(statements); assertNotNull(result); }
public boolean isRequireCall(PsiElement element) { PsiElement prevEl = element.getParent(); if (prevEl != null) { prevEl = prevEl.getParent(); } if (prevEl instanceof JSCallExpression) { if (prevEl.getChildren().length > 1) { String requireFunctionName = Settings.REQUIREJS_REQUIRE_FUNCTION_NAME; if (prevEl.getChildren()[0].getText().toLowerCase().equals(requireFunctionName)) { return true; } } } return false; }
private static JSExpression findExpressionInRange(PsiFile file,int startOffset,int endOffset) { PsiElement element1 = file.findElementAt(startOffset); PsiElement element2 = file.findElementAt(endOffset - 1); if(element1 instanceof PsiWhiteSpace) { startOffset = element1.getTextRange().getEndOffset(); } if(element2 instanceof PsiWhiteSpace) { endOffset = element2.getTextRange().getStartOffset(); } JSExpression expression = PsiTreeUtil.findElementOfClassAtRange(file,startOffset,endOffset,JSExpression.class); if(expression == null || expression.getTextRange().getEndOffset() != endOffset) { return null; } if(expression instanceof JSReferenceExpression && expression.getParent() instanceof JSCallExpression) { return null; } return expression; }
@Override public void visitJSCallExpression(JSCallExpression jsCallExpression) { super.visitJSCallExpression(jsCallExpression); final JSExpression methodExpression; try { methodExpression = jsCallExpression.getmethodExpression(); } catch (Exception e) { return; //catching an intelliJ CCE } if (!(methodExpression instanceof JSReferenceExpression)) { return; } final JSReferenceExpression referenceExpression = (JSReferenceExpression) methodExpression; final JSExpression qualifier = referenceExpression.getQualifier(); @NonNls final String methodName = referenceExpression.getReferencedname(); if (!"eval".equals(methodName) && !"setTimeout".equals(methodName) && !"setInterval".equals(methodName)) { return; } registerError(methodExpression); }
@Override public void visitJSCallExpression( @NotNull JSCallExpression expression) { super.visitJSCallExpression(expression); final JSExpression reference = expression.getmethodExpression(); if(!(reference instanceof JSReferenceExpression)) { return; } final JSExpression qualifier = ((JSReferenceExpression)reference).getQualifier(); if (qualifier == null) { return; } if (!isCallExpression(qualifier)) { return; } registerFunctionCallError(expression); }
private static boolean callExpressionDefinitelyRecurses( JSCallExpression exp,JSFunction method) { final JSFunction calledMethod = ControlFlowUtils.resolveMethod(exp); if (calledMethod != null && calledMethod.equals(method)) { return true; } final JSExpression methodExpression = exp.getmethodExpression(); if (methodExpression == null) { return false; } else if (RecursionUtil.expressionDefinitelyRecurses(methodExpression,method)) { return true; } for (final JSExpression arg : exp.getArgumentList().getArguments()) { if (RecursionUtil.expressionDefinitelyRecurses(arg,method)) { return true; } } return false; }
public static boolean containsTestsInFiles(JSFile file) { JSSourceElement[] statements = file.getStatements(); for(JSSourceElement statement : statements) { if(statement instanceof JSExpressionStatement) { JSExpression expression = ((JSExpressionStatement) statement).getExpression(); if(expression instanceof JSCallExpression) { JSExpression methodExpression = ((JSCallExpression) expression).getmethodExpression(); if(methodExpression instanceof JSReferenceExpression) { JSExpression qualifier = ((JSReferenceExpression) methodExpression).getQualifier(); if(qualifier != null) { continue; } String referencedname = ((JSReferenceExpression) methodExpression).getReferencedname(); if("describe".equals(referencedname)) { JSArgumentList argumentList = ((JSCallExpression) expression).getArgumentList(); if(argumentList != null && argumentList.getArguments().length == 2) { return true; } } } } } } return false; }
public JSCallExpression getCallExpression() { if(callExpression == null) { throw new RuntimeException("callExpression was not set but is being accessed"); } return callExpression; }
public MatchResult(PsiFile module,int index,String pluginResourceId,JSCallExpression callExpression) { this.index = index; this.path = path; this.quote = quote; this.module = module; this.pluginResourceId = pluginResourceId; this.pluginResourceFile = pluginResourceFile; this.callExpression = callExpression; }
@Override protected void addParameters(Template template,JSReferenceExpression referenceExpression,PsiFile file,Set<JavaScriptFeature> features) { JSCallExpression methodInvokation = (JSCallExpression) referenceExpression.getParent(); final JSArgumentList list = methodInvokation.getArgumentList(); final JSExpression[] expressions = list.getArguments(); int paramCount = expressions.length; for(int i = 0; i < paramCount; ++i) { if(i != 0) { template.addTextSegment(","); } String var = null; final JSExpression passedParameterValue = expressions[i]; if(passedParameterValue instanceof JSReferenceExpression) { var = ((JSReferenceExpression) passedParameterValue).getReferencedname(); } if(var == null || var.length() == 0) { var = "param" + (i != 0 ? Integer.toString(i + 1) : ""); } final String var1 = var; Expression expression = new MyExpression(var1); template.addVariable(var,expression,true); if(features.contains(JavaScriptFeature.CLASS)) { template.addTextSegment(":"); BaseCreateFix.guessExprTypeAndAddSuchVariable(passedParameterValue,template,var1,features); } } }
public static boolean isLHSExpression(JSExpression expr) { if(expr instanceof JSDeFinitionExpression) { expr = ((JSDeFinitionExpression) expr).getExpression(); } if(expr instanceof JSReferenceExpression) { return true; } if(expr instanceof JSParenthesizedExpression) { return isLHSExpression(((JSParenthesizedExpression) expr).getInnerExpression()); } if(expr instanceof JSIndexedPropertyAccessExpression) { return true; } if(expr instanceof JSCallExpression) { return true; } if(expr instanceof JSNewExpression) { return true; } return false; }
@Nullable public static JSArgumentList findArgumentList(final PsiFile file,final int offset) { JSArgumentList argList = ParameterInfoUtils.findParentOfType(file,offset,JSArgumentList.class); if(argList == null) { final JSCallExpression callExpression = ParameterInfoUtils.findParentOfType(file,JSCallExpression.class); if(callExpression != null) { argList = callExpression.getArgumentList(); } } return argList; }
protected void registerFunctionCallError(JSCallExpression expression){ final JSExpression methodExpression = expression.getmethodExpression(); PsiElement errorLocation = null; if (methodExpression instanceof JSReferenceExpression) { errorLocation = ((JSReferenceExpression)methodExpression).getReferenceNameElement(); } else if (methodExpression instanceof JSFunction) { final PsiElement node = ((JSFunction)methodExpression).getNameIdentifier(); if (node != null) errorLocation = node; else errorLocation = methodExpression; } registerError(errorLocation); }
private static boolean isCallExpression(JSExpression expression) { if (expression instanceof JSCallExpression ) { return true; } if (expression instanceof JSParenthesizedExpression) { final JSParenthesizedExpression parenthesizedExpression = (JSParenthesizedExpression) expression; final JSExpression containedExpression = parenthesizedExpression.getInnerExpression(); return isCallExpression(containedExpression); } return false; }
@Override public void visitJSCallExpression(JSCallExpression jsCallExpression) { super.visitJSCallExpression(jsCallExpression); final JSExpression methodExpression; try { methodExpression = jsCallExpression.getmethodExpression(); } catch (Exception e) { return; //catching an intelliJ CCE } if(!(methodExpression instanceof JSReferenceExpression)) { return; } final JSReferenceExpression referenceExpression = (JSReferenceExpression) methodExpression; final JSExpression qualifier = referenceExpression.getQualifier(); if(qualifier == null) { return; } @NonNls final String qualifierText = qualifier.getText(); if(!"document".equals(qualifierText)) { return; } @NonNls final String methodName = referenceExpression.getReferencedname(); if(!"write".equals(methodName) && !"writeln".equals(methodName)) { return; } registerError(methodExpression); }
@Override public boolean satisfiedBy(@NotNull PsiElement element) { if (!(element instanceof JSExpression)) { return false; } if (ErrorUtil.containsError(element)) { return false; } final JSExpression expression = (JSExpression) element; if (element instanceof JSLiteralExpression || ( element instanceof JSReferenceExpression && ((JSReferenceExpression)element).getQualifier() != null ) || expression instanceof JSCallExpression ) { return false; } if (!ExpressionUtil.isConstantExpression(expression)) { return false; } if (ExpressionUtil.computeConstantExpression(expression) == null) { return false; } final PsiElement parent = element.getParent(); if (!(parent instanceof JSExpression)) { return true; } return (!ExpressionUtil.isConstantExpression((JSExpression) parent)); }
@Override public void actionPerformed(AnActionEvent e) { final PsiFile psiFile = PsiFileUtil.getPsiFileInCurrentEditor(e.getProject()); final AMDImportOrganizer organizer = new AMDImportOrganizer(); CommandProcessor.getInstance().executeCommand(psiFile.getProject(),new Runnable() { @Override public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { int totalSize = 0; DefineResolver resolver = new DefineResolver(); Set<JSCallExpression> expressions = resolver.getAllImportBlocks(psiFile); for(JSCallExpression expression : expressions) { List<PsiElement> blockDefines = new ArrayList<PsiElement>(); List<PsiElement> blockParameters = new ArrayList<PsiElement>(); try { resolver.addDefinesAndParametersOfImportBlock(expression,blockDefines,blockParameters); } catch (InvalidDefineException e1) {} if(blockDefines.size() == 0 || blockParameters.size() == 0) { continue; } SortingResult result = organizer.sortDefinesAndParameters(blockDefines,blockParameters); totalSize += blockDefines.size(); organizer.reorder(blockDefines.toArray(new PsiElement[]{}),result.getDefines(),true,result); organizer.reorder(blockParameters.toArray(new PsiElement[]{}),result.getParameters(),result); } if(totalSize == 0) { Notifications.Bus.notify(new Notification("needsmoredojo","Organize AMD Imports","There were no AMD imports",NotificationType.WARNING)); return; } else { Notifications.Bus.notify(new Notification("needsmoredojo","Completed",NotificationType.informatION)); } } }); } },"Organize AMD Imports"); }
public Set<String> getDojoModulesInHtmlFile(PsiFile file) { final Set<String> modules = new HashSet<String>(); file.acceptChildren(new JSRecursiveElementVisitor() { @Override public void visitJSCallExpression(JSCallExpression node) { if(!node.getText().startsWith("require")) { super.visitJSCallExpression(node); return; } if(node.getArguments().length > 0 && node.getArguments()[0] instanceof JSArrayLiteralExpression) { JSArrayLiteralExpression arguments = (JSArrayLiteralExpression) node.getArguments()[0]; for(JSExpression literal : arguments.getExpressions()) { String literalText = literal.getText().replaceAll("'","").replaceAll("\"",""); if(!isDojoModule(literalText)) { modules.add(literalText); } } } super.visitJSCallExpression(node); } }); file.acceptChildren(new XmlRecursiveElementVisitor() { @Override public void visitXmlTag(XmlTag tag) { super.visitXmlTag(tag); } @Override public void visitXmlAttribute(XmlAttribute attribute) { if(attribute.getName().equals("data-dojo-type")) { if(!isDojoModule(attribute.getValue())) { modules.add(attribute.getValue()); } } super.visitXmlAttribute(attribute); } }); return modules; }
public Definestatement(JSArrayLiteralExpression arguments,JSFunctionExpression function,String className,JSCallExpression originalParent) { this.arguments = arguments; this.function = function; this.className = className; this.callExpression = originalParent; }
public UnusedImportBlockEntry(boolean isDefine,JSCallExpression block,List<PsiElement> defines,List<PsiElement> parameters) { this.block = block; this.defines = defines; this.parameters = parameters; this.isDefine = isDefine; }
public JSCallExpression getBlock() { return block; }
public JSCallExpression getCallExpression() { return callExpression; }
/** * given a module,returns a list of modules that it references in the define block * * @param module * @return */ public List<MatchResult> findFilesThatModuleReferences(PsiFile module) { DefineResolver resolver = new DefineResolver(); Set<JSCallExpression> callExpressions = resolver.getAllImportBlocks(module); List<MatchResult> matches = new ArrayList<MatchResult>(); for(JSCallExpression callExpression : callExpressions) { if(callExpression == null) { continue; } Definestatement statement = resolver.getDefinestatementItemsFromArguments(callExpression.getArguments(),callExpression); if(statement == null) { // define statement wasn't valid return matches; } for(int i=0;i<statement.getArguments().getExpressions().length;i++) { JSExpression expression = statement.getArguments().getExpressions()[i]; char quote = '"'; if(expression.getText().contains("'")) { quote = '\''; } // figure out which module it is String importModule = expression.getText().replaceAll("'",""); // get the module name String moduleName = NameResolver.getModuleName(importModule); String pluginResourceId = NameResolver.getAMdpluginResourceIfPossible(importModule,true); String modulePath = NameResolver.getModulePath(importModule); PsiFile pluginResourceFile = null; if(pluginResourceId.startsWith("!") && pluginResourceId.length() > 2 && pluginResourceId.charat(1) == '.') { PsiReference[] fileReferences = expression.getReferences(); if(fileReferences.length > 0) { PsiReference potentialReference = fileReferences[fileReferences.length-1]; pluginResourceFile = (PsiFile) potentialReference.resolve(); } } else if (pluginResourceId.startsWith("!") && pluginResourceId.length() > 2) { // this is an absolute reference } // get the list of possible strings/PsiFiles that would match it PsiFile[] files = new ImportResolver().getPossibleDojoImportFiles(module.getProject(),moduleName,false); // get the files that are being imported // Todo performance optimization LinkedHashMap<String,PsiFile> results = new ImportResolver().getChoicesFromFiles(files,module.getContainingFile(),true); if(results.containsKey(modulePath + moduleName)) { MatchResult match = new MatchResult(results.get(modulePath + moduleName),i,modulePath + moduleName,pluginResourceId,callExpression); matches.add(match); } } } return matches; }
@Override public void delete() throws IncorrectOperationException { PsiElement element = getParent(); element.replace(((JSCallExpression) element).getmethodExpression()); }
@Nullable private static JSArgumentList fillSignaturesForArgumentList(final CreateParameterInfoContext context,final @NotNull JSArgumentList argList) { final PsiElement psiElement = argList.getParent(); if(!(psiElement instanceof JSCallExpression)) { return null; } final JSCallExpression parent = (JSCallExpression) psiElement; final JSExpression methodExpression = parent.getmethodExpression(); if(methodExpression instanceof JSReferenceExpression) { final ResolveResult[] resolveResults = ((JSReferenceExpression) methodExpression).multiResolve(true); if(resolveResults.length > 0) { List<JSFunction> items = new ArrayList<JSFunction>(resolveResults.length); Set<String> availableSignatures = new HashSet<String>(); for(ResolveResult r : resolveResults) { PsiElement element = r.getElement(); if(element instanceof JSProperty) { element = ((JSProperty) element).getValue(); } doAddSignature(items,availableSignatures,element); } context.setItemsToShow(ArrayUtil.toObjectArray(items)); return argList; } } else if(methodExpression instanceof JSSuperExpression) { final PsiElement clazz = methodExpression.getReference().resolve(); if(clazz instanceof JSFunction) { context.setItemsToShow(new Object[]{clazz}); return argList; } } return null; }
private static boolean expressionDefinitelyRecurses(JSExpression exp,JSFunction method) { if (exp == null) { return false; } if (exp instanceof JSNewExpression) { return RecursionUtil.newExpressionDefinitelyRecurses( (JSNewExpression) exp,method); } if (exp instanceof JSCallExpression) { return RecursionUtil.callExpressionDefinitelyRecurses( (JSCallExpression) exp,method); } if (exp instanceof JSAssignmentExpression) { return RecursionUtil.assignmentExpressionDefinitelyRecurses( (JSAssignmentExpression) exp,method); } if (exp instanceof JSArrayLiteralExpression) { return RecursionUtil.arrayLiteralExpressionDefinitelyRecurses( (JSArrayLiteralExpression) exp,method); } if (exp instanceof JSIndexedPropertyAccessExpression) { return RecursionUtil.indexedPropertyAccessExpressionDefinitelyRecurses( (JSIndexedPropertyAccessExpression) exp,method); } if (exp instanceof JSPrefixExpression) { return RecursionUtil.prefixExpressionDefinitelyRecurses( (JSPrefixExpression) exp,method); } if (exp instanceof JSPostfixExpression) { return RecursionUtil.postfixExpressionDefinitelyRecurses( (JSPostfixExpression) exp,method); } if (exp instanceof JSBinaryExpression) { return RecursionUtil.binaryExpressionDefinitelyRecurses( (JSBinaryExpression) exp,method); } if (exp instanceof JSConditionalExpression) { return RecursionUtil.conditionalExpressionDefinitelyRecurses( (JSConditionalExpression) exp,method); } if (exp instanceof JSParenthesizedExpression) { return RecursionUtil.parenthesizedExpressionDefinitelyRecurses( (JSParenthesizedExpression) exp,method); } if (exp instanceof JSReferenceExpression) { return RecursionUtil.referenceExpressionDefinitelyRecurses( (JSReferenceExpression) exp,method); } if (exp instanceof JSLiteralExpression || exp instanceof JSThisExpression) { return false; } return false; }
com.intellij.lang.javascript.psi.JSCommaExpression的实例源码
public Collection<JSDeFinitionExpression> getDeFinitions() { final PsiElement firstChild = getFirstChild(); if (firstChild instanceof JSDeFinitionExpression) { return Collections.singletonList((JSDeFinitionExpression) firstChild); } if (firstChild instanceof JSParenthesizedExpression) { final PsiElement commaExpression = PsiTreeUtil.findChildOfType(firstChild,JSCommaExpression.class); if (commaExpression != null) { return PsiTreeUtil.findChildrenOfType(commaExpression,JSDeFinitionExpression.class); } } return Collections.emptyList(); }
public Collection<JSDeFinitionExpression> getDeFinitions() { final PsiElement firstChild = getFirstChild(); if (firstChild instanceof JSDeFinitionExpression) { return Collections.singletonList((JSDeFinitionExpression)firstChild); } else if (firstChild instanceof JSParenthesizedExpression) { final PsiElement commaExpression = PsiTreeUtil.findChildOfType(firstChild,JSDeFinitionExpression.class); } } return Collections.emptyList(); }
@Override public void visitJSCommaExpression(JSCommaExpression node) { super.visitJSCommaExpression(node); if(node.getParent() instanceof JSCommaExpression) { return; } if(node.getParent() instanceof JSForStatement) { return; } registerError(node); }
关于java.beans.Expression的实例源码和java.beans.introspection的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于com.facebook.presto.sql.tree.Expression的实例源码、com.intellij.lang.javascript.psi.JSBinaryExpression的实例源码、com.intellij.lang.javascript.psi.JSCallExpression的实例源码、com.intellij.lang.javascript.psi.JSCommaExpression的实例源码的相关知识,请在本站寻找。
本文标签: