org.mozilla.javascript.ast.Name Java Examples

The following examples show how to use org.mozilla.javascript.ast.Name. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ObjectLiteralTerm.java    From SJS with Apache License 2.0 6 votes vote down vote up
public List<String> getPropertyNames(){
	List<String> propNames = new ArrayList<String>();
	ObjectLiteral ol = (ObjectLiteral)this.getNode();
	for (ObjectProperty op : ol.getElements()){
		AstNode left = op.getLeft();
		if (left instanceof Name){
			propNames.add(((Name)left).getIdentifier());
		} else if (left instanceof StringLiteral){
			String identifier = ConstraintGenUtil.removeQuotes(((StringLiteral)left).toSource());
			propNames.add(identifier);
		} else {
			System.err.println(left.getClass().getName() + " " + left.toSource());
			throw new Error("unsupported case in getPropertyNames()");
		}
	}
	return propNames;
}
 
Example #2
Source File: ConstraintGenUtil.java    From SJS with Apache License 2.0 6 votes vote down vote up
public static List<String> getPropertyNames(ObjectLiteral ol){
	List<String> propNames = new ArrayList<String>();
	for (ObjectProperty op : ol.getElements()){
		AstNode left = op.getLeft();
		if (left instanceof Name){
			propNames.add(((Name)left).getIdentifier());
		} else if (left instanceof StringLiteral){
			String identifier = ConstraintGenUtil.removeQuotes(((StringLiteral)left).toSource());
			propNames.add(identifier);
		} else {
			System.err.println(left.getClass().getName() + " " + left.toSource());
			throw new Error("unsupported case in getPropertyNames()");
		}
	}
	return propNames;
}
 
Example #3
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 6 votes vote down vote up
/**
 * For a function definition (FunctionNode), create constraints equating its
 * parameters to param(.) variables, and equate the type of the function name
 * to the type of the entire function definition.
 */
private void createFunctionNodeConstraints(FunctionNode node, ITypeTerm funTerm){
	// if the function has a name, equate the types of the function node and the function name
	Name funName = node.getFunctionName();
	if (funName != null){
		ITypeTerm nameTerm = findOrCreateNameDeclarationTerm(funName);
		addSubTypeConstraint(funTerm, nameTerm, node.getLineno(), null);
	}

	// for a function f with params v1, v2, ... generate param(|f|,i) = |v_i|
	for (int i=0; i < node.getParamCount(); i++){
		AstNode param = node.getParams().get(i);
		if (param instanceof Name){
			Name name = (Name)param;
			ITypeTerm nameVar = findOrCreateNameDeclarationTerm(name);
			ITypeTerm paramVar = findOrCreateFunctionParamTerm(funTerm, i, node.getParamCount(), node.getLineno());
			addTypeEqualityConstraint(paramVar, nameVar, param.getLineno(), null);
		} else {
			error("createFunctionNodeConstraints: unexpected parameter type", node);
		}
	}

}
 
Example #4
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 6 votes vote down vote up
/**
 * generate constraints for assignments
 */
private void processAssignment(Assignment a) throws Error {
	AstNode left = a.getLeft();
	AstNode right = a.getRight();
	ITypeTerm expTerm = findOrCreateExpressionTerm(a);
	if (left instanceof Name){
		processAssignToVariable(a, left, right, expTerm);
	} else if (left instanceof PropertyGet) {
		PropertyGet pg = (PropertyGet)left;
		if (pg.getProperty().getIdentifier().equals("prototype")){
			processAssignToPrototype(a, left, right, expTerm);
		} else {
			processAssignToProperty(a, left, right, expTerm);
		}
		processExpression(pg.getTarget()); // TEST
	} else if (left instanceof ElementGet){
		processIndexedAssignment(a, left, right, expTerm);
	} else {
		error("unsupported LHS type in Assignment: " + left.getClass().getName(), left);
	}
}
 
Example #5
Source File: ConstraintFactory.java    From SJS with Apache License 2.0 6 votes vote down vote up
/**
 * Find or create a term representing a FunctionNode (function definition). The
 * created FunctionTerm provides methods for accessing the terms corresponding to the
 * function's parameters and return type. The boolean flag isMethod indicates whether
 * the function is a method.
 */
public FunctionTerm findOrCreateFunctionTerm(FunctionNode fun, FunctionTerm.FunctionKind funType) {
    if (!functionTerms.containsKey(fun)){
        FunctionTerm var = new FunctionTerm(fun, funType);
        var.setReturnVariable(this.findOrCreateFunctionReturnTerm(var, fun.getParamCount()));
        List<AstNode> params = fun.getParams();
        List<NameDeclarationTerm> paramVars = new ArrayList<NameDeclarationTerm>();
        for (int i=0; i < params.size(); i++){
            AstNode param = params.get(i);
            if (param instanceof Name){
                NameDeclarationTerm paramCV = this.findOrCreateNameDeclarationTerm((Name)param);
                paramVars.add(paramCV);
            } else {
                throw new Error("unimplemented case in findOrCreateFunctionVariable");
            }
        }
        var.setParamVariables(paramVars);
        functionTerms.put(fun, var);
    }
    return functionTerms.get(fun);
}
 
Example #6
Source File: Parser.java    From JsDroidCmd with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Parse the [expr] portion of an xml element reference, e.g.
 * @[expr], @*::[expr], or ns::[expr].
 */
private XmlElemRef xmlElemRef(int atPos, Name namespace, int colonPos)
    throws IOException
{
    int lb = ts.tokenBeg, rb = -1, pos = atPos != -1 ? atPos : lb;
    AstNode expr = expr();
    int end = getNodeEnd(expr);
    if (mustMatchToken(Token.RB, "msg.no.bracket.index")) {
        rb = ts.tokenBeg;
        end = ts.tokenEnd;
    }
    XmlElemRef ref = new XmlElemRef(pos, end - pos);
    ref.setNamespace(namespace);
    ref.setColonPos(colonPos);
    ref.setAtPos(atPos);
    ref.setExpression(expr);
    ref.setBrackets(lb, rb);
    return ref;
}
 
Example #7
Source File: MapLiteralTerm.java    From SJS with Apache License 2.0 6 votes vote down vote up
public List<String> getPropertyNames(){
	List<String> propNames = new ArrayList<String>();
	ObjectLiteral ol = (ObjectLiteral)this.getNode();
	for (ObjectProperty op : ol.getElements()){
		AstNode left = op.getLeft();
		if (left instanceof Name){
			propNames.add(((Name)left).getIdentifier());
		} else if (left instanceof StringLiteral){
			String identifier = ConstraintGenUtil.removeQuotes(((StringLiteral)left).toSource());
			propNames.add(identifier);
		} else {
			System.err.println(left.getClass().getName() + " " + left.toSource());
			throw new Error("unsupported case in getPropertyNames()");
		}
	}
	return propNames;
}
 
Example #8
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 6 votes vote down vote up
/**
 * Create constraints for an object literal.
 */
private ITypeTerm processObjectLiteralForObject(ObjectLiteral n) {
	ITypeTerm expTerm = findOrCreateObjectLiteralTerm(n);
	ObjectLiteral o = (ObjectLiteral)n;
	for (ObjectProperty prop : o.getElements()){
		AstNode left = prop.getLeft();
		AstNode right = prop.getRight();
		if (left instanceof Name){
			String identifier = ((Name)left).getIdentifier();

			// for object literal o = { name_1 : exp_1, ..., name_k : exp_k } generate
			// a constraint |exp_i| <: prop(|o|, name_i)

			ITypeTerm propTerm = findOrCreatePropertyAccessTerm(expTerm, identifier, null);
			ITypeTerm valTerm = processExpression(right);
			processCopy(right, valTerm, propTerm, n.getLineno(), null);
		}
	}
	return expTerm;
}
 
Example #9
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 6 votes vote down vote up
/**
 * for an expression that consists of a simple reference to a variable, we create an ITerm
 * for that expression, find the unique representative for the referenced variable, and
 * generate a constraint that equates these.
 */
private ITypeTerm processVariableReference(Name name) {
	ITypeTerm expTerm = findOrCreateExpressionTerm(name);
	if (!ConstraintGenUtil.isGlobal(name)){ // no need for NameDeclarationTerm for global variables
		Name declaration = ConstraintGenUtil.findDecl(name);
		ITypeTerm nameTerm = findOrCreateNameDeclarationTerm(declaration);
		addTypeEqualityConstraint(expTerm, nameTerm, name.getLineno(), null);
	} else {
		String identifier = name.getIdentifier();
		if (identifier.equals("undefined")){
			addTypeEqualityConstraint(new TypeParamTerm(name), findOrCreateExpressionTerm(name), name.getLineno(), null);
		} else {
			ITypeTerm globalTerm = findOrCreateGlobalDeclarationTerm(name, jsEnv);
			addTypeEqualityConstraint(globalTerm, expTerm, name.getLineno(), null);
			createConstraintsForGlobalFunction(name);
		}
	}
	return expTerm;
}
 
Example #10
Source File: IRFactory.java    From JsDroidCmd with Mozilla Public License 2.0 6 votes vote down vote up
private Node transformXmlRef(Node pn, XmlRef node, int memberTypeFlags) {
    if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) != 0)
        decompiler.addToken(Token.XMLATTR);
    Name namespace = node.getNamespace();
    String ns = namespace != null ? namespace.getIdentifier() : null;
    if (ns != null) {
        decompiler.addName(ns);
        decompiler.addToken(Token.COLONCOLON);
    }
    if (node instanceof XmlPropRef) {
        String name = ((XmlPropRef)node).getPropName().getIdentifier();
        decompiler.addName(name);
        return createPropertyGet(pn, ns, name, memberTypeFlags);
    } else {
        decompiler.addToken(Token.LB);
        Node expr = transform(((XmlElemRef)node).getExpression());
        decompiler.addToken(Token.RB);
        return createElementGet(pn, ns, expr, memberTypeFlags);
    }
}
 
Example #11
Source File: ConstraintFactory.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * Find or create a term representing an expression consisting of a global variable name
 */
public EnvironmentDeclarationTerm findOrCreateGlobalDeclarationTerm(final Name name, JSEnvironment env){
    if (!globalVarTerms.containsKey(name)){
        globalVarTerms.put(name, new EnvironmentDeclarationTerm(name, env));
    }
    return globalVarTerms.get(name);
}
 
Example #12
Source File: Parser.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Create a {@code Name} node using the token info from the
 * last scanned name.  In some cases we need to either synthesize
 * a name node, or we lost the name token information by peeking.
 * If the {@code token} parameter is not {@link Token#NAME}, then
 * we use token info saved in instance vars.
 */
private Name createNameNode(boolean checkActivation, int token) {
    int beg = ts.tokenBeg;
    String s = ts.getString();
    int lineno = ts.lineno;
    if (!"".equals(prevNameTokenString)) {
        beg = prevNameTokenStart;
        s = prevNameTokenString;
        lineno = prevNameTokenLineno;
        prevNameTokenStart = 0;
        prevNameTokenString = "";
        prevNameTokenLineno = 0;
    }
    if (s == null) {
        if (compilerEnv.isIdeMode()) {
            s = "";
        } else {
            codeBug();
        }
    }
    Name name = new Name(beg, s);
    name.setLineno(lineno);
    if (checkActivation) {
        checkActivationName(s, token);
    }
    return name;
}
 
Example #13
Source File: ConstraintFactory.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * Find or create a term representing the name, without first mapping the name to its
 * declaration
 */
public NameDeclarationTerm findOrCreateNameDeclTermNoLookup(final Name name) {
    if (!nameTerms.containsKey(name)){
        nameTerms.put(name, new NameDeclarationTerm(name));
    }
    return nameTerms.get(name);

}
 
Example #14
Source File: Parser.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
private void checkCallRequiresActivation(AstNode pn) {
    if ((pn.getType() == Token.NAME
         && "eval".equals(((Name)pn).getIdentifier()))
        || (pn.getType() == Token.GETPROP &&
            "eval".equals(((PropertyGet)pn).getProperty().getIdentifier())))
        setRequiresActivation();
}
 
Example #15
Source File: Parser.java    From JsDroidCmd with Mozilla Public License 2.0 5 votes vote down vote up
private void arrowFunctionParams(FunctionNode fnNode, AstNode params, Map<String, Node> destructuring, Set<String> paramNames) {
    if (params instanceof ArrayLiteral || params instanceof ObjectLiteral) {
        markDestructuring(params);
        fnNode.addParam(params);
        String pname = currentScriptOrFn.getNextTempName();
        defineSymbol(Token.LP, pname, false);
        destructuring.put(pname, params);
    } else if (params instanceof InfixExpression && params.getType() == Token.COMMA) {
        arrowFunctionParams(fnNode, ((InfixExpression)params).getLeft(), destructuring, paramNames);
        arrowFunctionParams(fnNode, ((InfixExpression)params).getRight(), destructuring, paramNames);
    } else if (params instanceof Name) {
        fnNode.addParam(params);
        String paramName = ((Name)params).getIdentifier();
        defineSymbol(Token.LP, paramName);

        if (this.inUseStrictDirective) {
            if ("eval".equals(paramName) ||
                "arguments".equals(paramName))
                {
                    reportError("msg.bad.id.strict", paramName);
                }
            if (paramNames.contains(paramName))
                addError("msg.dup.param.strict", paramName);
            paramNames.add(paramName);
        }
    } else {
        reportError("msg.no.parm", params.getPosition(), params.getLength());
        fnNode.addParam(makeErrorNode());
    }
}
 
Example #16
Source File: ConstraintGenUtil.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the declaration of the called function. Assumes that the call's target
 * is a Name, which is passed as the second parameter.
 *
 */
static FunctionNode findFunDecl(FunctionCall fc, Name funName){
	List<FunctionNode> funsFound = findFunDecl2(fc, new ArrayList<FunctionNode>());
	for (int i=0; i < funsFound.size(); i++){
		FunctionNode fun = funsFound.get(i);
		if (funName.getIdentifier().equals(fun.getName())){
			return fun;
		}
	}
	return null;
}
 
Example #17
Source File: ConstraintGenUtil.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the declaration of the referenced Name.
 */
static Name findDecl(Name name){
	List<Name> declsFound = findDecl2(name);
	for (int i=0; i < declsFound.size(); i++){
		Name name2 = declsFound.get(i);
		if (name.getIdentifier().equals(name2.getIdentifier())){
			return name2;
		}
	}
	return null;
}
 
Example #18
Source File: ConstraintGenUtil.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if an object literal is an object by checking that all
 * properties are unquoted.
 */
static boolean isObject(ObjectLiteral o){
	boolean result = (o.getElements().size() > 0);
	for (ObjectProperty prop : o.getElements()){
		AstNode left = prop.getLeft();
		result = result && (left instanceof Name);
	}
	return result;
}
 
Example #19
Source File: Node.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Can only be called when node has String context. */
public void setScope(Scope s) {
    if (s == null) Kit.codeBug();
    if (!(this instanceof Name)) {
        throw Kit.codeBug();
    }
    ((Name)this).setScope(s);
}
 
Example #20
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
   * Syntactically identify module imports
   */
  private boolean isSyntacticModuleRequire(FunctionCall fc) {
AstNode target = fc.getTarget();
      if (target instanceof Name) {
          Name name = (Name)target;
          return name.getIdentifier().equals("require") && fc.getArguments().size() == 1 && fc.getArguments().get(0) instanceof StringLiteral;
      } else {
          return false;
      }
  }
 
Example #21
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * generate constraints for a for-in loop
 */
private void processForInLoop(ForInLoop loop) {
	AstNode it = loop.getIterator();
	AstNode obj = loop.getIteratedObject();
	ITypeTerm objTerm = processExpression(obj);
	MapType mapType = new MapType(factory.freshTypeVar());
       addSubTypeConstraint(
               objTerm,
               findOrCreateTypeTerm(mapType, loop.getLineno()),
               loop.getLineno(),
               (solution) -> typeEqualityError("for-in loop can only iterate over map objects; " + obj.toSource() + " is not a map",
                       solution.typeOfTerm(objTerm), mapType, locationOf(obj)));
	if (it instanceof VariableDeclaration){
		VariableDeclaration vd = (VariableDeclaration)it;
		for (VariableInitializer vi : vd.getVariables()){
			AstNode target = vi.getTarget();
			if (target instanceof Name){
				ITypeTerm leftTerm = findOrCreateNameDeclarationTerm((Name)target);
                   addSubTypeConstraint(
                           leftTerm,
                           findOrCreateTypeTerm(StringType.make(),
                                   loop.getLineno()),
                           loop.getLineno(),
                           (solution) -> typeEqualityError(
                                   "loop variable " + it.toSource() + " of for-in loop must have string type",
                                   solution.typeOfTerm(leftTerm),
                                   StringType.make(), locationOf(it)));
			}
		}
	} else {
		error("unhandled type of iterator in for-in loop: " + it.getClass().getName(), it);
	}
}
 
Example #22
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * generate constraints for initializers
 */
private void processVariableInitializer(AstNode node) throws Error {
	VariableInitializer vi = (VariableInitializer)node;
	AstNode varname = vi.getTarget();
	AstNode initializer = vi.getInitializer();
	if (varname instanceof Name){
           ITypeTerm leftTerm = findOrCreateNameDeclarationTerm((Name)varname); // declaration of variable, so no need to create ITerm for expression
		if (initializer != null){
			ITypeTerm rightTerm = processExpression(initializer);
			processCopy(initializer, rightTerm, leftTerm,
					node.getLineno(), (solution) -> subtypeError("bad initialization of " + varname.toSource(),
							solution.typeOfTerm(rightTerm), solution.typeOfTerm(leftTerm), locationOf(node)));
		}
		// in case of multiple declarations of same identifier,
		// equate the type of this particular Name to the type of
		// the canonical Name
           ITypeTerm localTerm = factory.findOrCreateNameDeclTermNoLookup((Name) varname);
           if (localTerm != leftTerm) {
               addTypeEqualityConstraint(localTerm, leftTerm, node.getLineno(),
                       (solution) -> typeEqualityError("different declarations within the same scope must have the same type",
                               solution.typeOfTerm(localTerm), solution.typeOfTerm(leftTerm), locationOf(node)));

           }
	} else {
		error("unsupported type of VariableInitializer", varname);
	}
}
 
Example #23
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * assignment to an object property
 */
private void processAssignToProperty(Assignment a, AstNode left, AstNode right, ITypeTerm expTerm) throws Error {

	PropertyGet pg = (PropertyGet)left;
	AstNode base = pg.getTarget();
	Name prop = pg.getProperty();
	ITypeTerm pgTerm = findOrCreateExpressionTerm(pg);

	ITypeTerm baseTerm;
	if (base instanceof KeywordLiteral && ConstraintGenUtil.isThis(base)){
		baseTerm = findOrCreateThisTerm(base);
	} else {
		baseTerm = generateReceiverConstraints(pg);
	}

	int assignLineNo = a.getLineno();
	// detect assignments of the form C.prototype.foo = ...
	if (base instanceof PropertyGet) {
		PropertyGet basePG = (PropertyGet) base;
		String baseProp = basePG.getProperty().getIdentifier();
		if (baseProp.equals("prototype")) {
			checkForValidProtoPropAssign(a, pg, assignLineNo, basePG);
		}
	}
	ITypeTerm leftTerm = findOrCreatePropertyAccessTerm(baseTerm, prop.getIdentifier(), null);
	ITypeTerm rightTerm = processExpression(right);
	addTypeEqualityConstraint(pgTerm, leftTerm, assignLineNo, (solution) ->
			typeEqualityError("incompatible types",
					solution.typeOfTerm(leftTerm), solution.typeOfTerm(pgTerm), locationOf(pg)));
	addTypeEqualityConstraint(expTerm, leftTerm, assignLineNo, (solution) ->
			typeEqualityError("incompatible types",
					solution.typeOfTerm(leftTerm), solution.typeOfTerm(expTerm), locationOf(a)));
	processCopy(right, rightTerm, leftTerm, assignLineNo,
			(solution) -> badPropertyWrite(pg, solution.typeOfTerm(baseTerm), hasType(leftTerm, solution) ? solution.typeOfTerm(leftTerm) : null, solution.typeOfTerm(rightTerm)));
}
 
Example #24
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 5 votes vote down vote up
private void checkForSameName(int assignLineNo, Name baseName,
		AstNode other) {
	if (!(other instanceof Name)) {
		error("assignment to property of prototype not valid (line " + assignLineNo + ")", baseName);
		return;
	}
	if (!baseName.getIdentifier().equals(((Name)other).getIdentifier())) {
		error("assignment to property of prototype not valid (line " + assignLineNo + ")", baseName);
		return;
	}
}
 
Example #25
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * Generate constraints for the (possibly nested) receiver of a property-get expression.
 */
private ITypeTerm generateReceiverConstraints(PropertyGet pg) throws Error {
	AstNode base = pg.getTarget();
	ITypeTerm baseTerm = findOrCreateExpressionTerm(base); // make term for expression
	if (base instanceof Name) {
		Name name = (Name)base;
		ITypeTerm nameTerm = findOrCreateNameDeclarationTerm(name); // find unique representative for referenced Name
		addTypeEqualityConstraint(baseTerm, nameTerm, base.getLineno(), null);
	} else if (base instanceof PropertyGet) {
		PropertyGet basePG = (PropertyGet)base;
		ITypeTerm bbaseTerm = generateReceiverConstraints(basePG);
		String baseProperty = basePG.getProperty().getIdentifier();
		ITypeTerm basePATerm;
		if (basePG.getProperty().getIdentifier().equals("prototype")){
			basePATerm = findOrCreateProtoTerm(bbaseTerm, pg.getLineno());
		} else {
			basePATerm = findOrCreatePropertyAccessTerm(bbaseTerm, baseProperty, basePG);
		}
		addTypeEqualityConstraint(baseTerm, basePATerm, basePG.getLineno(), null);
	} else if (base instanceof KeywordLiteral && ConstraintGenUtil.isThis(base)){
		processExpression(base);
		//error("unsupported property get with base this: "+pg.toSource());
	} else if (base instanceof ElementGet) {
	    ElementGet baseEGet = (ElementGet) base;
	    processElementGet(baseEGet);
	} else {
		System.err.println("base = " + base.toSource() + ", type = " + base.getClass().getName() );
		error("unsupported property get: " + pg.toSource(), pg);
	}
	return baseTerm;
}
 
Example #26
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * assignment to a variable
 */
private void processAssignToVariable(Assignment a, AstNode left, AstNode right, ITypeTerm expTerm) {
	ITypeTerm leftTerm = findOrCreateExpressionTerm(left);
	ITypeTerm nameTerm = findOrCreateNameDeclarationTerm((Name) left); // find unique representative for the Name
	addTypeEqualityConstraint(leftTerm, nameTerm, a.getLineno(), null); // equate to the LHS expression
	ITypeTerm rightTerm = processExpression(right);
	addTypeEqualityConstraint(expTerm, leftTerm, a.getLineno(),
			(solution) -> genericTypeError("assignment " + shortSrc(a), locationOf(a)));
	processCopy(right, rightTerm, leftTerm,
			a.getLineno(),
			(solution) -> subtypeError(shortSrc(right) + " assigned to " + shortSrc(left),
					solution.typeOfTerm(rightTerm), solution.typeOfTerm(leftTerm), locationOf(a)));
}
 
Example #27
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * Create constraints for parameterized external functions such as Array<T>
 */
private void createConstraintsForGlobalFunction(Name name) {
	ITypeTerm term = findOrCreateExpressionTerm(name);
	String functionName = name.getIdentifier();
	Type type = jsEnv.get(functionName);
	if (type == null){
		error("reference to unknown global: " + name.getIdentifier(), name);
		return;
	}
	ITypeTerm typeParamTerm = new TypeParamTerm(name);
	if (ConstraintGenUtil.isParameterized(type)){
		generateConstraintsForType(name, typeParamTerm, term, type);
	}
}
 
Example #28
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 5 votes vote down vote up
/**
 * Analyze the signature of a generic type and generate constraints that equate
 * a variable to terms corresponding to all occurrences of type parameters
 */
private void generateConstraintsForType(Name name, ITypeTerm TP, ITypeTerm term, Type type) {

	if (type instanceof IntersectionType){
		IntersectionType iType = (IntersectionType)type;
		for (Type t : iType.getTypes()){
			generateConstraintsForType(name, TP, term, t);
		}
	} else if (type instanceof ArrayType && ((ArrayType)type).elemType().isVar()){
	// Array<T> : TP = Elem(term)
		addTypeEqualityConstraint(TP, findOrCreateIndexedTerm(term, name.getLineno()), name.getLineno(), null);
	} else if (type instanceof FunctionType){
		FunctionType fType = (FunctionType)type;
		Type returnType = fType.returnType();
		// (...) -> Array<T> : TP = Elem(ret(term))
		if (returnType instanceof ArrayType && ((ArrayType)returnType).elemType().isVar()){
			ITypeTerm retTerm = findOrCreateFunctionReturnTerm(term, fType.nrParams(), name.getLineno(), null);
			addTypeEqualityConstraint(TP, findOrCreateIndexedTerm(retTerm, name.getLineno()), name.getLineno(), null);
			createArrayConstraints(retTerm, name);
		}
		for (int i=0; i < fType.nrParams(); i++){
			Type paramType = fType.paramTypes().get(i);

			// (..., T, ...) -> Array<T> : TP = param(term, i)
			if (paramType.isVar()){
				ITypeTerm paramTerm = findOrCreateFunctionParamTerm(term, i, fType.nrParams(), name.getLineno());
				addTypeEqualityConstraint(TP, paramTerm, name.getLineno(), null);
			}
		}
	}
}
 
Example #29
Source File: ConstraintVisitor.java    From SJS with Apache License 2.0 5 votes vote down vote up
private ITypeTerm findOrCreateNameDeclarationTerm(Name name) {
	NameDeclarationTerm t;
	try {
		t = factory.findOrCreateNameDeclarationTerm(name);
	} catch (Error e) { // TODO: factory method should throw something meaningful or return null
		return expError("unknown name '" + name.getIdentifier() + '\'', name);
	}
	generator.addTermLineNumber(t, name.getLineno());
	return t;
}
 
Example #30
Source File: ClassDefScanner.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Find the textual name of the given node.
 */
@Nullable
private String nameOf(final AstNode node) {
  if (node instanceof Name) {
    return ((Name) node).getIdentifier();
  }
  else if (node instanceof PropertyGet) {
    PropertyGet prop = (PropertyGet) node;
    return String.format("%s.%s", nameOf(prop.getTarget()), nameOf(prop.getProperty()));
  }
  else if (node instanceof StringLiteral) {
    return ((StringLiteral) node).getValue();
  }
  return null;
}