Package com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger

Examples of com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger.Event


  /**
   * Runs the module's user startup code.
   */
  public final void onLoad(TreeLogger logger) throws UnableToCompleteException {
    Event moduleSpaceLoadEvent = SpeedTracerLogger.start(DevModeEventType.MODULE_SPACE_LOAD);

    // Tell the host we're ready for business.
    //
    host.onModuleReady(this);

    // Make sure we can resolve JSNI references to static Java names.
    //
    try {
      createStaticDispatcher(logger);
      Object staticDispatch = getStaticDispatcher();
      invokeNativeVoid("__defineStatic", null, new Class[] {Object.class},
          new Object[] {staticDispatch});
    } catch (Throwable e) {
      logger.log(TreeLogger.ERROR, "Unable to initialize static dispatcher", e);
      throw new UnableToCompleteException();
    }

    // Actually run user code.
    //
    String entryPointTypeName = null;
    try {
      // Set up GWT-entry code
      Class<?> implClass = loadClassFromSourceName("com.google.gwt.core.client.impl.Impl");
      Method registerEntry = implClass.getDeclaredMethod("registerEntry");
      registerEntry.setAccessible(true);
      registerEntry.invoke(null);

      Method enter = implClass.getDeclaredMethod("enter");
      enter.setAccessible(true);
      enter.invoke(null);

      String[] entryPoints = host.getEntryPointTypeNames();
      if (entryPoints.length > 0) {
        try {
          for (int i = 0; i < entryPoints.length; i++) {
            entryPointTypeName = entryPoints[i];
            Method onModuleLoad = null;
            Object module;

            // Try to initialize EntryPoint, else throw up glass panel
            try {
              Class<?> clazz = loadClassFromSourceName(entryPointTypeName);
              try {
                onModuleLoad = clazz.getMethod("onModuleLoad");
                if (!Modifier.isStatic(onModuleLoad.getModifiers())) {
                  // it's non-static, so we need to rebind the class
                  onModuleLoad = null;
                }
              } catch (NoSuchMethodException e) {
                // okay, try rebinding it; maybe the rebind result will have one
              }
              module = null;
              if (onModuleLoad == null) {
                module = rebindAndCreate(entryPointTypeName);
                onModuleLoad = module.getClass().getMethod("onModuleLoad");
                // Record the rebound name of the class for stats (below).
                entryPointTypeName = module.getClass().getName().replace(
                    '$', '.');
              }
            } catch (Throwable e) {
              displayErrorGlassPanel(
                  "EntryPoint initialization exception", entryPointTypeName, e);
              throw e;
            }

            // Try to invoke onModuleLoad, else throw up glass panel
            try {
              onModuleLoad.setAccessible(true);
              invokeNativeVoid("fireOnModuleLoadStart", null,
                  new Class[]{String.class}, new Object[]{entryPointTypeName});

              Event onModuleLoadEvent = SpeedTracerLogger.start(
                  DevModeEventType.ON_MODULE_LOAD);
              try {
                onModuleLoad.invoke(module);
              } finally {
                onModuleLoadEvent.end();
              }
            } catch (Throwable e) {
              displayErrorGlassPanel(
                  "onModuleLoad() threw an exception", entryPointTypeName, e);
              throw e;
View Full Code Here


    Throwable caught = null;
    String msg = null;
    String resultName = null;
    Class<?> resolvedClass = null;

    Event moduleSpaceRebindAndCreate =
        SpeedTracerLogger.start(DevModeEventType.MODULE_SPACE_REBIND_AND_CREATE);
    try {
      // Rebind operates on source-level names.
      //
      String sourceName = BinaryName.toSourceName(requestedClassName);
      resultName = rebind(sourceName);
      moduleSpaceRebindAndCreate.addData(
          "Requested Class", requestedClassName, "Result Name", resultName);
      resolvedClass = loadClassFromSourceName(resultName);
      if (Modifier.isAbstract(resolvedClass.getModifiers())) {
        msg = "Deferred binding result type '" + resultName
            + "' should not be abstract";
      } else {
        Constructor<?> ctor = resolvedClass.getDeclaredConstructor();
        ctor.setAccessible(true);
        return (T) ctor.newInstance();
      }
    } catch (ClassNotFoundException e) {
      msg = "Could not load deferred binding result type '" + resultName + "'";
      caught = e;
    } catch (InstantiationException e) {
      caught = e;
    } catch (IllegalAccessException e) {
      caught = e;
    } catch (ExceptionInInitializerError e) {
      caught = e.getException();
    } catch (NoSuchMethodException e) {
      // If it is a nested class and not declared as static,
      // then it's not accessible from outside.
      //
      if (resolvedClass.getEnclosingClass() != null
          && !Modifier.isStatic(resolvedClass.getModifiers())) {
        msg = "Rebind result '" + resultName
        + " is a non-static inner class";
      } else {
        msg = "Rebind result '" + resultName
        + "' has no default (zero argument) constructors.";
      }
      caught = e;
    } catch (InvocationTargetException e) {
      caught = e.getTargetException();
    } finally {
      moduleSpaceRebindAndCreate.end();
    }

    // Always log here because sometimes this method gets called from static
    // initializers and other unusual places, which can obscure the problem.
    //
View Full Code Here

  /**
   * Handles loading a class that might be nested given a source type name.
   */
  private Class<?> loadClassFromSourceName(String sourceName)
      throws ClassNotFoundException {
    Event moduleSpaceClassLoad = SpeedTracerLogger.start(
        DevModeEventType.MODULE_SPACE_CLASS_LOAD, "Source Name", sourceName);
    try {
      String toTry = sourceName;
      while (true) {
        try {
          return Class.forName(toTry, true, getIsolatedClassLoader());
        } catch (ClassNotFoundException e) {
          // Assume that the last '.' should be '$' and try again.
          //
          int i = toTry.lastIndexOf('.');
          if (i == -1) {
            throw e;
          }

          toTry = toTry.substring(0, i) + "$" + toTry.substring(i + 1);
        }
      }
    } finally {
      moduleSpaceClassLoad.end();
    }
  }
View Full Code Here

  /**
   * Preinitializes the classpath for a given {@link ResourceLoader}.
   */
  public static void preload(TreeLogger logger, ResourceLoader resources) {
    Event resourceOracle =
        SpeedTracerLogger.start(CompilerEventType.RESOURCE_ORACLE, "phase", "preload");
    List<ClassPathEntry> entries = getAllClassPathEntries(logger, resources);
    for (ClassPathEntry entry : entries) {
      // We only handle pre-indexing jars, the file system could change.
      if (entry instanceof ZipFileClassPathEntry) {
        ZipFileClassPathEntry zpe = (ZipFileClassPathEntry) entry;
        zpe.index(logger);
      }
    }
    resourceOracle.end();
  }
View Full Code Here

    int len = 1 + rest.length;
    ResourceOracleImpl[] oracles = new ResourceOracleImpl[1 + rest.length];
    oracles[0] = first;
    System.arraycopy(rest, 0, oracles, 1, rest.length);

    Event resourceOracle =
        SpeedTracerLogger.start(CompilerEventType.RESOURCE_ORACLE, "phase", "refresh");
    TreeLogger refreshBranch = Messages.REFRESHING_RESOURCES.branch(logger, null);

    /*
     * Allocate fresh data structures in anticipation of needing to honor the
     * "new identity for the collections if anything changes" guarantee. Use a
     * LinkedHashMap because we do not want the order to change.
     */
    List<Map<String, ResourceData>> resourceDataMaps = new ArrayList<Map<String, ResourceData>>();

    List<PathPrefixSet> pathPrefixSets = new ArrayList<PathPrefixSet>();
    for (ResourceOracleImpl oracle : oracles) {
      if (!oracle.classPath.equals(oracles[0].classPath)) {
        throw new IllegalArgumentException("Refreshing multiple oracles with different classpaths");
      }
      resourceDataMaps.add(new LinkedHashMap<String, ResourceData>());
      pathPrefixSets.add(oracle.pathPrefixSet);
    }

    /*
     * Walk across path roots (i.e. classpath entries) in priority order. This
     * is a "reverse painter's algorithm", relying on being careful never to add
     * a resource that has already been added to the new map under construction
     * to create the effect that resources founder earlier on the classpath take
     * precedence.
     *
     * Exceptions: super has priority over non-super; and if there are two super
     * resources with the same path, the one with the higher-priority path
     * prefix wins.
     */
    for (ClassPathEntry pathRoot : oracles[0].classPath) {
      TreeLogger branchForClassPathEntry =
          Messages.EXAMINING_PATH_ROOT.branch(refreshBranch, pathRoot.getLocation(), null);

      List<Map<AbstractResource, PathPrefix>> resourceToPrefixMaps =
          pathRoot.findApplicableResources(branchForClassPathEntry, pathPrefixSets);
      for (int i = 0; i < len; ++i) {
        Map<String, ResourceData> resourceDataMap = resourceDataMaps.get(i);
        Map<AbstractResource, PathPrefix> resourceToPrefixMap = resourceToPrefixMaps.get(i);
        for (Entry<AbstractResource, PathPrefix> entry : resourceToPrefixMap.entrySet()) {
          ResourceData newCpeData = new ResourceData(entry.getKey(), entry.getValue());
          String resourcePath = newCpeData.resource.getPath();
          ResourceData oldCpeData = resourceDataMap.get(resourcePath);
          // Old wins unless the new resource has higher priority.
          if (oldCpeData == null || oldCpeData.compareTo(newCpeData) < 0) {
            resourceDataMap.put(resourcePath, newCpeData);
          } else {
            Messages.IGNORING_SHADOWED_RESOURCE.log(branchForClassPathEntry, resourcePath, null);
          }
        }
      }
    }

    for (int i = 0; i < len; ++i) {
      Map<String, ResourceData> resourceDataMap = resourceDataMaps.get(i);
      Map<String, Resource> externalMap = new HashMap<String, Resource>();
      Set<Resource> externalSet = new HashSet<Resource>();
      for (Entry<String, ResourceData> entry : resourceDataMap.entrySet()) {
        String path = entry.getKey();
        ResourceData data = entry.getValue();
        externalMap.put(path, data.resource);
        externalSet.add(data.resource);
      }

      // Update exposed collections with new (unmodifiable) data structures.
      oracles[i].exposedResources = Collections.unmodifiableSet(externalSet);
      oracles[i].exposedResourceMap = Collections.unmodifiableMap(externalMap);
      oracles[i].exposedPathNames = Collections.unmodifiableSet(externalMap.keySet());
    }

    resourceOracle.end();
  }
View Full Code Here

   * @throws UnableToCompleteException
   */
  public static ModuleDef loadFromResources(TreeLogger logger, String moduleName,
      ResourceLoader resources, boolean refresh) throws UnableToCompleteException {

    Event moduleDefLoadFromClassPathEvent = SpeedTracerLogger.start(
        CompilerEventType.MODULE_DEF, "phase", "loadFromClassPath", "moduleName", moduleName);
    try {
      // Look up the module's physical name; if null, we are either encountering
      // the module for the first time, or else the name is already physical
      String physicalName = moduleEffectiveNameToPhysicalName.get(moduleName);
      if (physicalName != null) {
        moduleName = physicalName;
      }
      ModuleDef moduleDef = tryGetLoadedModule(moduleName, refresh);
      if (moduleDef != null) {
        return moduleDef;
      }
      ModuleDefLoader loader = new ModuleDefLoader(resources);
      return ModuleDefLoader.doLoadModule(loader, logger, moduleName, resources);
    } finally {
      moduleDefLoadFromClassPathEvent.end();
    }
  }
View Full Code Here

  private static ModuleDef doLoadModule(ModuleDefLoader loader, TreeLogger logger,
      String moduleName, ResourceLoader resources)
      throws UnableToCompleteException {

    ModuleDef moduleDef = new ModuleDef(moduleName, resources);
    Event moduleLoadEvent = SpeedTracerLogger.start(CompilerEventType.MODULE_DEF,
        "phase", "strategy.load()");
    loader.load(logger, moduleName, moduleDef);
    moduleLoadEvent.end();

    // Do any final setup.
    //
    Event moduleNormalizeEvent = SpeedTracerLogger.start(CompilerEventType.MODULE_DEF,
        "phase", "moduleDef.normalize()");
    moduleDef.normalize(logger);
    moduleNormalizeEvent.end();

    // Add the "physical" module name: com.google.Module
    getModulesCache().put(moduleName, moduleDef);

    // Add a mapping from the module's effective name to its physical name
View Full Code Here

    return buildFrom(logger, resources, delegate, false);
  }

  public static CompilationState buildFrom(TreeLogger logger, Set<Resource> resources,
      AdditionalTypeProviderDelegate delegate, boolean suppressErrors) {
    Event event = SpeedTracerLogger.start(DevModeEventType.CSB_BUILD_FROM_ORACLE);
    try {
      return instance.doBuildFrom(logger, resources, delegate, suppressErrors);
    } finally {
      event.end();
    }
  }
View Full Code Here

  private void injectJsniMethods(CompilationUnit unit) {
    if (unit == null || unit.getJsniMethods() == null) {
      return;
    }
    Event event = SpeedTracerLogger.start(DevModeEventType.LOAD_JSNI, "unit",
        unit.getTypeName());
    try {
      shellJavaScriptHost.createNativeMethods(logger, unit.getJsniMethods(),
          this);
    } finally {
      event.end();
    }
  }
View Full Code Here

  public static PermutationResult compilePermutation(TreeLogger logger, UnifiedAst unifiedAst,
      Permutation permutation) throws UnableToCompleteException {
    JJSOptions options = unifiedAst.getOptions();
    long startTimeMilliseconds = System.currentTimeMillis();

    Event jjsCompilePermutationEvent =
        SpeedTracerLogger.start(CompilerEventType.JJS_COMPILE_PERMUTATION, "name", permutation
            .prettyPrint());

    InternalCompilerException.preload();
    PropertyOracle[] propertyOracles = permutation.getPropertyOracles();
    int permutationId = permutation.getId();
    if (logger.isLoggable(TreeLogger.INFO)) {
      logger.log(TreeLogger.INFO, "Compiling permutation " + permutationId + "...");
    }
    long permStart = System.currentTimeMillis();
    try {
      if (JProgram.isTracingEnabled()) {
        System.out.println("------------------------------------------------------------");
        System.out.println("|                     (new permuation)                     |");
        System.out.println("------------------------------------------------------------");
        System.out.println("Properties: " + permutation.prettyPrint());
      }

      AST ast = unifiedAst.getFreshAst();
      JProgram jprogram = ast.getJProgram();
      JsProgram jsProgram = ast.getJsProgram();

      Map<StandardSymbolData, JsName> symbolTable =
          new TreeMap<StandardSymbolData, JsName>(new SymbolData.ClassIdentComparator());

      ResolveRebinds.exec(jprogram, permutation.getOrderedRebindAnswers());

      // (4) Optimize the normalized Java AST for each permutation.
      int optimizationLevel = options.getOptimizationLevel();
      if (optimizationLevel == OptionOptimize.OPTIMIZE_LEVEL_DRAFT) {
        draftOptimize(jprogram);
      } else {
        optimize(options, jprogram);
      }

      RemoveEmptySuperCalls.exec(jprogram);

      // (5) "Normalize" the high-level Java tree into a lower-level tree more
      // suited for JavaScript code generation. Don't go reordering these
      // willy-nilly because there are some subtle interdependencies.
      JsoDevirtualizer.exec(jprogram);
      CatchBlockNormalizer.exec(jprogram);
      PostOptimizationCompoundAssignmentNormalizer.exec(jprogram);
      LongCastNormalizer.exec(jprogram);
      LongEmulationNormalizer.exec(jprogram);
      CastNormalizer.exec(jprogram, options.isCastCheckingDisabled());
      ArrayNormalizer.exec(jprogram);
      EqualityNormalizer.exec(jprogram);

      // (6) Perform further post-normalization optimizations
      // Prune everything
      Pruner.exec(jprogram, false);
      // prune all Object.getClass() overrides and replace with inline field ref
      ReplaceGetClassOverrides.exec(jprogram);

      // (7) Generate a JavaScript code DOM from the Java type declarations
      jprogram.typeOracle.recomputeAfterOptimizations();
      JavaToJavaScriptMap jjsmap =
          GenerateJavaScriptAST.exec(jprogram, jsProgram, options.getOutput(), symbolTable,
              propertyOracles);

      // (8) Normalize the JS AST.
      // Fix invalid constructs created during JS AST gen.
      JsNormalizer.exec(jsProgram);
      // Resolve all unresolved JsNameRefs.
      JsSymbolResolver.exec(jsProgram);
      // Move all function definitions to a top-level scope, to reduce weirdness
      EvalFunctionsAtTopScope.exec(jsProgram, jjsmap);

      // (9) Optimize the JS AST.
      if (optimizationLevel > OptionOptimize.OPTIMIZE_LEVEL_DRAFT) {
        optimizeJs(options, jsProgram);

        /*
         * Coalesce redundant labels in switch statements.
         */
        JsDuplicateCaseFolder.exec(jsProgram);
      }

      /*
       * Creates new variables, must run before code splitter and namer.
       */
      JsStackEmulator.exec(jprogram, jsProgram, propertyOracles, jjsmap);

      /*
       * Work around Safari 5 bug by rewriting a >> b as ~~a >> b.
       *
       * No shifts may be generated after this point.
       */
      JsCoerceIntShift.exec(jsProgram, logger, propertyOracles);

      // (10) Split up the program into fragments
      SyntheticArtifact dependencies = null;
   
      if (options.isRunAsyncEnabled()) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int fragmentsMerge = options.getFragmentsMerge();
       
        // Pick and choose which code splitter to use. Only use the experimental
        // one when the user explicitly decides the project needs fragment
        // merging.
        if (fragmentsMerge > 0) {
          CodeSplitter2.exec(logger, jprogram, jsProgram, jjsmap, fragmentsMerge,
              chooseDependencyRecorder(options.isSoycEnabled(), baos));
        } else {
          CodeSplitter.exec(logger, jprogram, jsProgram, jjsmap, chooseDependencyRecorder(options
              .isSoycEnabled(), baos));
        }
        if (baos.size() == 0 && options.isSoycEnabled()) {
          recordNonSplitDependencies(jprogram, baos);
        }
        if (baos.size() > 0) {
          dependencies =
              new SyntheticArtifact(SoycReportLinker.class, "dependencies" + permutationId
                  + ".xml.gz", baos.toByteArray());
        }
      }

      // detect if browser is ie6 or not known
      boolean isIE6orUnknown = findBooleanProperty(propertyOracles, logger, "user.agent", "ie6",
          true, false, true);

      boolean isSourceMapsEnabled = findBooleanProperty(propertyOracles, logger,
          "compiler.useSourceMaps", "true", true, false, false);
      // (10.5) Obfuscate
      Map<JsName, String> obfuscateMap = Maps.create();
      switch (options.getOutput()) {
        case OBFUSCATED:
          obfuscateMap = JsStringInterner.exec(jprogram, jsProgram, isIE6orUnknown);
          JsObfuscateNamer.exec(jsProgram);
          if (options.isAggressivelyOptimize()) {
            if (JsStackEmulator.getStackMode(propertyOracles) == JsStackEmulator.StackMode.STRIP) {
              boolean changed = false;
              for (int i = 0; i < jsProgram.getFragmentCount(); i++) {
                JsBlock fragment = jsProgram.getFragmentBlock(i);
                changed = JsDuplicateFunctionRemover.exec(jsProgram, fragment) || changed;
              }
              if (changed) {
                JsUnusedFunctionRemover.exec(jsProgram);
              }
            }
          }
          break;
        case PRETTY:
          // We don't intern strings in pretty mode to imprmakeSouove readability
          JsPrettyNamer.exec(jsProgram);
          break;
        case DETAILED:
          obfuscateMap = JsStringInterner.exec(jprogram, jsProgram, isIE6orUnknown);
          JsVerboseNamer.exec(jsProgram);
          break;
        default:
          throw new InternalCompilerException("Unknown output mode");
      }

      // (10.8) Handle cross-island references.
      // No new JsNames or references to JSNames can be introduced after this
      // point.
      HandleCrossFragmentReferences.exec(logger, jsProgram, propertyOracles);

      // (11) Perform any post-obfuscation normalizations.

      // Work around an IE7 bug,
      // http://code.google.com/p/google-web-toolkit/issues/detail?id=1440
      // note, JsIEBlockTextTransformer now handles restructuring top level
      // blocks, this class now handles non-top level blocks only.
      boolean splitBlocks = isIE6orUnknown;

      if (splitBlocks) {
        JsIEBlockSizeVisitor.exec(jsProgram);
      }
      JsBreakUpLargeVarStatements.exec(jsProgram, propertyOracles);

      // (12) Generate the final output text.
      String[] js = new String[jsProgram.getFragmentCount()];
      StatementRanges[] ranges = new StatementRanges[js.length];
      SizeBreakdown[] sizeBreakdowns =
          options.isSoycEnabled() || options.isCompilerMetricsEnabled()
              ? new SizeBreakdown[js.length] : null;
      List<Map<Range, SourceInfo>> sourceInfoMaps = new ArrayList<Map<Range, SourceInfo>>();
      generateJavaScriptCode(options, jprogram, jsProgram, jjsmap, js, ranges,
          sizeBreakdowns, sourceInfoMaps, splitBlocks, isSourceMapsEnabled);

      PermutationResult toReturn =
          new PermutationResultImpl(js, permutation, makeSymbolMap(symbolTable, jsProgram), ranges);
      CompilationMetricsArtifact compilationMetrics = null;
      // TODO: enable this when ClosureCompiler is enabled
      if (!options.isClosureCompilerEnabled() && options.isCompilerMetricsEnabled()) {
        compilationMetrics = new CompilationMetricsArtifact(permutation.getId());
        compilationMetrics.setCompileElapsedMilliseconds(System.currentTimeMillis()
            - startTimeMilliseconds);
        compilationMetrics.setElapsedMilliseconds(System.currentTimeMillis()
            - ManagementFactory.getRuntimeMXBean().getStartTime());
        compilationMetrics.setJsSize(sizeBreakdowns);
        compilationMetrics.setPermutationDescription(permutation.prettyPrint());
        toReturn.addArtifacts(Lists.create(unifiedAst.getModuleMetrics(), unifiedAst
            .getPrecompilationMetrics(), compilationMetrics));
      }

      // TODO: enable this when ClosureCompiler is enabled
      if (!options.isClosureCompilerEnabled()) {
        toReturn.addArtifacts(makeSoycArtifacts(logger, permutationId, jprogram, js, sizeBreakdowns,
            options.isSoycExtra() ? sourceInfoMaps : null, dependencies, jjsmap, obfuscateMap,
            unifiedAst.getModuleMetrics(), unifiedAst.getPrecompilationMetrics(), compilationMetrics,
            options.isSoycHtmlDisabled()));
      }

      // TODO: enable this when ClosureCompiler is enabled
      if (!options.isClosureCompilerEnabled() && isSourceMapsEnabled) {
        logger.log(TreeLogger.INFO, "Source Maps Enabled");
        toReturn.addArtifacts(SourceMapRecorder.makeSourceMapArtifacts(sourceInfoMaps,
            permutationId));
      }

      logTrackingStats(logger);
      if (logger.isLoggable(TreeLogger.TRACE)) {
        logger.log(TreeLogger.TRACE, "Permutation took " + (System.currentTimeMillis() - permStart)
            + " ms");
      }
      return toReturn;
    } catch (Throwable e) {
      throw CompilationProblemReporter.logAndTranslateException(logger, e);
    } finally {
      jjsCompilePermutationEvent.end();
    }
  }
View Full Code Here

TOP

Related Classes of com.google.gwt.dev.util.log.speedtracer.SpeedTracerLogger.Event

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.