com.google.javascript.jscomp.TypedScope Java Examples

The following examples show how to use com.google.javascript.jscomp.TypedScope. 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: TypeCollector.java    From jsinterop-generator with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean visitTopScope(TypedScope scope) {
  Type globalJavaType = createGlobalJavaType(packagePrefix, globalScopeClassName);

  if (!getContext().getExternDependencyFiles().isEmpty()) {
    // We don't add the global type to the dependency mapping file so we cannot use that
    // information to decide if there is already a global scope defined in the dependencies.
    // It's simply safe to assume that if there are dependencies, a global scope is already
    // defined. The goal of the current type is to collect global scope members defined by
    // dependencies and will never be emitted.
    // If the current sources define function/variable on the global scope, a specific
    // extension type will be created for the global scope.
    globalJavaType.setExtern(true);
    // Change the name in order to not conflict with the real type that can be created later.
    globalJavaType.setName("__Global_Dependencies");
  }

  getJavaTypeRegistry().registerJavaGlobalType(scope.getTypeOfThis(), globalJavaType);
  getContext().getJavaProgram().addType(globalJavaType);
  // push the current java type to be able to create an extension type later.
  super.pushCurrentJavaType(globalJavaType);

  return true;
}
 
Example #2
Source File: NodeModulePassTest.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
@Test
public void canReferenceConstructorExportedByAnotherModule() {
  CompilerUtil compiler = createCompiler(path("x/foo.js"), path("x/bar.js"));

  compiler.compile(
      createSourceFile(path("x/foo.js"), "/** @constructor */", "exports.Foo = function(){};"),
      createSourceFile(
          path("x/bar.js"),
          "var foo = require('./foo');",
          "/** @type {function(new: foo.Foo)} */",
          "exports.Foo = foo.Foo;"));

  TypedScope scope = compiler.getCompiler().getTopScope();
  TypedVar var = scope.getVar("module$exports$module$x$bar");

  JSType type = var.getInitialValue().getJSType().findPropertyType("Foo");
  assertTrue(type.isConstructor());

  type = type.toObjectType().getTypeOfThis();
  assertEquals("module$exports$module$x$foo.Foo", type.toString());
}
 
Example #3
Source File: NodeModulePassTest.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
@Test
public void canReferenceConstructorDefinedInTheGlobalScope() {
  CompilerUtil compiler = createCompiler(path("x/bar.js"));

  compiler.compile(
      createSourceFile(path("x/foo.js"), "/** @constructor */", "function Foo() {}"),
      createSourceFile(
          path("x/bar.js"), "/** @type {function(new: Foo)} */", "exports.Foo = Foo;"));

  TypedScope scope = compiler.getCompiler().getTopScope();
  TypedVar var = scope.getVar("module$exports$module$x$bar");

  JSType type = var.getInitialValue().getJSType().findPropertyType("Foo");
  assertTrue(type.isConstructor());

  type = type.toObjectType().getTypeOfThis();
  assertEquals("Foo", type.toString());
}
 
Example #4
Source File: MemberCollector.java    From jsinterop-generator with Apache License 2.0 5 votes vote down vote up
@Override
public void accept(TypedScope scope) {
  super.accept(scope);

  if (!parameterNameMapping.isEmpty()) {
    getContext().getProblems().warning("Unused parameter name mapping: %s", parameterNameMapping);
  }
}
 
Example #5
Source File: AbstractClosureVisitor.java    From jsinterop-generator with Apache License 2.0 5 votes vote down vote up
public void accept(TypedScope scope) {
  pushCurrentJavaType(scope.getTypeOfThis());
  if (visitTopScope(scope)) {
    for (TypedVar symbol : scope.getVarIterable()) {
      if (isDefinedInExternFiles(symbol) && isNotNamespaced(symbol)) {
        accept(symbol, true);
      }
    }
  }
  popCurrentJavaType();
}
 
Example #6
Source File: NodeModulePassTest.java    From js-dossier with Apache License 2.0 5 votes vote down vote up
@Test
public void savesOriginalTypeNameInJsDoc() {
  CompilerUtil compiler = createCompiler(path("foo.js"));

  compiler.compile(
      createSourceFile(
          path("foo.js"),
          "/** @constructor */",
          "var Builder = function(){};",
          "/** @return {!Builder} . */",
          "Builder.prototype.returnThis = function() { return this; };",
          "exports.Builder = Builder"));

  TypedScope scope = compiler.getCompiler().getTopScope();
  TypedVar var = scope.getVar("module$exports$module$foo");
  JSType type = var.getInitialValue().getJSType().findPropertyType("Builder");
  assertTrue(type.isConstructor());

  type = type.toObjectType().getTypeOfThis();
  assertEquals("module$exports$module$foo.Builder", type.toString());

  type = type.toObjectType().getPropertyType("returnThis");
  assertTrue(type.toString(), type.isFunctionType());

  JSDocInfo info = type.getJSDocInfo();
  assertNotNull(info);

  Node node = getOnlyElement(info.getTypeNodes());
  assertEquals(Token.BANG, node.getToken());

  node = node.getFirstChild();
  assertTrue(node.isString());
  assertEquals("module$exports$module$foo.Builder", node.getString());
  assertEquals("Builder", node.getProp(Node.ORIGINALNAME_PROP));
}
 
Example #7
Source File: NodeModulePassTest.java    From js-dossier with Apache License 2.0 5 votes vote down vote up
@Test
public void canUseModuleInternalTypedefsInJsDoc() {
  CompilerUtil compiler = createCompiler(path("foo.js"));

  compiler.compile(
      createSourceFile(
          path("foo.js"),
          "/** @typedef {{x: number}} */",
          "var Variable;",
          "",
          "/**",
          " * @param {Variable} a .",
          " * @param {Variable} b .",
          " * @return {Variable} .",
          " */",
          "exports.add = function(a, b) {",
          "  return {x: a.x + b.x};",
          "};"));

  TypedScope scope = compiler.getCompiler().getTopScope();
  TypedVar var = scope.getVar("module$exports$module$foo");
  JSType type = var.getInitialValue().getJSType().toObjectType().getPropertyType("add");
  assertTrue(type.isFunctionType());

  JSDocInfo info = type.getJSDocInfo();
  Node node = info.getTypeNodes().iterator().next();
  assertTrue(node.isString());
  assertEquals("module$contents$module$foo_Variable", node.getString());
  assertEquals("Variable", node.getProp(Node.ORIGINALNAME_PROP));
}
 
Example #8
Source File: ClosureJsInteropGenerator.java    From jsinterop-generator with Apache License 2.0 4 votes vote down vote up
private Program generateJavaProgram() {
  List<SourceFile> allSources =
      ImmutableList.<SourceFile>builder()
          .addAll(options.getDependencies())
          .addAll(options.getSources())
          .build();

  checkJavascriptCompilationResults(
      compiler.compile(new ArrayList<>(), allSources, createCompilerOptions()));

  GenerationContext ctx =
      GenerationContext.builder()
          .compiler(compiler)
          .sourceFiles(options.getSources())
          .externDependencyFiles(options.getDependencies())
          .javaProgram(new Program(readKeyValueFiles(options.getDependencyMappingFiles())))
          .typeRegistry(new ClosureTypeRegistry())
          .nameMapping(readKeyValueFiles(options.getNameMappingFiles()))
          .problems(problems)
          .build();

  TypedScope topScope = compiler.getTopScope();

  new TypeCollector(
          ctx,
          options.getPackagePrefix(),
          options.getExtensionTypePrefix(),
          options.getGlobalScopeClassName())
      .accept(topScope);

  new AnonymousTypeCollector(ctx).accept(topScope);

  new ThisTemplateTypeVisitor(ctx).accept(topScope);

  new MemberCollector(ctx).accept(topScope);

  new InheritanceVisitor(ctx).accept(topScope);

  new TypeParameterCollector(ctx).accept(topScope);

  return ctx.getJavaProgram();
}
 
Example #9
Source File: AbstractClosureVisitor.java    From jsinterop-generator with Apache License 2.0 4 votes vote down vote up
protected boolean visitTopScope(TypedScope scope) {
  return true;
}
 
Example #10
Source File: DeclarationGenerator.java    From clutz with MIT License 4 votes vote down vote up
/**
 * Reserved words are problematic because they cannot be used as var declarations, but are valid
 * properties. For example:
 *
 * <pre>
 * var switch = 0;  // parses badly in JS.
 * foo.switch = 0;  // ok.
 * </pre>
 *
 * This means that closure code is allowed to goog.provide('ng.components.switch'), which cannot
 * trivially translate in TS to:
 *
 * <pre>
 * namespace ng.components {
 *   var switch : ...;
 * }
 * </pre>
 *
 * Instead, go one step higher and generate:
 *
 * <pre>
 * namespace ng {
 *   var components : {switch: ..., };
 * }
 * </pre>
 *
 * This turns a namespace into a property of its parent namespace. Note: this violates the
 * invariant that generated namespaces are 1-1 with getNamespace of goog.provides.
 */
private void processReservedSymbols(TreeSet<String> provides, TypedScope topScope) {
  Set<String> collapsedNamespaces = new TreeSet<>();
  for (String reservedProvide : provides) {
    if (RESERVED_JS_WORDS.contains(getUnqualifiedName(reservedProvide))) {
      TypedVar var = topScope.getOwnSlot(reservedProvide);
      String namespace = getNamespace(reservedProvide);
      if (collapsedNamespaces.contains(namespace)) continue;
      collapsedNamespaces.add(namespace);
      Set<String> properties = getSubNamespace(provides, namespace);
      if (var != null) {
        emitGeneratedFromFileComment(var.getSourceFile());
      }
      emitNamespaceBegin(getNamespace(namespace));
      emit("let");
      emit(getUnqualifiedName(namespace));
      emit(": {");
      Iterator<String> bundledIt = properties.iterator();
      while (bundledIt.hasNext()) {
        emit(getUnqualifiedName(bundledIt.next()));
        emit(":");
        if (var != null) {
          TreeWalker walker = new TreeWalker(compiler.getTypeRegistry(), provides, false, false);
          walker.visitType(var.getType());
        } else {
          emit("any");
        }
        if (bundledIt.hasNext()) emit(",");
      }
      emit("};");
      emitBreak();
      emitNamespaceEnd();
      for (String property : properties) {
        // Assume that all symbols that are siblings of the reserved word are default exports.
        declareModule(property, true, property, true, var != null ? var.getSourceFile() : null);
      }
    }
  }
  // Remove the symbols that we have emitted above.
  Iterator<String> it = provides.iterator();
  while (it.hasNext()) {
    if (collapsedNamespaces.contains(getNamespace(it.next()))) it.remove();
  }
}
 
Example #11
Source File: BuildSymbolTablePassTest.java    From js-dossier with Apache License 2.0 4 votes vote down vote up
@Test
public void googScope() {
  Scenario scenario = new Scenario();
  SymbolTable table =
      scenario
          .addFile(
              stdInput,
              "goog.provide('foo.bar.baz');",
              "goog.scope(function() {",
              "const fbb = foo.bar.baz;",
              "fbb.quot = function() {};",
              "fbb.quot.quux = 123;",
              "fbb.A = class X {};",
              "foo.bar.baz.B = class Y {};",
              "});",
              "foo.bar.baz.end = 1;")
          .compile();

  assertThat(table)
      .containsExactly(
          "foo.bar.baz",
          "foo.bar.baz.quot",
          "foo.bar.baz.quot.quux",
          "foo.bar.baz.A",
          "foo.bar.baz.B",
          "foo.bar.baz.end");

  // Need to find the node for fbb.quot so we can find the symbol table for the block.
  TypedScope scope = scenario.getCompiler().getTopScope();
  TypedVar var = scope.getVar("foo.bar.baz.quot");
  SymbolTable varTable = table.findTableFor(var.getNode());

  assertThat(varTable).isNotSameAs(table);
  assertThat(varTable.getParentScope()).isSameAs(table);
  assertThat(varTable).containsExactly("fbb", "fbb.quot", "fbb.quot.quux", "fbb.A");
  assertThat(varTable).hasOwnSymbol("fbb").that().isAReferenceTo("foo.bar.baz");
  assertThat(varTable).hasOwnSymbol("fbb.quot").that().isAReferenceTo("foo.bar.baz.quot");
  assertThat(varTable)
      .hasOwnSymbol("fbb.quot.quux")
      .that()
      .isAReferenceTo("foo.bar.baz.quot.quux");
  assertThat(varTable).hasOwnSymbol("fbb.A").that().isAReferenceTo("foo.bar.baz.A");
}