Search in sources :

Example 16 with JSTypeExpression

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

the class Es6TypedToEs6Converter method visitInterface.

private void visitInterface(NodeTraversal t, Node n, Node parent) {
    maybeAddGenerics(n, n);
    Node name = n.getFirstChild();
    Node superTypes = name.getNext();
    JSDocInfoBuilder doc = JSDocInfoBuilder.maybeCopyFrom(n.getJSDocInfo());
    doc.recordInterface();
    if (!superTypes.isEmpty()) {
        for (Node child : superTypes.children()) {
            Node type = convertWithLocation(child);
            doc.recordExtendedInterface(new JSTypeExpression(type, n.getSourceFileName()));
        }
    }
    Node insertionPoint = n;
    Node members = n.getLastChild();
    for (Node member : members.children()) {
        if (member.isCallSignature()) {
            compiler.report(JSError.make(n, CALL_SIGNATURE_NOT_SUPPORTED));
        }
        if (member.isIndexSignature()) {
            doc.recordExtendedInterface(createIObject(t, member));
        }
        // Synthesize a block for method signatures, or convert it to a member variable if optional.
        if (member.isMemberFunctionDef()) {
            Node function = member.getFirstChild();
            if (function.isOptionalEs6Typed()) {
                member = convertMemberFunctionToMemberVariable(member);
            } else {
                function.getLastChild().setToken(Token.BLOCK);
            }
        }
        if (member.isMemberVariableDef()) {
            Node newNode = createPropertyDefinition(t, member, name.getString());
            insertionPoint.getParent().addChildAfter(newNode, insertionPoint);
            insertionPoint = newNode;
        }
    }
    n.setJSDocInfo(doc.build());
    // Convert interface to class
    n.setToken(Token.CLASS);
    Node empty = new Node(Token.EMPTY).useSourceInfoIfMissingFrom(n);
    n.replaceChild(superTypes, empty);
    members.setToken(Token.CLASS_MEMBERS);
    maybeCreateQualifiedDeclaration(t, n, parent);
    t.reportCodeChange();
}
Also used : TypeDeclarationNode(com.google.javascript.rhino.Node.TypeDeclarationNode) Node(com.google.javascript.rhino.Node) JSTypeExpression(com.google.javascript.rhino.JSTypeExpression) JSDocInfoBuilder(com.google.javascript.rhino.JSDocInfoBuilder)

Example 17 with JSTypeExpression

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

the class Es6RewriteClass method visitMethod.

/**
 * Handles transpilation of a standard class member function. Getters, setters, and the
 * constructor are not handled here.
 */
private void visitMethod(Node member, ClassDeclarationMetadata metadata) {
    Node qualifiedMemberAccess = getQualifiedMemberAccess(member, metadata);
    Node method = member.getLastChild().detach();
    // Use the source info from the method (a FUNCTION) not the MEMBER_FUNCTION_DEF
    // because the MEMBER_FUNCTION_DEf source info only corresponds to the identifier
    Node assign = astFactory.createAssign(qualifiedMemberAccess, method).srcrefIfMissing(method);
    JSDocInfo info = member.getJSDocInfo();
    if (member.isStaticMember() && NodeUtil.referencesOwnReceiver(assign.getLastChild())) {
        JSDocInfo.Builder memberDoc = JSDocInfo.Builder.maybeCopyFrom(info);
        // adding an @this type prevents a JSC_UNSAFE_THIS error later on.
        memberDoc.recordThisType(new JSTypeExpression(new Node(Token.BANG, new Node(Token.QMARK)).srcrefTree(member), member.getSourceFileName()));
        info = memberDoc.build();
    }
    if (info != null) {
        assign.setJSDocInfo(info);
    }
    Node newNode = NodeUtil.newExpr(assign);
    metadata.insertNodeAndAdvance(newNode);
}
Also used : Node(com.google.javascript.rhino.Node) JSTypeExpression(com.google.javascript.rhino.JSTypeExpression) JSDocInfo(com.google.javascript.rhino.JSDocInfo)

Example 18 with JSTypeExpression

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

the class TemplateAstMatcher method prepTemplatePlaceholders.

/**
 * Build parameter and local information for the template and replace
 * the references in the template 'fn' with placeholder nodes use to
 * facility matching.
 */
private void prepTemplatePlaceholders(Node fn) {
    final List<String> locals = templateLocals;
    final List<String> params = templateParams;
    final Map<String, JSType> paramTypes = new HashMap<>();
    // drop the function name so it isn't include in the name maps
    String fnName = fn.getFirstChild().getString();
    fn.getFirstChild().setString("");
    // Build a list of parameter names and types.
    Node templateParametersNode = fn.getSecondChild();
    JSDocInfo info = NodeUtil.getBestJSDocInfo(fn);
    if (templateParametersNode.hasChildren()) {
        Preconditions.checkNotNull(info, "Missing JSDoc declaration for template function %s", fnName);
    }
    for (Node paramNode = templateParametersNode.getFirstChild(); paramNode != null; paramNode = paramNode.getNext()) {
        String name = paramNode.getString();
        JSTypeExpression expression = info.getParameterType(name);
        Preconditions.checkNotNull(expression, "Missing JSDoc for parameter %s of template function %s", name, fnName);
        JSType type = typeRegistry.evaluateTypeExpression(expression, topScope);
        checkNotNull(type);
        params.add(name);
        paramTypes.put(name, type);
    }
    // Find references to string literals, local variables and parameters and replace them.
    traverse(fn, new Visitor() {

        @Override
        public void visit(Node n) {
            if (n.isName()) {
                Node parent = n.getParent();
                String name = n.getString();
                if (!name.isEmpty() && parent.isVar() && !locals.contains(name)) {
                    locals.add(n.getString());
                }
                if (params.contains(name)) {
                    JSType type = paramTypes.get(name);
                    boolean isStringLiteral = type.isStringValueType() && name.startsWith("string_literal");
                    replaceNodeInPlace(n, createTemplateParameterNode(params.indexOf(name), type, isStringLiteral));
                } else if (locals.contains(name)) {
                    replaceNodeInPlace(n, createTemplateLocalNameNode(locals.indexOf(name)));
                }
            }
        }
    });
}
Also used : JSType(com.google.javascript.rhino.jstype.JSType) HashMap(java.util.HashMap) Node(com.google.javascript.rhino.Node) JSTypeExpression(com.google.javascript.rhino.JSTypeExpression) JSDocInfo(com.google.javascript.rhino.JSDocInfo)

Example 19 with JSTypeExpression

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

the class AstValidatorTest method testCastOnLeftSideOfAssign.

@Test
public void testCastOnLeftSideOfAssign() {
    // Since we're building the AST by hand, there won't be any types on it.
    typeInfoValidationMode = AstValidator.TypeInfoValidation.NONE;
    JSDocInfo.Builder jsdoc = JSDocInfo.builder();
    jsdoc.recordType(new JSTypeExpression(IR.string("number"), "<AstValidatorTest>"));
    Node n = IR.exprResult(new Node(Token.ASSIGN, IR.cast(IR.name("x"), jsdoc.build()), IR.number(0)));
    setTestSourceLocationForTree(n);
    expectValid(n, Check.STATEMENT);
}
Also used : Node(com.google.javascript.rhino.Node) JSTypeExpression(com.google.javascript.rhino.JSTypeExpression) JSDocInfo(com.google.javascript.rhino.JSDocInfo) Test(org.junit.Test)

Example 20 with JSTypeExpression

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

the class FunctionTypeBuilder method buildTemplateTypesFromJSDocInfo.

private ImmutableList<TemplateType> buildTemplateTypesFromJSDocInfo(JSDocInfo info, boolean allowTypeTransformations) {
    ImmutableMap<String, JSTypeExpression> infoTypeKeys = info.getTemplateTypes();
    ImmutableMap<String, Node> infoTypeTransformations = info.getTypeTransformations();
    if (infoTypeKeys.isEmpty() && infoTypeTransformations.isEmpty()) {
        return ImmutableList.of();
    }
    // Temporarily bootstrap the template environment with unbound (unknown bound) template types
    List<TemplateType> unboundedTemplates = new ArrayList<>();
    for (String templateKey : infoTypeKeys.keySet()) {
        unboundedTemplates.add(typeRegistry.createTemplateType(templateKey));
    }
    this.templateScope = typeRegistry.createScopeWithTemplates(templateScope, unboundedTemplates);
    // Evaluate template type bounds with bootstrapped environment and reroute the bounds to these
    ImmutableList.Builder<TemplateType> templates = ImmutableList.builder();
    Map<TemplateType, JSType> templatesToBounds = new LinkedHashMap<>();
    for (Map.Entry<String, JSTypeExpression> entry : infoTypeKeys.entrySet()) {
        JSTypeExpression expr = entry.getValue();
        JSType typeBound = typeRegistry.evaluateTypeExpression(entry.getValue(), templateScope);
        // treatment in the future, since "unknown" is currently used as a proxy for "implicit".
        if (expr.isExplicitUnknownTemplateBound()) {
            reportError(TEMPLATE_TYPE_ILLEGAL_BOUND, String.valueOf(typeBound), entry.getKey());
        }
        TemplateType template = typeRegistry.getType(templateScope, entry.getKey()).toMaybeTemplateType();
        if (template != null) {
            templatesToBounds.put(template, typeBound);
        } else {
            templatesToBounds.put(typeRegistry.createTemplateType(entry.getKey(), typeBound), typeBound);
        }
    }
    for (Map.Entry<TemplateType, JSType> entry : templatesToBounds.entrySet()) {
        TemplateType template = entry.getKey();
        JSType bound = entry.getValue();
        template.setBound(bound);
        templates.add(template);
    }
    for (Map.Entry<String, Node> entry : infoTypeTransformations.entrySet()) {
        if (allowTypeTransformations) {
            templates.add(typeRegistry.createTemplateTypeWithTransformation(entry.getKey(), entry.getValue()));
        } else {
            reportWarning(TEMPLATE_TRANSFORMATION_ON_CLASS, entry.getKey());
        }
    }
    ImmutableList<TemplateType> builtTemplates = templates.build();
    for (TemplateType template : builtTemplates) {
        if (template.containsCycle()) {
            reportError(RhinoErrorReporter.PARSE_ERROR, "Cycle detected in inheritance chain of type " + template.getReferenceName());
        }
    }
    return builtTemplates;
}
Also used : JSType(com.google.javascript.rhino.jstype.JSType) ImmutableList(com.google.common.collect.ImmutableList) Node(com.google.javascript.rhino.Node) ArrayList(java.util.ArrayList) TemplateType(com.google.javascript.rhino.jstype.TemplateType) LinkedHashMap(java.util.LinkedHashMap) JSTypeExpression(com.google.javascript.rhino.JSTypeExpression) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Aggregations

JSTypeExpression (com.google.javascript.rhino.JSTypeExpression)101 Node (com.google.javascript.rhino.Node)67 JSDocInfo (com.google.javascript.rhino.JSDocInfo)58 Test (org.junit.Test)26 JSDocInfoBuilder (com.google.javascript.rhino.JSDocInfoBuilder)18 MemberDefinition (com.google.javascript.jscomp.PolymerPass.MemberDefinition)9 JSType (com.google.javascript.rhino.jstype.JSType)9 ArrayList (java.util.ArrayList)8 TypeDeclarationNode (com.google.javascript.rhino.Node.TypeDeclarationNode)7 Map (java.util.Map)6 NodeSubject.assertNode (com.google.javascript.jscomp.testing.NodeSubject.assertNode)4 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 ImmutableList (com.google.common.collect.ImmutableList)3 ImmutableMap (com.google.common.collect.ImmutableMap)3 Visibility (com.google.javascript.rhino.JSDocInfo.Visibility)3 LinkedHashMap (java.util.LinkedHashMap)3 ImmutableSet (com.google.common.collect.ImmutableSet)2 Name (com.google.javascript.jscomp.GlobalNamespace.Name)2 Ref (com.google.javascript.jscomp.GlobalNamespace.Ref)2