Search in sources :

Example 71 with JSType

use of com.google.javascript.rhino.jstype.JSType in project closure-compiler by google.

the class TypeInferenceTest method testAssertInstanceof_stringCtor_narrowsAllTypeToString.

@Test
public void testAssertInstanceof_stringCtor_narrowsAllTypeToString() {
    JSType startType = createNullableType(ALL_TYPE);
    includeAssertInstanceof();
    assuming("x", startType);
    inFunction("out1 = x; goog.asserts.assertInstanceof(x, String); out2 = x;");
    verify("out1", startType);
    verify("out2", STRING_OBJECT_TYPE);
}
Also used : JSType(com.google.javascript.rhino.jstype.JSType) Test(org.junit.Test)

Example 72 with JSType

use of com.google.javascript.rhino.jstype.JSType in project closure-compiler by google.

the class TypeInferenceTest method assertTypeOfExpression.

/**
 * Returns a TypeSubject for the JSType of the expression with the given label.
 *
 * <p>Asserts that a statement with the given label existed in the code last passed to
 * parseAndRunTypeInference(). Also asserts that the statement is an EXPR_RESULT whose expression
 * has a non-null JSType.
 */
private TypeSubject assertTypeOfExpression(String label) {
    Node statementNode = getLabeledStatement(label).statementNode;
    assertWithMessage("Not an expression statement.").that(statementNode.isExprResult()).isTrue();
    JSType jsType = statementNode.getOnlyChild().getJSType();
    assertWithMessage("Expression type is null").that(jsType).isNotNull();
    return assertType(jsType);
}
Also used : JSType(com.google.javascript.rhino.jstype.JSType) Node(com.google.javascript.rhino.Node) NodeSubject.assertNode(com.google.javascript.rhino.testing.NodeSubject.assertNode)

Example 73 with JSType

use of com.google.javascript.rhino.jstype.JSType in project closure-compiler by google.

the class TypeInferenceTest method testAssert5.

@Test
public void testAssert5() {
    JSType startType = createNullableType(OBJECT_TYPE);
    assuming("x", startType);
    assuming("y", startType);
    inFunction("goog.asserts.assert(x || y); out1 = x; out2 = y;");
    verify("out1", startType);
    verify("out2", startType);
}
Also used : JSType(com.google.javascript.rhino.jstype.JSType) Test(org.junit.Test)

Example 74 with JSType

use of com.google.javascript.rhino.jstype.JSType in project closure-compiler by google.

the class TypeInferenceTest method testObjectDestructuringDeclarationInference.

@Test
public void testObjectDestructuringDeclarationInference() {
    JSType recordType = registry.createRecordType(ImmutableMap.of("x", getNativeType(STRING_TYPE), "y", getNativeType(NUMBER_TYPE)));
    assuming("obj", recordType);
    inFunction(lines(// preserve newline
    "let {x, y} = obj; ", "X: x;", "Y: y;"));
    assertTypeOfExpression("X").toStringIsEqualTo("string");
    assertTypeOfExpression("Y").toStringIsEqualTo("number");
    assertScopeEnclosing("X").declares("x").withTypeThat().toStringIsEqualTo("string");
}
Also used : JSType(com.google.javascript.rhino.jstype.JSType) Test(org.junit.Test)

Example 75 with JSType

use of com.google.javascript.rhino.jstype.JSType in project closure-compiler by google.

the class TypeInferenceTest method parseAndRunTypeInference.

@SuppressWarnings({ "MustBeClosedChecker" })
private void parseAndRunTypeInference(Node root, Node cfgRoot) {
    this.closer.close();
    TypedScopeCreator scopeCreator = new TypedScopeCreator(compiler);
    TypedScope assumedScope;
    try (JSTypeResolver.Closer closer = this.registry.getResolver().openForDefinition()) {
        // Create the scope with the assumptions.
        // Also populate a map allowing us to look up labeled statements later.
        labeledStatementMap = new HashMap<>();
        NodeTraversal.builder().setCompiler(compiler).setCallback(new AbstractScopedCallback() {

            @Override
            public void enterScope(NodeTraversal t) {
                t.getTypedScope();
            }

            @Override
            public void visit(NodeTraversal t, Node n, Node parent) {
                TypedScope scope = t.getTypedScope();
                if (parent != null && parent.isLabel() && !n.isLabelName()) {
                    // First child of a LABEL is a LABEL_NAME, n is the second child.
                    Node labelNameNode = checkNotNull(n.getPrevious(), n);
                    checkState(labelNameNode.isLabelName(), labelNameNode);
                    String labelName = labelNameNode.getString();
                    assertWithMessage("Duplicate label name: %s", labelName).that(labeledStatementMap).doesNotContainKey(labelName);
                    labeledStatementMap.put(labelName, new LabeledStatement(n, scope));
                }
            }
        }).setScopeCreator(scopeCreator).traverse(root);
        assumedScope = scopeCreator.createScope(cfgRoot);
        for (Map.Entry<String, JSType> entry : assumptions.entrySet()) {
            assumedScope.declare(entry.getKey(), null, entry.getValue(), null, false);
        }
        scopeCreator.resolveWeakImportsPreResolution();
    }
    scopeCreator.finishAndFreeze();
    // Create the control graph.
    ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false, true);
    cfa.process(null, cfgRoot);
    ControlFlowGraph<Node> cfg = cfa.getCfg();
    // Create a simple reverse abstract interpreter.
    ReverseAbstractInterpreter rai = compiler.getReverseAbstractInterpreter();
    // Do the type inference by data-flow analysis.
    TypeInference dfa = new TypeInference(compiler, cfg, rai, assumedScope, scopeCreator, ASSERTION_FUNCTION_MAP);
    dfa.analyze();
    // Get the scope of the implicit return.
    LinearFlowState<FlowScope> rtnState = cfg.getImplicitReturn().getAnnotation();
    if (cfgRoot.isFunction()) {
        // Reset the flow scope's syntactic scope to the function block, rather than the function
        // node
        // itself.  This allows pulling out local vars from the function by name to verify their
        // types.
        returnScope = rtnState.getIn().withSyntacticScope(scopeCreator.createScope(cfgRoot.getLastChild()));
    } else {
        returnScope = rtnState.getIn();
    }
    this.closer = this.registry.getResolver().openForDefinition();
}
Also used : ReverseAbstractInterpreter(com.google.javascript.jscomp.type.ReverseAbstractInterpreter) JSType(com.google.javascript.rhino.jstype.JSType) StaticTypedScope(com.google.javascript.rhino.jstype.StaticTypedScope) Node(com.google.javascript.rhino.Node) NodeSubject.assertNode(com.google.javascript.rhino.testing.NodeSubject.assertNode) AbstractScopedCallback(com.google.javascript.jscomp.NodeTraversal.AbstractScopedCallback) JSTypeResolver(com.google.javascript.rhino.jstype.JSTypeResolver) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) FlowScope(com.google.javascript.jscomp.type.FlowScope)

Aggregations

JSType (com.google.javascript.rhino.jstype.JSType)447 Test (org.junit.Test)182 Node (com.google.javascript.rhino.Node)158 FunctionType (com.google.javascript.rhino.jstype.FunctionType)71 ObjectType (com.google.javascript.rhino.jstype.ObjectType)71 NodeSubject.assertNode (com.google.javascript.rhino.testing.NodeSubject.assertNode)30 JSDocInfo (com.google.javascript.rhino.JSDocInfo)19 TemplateType (com.google.javascript.rhino.jstype.TemplateType)14 FlowScope (com.google.javascript.jscomp.type.FlowScope)13 CheckReturnValue (com.google.errorprone.annotations.CheckReturnValue)11 JSTypeExpression (com.google.javascript.rhino.JSTypeExpression)9 UnionType (com.google.javascript.rhino.jstype.UnionType)9 JSTypeRegistry (com.google.javascript.rhino.jstype.JSTypeRegistry)8 TemplateTypeMap (com.google.javascript.rhino.jstype.TemplateTypeMap)8 LinkedHashMap (java.util.LinkedHashMap)8 ImmutableList (com.google.common.collect.ImmutableList)7 Color (com.google.javascript.jscomp.colors.Color)7 StaticTypedSlot (com.google.javascript.rhino.jstype.StaticTypedSlot)7 ArrayList (java.util.ArrayList)7 ImmutableMap (com.google.common.collect.ImmutableMap)6