Search in sources :

Example 1 with Module

use of com.google.javascript.jscomp.modules.Module in project closure-compiler by google.

the class RewriteDynamicImports method visit.

@Override
public void visit(NodeTraversal t, Node n, Node parent) {
    if (n.getToken() != Token.DYNAMIC_IMPORT) {
        return;
    }
    // If the module specifier is a string, attempt to resolve the module
    final ModuleMap moduleMap = compiler.getModuleMap();
    final Node importSpecifier = n.getFirstChild();
    if (importSpecifier.isStringLit() && moduleMap != null) {
        final ModulePath targetPath = t.getInput().getPath().resolveJsModule(importSpecifier.getString(), n.getSourceFileName(), n.getLineno(), n.getCharno());
        final Module module = (targetPath == null) ? null : compiler.getModuleMap().getModule(targetPath);
        final String targetModuleVarName = (module == null) ? null : GlobalizedModuleName.create(module.metadata(), null, null).aliasName().join();
        final Var targetModuleNS = (targetModuleVarName == null) ? null : t.getScope().getVar(targetModuleVarName);
        if (targetModuleNS != null) {
            final JSChunk targetModule = targetModuleNS.getInput().getChunk();
            // No further rewriting occurs for this case.
            if (t.getChunk() == targetModule) {
                replaceDynamicImportWithPromise(t, n, targetModuleNS);
                return;
            } else {
                // The target output chunk is recognized and different from the current chunk.
                // Retarget the import specifier path to the output chunk path and rewrite
                // the import to reference the rewritten global module namespace variable.
                retargetImportSpecifier(t, n, targetModule);
                if (NodeUtil.isExpressionResultUsed(n)) {
                    addChainedThen(n, targetModuleNS);
                }
            }
        }
    }
    if (aliasIsValid()) {
        aliasDynamicImport(t, n);
    } else if (this.alias != null) {
        t.report(n, DYNAMIC_IMPORT_INVALID_ALIAS);
    } else if (requiresAliasing) {
        t.report(n, DYNAMIC_IMPORT_ALIASING_REQUIRED);
    }
}
Also used : ModulePath(com.google.javascript.jscomp.deps.ModuleLoader.ModulePath) Node(com.google.javascript.rhino.Node) Module(com.google.javascript.jscomp.modules.Module) ModuleMap(com.google.javascript.jscomp.modules.ModuleMap)

Example 2 with Module

use of com.google.javascript.jscomp.modules.Module in project closure-compiler by google.

the class RewriteGoogJsImports method rewriteImports.

private void rewriteImports(Node scriptRoot) {
    if (Es6RewriteModules.isEs6ModuleRoot(scriptRoot)) {
        Node googImportNode = findGoogImportNode(scriptRoot);
        NodeTraversal.traverse(compiler, scriptRoot, new FindReexports(googImportNode != null));
        Module module = moduleMap.getModule(compiler.getInput(scriptRoot.getInputId()).getPath());
        checkNotNull(module);
        if (googImportNode != null && mode == Mode.LINT_AND_REWRITE) {
            // If googModule is null then goog.js was not part of the input. Try to be fault tolerant
            // and just assume that everything exported is on the global goog.
            new ReferenceReplacer(scriptRoot, googImportNode, module, /* globalizeAllReferences= */
            googModule == null);
        }
    }
}
Also used : Node(com.google.javascript.rhino.Node) Module(com.google.javascript.jscomp.modules.Module)

Example 3 with Module

use of com.google.javascript.jscomp.modules.Module in project closure-compiler by google.

the class PolymerBehaviorExtractor method resolveModuleNamespaceBinding.

/**
 * Resolves a name that imports the 'namespace' of a module or provide.
 */
private ResolveBehaviorNameResult resolveModuleNamespaceBinding(Binding b, String rest) {
    if (b.metadata().isGoogModule()) {
        return resolveBehaviorName(GOOG_MODULE_EXPORTS + rest, b.metadata());
    } else if (b.metadata().isGoogProvide()) {
        return resolveBehaviorName(b.closureNamespace() + rest, b.metadata());
    }
    // ES module import *.
    checkState(b.metadata().isEs6Module());
    if (rest.isEmpty()) {
        // The namespace imported by `import *` is never a @polymerBehavior.
        return FAILED_RESOLVE_RESULT;
    }
    // Remove leading '.'.
    rest = rest.substring(1);
    int dot = rest.indexOf('.');
    // Given:
    // `const internalName = 0; export {internalName as exportName};`
    // `import * as mod from './x'; use(mod.exportName.Behavior);`
    // 1. get the internal name `internalName` from` exportName`.
    // 2. then proceed to resolve `internalName.Behavior` in './x'.
    String exportedName = dot == -1 ? rest : rest.substring(0, dot);
    Module originalModule = moduleMap.getModule(b.metadata().path());
    Binding exportBinding = originalModule.namespace().get(exportedName);
    if (exportBinding == null || !exportBinding.isCreatedByEsExport()) {
        // This is an invalid import, and will cause an error elsewhere.
        return FAILED_RESOLVE_RESULT;
    }
    return resolveBehaviorName(exportBinding.originatingExport().localName() + (dot == -1 ? "" : rest.substring(dot)), b.metadata());
}
Also used : Binding(com.google.javascript.jscomp.modules.Binding) Module(com.google.javascript.jscomp.modules.Module)

Example 4 with Module

use of com.google.javascript.jscomp.modules.Module in project closure-compiler by google.

the class PolymerBehaviorExtractor method resolveBehaviorNameInternal.

/**
 * Implements behavior resolution. Call {@link #resolveBehaviorName(String, ModuleMetadata)}}
 * instead.
 */
private ResolveBehaviorNameResult resolveBehaviorNameInternal(String name, ModuleMetadata moduleMetadata) {
    // Check if this name is a module import/require.
    ResolveBehaviorNameResult result = getNameIfModuleImport(name, moduleMetadata);
    if (result != null) {
        return result;
    }
    // Check if this name is possibly from a legacy goog.module
    ResolveBehaviorNameResult legacyResolve = resolveReferenceToLegacyGoogModule(name);
    if (legacyResolve != null) {
        return legacyResolve;
    }
    // If not, look it up within the current module.
    Name moduleLevelName = moduleMetadata != null ? globalNames.getNameFromModule(moduleMetadata, name) : null;
    Name globalName = moduleLevelName == null ? globalNames.getSlot(name) : moduleLevelName;
    if (globalName == null) {
        return FAILED_RESOLVE_RESULT;
    }
    // Whether the declaration of this node is in the top-level global scope, as opposed to a module
    // or an IIFE.
    boolean isGlobalDeclaration = moduleLevelName == null;
    // Use any set as a backup declaration, even if it's local.
    Ref declarationRef = globalName.getDeclaration();
    if (declarationRef == null) {
        for (Ref ref : globalName.getRefs()) {
            if (ref.isSet()) {
                isGlobalDeclaration = false;
                declarationRef = ref;
                break;
            }
        }
    }
    if (declarationRef == null) {
        return FAILED_RESOLVE_RESULT;
    }
    Node declarationNode = declarationRef.getNode();
    if (declarationNode == null) {
        return FAILED_RESOLVE_RESULT;
    }
    Node rValue = NodeUtil.getRValueOfLValue(declarationNode);
    if (rValue == null) {
        return FAILED_RESOLVE_RESULT;
    }
    if (rValue.isQualifiedName()) {
        // Another identifier; recurse.
        Scope declarationScope = declarationRef.scope.getClosestHoistScope();
        Module m = ModuleImportResolver.getModuleFromScopeRoot(compiler.getModuleMap(), compiler, declarationScope.getRootNode());
        return resolveBehaviorName(getQualifiedNameThroughCast(rValue), m != null ? m.metadata() : null);
    }
    JSDocInfo behaviorInfo = NodeUtil.getBestJSDocInfo(declarationNode);
    if (behaviorInfo == null || !behaviorInfo.isPolymerBehavior()) {
        compiler.report(JSError.make(declarationNode, PolymerPassErrors.POLYMER_UNANNOTATED_BEHAVIOR));
    }
    return new ResolveBehaviorNameResult(rValue, isGlobalDeclaration, moduleMetadata);
}
Also used : Ref(com.google.javascript.jscomp.GlobalNamespace.Ref) Node(com.google.javascript.rhino.Node) Module(com.google.javascript.jscomp.modules.Module) JSDocInfo(com.google.javascript.rhino.JSDocInfo) Name(com.google.javascript.jscomp.GlobalNamespace.Name) QualifiedName(com.google.javascript.rhino.QualifiedName)

Example 5 with Module

use of com.google.javascript.jscomp.modules.Module in project closure-compiler by google.

the class ModuleRenaming method getGlobalNameForJsDoc.

/**
 * Returns the globalized name of a reference to a binding in JS Doc.
 *
 * <p>For example:
 *
 * <pre>
 *   // bar
 *   export class Bar {}
 * </pre>
 *
 * <pre>
 *   // foo
 *   import * as bar from 'bar';
 *   export {bar};
 * </pre>
 *
 * <pre>
 *   import * as foo from 'foo';
 *   let /** !foo.bar.Bar *\/ b;
 * </pre>
 *
 * <p>Should call this method with the binding for {@code foo} and a list ("bar", "Bar"). In this
 * example any of these properties could also be modules. This method will replace as much as the
 * GETPROP as it can with module exported variables. Meaning in the above example this would
 * return something like "baz$$module$bar", whereas if this method were called for just "foo.bar"
 * it would return "module$bar", as it refers to a module object itself.
 */
static String getGlobalNameForJsDoc(ModuleMap moduleMap, Binding binding, List<String> propertyChain) {
    int prop = 0;
    while (binding.isModuleNamespace() && binding.metadata().isEs6Module() && prop < propertyChain.size()) {
        String propertyName = propertyChain.get(prop);
        Module m = moduleMap.getModule(binding.metadata().path());
        if (m.namespace().containsKey(propertyName)) {
            binding = m.namespace().get(propertyName);
        } else {
            // error, but we're working on type checking modules soon.
            break;
        }
        prop++;
    }
    QualifiedName globalName = getGlobalName(binding);
    while (prop < propertyChain.size()) {
        globalName = globalName.getprop(propertyChain.get(prop++));
    }
    return globalName.join();
}
Also used : QualifiedName(com.google.javascript.rhino.QualifiedName) Module(com.google.javascript.jscomp.modules.Module)

Aggregations

Module (com.google.javascript.jscomp.modules.Module)16 Node (com.google.javascript.rhino.Node)11 QualifiedName (com.google.javascript.rhino.QualifiedName)5 ModuleMap (com.google.javascript.jscomp.modules.ModuleMap)4 Binding (com.google.javascript.jscomp.modules.Binding)3 JSType (com.google.javascript.rhino.jstype.JSType)3 ModulePath (com.google.javascript.jscomp.deps.ModuleLoader.ModulePath)2 ModuleMetadata (com.google.javascript.jscomp.modules.ModuleMetadataMap.ModuleMetadata)2 JSDocInfo (com.google.javascript.rhino.JSDocInfo)2 ObjectType (com.google.javascript.rhino.jstype.ObjectType)2 StaticTypedScope (com.google.javascript.rhino.jstype.StaticTypedScope)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Nullable (javax.annotation.Nullable)2 ImmutableMap (com.google.common.collect.ImmutableMap)1 CheckReturnValue (com.google.errorprone.annotations.CheckReturnValue)1 Name (com.google.javascript.jscomp.GlobalNamespace.Name)1 Ref (com.google.javascript.jscomp.GlobalNamespace.Ref)1 ModuleMetadataMap (com.google.javascript.jscomp.modules.ModuleMetadataMap)1 FlowScope (com.google.javascript.jscomp.type.FlowScope)1