TODO: handle generics and inner classes
327089
private static String getSignature(IMethod mtd) {
    String classType =
        mtd.getDeclaringClass().getName().toString().replaceAll("/", "\\.").substring(1);
    classType = classType.replaceAll("\\$", "\\."); // handle inner class
    String returnType = mtd.isInit() ? null : getSimpleTypeName(mtd.getReturnType());
    String strArgTypes = "";
    int argi = mtd.isStatic() ? 0 : 1; // Skip 'this' parameter
    for (; argi < mtd.getNumberOfParameters(); argi++) {
      strArgTypes += getSimpleTypeName(mtd.getParameterType(argi));
      if (argi < mtd.getNumberOfParameters() - 1) strArgTypes += ", ";
    }
    return classType
        + ":"
        + (returnType == null ? "void " : returnType + " ")
        + mtd.getName().toString()
        + "("
        + strArgTypes
        + ")";
  }
1296854
@Override
    public void handleLoadInstruction(LoadInstruction obj) {
        int numProduced = obj.produceStack(cpg);
        if (numProduced == Const.UNPREDICTABLE) {
            throw new InvalidBytecodeException("Unpredictable stack production");
        }

        if (numProduced != 1) {
            super.handleLoadInstruction(obj);
            return;
        }
        int index = obj.getIndex();
        TypeFrame frame = getFrame();
        Type value = frame.getValue(index);
        if (value instanceof ReferenceType && !(value instanceof GenericObjectType)) {
            GenericObjectType gType = getLocalVariable(index,
                    getLocation().getHandle().getPosition());
            value = GenericUtilities.merge(gType, value);
        }
        boolean isExact = frame.isExact(index);
        frame.pushValue(value);
        if (isExact) {
            setTopOfStackIsExact();
        }
    }
753561
function (out) {
            var tplParam = out.templateParam;
            // normal inheritance processing: set out.parentClasspath, out.parentClassName and out.parentClassType
            if (tplParam.$extends) {
                out.parentClasspath = tplParam.$extends;
                out.parentClassType = this._classType;
            } else {
                out.parentClasspath = this._superClass;
            }
            if (out.parentClasspath) {
                out.parentClassName = this._getClassName(out.parentClasspath);
            }
        }
494873
@SafeVarargs
    public static <T extends ParseTreeListener> T create(Class<T> type, T... delegates) {
        ImmutableList<T> listeners = ImmutableList.copyOf(delegates);
        return Reflection.newProxy(type, new AbstractInvocationHandler() {

            @Override
            @ParametersAreNonnullByDefault
            protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
                for (T listener : listeners) {
                    method.invoke(listener, args);
                }
                return null;
            }

            @Override
            public String toString() {
                return MoreObjects.toStringHelper("CompositeParseTreeListener")
                        .add("listeners", listeners)
                        .toString();
            }
        });

    }
311816
void expectAnyObject(Node n, JSType type, String msg) {
    JSType anyObjectType = getNativeType(NO_OBJECT_TYPE);
    if (!anyObjectType.isSubtypeOf(type) && !type.isEmptyType()) {
      mismatch(n, msg, type, anyObjectType);
    }
  }
763950
@SuppressWarnings("unchecked")
  public static <T> Class<T> wrap(Class<T> type) {
    return (type.isPrimitive() || type == void.class) ? (Class<T>) PrimitiveToWrappers.get(type) : type;
  }
64454
function (out) {
            var tplParam = out.templateParam;
            out.writeln("module.exports = Aria.classDefinition({");
            out.increaseIndent();
            out.writeln("$classpath: ", out.stringify(tplParam.$classpath), ",");
            if (out.parentClasspath) {
                out.writeln("$extends: require(", out.stringify(Aria.getLogicalPath(out.parentClasspath, Aria.ACCEPTED_TYPES[out.parentClassType])), "),");
            }
        }
948067
function handleAttributeContext(attrNode, context) {
    if (!attrNode.type && attrNode.inherit !== 'inherit') attrNode.type = 'string';

    if (attrNode.map) {
        Object.keys(attrNode.map).forEach(mappingName => {
            const mapping = attrNode.map[mappingName];

            Object.keys(mapping).forEach(dataSourceName => {
                if (!context.dataSourceAttributes[dataSourceName]) {
                    throw new ImplementationError(
                        `Unknown DataSource "${dataSourceName}" in map${context.errorContext}`
                    );
                }

                context.dataSourceAttributes[dataSourceName].push(mapping[dataSourceName]);
            });
        });

        if ('value' in attrNode) {
            throw new ImplementationError(
                'Static "value" in combination with "map" makes no sense' + context.errorContext
            );
        }
    }
}
436947
function visitTypedFunction(traverse, node, path, state) {
  var klass = getParentClassDeclaration(path);
  var generics = klass && klass.typeParameters ? toLookup(klass.typeParameters.params.map(getName)) : {};
  if (node.typeParameters) {
    generics = mixin(generics, toLookup(node.typeParameters.params.map(getName)));
  }
  var ctx = new Context(state, generics);
  var rest = node.rest ? ', ' + ctx.getType(node.rest.typeAnnotation.typeAnnotation) : '';
  var types = [];
  var params = [];
  node.params.forEach(function (param) {
    var type = ctx.getType(param.typeAnnotation ? param.typeAnnotation.typeAnnotation : null);
    types.push(param.optional ? ctx.getProperty('optional') + '(' + type + ')' : type);
    params.push(param.name);
  });

  utils.catchup(node.body.range[0] + 1, state);

  if (params.length || rest) {
    utils.append(ctx.getProperty('check') + '(arguments, ' + ctx.getProperty('arguments') + '([' + types.join(', ') + ']' + rest + '));', state);
  }

  if (node.returnType) {
    var returnType = ctx.getType(node.returnType.typeAnnotation);
    utils.append(' var ret = (function (' + params.join(', ') + ') {', state);
    traverse(node.body, path, state);
    utils.catchup(node.body.range[1] - 1, state);
    utils.append('}).apply(this, arguments); return ' + ctx.getProperty('check') + '(ret, ' + returnType + ');', state);
  } else {
    traverse(node.body, path, state);
  }

  return false;
}
484607
@SuppressWarnings("unchecked")
    public <T> T convert(Object source, String syntax, Class<T> toClass) {
        Object result = null;

        // What are we converting form
        Class<?> fromClass = source.getClass();

        // Deal with primitives
        Class<?> targetClass = toClass;
        if (toClass.isPrimitive()) {
            targetClass = primitiveTypeMap.get(toClass);
        }

        // Try to convert with any syntax we have been given
        Converter syntaxConverter = converters.get(makeConverterKey(fromClass, syntax, targetClass));
        if (syntaxConverter != null) {
            try {
                result = syntaxConverter.convert(source, targetClass);
            } catch (Exception e) {
                // Ignore as we may still be able to convert successfully
            }
        }

        // Do we actually need to do any conversion?
        if (result == null && targetClass.isAssignableFrom(fromClass)) {
            result = source;
        }

        // If we were given a syntax and we failed to convert drop back to any mapping
        // that will work from class -> to class
        if (result == null && syntax != null) {
            Converter nullSyntaxConverter = converters.get(makeConverterKey(fromClass, null, targetClass));
            if (nullSyntaxConverter != null) {
                try {
                    result = nullSyntaxConverter.convert(source, targetClass);
                } catch (Exception e) {
                    // Handled at the end of the method
                }
            }
        }

        if (result == null) {
            throw new ConverterException(String.format(
                    "Cannot convert %1$s of class %2$s via syntax %3$s to class %4$s", source, source.getClass(),
                    syntax, toClass));
        }

        // We cannot do the safe thing of doing a .cast as we need to rely on auto-unboxing to deal with primitives!
        return (T)result;
    }
161978
@SuppressWarnings("PMD.LooseCoupling")
    public static LinkedHashMap<String, Type> createGenericsMap(final Class<?> type,
                                                                final List<? extends Type> generics) {
        final TypeVariable<? extends Class<?>>[] params = type.getTypeParameters();
        if (params.length != generics.size()) {
            throw new IllegalArgumentException(String.format(
                    "Can't build generics map for %s with %s because of incorrect generics count",
                    type.getSimpleName(), Arrays.toString(generics.toArray())));
        }
        final LinkedHashMap<String, Type> res = new LinkedHashMap<String, Type>();
        int i = 0;
        for (TypeVariable var : params) {
            res.put(var.getName(), generics.get(i++));
        }
        // add possible outer class generics to avoid unknown generics
        return GenericsResolutionUtils.fillOuterGenerics(type, res, null);
    }
734263
public Object convert(String rawString, Type type, Class<?> genericSubType) {

        Object converted = null;

        if (genericSubType == null && type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Type[] aTypes = pType.getActualTypeArguments();
            Type genericTypeArg = aTypes.length == 1 ? aTypes[0] : null; //initially only support one type arg
            if (genericTypeArg instanceof Class) { //for the moment we only support a class ... so no type variables; e.g. List<String> is ok but List<T> is not
                Class<?> genericClassArg = (Class<?>) genericTypeArg;
                converted = convert(rawString, pType.getRawType(), genericClassArg);
            } else {
                throw new IllegalArgumentException(Tr.formatMessage(tc, "generic.type.variables.notsupported.CWMCG0018E", type, genericTypeArg));
            }
        } else {
            //first box any primitives
            if (type instanceof Class<?>) {
                Class<?> clazz = (Class<?>) type;
                if (clazz.isPrimitive()) {
                    type = ClassUtils.primitiveToWrapper(clazz);
                }
            }

            //do a simple lookup in the map of converters
            ConversionStatus status = simpleConversion(rawString, type, genericSubType);

            if (!status.isConverterFound() && type instanceof Class) {
                Class<?> requestedClazz = (Class<?>) type;

                //try array conversion
                if (requestedClazz.isArray()) {
                    Class<?> arrayType = requestedClazz.getComponentType();
                    Class<?> conversionType = arrayType;
                    //first convert primitives to wrapper types
                    if (arrayType.isPrimitive()) {
                        conversionType = ClassUtils.primitiveToWrapper(arrayType);
                    }
                    //convert to an array of the wrapper type
                    Object[] wrappedArray = convertArray(rawString, conversionType);// convertArray will throw ConverterNotFoundException if it can't find a converter

                    //switch back to the primitive type if required
                    Object value = wrappedArray;
                    if (arrayType.isPrimitive()) {
                        value = toPrimitiveArray(wrappedArray, arrayType);
                    }

                    status.setConverted(value);
                }

                //try implicit converters (e.g. String Constructors)
                if (!status.isConverterFound()) {
                    status = implicitConverters(rawString, requestedClazz);
                }

                //try to find any compatible converters
                if (!status.isConverterFound()) {
                    status = convertCompatible(rawString, requestedClazz);
                }

            }

            if (!status.isConverterFound()) {
                throw new IllegalArgumentException(Tr.formatMessage(tc, "could.not.find.converter.CWMCG0014E", type.getTypeName()));
            }

            converted = status.getConverted();
        }
        return converted;

    }
764417
public static Class<?> getListInnerClassFromGenericType(Type genericType) {
        ParameterizedType innerClass = (ParameterizedType) genericType;
        return (Class<?>) innerClass.getActualTypeArguments()[0];
    }
397849
<T> Class<?> transform(Class<T> proxyInterface) {
    try {
      String packageName = proxyInterface.getPackage().getName();
      String genericProxyInterfaceName =
          packageName + "." + PROXY_PREFIX + proxyInterface.getSimpleName();
      try {
        return Class.forName(genericProxyInterfaceName);
      } catch (ClassNotFoundException e) {
        pool.insertClassPath(new ClassClassPath(proxyInterface));
        CtClass copy = pool.getAndRename(proxyInterface.getName(), genericProxyInterfaceName);
        replaceGenericResponseMethods(copy);

        return copy
            .toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain());
      }
    } catch (NotFoundException e) {
      throw new RuntimeException(e);
    } catch (CannotCompileException e) {
      throw new RuntimeException(e);
    } catch (BadBytecode e) {
      throw new RuntimeException(e);
    }
  }
270911
@SuppressWarnings("unchecked")
    protected <T> T cast(Object arg, Class<T> type) {
        if (arg == null) {
            throw new NullPointerException("Argument is null");
        }
        if (!type.isInstance(arg)) {
            throw FormatException.illegalFormat(getFormatName(), arg.getClass());
        }
        return (T) arg;
    }
754771
@SuppressWarnings("unchecked")
    private static <R, T extends Throwable> R typeErasure(final Throwable throwable) throws T {
        throw (T) throwable;
    }
1296542
public void resolveType() {
        if (getTypeStyle() == null) {
            setTypeStyle("");
        }
        final String fieldType = getFieldType();
        String generics = "";
        if (fieldType.contains("<")) {
            generics = fieldType.substring(fieldType.indexOf('<'));
        }
        if (getTypeStyle().equals("smart")) {
            setType(fieldType);
        } else if (getTypeStyle().length() > 0) {
            if (getTypeStyle().contains("<>")) {
                setType(getTypeStyle().replace("<>", generics));
            } else if (getTypeStyle().contains("<")) {
                setType(getTypeStyle());
            } else {
                setType(getTypeStyle() + generics);
            }
        } else {
            setType(fieldType);
        }
    }