Esempio n. 1
0
  /**
   * General main for all the prototoype generators Arguments: 0: Filename with the training data
   * set to be condensed. 1: Filename wich will contain the test data set
   *
   * @param args Arguments of the main function.
   */
  public static void main(String[] args) {
    Parameters.setUse("AVG", "");
    Parameters.assertBasicArgs(args);

    PrototypeSet training = PrototypeGenerationAlgorithm.readPrototypeSet(args[0]);
    PrototypeSet test = PrototypeGenerationAlgorithm.readPrototypeSet(args[1]);

    AVG generator = new AVG(training);

    PrototypeSet resultingSet = generator.execute();
    int accuracy1NN = KNN.classficationAccuracy(resultingSet, test);
    generator.showResultsOfAccuracy(Parameters.getFileName(), accuracy1NN, test);
  }
Esempio n. 2
0
  /** Test default package versions. */
  public static void testDefaultPackageVersion() throws Exception {
    Builder a = new Builder();
    a.addClasspath(new File("bin"));
    a.setProperty("Bundle-Version", "1.2.3");
    a.setProperty("Export-Package", "test.refer");
    Jar jar = a.build();

    Manifest m = jar.getManifest();
    Parameters exports =
        Processor.parseHeader(m.getMainAttributes().getValue(Constants.EXPORT_PACKAGE), null);
    Map<String, String> attrs = exports.get("test.refer");
    assertNotNull(attrs);
    assertEquals("1.2.3", attrs.get("version"));
  }
Esempio n. 3
0
  protected MMObjectNode getGroupOrUserNode(Parameters a) {
    MMObjectNode groupOrUser = getNode(a.getString(PARAMETER_GROUPORUSER));
    if (groupOrUser == null)
      throw new IllegalArgumentException(
          "There is no node with id '" + a.get(PARAMETER_GROUPORUSER) + "'");

    MMObjectBuilder parent = groupOrUser.getBuilder();
    MMObjectBuilder userBuilder = Authenticate.getInstance().getUserProvider().getUserBuilder();
    if (!(parent instanceof Groups || userBuilder.getClass().isInstance(parent))) {
      throw new IllegalArgumentException(
          "Node '" + a.get(PARAMETER_GROUPORUSER) + "' does not represent a group or a user");
    }
    return groupOrUser;
  }
Esempio n. 4
0
  public LambdaInfo getLambdaIfExists(AbstractInsnNode insnNode) {
    if (insnNode.getOpcode() == Opcodes.ALOAD) {
      int varIndex = ((VarInsnNode) insnNode).var;
      if (varIndex < parameters.totalSize()) {
        return parameters.get(varIndex).getLambda();
      }
    } else if (insnNode instanceof FieldInsnNode) {
      FieldInsnNode fieldInsnNode = (FieldInsnNode) insnNode;
      if (fieldInsnNode.name.startsWith("$$$")) {
        return findCapturedField(fieldInsnNode, nodeRemapper).getLambda();
      }
    }

    return null;
  }
  private Object[] paramsFromSource() {
    if (sourceClassUndefined()) return new Object[] {};

    Class<?> sourceClass = parametersAnnotation.source();

    return fillResultWithAllParamProviderMethods(sourceClass);
  }
Esempio n. 6
0
 /** Prints the classifier. */
 public void print() {
   System.out.print("  Act: " + action + "   Conf:  ");
   for (int i = 0; i < rep.length; i++) {
     rep[i].print();
   }
   if (parameters != null) parameters.print();
 } // end print
Esempio n. 7
0
 @Override
 public void render(Parameters blockParameters, Writer w, RenderHints hints)
     throws FrameworkException {
   log.debug("Error rendering " + blockParameters);
   switch (getType()) {
     case BODY:
       try {
         decorateIntro(hints, w, "error");
         w.write("<h1>" + error.status);
         w.write(": ");
         CharTransformer escape = new Xml(Xml.ESCAPE);
         w.write(escape.transform(error.exception.getMessage()));
         w.write(" ");
         w.write(escape.transform(url));
         w.write("</h1>");
         w.write("<pre>");
         HttpServletRequest request = blockParameters.get(Parameter.REQUEST);
         error.getErrorReport(w, request, escape);
         w.write("</pre>");
         decorateOutro(hints, w);
       } catch (IOException eio) {
         throw new FrameworkException(eio.getMessage(), eio);
       }
       break;
     default:
   }
 }
Esempio n. 8
0
  /**
   * Tests if the implementation of the EventHandler (which is marked as a ConsumerType) causes the
   * import of the api package to use the consumer version policy.
   */
  public static void testConsumerType() throws Exception {
    Builder a = new Builder();
    a.addClasspath(new File("bin"));
    a.setPrivatePackage("test.versionpolicy.uses");
    a.setExportPackage("test.versionpolicy.api");
    a.setProperty("build", "123");
    Jar jar = a.build();
    assertTrue(a.check());
    Manifest m = jar.getManifest();
    m.write(System.err);
    Domain d = Domain.domain(m);

    Parameters parameters = d.getImportPackage();
    Attrs attrs = parameters.get("test.versionpolicy.api");
    assertNotNull(attrs);
    assertEquals("[1.2,2)", attrs.get("version"));
  }
Esempio n. 9
0
 /**
  * Prints the classifier to the specified file.
  *
  * @param fout is the file output where the classifier has to be printed.
  */
 public void print(PrintWriter fout) {
   fout.print(" ");
   for (int i = 0; i < rep.length; i++) {
     rep[i].print(fout);
   }
   fout.print("  " + action + "  ");
   if (parameters != null) parameters.print(fout);
 }
Esempio n. 10
0
  /**
   * Test if the implementation of "AnnotatedProviderInterface", which is annotated with OSGi
   * R6 @ProviderType, causes import of the api package to use the provider version policy
   */
  public static void testProviderTypeR6() throws Exception {
    Builder b = new Builder();
    b.addClasspath(new File("bin"));
    b.setPrivatePackage("test.versionpolicy.implemented.osgi");
    b.setProperty("build", "123");

    Jar jar = b.build();
    assertTrue(b.check());
    Manifest m = jar.getManifest();
    m.write(System.err);

    Domain d = Domain.domain(m);
    Parameters params = d.getImportPackage();
    Attrs attrs = params.get("test.version.annotations.osgi");
    assertNotNull(attrs);
    assertEquals("[1.2,1.3)", attrs.get("version"));
  }
Esempio n. 11
0
 @SuppressWarnings("unchecked")
 protected void setBlockParametersForRender(State state, Parameters blockParameters) {
   ServletRequest request = state.getRequest();
   String prefix = getPrefix(state);
   log.debug("prefix " + prefix);
   blockParameters.setAutoCasting(true);
   for (Map.Entry<String, String[]> entry :
       ((Map<String, String[]>) request.getParameterMap()).entrySet()) {
     String key = entry.getKey();
     if (key.startsWith(prefix)) {
       log.trace("setting" + entry);
       blockParameters.setIfDefined(key.substring(prefix.length()), entry.getValue());
     }
   }
   if (log.isDebugEnabled()) {
     log.debug("Set " + blockParameters);
   }
 }
Esempio n. 12
0
 @Override
 public Block getRenderingBlock(Parameters frameworkParameters) {
   HttpServletRequest request = frameworkParameters.get(Parameter.REQUEST);
   State state = State.getState(request);
   if (state.isRendering()) {
     return state.getBlock();
   } else {
     return null;
   }
 }
Esempio n. 13
0
 /**
  * I think in the basic framework this method is never called explicitely, because processing is
  * done implicitly by the render
  */
 @Override
 public void process(
     Processor processor, Parameters blockParameters, Parameters frameworkParameters)
     throws FrameworkException {
   HttpServletRequest request = frameworkParameters.get(Parameter.REQUEST);
   State state = State.getState(request);
   state.startBlock(frameworkParameters, null);
   setBlockParametersForProcess(state, blockParameters);
   processor.process(blockParameters);
 }
Esempio n. 14
0
 @Override
 public String getProcessUrl(
     String path, Map<String, ?> parameters, Parameters frameworkParameters, boolean escapeAmps)
     throws FrameworkException {
   HttpServletRequest request =
       BasicUrlConverter.getUserRequest(frameworkParameters.get(Parameter.REQUEST));
   State state = State.getState(request);
   frameworkParameters.set(ACTION, state.getId());
   Url url = urlConverter.getProcessUrl(path, parameters, frameworkParameters, escapeAmps);
   if (url == Url.NOT) {
     log.debug("Fall back url");
     return fallbackConverter
         .getProcessUrl(path, parameters, frameworkParameters, escapeAmps)
         .getUrl();
   } else {
     log.debug("Url converter url " + url);
     return url.getUrl();
   }
 }
  @Override
  public void prepare(Map map, TopologyContext topologyContext, OutputCollector outputCollector) {
    int minNumberOfMatches = Math.min(getInt(map, "minNumberOfMatches"), 4);
    this.collector = outputCollector;
    // TODO: get path to logos & parameters from config
    Parameters parameters =
        new Parameters()
            .withMatchingParameters(
                new Parameters.MatchingParameters().withMinimalNumberOfMatches(minNumberOfMatches));

    sift =
        new opencv_nonfree.SIFT(
            0,
            3,
            parameters.getSiftParameters().getContrastThreshold(),
            parameters.getSiftParameters().getEdgeThreshold(),
            parameters.getSiftParameters().getSigma());

    List<String> templateFiles = getListOfStrings(map, "originalTemplateFileNames");
    int maxAdditionTemp = ConfigUtil.getInt(map, "maxAdditionTemp", 4);
    detectors = new ArrayList<>();
    for (int logoIndex = 0; logoIndex < templateFiles.size(); logoIndex++) {
      detectors.add(
          new StormVideoLogoDetectorGamma(
              parameters, templateFiles.get(logoIndex), logoIndex, maxAdditionTemp));
    }
    // detector = new StormVideoLogoDetector(parameters, templateFiles);
    // receivedUpdatesFrom = new HashSet<>();
    // Modified by Tom on Sep 8, 2014
    receivedUpdatesFrom =
        new LinkedHashMap<Serializable.PatchIdentifier, Boolean>() {
          @Override
          protected boolean removeEldestEntry(
              Map.Entry<Serializable.PatchIdentifier, Boolean> eldest) {
            return size() > MaxSizeOfReceivedUpdatesFrom;
          }
        };

    frameMap = new HashMap<>();
    patchQueue = new HashMap<>();
    templateQueue = new HashMap<>();
  }
Esempio n. 16
0
  /**
   * Returns if the classifier of the class subsumes the classifier passed as a parameter.
   *
   * @param cl is the subsumed classifier.
   * @return a boolean indicating if it subsumes
   */
  public boolean doesSubsume(Classifier cl) {

    if (rep.getAction() != cl.rep.getAction()) return false;

    if (parameters.couldSubsume()) {
      if (rep.isMoreGeneral(cl.rep)) {
        return true;
      }
    }
    return false;
  } // end doesSubsume
Esempio n. 17
0
  /**
   * Tests if the implementation of the EventAdmin (which is marked as a ProviderType) causes the
   * import of the api package to use the provider version policy.
   */
  public static void testProviderType() throws Exception {
    Builder a = new Builder();
    a.addClasspath(new File("bin"));
    a.setPrivatePackage("test.versionpolicy.implemented");
    a.setExportPackage("test.versionpolicy.api");
    a.setImportPackage("test.versionpolicy.api"); // what changed so this is
    // not automatically
    // added?
    a.setProperty("build", "123");
    Jar jar = a.build();
    assertTrue(a.check());
    Manifest m = jar.getManifest();
    m.write(System.err);
    Domain d = Domain.domain(m);

    Parameters parameters = d.getImportPackage();
    Attrs attrs = parameters.get("test.versionpolicy.api");
    assertNotNull(attrs);
    assertEquals("[1.2,1.3)", attrs.get("version"));
  }
Esempio n. 18
0
 @SuppressWarnings("unchecked")
 @Override
 public <C> C setSettingValue(Setting<C> setting, Parameters parameters, C value) {
   if (parameters == null)
     throw new SecurityException("You should provide Cloud and request parameters");
   boolean useSession = parameters.get(USE_REQ);
   if (useSession) {
     C ret = getSettingValue(setting, parameters);
     HttpServletRequest req = parameters.get(Parameter.REQUEST);
     req.getSession(true).setAttribute(getKey(setting), value);
     return ret;
   } else {
     Cloud cloud = parameters.get(Parameter.CLOUD);
     if (cloud.getUser().getRank() == org.mmbase.security.Rank.ADMIN) {
       saveSettingValue(setting, value);
       return (C) settingValues.put(setting, value);
     } else {
       throw new SecurityException("Permission denied");
     }
   }
 }
Esempio n. 19
0
  /** Check implementation version policy. Uses the package test.versionpolicy.(uses|implemented) */
  static void assertPolicy(String pack, String type) throws Exception {
    Builder a = new Builder();
    a.addClasspath(new File("bin"));
    a.setProperty("Export-Package", "test.versionpolicy.api");
    Jar jar = a.build();

    Builder b = new Builder();
    b.addClasspath(jar);
    b.addClasspath(new File("bin"));

    b.setProperty("-versionpolicy-impl", "IMPL");
    b.setProperty("-versionpolicy-uses", "USES");
    b.setProperty("Private-Package", pack);
    b.build();
    Manifest m = b.getJar().getManifest();
    m.write(System.err);
    Map<String, String> map = b.getImports().getByFQN("test.versionpolicy.api");
    assertNotNull(map);
    // String s = map.get(Constants.IMPLEMENTED_DIRECTIVE);
    // assertEquals("true", s);
    Parameters mp = Processor.parseHeader(m.getMainAttributes().getValue("Import-Package"), null);
    assertEquals(type, mp.get("test.versionpolicy.api").get("version"));
  }
Esempio n. 20
0
  /**
   * Returns if the classifier of the class subsumes the classifier passed as a parameter.
   *
   * @param cl is the subsumed classifier.
   * @return a boolean indicating if it subsumes
   */
  public boolean doesSubsume(Classifier cl) {
    int i;

    // First, check if the condition is the same
    if (action != cl.getAction()) return false;

    // Then, check that is more general
    if (parameters.couldSubsume()) {
      for (i = 0; i < rep.length; i++) {
        if (!rep[i].isMoreGeneral(cl.rep[i])) return false;
      }
      return true;
    }
    return false;
  } // end doesSubsume
Esempio n. 21
0
 @SuppressWarnings("unchecked")
 @Override
 public <C> C getSettingValue(Setting<C> setting, Parameters parameters) {
   boolean useSession = parameters != null && parameters.get(USE_REQ);
   if (useSession) {
     HttpServletRequest req = parameters.get(Parameter.REQUEST);
     if (req != null) {
       Object v = req.getSession(true).getAttribute(getKey(setting));
       if (v != null) {
         return setting.getDataType().cast(v, null, null);
       }
     }
   }
   if (settingValues.containsKey(setting)) {
     return (C) settingValues.get(setting);
   } else {
     C settingValue = loadSettingValue(setting);
     if (settingValue != null) {
       settingValues.put(setting, settingValue);
       return settingValue;
     }
     return setting.getDataType().getDefaultValue();
   }
 }
Esempio n. 22
0
 @Override
 public Node getUserNode(Parameters frameworkParameters) {
   Cloud cloud = frameworkParameters.get(Parameter.CLOUD);
   if (cloud == null) {
     return null;
   } else {
     try {
       int userNode = cloud.getCloudContext().getAuthentication().getNode(cloud.getUser());
       if (cloud.hasNode(userNode)) {
         return cloud.getNode(userNode);
       } else {
         return null;
       }
     } catch (UnsupportedOperationException uoe) {
       // never mind
       return null;
     }
   }
 }
Esempio n. 23
0
  /**
   * Prints the desnormalized classifier to the specified file.
   *
   * @param fout is the file output where the classifier has to be printed.
   */
  public void printNotNorm(PrintWriter fout) {
    int i = 0;
    fout.print(" ");
    try {
      for (i = 0; i < rep.length; i++) {
        if (Config.typeOfAttributes[i].equals("ternary")) {
          rep[i].print(fout);
        } else if (Config.typeOfAttributes[i].equals("integer")) {
          rep[i].printNotNorm(fout, Config.attBounds[i][0]);
        } else if (Config.typeOfAttributes[i].equals("real")) {
          rep[i].printNotNorm(fout, Config.attBounds[i][0], Config.attBounds[i][1]);
        }
      }
    } catch (Exception e) {
      System.out.println("Exception when printing the attribute: " + i);
      e.printStackTrace();
    }
    fout.print("\t " + (String) Config.classConv.elementAt(action));

    if (parameters != null) parameters.print(fout);
  }
 private boolean sourceClassUndefined() {
   return parametersAnnotation.source().isAssignableFrom(NullType.class);
 }
 private Object[] paramsFromValue() {
   Object[] params = parametersAnnotation.value();
   return params;
 }
  private Object[] paramsFromMethod() {
    String methodName = parametersAnnotation.method();
    if ("".equals(methodName)) methodName = defaultMethodName();

    return invokeMethodWithParams(methodName);
  }
Esempio n. 27
0
  @NotNull
  public MethodNode prepareNode(@NotNull MethodNode node) {
    final int capturedParamsSize = parameters.getCaptured().size();
    final int realParametersSize = parameters.getReal().size();
    Type[] types = Type.getArgumentTypes(node.desc);
    Type returnType = Type.getReturnType(node.desc);

    ArrayList<Type> capturedTypes = parameters.getCapturedTypes();
    Type[] allTypes =
        ArrayUtil.mergeArrays(types, capturedTypes.toArray(new Type[capturedTypes.size()]));

    node.instructions.resetLabels();
    MethodNode transformedNode =
        new MethodNode(
            InlineCodegenUtil.API,
            node.access,
            node.name,
            Type.getMethodDescriptor(returnType, allTypes),
            node.signature,
            null) {

          private final boolean isInliningLambda = nodeRemapper.isInsideInliningLambda();

          private int getNewIndex(int var) {
            return var + (var < realParametersSize ? 0 : capturedParamsSize);
          }

          @Override
          public void visitVarInsn(int opcode, int var) {
            super.visitVarInsn(opcode, getNewIndex(var));
          }

          @Override
          public void visitIincInsn(int var, int increment) {
            super.visitIincInsn(getNewIndex(var), increment);
          }

          @Override
          public void visitMaxs(int maxStack, int maxLocals) {
            super.visitMaxs(maxStack, maxLocals + capturedParamsSize);
          }

          @Override
          public void visitLineNumber(int line, @NotNull Label start) {
            if (isInliningLambda) {
              super.visitLineNumber(line, start);
            }
          }

          @Override
          public void visitLocalVariable(
              @NotNull String name,
              @NotNull String desc,
              String signature,
              @NotNull Label start,
              @NotNull Label end,
              int index) {
            if (isInliningLambda) {
              super.visitLocalVariable(name, desc, signature, start, end, getNewIndex(index));
            }
          }
        };

    node.accept(transformedNode);

    transformCaptured(transformedNode);

    return transformedNode;
  }
Esempio n. 28
0
  private MethodNode doInline(MethodNode node) {

    final Deque<InvokeCall> currentInvokes = new LinkedList<InvokeCall>(invokeCalls);

    final MethodNode resultNode =
        new MethodNode(node.access, node.name, node.desc, node.signature, null);

    final Iterator<AnonymousObjectGeneration> iterator = anonymousObjectGenerations.iterator();

    RemappingMethodAdapter remappingMethodAdapter =
        new RemappingMethodAdapter(
            resultNode.access, resultNode.desc, resultNode, new TypeRemapper(currentTypeMapping));

    InlineAdapter lambdaInliner =
        new InlineAdapter(remappingMethodAdapter, parameters.totalSize()) {

          private AnonymousObjectGeneration anonymousObjectGen;

          private void handleAnonymousObjectGeneration() {
            anonymousObjectGen = iterator.next();

            if (anonymousObjectGen.shouldRegenerate()) {
              // TODO: need poping of type but what to do with local funs???
              Type newLambdaType =
                  Type.getObjectType(inliningContext.nameGenerator.genLambdaClassName());
              currentTypeMapping.put(
                  anonymousObjectGen.getOwnerInternalName(), newLambdaType.getInternalName());
              AnonymousObjectTransformer transformer =
                  new AnonymousObjectTransformer(
                      anonymousObjectGen.getOwnerInternalName(),
                      inliningContext.subInlineWithClassRegeneration(
                          inliningContext.nameGenerator, currentTypeMapping, anonymousObjectGen),
                      isSameModule,
                      newLambdaType);

              InlineResult transformResult =
                  transformer.doTransform(anonymousObjectGen, nodeRemapper);
              result.addAllClassesToRemove(transformResult);

              if (inliningContext.isInliningLambda && !anonymousObjectGen.isStaticOrigin()) {
                // this class is transformed and original not used so we should remove original one
                // after inlining
                // Note: It is unsafe to remove anonymous class that is referenced by GETSTATIC
                // within lambda
                // because it can be local function from outer scope
                result.addClassToRemove(anonymousObjectGen.getOwnerInternalName());
              }

              if (transformResult.getReifiedTypeParametersUsages().wereUsedReifiedParameters()) {
                ReifiedTypeInliner.putNeedClassReificationMarker(mv);
                result
                    .getReifiedTypeParametersUsages()
                    .mergeAll(transformResult.getReifiedTypeParametersUsages());
              }
            }
          }

          @Override
          public void anew(@NotNull Type type) {
            if (isAnonymousConstructorCall(type.getInternalName(), "<init>")) {
              handleAnonymousObjectGeneration();
            }

            // in case of regenerated anonymousObjectGen type would be remapped to new one via
            // remappingMethodAdapter
            super.anew(type);
          }

          @Override
          public void visitMethodInsn(
              int opcode, String owner, String name, String desc, boolean itf) {
            if (
            /*INLINE_RUNTIME.equals(owner) &&*/ isInvokeOnLambda(owner, name)) { // TODO add method
              assert !currentInvokes.isEmpty();
              InvokeCall invokeCall = currentInvokes.remove();
              LambdaInfo info = invokeCall.lambdaInfo;

              if (info == null) {
                // noninlinable lambda
                super.visitMethodInsn(opcode, owner, name, desc, itf);
                return;
              }

              int valueParamShift = getNextLocalIndex(); // NB: don't inline cause it changes
              putStackValuesIntoLocals(
                  info.getInvokeParamsWithoutCaptured(), valueParamShift, this, desc);

              addInlineMarker(this, true);
              Parameters lambdaParameters = info.addAllParameters(nodeRemapper);

              InlinedLambdaRemapper newCapturedRemapper =
                  new InlinedLambdaRemapper(
                      info.getLambdaClassType().getInternalName(), nodeRemapper, lambdaParameters);

              setLambdaInlining(true);
              MethodInliner inliner =
                  new MethodInliner(
                      info.getNode(),
                      lambdaParameters,
                      inliningContext.subInlineLambda(info),
                      newCapturedRemapper,
                      true /*cause all calls in same module as lambda*/,
                      "Lambda inlining " + info.getLambdaClassType().getInternalName());

              LocalVarRemapper remapper = new LocalVarRemapper(lambdaParameters, valueParamShift);
              InlineResult lambdaResult =
                  inliner.doInline(
                      this.mv, remapper, true, info); // TODO add skipped this and receiver
              result.addAllClassesToRemove(lambdaResult);

              // return value boxing/unboxing
              Method bridge =
                  typeMapper
                      .mapSignature(
                          ClosureCodegen.getErasedInvokeFunction(info.getFunctionDescriptor()))
                      .getAsmMethod();
              Method delegate =
                  typeMapper.mapSignature(info.getFunctionDescriptor()).getAsmMethod();
              StackValue.onStack(delegate.getReturnType()).put(bridge.getReturnType(), this);
              setLambdaInlining(false);
              addInlineMarker(this, false);
            } else if (isAnonymousConstructorCall(owner, name)) { // TODO add method
              assert anonymousObjectGen != null
                  : "<init> call not corresponds to new call" + owner + " " + name;
              if (anonymousObjectGen.shouldRegenerate()) {
                // put additional captured parameters on stack
                for (CapturedParamDesc capturedParamDesc :
                    anonymousObjectGen.getAllRecapturedParameters()) {
                  visitFieldInsn(
                      Opcodes.GETSTATIC,
                      capturedParamDesc.getContainingLambdaName(),
                      "$$$" + capturedParamDesc.getFieldName(),
                      capturedParamDesc.getType().getDescriptor());
                }
                super.visitMethodInsn(
                    opcode,
                    anonymousObjectGen.getNewLambdaType().getInternalName(),
                    name,
                    anonymousObjectGen.getNewConstructorDescriptor(),
                    itf);
                anonymousObjectGen = null;
              } else {
                super.visitMethodInsn(
                    opcode, changeOwnerForExternalPackage(owner, opcode), name, desc, itf);
              }
            } else if (ReifiedTypeInliner.isNeedClassReificationMarker(
                new MethodInsnNode(opcode, owner, name, desc, false))) {
              // we will put it if needed in anew processing
            } else {
              super.visitMethodInsn(
                  opcode, changeOwnerForExternalPackage(owner, opcode), name, desc, itf);
            }
          }

          @Override
          public void visitFieldInsn(
              int opcode, @NotNull String owner, @NotNull String name, @NotNull String desc) {
            if (opcode == Opcodes.GETSTATIC && isAnonymousSingletonLoad(owner, name)) {
              handleAnonymousObjectGeneration();
            }
            super.visitFieldInsn(opcode, owner, name, desc);
          }

          @Override
          public void visitMaxs(int stack, int locals) {
            lambdasFinallyBlocks = resultNode.tryCatchBlocks.size();
            super.visitMaxs(stack, locals);
          }
        };

    node.accept(lambdaInliner);

    return resultNode;
  }
Esempio n. 29
0
  private InlineResult inlineCall(SMAPAndMethodNode nodeAndSmap) {
    MethodNode node = nodeAndSmap.getNode();
    ReifiedTypeParametersUsages reificationResult =
        reifiedTypeInliner.reifyInstructions(node.instructions);
    generateClosuresBodies();

    // through generation captured parameters will be added to invocationParamBuilder
    putClosureParametersOnStack();

    addInlineMarker(codegen.v, true);

    Parameters parameters = invocationParamBuilder.buildParameters();

    InliningContext info =
        new RootInliningContext(
            expressionMap,
            state,
            codegen.getInlineNameGenerator().subGenerator(functionDescriptor.getName().asString()),
            codegen.getContext(),
            callElement,
            codegen.getParentCodegen().getClassName(),
            reifiedTypeInliner);

    MethodInliner inliner =
        new MethodInliner(
            node,
            parameters,
            info,
            new FieldRemapper(null, null, parameters),
            isSameModule,
            "Method inlining " + callElement.getText(),
            createNestedSourceMapper(nodeAndSmap)); // with captured

    LocalVarRemapper remapper = new LocalVarRemapper(parameters, initialFrameSize);

    MethodNode adapter = InlineCodegenUtil.createEmptyMethodNode();
    // hack to keep linenumber info, otherwise jdi will skip begin of linenumber chain
    adapter.visitInsn(Opcodes.NOP);

    InlineResult result = inliner.doInline(adapter, remapper, true, LabelOwner.SKIP_ALL);
    result.getReifiedTypeParametersUsages().mergeAll(reificationResult);

    CallableMemberDescriptor descriptor = codegen.getContext().getContextDescriptor();
    final Set<String> labels =
        getDeclarationLabels(
            DescriptorToSourceUtils.descriptorToDeclaration(descriptor), descriptor);
    LabelOwner labelOwner =
        new LabelOwner() {
          @Override
          public boolean isMyLabel(@NotNull String name) {
            return labels.contains(name);
          }
        };

    List<MethodInliner.PointForExternalFinallyBlocks> infos =
        MethodInliner.processReturns(adapter, labelOwner, true, null);
    generateAndInsertFinallyBlocks(
        adapter,
        infos,
        ((StackValue.Local) remapper.remap(parameters.totalSize() + 1).value).index);
    removeFinallyMarkers(adapter);

    adapter.accept(new InliningInstructionAdapter(codegen.v));

    addInlineMarker(codegen.v, false);

    return result;
  }
  private void generateConstructorAndFields(
      @NotNull ClassBuilder classBuilder,
      @NotNull ParametersBuilder allCapturedBuilder,
      @NotNull ParametersBuilder constructorInlineBuilder,
      @NotNull AnonymousObjectGeneration anonymousObjectGen,
      @NotNull FieldRemapper parentRemapper,
      @NotNull List<CapturedParamInfo> constructorAdditionalFakeParams) {
    List<Type> descTypes = new ArrayList<Type>();

    Parameters constructorParams = constructorInlineBuilder.buildParameters();
    int[] capturedIndexes =
        new int[constructorParams.getReal().size() + constructorParams.getCaptured().size()];
    int index = 0;
    int size = 0;

    // complex processing cause it could have super constructor call params
    for (ParameterInfo info : constructorParams) {
      if (!info.isSkipped()) { // not inlined
        if (info.isCaptured() || info instanceof CapturedParamInfo) {
          capturedIndexes[index] = size;
          index++;
        }

        if (size != 0) { // skip this
          descTypes.add(info.getType());
        }
        size += info.getType().getSize();
      }
    }

    String constructorDescriptor =
        Type.getMethodDescriptor(Type.VOID_TYPE, descTypes.toArray(new Type[descTypes.size()]));
    // TODO for inline method make public class
    anonymousObjectGen.setNewConstructorDescriptor(constructorDescriptor);
    MethodVisitor constructorVisitor =
        classBuilder.newMethod(
            NO_ORIGIN,
            AsmUtil.NO_FLAG_PACKAGE_PRIVATE,
            "<init>",
            constructorDescriptor,
            null,
            ArrayUtil.EMPTY_STRING_ARRAY);

    // initialize captured fields
    List<NewJavaField> newFieldsWithSkipped =
        TransformationUtilsKt.getNewFieldsToGenerate(allCapturedBuilder.listCaptured());
    List<FieldInfo> fieldInfoWithSkipped =
        TransformationUtilsKt.transformToFieldInfo(newLambdaType, newFieldsWithSkipped);

    int paramIndex = 0;
    InstructionAdapter capturedFieldInitializer = new InstructionAdapter(constructorVisitor);
    for (int i = 0; i < fieldInfoWithSkipped.size(); i++) {
      FieldInfo fieldInfo = fieldInfoWithSkipped.get(i);
      if (!newFieldsWithSkipped.get(i).getSkip()) {
        AsmUtil.genAssignInstanceFieldFromParam(
            fieldInfo, capturedIndexes[paramIndex], capturedFieldInitializer);
      }
      paramIndex++;
    }

    // then transform constructor
    // HACK: in inlinining into constructor we access original captured fields with field access not
    // local var
    // but this fields added to general params (this assumes local var access) not captured one,
    // so we need to add them to captured params
    for (CapturedParamInfo info : constructorAdditionalFakeParams) {
      CapturedParamInfo fake = constructorInlineBuilder.addCapturedParamCopy(info);

      if (fake.getLambda() != null) {
        // set remap value to skip this fake (captured with lambda already skipped)
        StackValue composed =
            StackValue.field(
                fake.getType(), oldObjectType, fake.getNewFieldName(), false, StackValue.LOCAL_0);
        fake.setRemapValue(composed);
      }
    }

    inlineMethodAndUpdateGlobalResult(
        anonymousObjectGen,
        parentRemapper,
        capturedFieldInitializer,
        constructor,
        constructorInlineBuilder,
        true);
    constructorVisitor.visitEnd();
    AsmUtil.genClosureFields(
        TransformationUtilsKt.toNameTypePair(
            TransformationUtilsKt.filterSkipped(newFieldsWithSkipped)),
        classBuilder);
  }