Transpiler.java

  1. /*
  2.  * Copyright 2016 The Closure Compiler Authors.
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *     http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */

  16. package com.google.javascript.jscomp.transpile;

  17. import java.nio.file.Path;

  18. /**
  19.  * Common interface for a transpiler.
  20.  *
  21.  * <p>
  22.  * There are a number of considerations when implementing this interface.
  23.  * Specifically,
  24.  * <ol>
  25.  * <li>Which compiler and options to use, including language mode and any
  26.  * specific Compiler subclass. This is handled by {@code BaseTranspiler}
  27.  * accepting a {@code CompilerSupplier}.
  28.  * <li>Whether or not to generate external or embedded source maps. This
  29.  * is handled by returning a {@link TranspileResult}, which is able to
  30.  * return any combination of embedded or external source map.
  31.  * <li>Specification of a {@code sourceURL}, handling of {@code goog.module},
  32.  * or other postprocessing, such as wrapping the script in {@code eval}.
  33.  * This is left to other collaborators.
  34.  * <li>Caching. This is handled by a {@code CachingTranspiler} that
  35.  * decorates an existing {@code Transpiler} with caching behavior.
  36.  * </ol>
  37.  */
  38. public interface Transpiler {
  39.   /**
  40.    * Transforms the given chunk of code.  The input should be an entire file
  41.    * worth of code.
  42.    */
  43.   TranspileResult transpile(Path path, String code);

  44.   /**
  45.    * Returns any necessary runtime code as a string.  This should include
  46.    * everything that could possibly be required at runtime, regardless of
  47.    * whether it's actually used by any of the code that will be transpiled.
  48.    */
  49.   String runtime();

  50.   /**
  51.    * Null implementation that does no transpilation at all.
  52.    */
  53.   Transpiler NULL = new Transpiler() {
  54.     @Override
  55.     public TranspileResult transpile(Path path, String code) {
  56.       return new TranspileResult(path, code, code, "");
  57.     }

  58.     @Override
  59.     public String runtime() {
  60.       return "";
  61.     }
  62.   };
  63. }