Parse a list of type parameters into {@link TypeParameter} objects.

@param parser
the parser
@param definingClassName
the defining class name
@return the list of {@link TypeParameter} objects.
@throws ParseException
if parsing fails
763620
static List<TypeParameter> parseList(final Parser parser, final String definingClassName)
            throws ParseException {
        if (parser.peek() != '<') {
            return Collections.emptyList();
        }
        parser.expect('<');
        final List<TypeParameter> typeParams = new ArrayList<>(1);
        while (parser.peek() != '>') {
            if (!parser.hasMore()) {
                throw new ParseException(parser, "Missing '>'");
            }
            if (!TypeUtils.getIdentifierToken(parser)) {
                throw new ParseException(parser, "Could not parse identifier token");
            }
            final String identifier = parser.currToken();
            // classBound may be null
            final ReferenceTypeSignature classBound = ReferenceTypeSignature.parseClassBound(parser,
                    definingClassName);
            List<ReferenceTypeSignature> interfaceBounds;
            if (parser.peek() == ':') {
                interfaceBounds = new ArrayList<>();
                while (parser.peek() == ':') {
                    parser.expect(':');
                    final ReferenceTypeSignature interfaceTypeSignature = ReferenceTypeSignature
                            .parseReferenceTypeSignature(parser, definingClassName);
                    if (interfaceTypeSignature == null) {
                        throw new ParseException(parser, "Missing interface type signature");
                    }
                    interfaceBounds.add(interfaceTypeSignature);
                }
            } else {
                interfaceBounds = Collections.emptyList();
            }
            typeParams.add(new TypeParameter(identifier, classBound, interfaceBounds));
        }
        parser.expect('>');
        return typeParams;
    }
737903
public static <T> Parser<T> tokenType(final Class<? extends T> type, final String name) {
    return token(new TokenMap<T>() {
      @Override public T map(Token token) {
        if (type.isInstance(token.value())) {
          return type.cast(token.value());
        }
        return null;
      }
      @Override public String toString() {
        return name;
      }
    });
  }
174380
JCTypeParameter typeParameter() {
        int pos = token.pos;
        List<JCAnnotation> annos = typeAnnotationsOpt();
        Name name = ident();
        ListBuffer<JCExpression> bounds = new ListBuffer<>();
        if (token.kind == EXTENDS) {
            nextToken();
            bounds.append(parseType());
            while (token.kind == AMP) {
                nextToken();
                bounds.append(parseType());
            }
        }
        return toP(F.at(pos).TypeParameter(name, bounds.toList(), annos));
    }
695475
public static <T> Parser<List<T>> list(Iterable<? extends Parser<? extends T>> parsers) {
    final Parser<? extends T>[] array = toArray(parsers);
    return new Parser<List<T>>() {
      @Override boolean apply(ParseContext ctxt) {
        ArrayList<T> list = Lists.arrayList(array.length);
        for (Parser<? extends T> parser : array) {
          if (!parser.apply(ctxt)) return false;
          list.add(parser.getReturn(ctxt));
        }
        ctxt.result = list;
        return true;
      }
      
      @Override public String toString() {
        return "list";
      }
    };
  }
992909
static ReferenceTypeSignature parseReferenceTypeSignature(final Parser parser, final String definingClassName)
            throws ParseException {
        final ClassRefTypeSignature classTypeSignature = ClassRefTypeSignature.parse(parser, definingClassName);
        if (classTypeSignature != null) {
            return classTypeSignature;
        }
        final TypeVariableSignature typeVariableSignature = TypeVariableSignature.parse(parser, definingClassName);
        if (typeVariableSignature != null) {
            return typeVariableSignature;
        }
        final ArrayTypeSignature arrayTypeSignature = ArrayTypeSignature.parse(parser, definingClassName);
        if (arrayTypeSignature != null) {
            return arrayTypeSignature;
        }
        return null;
    }
432596
public static List<Integer> parserIntegerList(JsonPullParser parser) throws IOException,
			JsonFormatException {

		State eventType = parser.getEventType();
		if (eventType == State.VALUE_NULL) {
			return null;
		}
		if (eventType != State.START_ARRAY) {
			throw new IllegalStateException("not started brace!");
		}
		List<Integer> list = new ArrayList<Integer>();
		while (parser.lookAhead() != State.END_ARRAY) {
			eventType = parser.getEventType();
			if (eventType == State.VALUE_NULL) {
				list.add(null);
			} else if (eventType == State.VALUE_LONG) {
				list.add((int) parser.getValueLong());
			} else {
				throw new IllegalStateException("unexpected state. expected=VALUE_LONG, but get="
						+ eventType.toString());
			}
		}
		parser.getEventType();
		return list;
	}
610054
private static boolean parseElementInternal(
      XmlPullParser parser,
      ArrayList<Type> context,
      Object destination,
      Type valueType,
      XmlNamespaceDictionary namespaceDictionary,
      CustomizeParser customizeParser)
      throws IOException, XmlPullParserException {
    // TODO(yanivi): method is too long; needs to be broken down into smaller methods and comment
    // better
    GenericXml genericXml = destination instanceof GenericXml ? (GenericXml) destination : null;
    @SuppressWarnings("unchecked")
    Map<String, Object> destinationMap =
        genericXml == null && destination instanceof Map<?, ?> ? Map.class.cast(destination) : null;

    // if there is a class, we want to put the data into, create the class Info for this
    ClassInfo classInfo =
        destinationMap != null || destination == null ? null : ClassInfo.of(destination.getClass());
    if (parser.getEventType() == XmlPullParser.START_DOCUMENT) {
      parser.next();
    }
    parseNamespacesForElement(parser, namespaceDictionary);
    // generic XML
    if (genericXml != null) {
      genericXml.namespaceDictionary = namespaceDictionary;
      String name = parser.getName();
      String namespace = parser.getNamespace();
      String alias = namespaceDictionary.getNamespaceAliasForUriErrorOnUnknown(namespace);
      genericXml.name = alias.length() == 0 ? name : alias + ":" + name;
    }
    // attributes
    if (destination != null) {
      int attributeCount = parser.getAttributeCount();
      for (int i = 0; i < attributeCount; i++) {
        // TODO(yanivi): can have repeating attribute values, e.g. "@a=value1 @a=value2"?
        String attributeName = parser.getAttributeName(i);
        String attributeNamespace = parser.getAttributeNamespace(i);
        String attributeAlias =
            attributeNamespace.length() == 0
                ? ""
                : namespaceDictionary.getNamespaceAliasForUriErrorOnUnknown(attributeNamespace);
        String fieldName = getFieldName(true, attributeAlias, attributeNamespace, attributeName);
        Field field = classInfo == null ? null : classInfo.getField(fieldName);
        parseAttributeOrTextContent(
            parser.getAttributeValue(i),
            field,
            valueType,
            context,
            destination,
            genericXml,
            destinationMap,
            fieldName);
      }
    }
    Field field;
    ArrayValueMap arrayValueMap = new ArrayValueMap(destination);
    boolean isStopped = false;
    // TODO(yanivi): support Void type as "ignore" element/attribute
    main:
    while (true) {
      int event = parser.next();
      switch (event) {
        case XmlPullParser.END_DOCUMENT:
          isStopped = true;
          break main;
        case XmlPullParser.END_TAG:
          isStopped =
              customizeParser != null
                  && customizeParser.stopAfterEndTag(parser.getNamespace(), parser.getName());
          break main;
        case XmlPullParser.TEXT:
          // parse text content
          if (destination != null) {
            field = classInfo == null ? null : classInfo.getField(TEXT_CONTENT);
            parseAttributeOrTextContent(
                parser.getText(),
                field,
                valueType,
                context,
                destination,
                genericXml,
                destinationMap,
                TEXT_CONTENT);
          }
          break;
        case XmlPullParser.START_TAG:
          if (customizeParser != null
              && customizeParser.stopBeforeStartTag(parser.getNamespace(), parser.getName())) {
            isStopped = true;
            break main;
          }
          if (destination == null) {
            parseTextContentForElement(parser, context, true, null);
          } else {
            // element
            parseNamespacesForElement(parser, namespaceDictionary);
            String namespace = parser.getNamespace();
            String alias = namespaceDictionary.getNamespaceAliasForUriErrorOnUnknown(namespace);

            //  get the "real" field name of the
            String fieldName = getFieldName(false, alias, namespace, parser.getName());

            // fetch the field from the classInfo
            field = classInfo == null ? null : classInfo.getField(fieldName);
            Type fieldType = field == null ? valueType : field.getGenericType();
            fieldType = Data.resolveWildcardTypeOrTypeVariable(context, fieldType);
            // field type is now class, parameterized type, or generic array type
            // resolve a parameterized type to a class
            Class<?> fieldClass = fieldType instanceof Class<?> ? (Class<?>) fieldType : null;
            if (fieldType instanceof ParameterizedType) {
              fieldClass = Types.getRawClass((ParameterizedType) fieldType);
            }
            boolean isArray = Types.isArray(fieldType);
            // text content
            boolean ignore = field == null && destinationMap == null && genericXml == null;
            // is the field an Enum
            boolean isEnum = fieldClass != null && fieldClass.isEnum();
            if (ignore || Data.isPrimitive(fieldType) || isEnum) {
              int level = 1;
              while (level != 0) {
                switch (parser.next()) {
                  case XmlPullParser.END_DOCUMENT:
                    isStopped = true;
                    break main;
                  case XmlPullParser.START_TAG:
                    level++;
                    break;
                  case XmlPullParser.END_TAG:
                    level--;
                    break;
                  case XmlPullParser.TEXT:
                    if (!ignore && level == 1) {
                      parseAttributeOrTextContent(
                          parser.getText(),
                          field,
                          valueType,
                          context,
                          destination,
                          genericXml,
                          destinationMap,
                          fieldName);
                    }
                    break;
                  default:
                    break;
                }
              }
            } else if (fieldType == null
                || fieldClass != null && Types.isAssignableToOrFrom(fieldClass, Map.class)) {
              // store the element as a map
              Map<String, Object> mapValue = Data.newMapInstance(fieldClass);
              int contextSize = context.size();
              if (fieldType != null) {
                context.add(fieldType);
              }
              Type subValueType =
                  fieldType != null && Map.class.isAssignableFrom(fieldClass)
                      ? Types.getMapValueParameter(fieldType)
                      : null;
              subValueType = Data.resolveWildcardTypeOrTypeVariable(context, subValueType);
              isStopped =
                  parseElementInternal(
                      parser,
                      context,
                      mapValue,
                      subValueType,
                      namespaceDictionary,
                      customizeParser);
              if (fieldType != null) {
                context.remove(contextSize);
              }
              if (destinationMap != null) {
                // map but not GenericXml: store as ArrayList of elements
                @SuppressWarnings("unchecked")
                Collection<Object> list = (Collection<Object>) destinationMap.get(fieldName);
                if (list == null) {
                  list = new ArrayList<Object>(1);
                  destinationMap.put(fieldName, list);
                }
                list.add(mapValue);
              } else if (field != null) {
                // not a map: store in field value
                FieldInfo fieldInfo = FieldInfo.of(field);
                if (fieldClass == Object.class) {
                  // field is an Object: store as ArrayList of element maps
                  @SuppressWarnings("unchecked")
                  Collection<Object> list = (Collection<Object>) fieldInfo.getValue(destination);
                  if (list == null) {
                    list = new ArrayList<Object>(1);
                    fieldInfo.setValue(destination, list);
                  }
                  list.add(mapValue);
                } else {
                  // field is a Map: store as a single element map
                  fieldInfo.setValue(destination, mapValue);
                }
              } else {
                // GenericXml: store as ArrayList of elements
                GenericXml atom = (GenericXml) destination;
                @SuppressWarnings("unchecked")
                Collection<Object> list = (Collection<Object>) atom.get(fieldName);
                if (list == null) {
                  list = new ArrayList<Object>(1);
                  atom.set(fieldName, list);
                }
                list.add(mapValue);
              }
            } else if (isArray || Types.isAssignableToOrFrom(fieldClass, Collection.class)) {
              // TODO(yanivi): some duplicate code here; isolate into reusable methods
              FieldInfo fieldInfo = FieldInfo.of(field);
              Object elementValue = null;
              Type subFieldType =
                  isArray
                      ? Types.getArrayComponentType(fieldType)
                      : Types.getIterableParameter(fieldType);
              Class<?> rawArrayComponentType =
                  Types.getRawArrayComponentType(context, subFieldType);
              subFieldType = Data.resolveWildcardTypeOrTypeVariable(context, subFieldType);
              Class<?> subFieldClass =
                  subFieldType instanceof Class<?> ? (Class<?>) subFieldType : null;
              if (subFieldType instanceof ParameterizedType) {
                subFieldClass = Types.getRawClass((ParameterizedType) subFieldType);
              }
              boolean isSubEnum = subFieldClass != null && subFieldClass.isEnum();
              if (Data.isPrimitive(subFieldType) || isSubEnum) {
                elementValue = parseTextContentForElement(parser, context, false, subFieldType);
              } else if (subFieldType == null
                  || subFieldClass != null
                      && Types.isAssignableToOrFrom(subFieldClass, Map.class)) {
                elementValue = Data.newMapInstance(subFieldClass);
                int contextSize = context.size();
                if (subFieldType != null) {
                  context.add(subFieldType);
                }
                Type subValueType =
                    subFieldType != null && Map.class.isAssignableFrom(subFieldClass)
                        ? Types.getMapValueParameter(subFieldType)
                        : null;
                subValueType = Data.resolveWildcardTypeOrTypeVariable(context, subValueType);
                isStopped =
                    parseElementInternal(
                        parser,
                        context,
                        elementValue,
                        subValueType,
                        namespaceDictionary,
                        customizeParser);
                if (subFieldType != null) {
                  context.remove(contextSize);
                }
              } else {
                elementValue = Types.newInstance(rawArrayComponentType);
                int contextSize = context.size();
                context.add(fieldType);
                isStopped =
                    parseElementInternal(
                        parser, context, elementValue, null, namespaceDictionary, customizeParser);
                context.remove(contextSize);
              }
              if (isArray) {
                // array field: add new element to array value map
                if (field == null) {
                  arrayValueMap.put(fieldName, rawArrayComponentType, elementValue);
                } else {
                  arrayValueMap.put(field, rawArrayComponentType, elementValue);
                }
              } else {
                // collection: add new element to collection
                @SuppressWarnings("unchecked")
                Collection<Object> collectionValue =
                    (Collection<Object>)
                        (field == null
                            ? destinationMap.get(fieldName)
                            : fieldInfo.getValue(destination));
                if (collectionValue == null) {
                  collectionValue = Data.newCollectionInstance(fieldType);
                  setValue(
                      collectionValue, field, destination, genericXml, destinationMap, fieldName);
                }
                collectionValue.add(elementValue);
              }
            } else {
              // not an array/iterable or a map, but we do have a field
              Object value = Types.newInstance(fieldClass);
              int contextSize = context.size();
              context.add(fieldType);
              isStopped =
                  parseElementInternal(
                      parser, context, value, null, namespaceDictionary, customizeParser);
              context.remove(contextSize);
              setValue(value, field, destination, genericXml, destinationMap, fieldName);
            }
          }
          if (isStopped || parser.getEventType() == XmlPullParser.END_DOCUMENT) {
            isStopped = true;
            break main;
          }
          break; // break Switch;
      } // end -- switch (event)
    } // end -- main: while (true)
    arrayValueMap.setValues();
    return isStopped;
  }
998988
protected Method getParse(Class cls) throws Exception {
    Method meth = methodCache.get(cls);
    if (null == meth) {
      meth = cls.getMethod("parseFrom", new Class[]{ byte[].class });
      methodCache.put(cls, meth);
    }
    return meth;
  }
599319
public static Object loadGenInstance(String classname) throws ParserException
    {
        try
        {
            Class<?> parserClass;
            try
            {
                parserClass = Class.forName(classname);
            }
            catch (ClassNotFoundException ex)
            {
                return null;
            }
            return parserClass.newInstance();
        }
        catch (InstantiationException | IllegalAccessException ex)
        {
            throw new ParserException(ex);
        }
    }
1281331
public <T extends TypeDefinition> List<T> getTypes(Class<T> targetClass) {
        return types.values().stream()
                .filter(targetClass::isInstance)
                .map(targetClass::cast)
                .collect(Collectors.toList());
    }
117503
public static Class<?>[] getConstructorParameters(Class<?> type, Class<?>[] givenTypes) {
        next_constructor:
        for (Constructor<?> constructor : type.getConstructors()) {
            int matches = 0;
            Class<?>[] parameters = constructor.getParameterTypes();
            Iterator<Class<?>> parameterIterator = Arrays
                    .asList(parameters)
                    .iterator();
            if (!isEmpty(givenTypes)
                    && !isEmpty(parameters)) {
                Class<?> parameter = null;
                for (Class<?> argument : givenTypes) {

                    if (parameterIterator.hasNext()) {
                        parameter = parameterIterator.next();
                        if (!compatible(parameter, argument)) {
                            continue next_constructor;
                        }
                        matches++;
                    } else if (constructor.isVarArgs()) {
                        if (!compatible(parameter, argument)) {
                            continue next_constructor;
                        }
                    } else {
                        continue next_constructor; //default
                    }
                }
                if (matches == parameters.length) {
                    return parameters;
                }
            } else if (isEmpty(givenTypes)
                    && isEmpty(parameters)) {
                return NO_ARGS;
            }
        }
        throw new ExpressionException("No constructor found for " + type.toString()
                + " with parameters: " + Arrays.deepToString(givenTypes));
    }
580064
public <T> T parse(String input, Class<T> targetType) {
        return typeParser.parse(input, targetType);
    }
992966
public void parseDeclarations( IGosuClass gsCls )
  {
    IGosuClassInternal gsClass = (IGosuClassInternal)gsCls;

    if( gsClass.isDeclarationsCompiled() )
    {
      if( !gsClass.isInnerDeclarationsCompiled() )
      {
        if( parseDeclarationsOfLeftOverInnerClasses( gsClass ) )
        {
          gsClass.setInnerDeclarationsCompiled();
        }
      }
      return;
    }

    boolean bPushedScope = pushScopeIfNeeded( gsClass );

    getTokenizer().pushOffsetMarker( this );
    ScriptPartId scriptPartId = new ScriptPartId( gsClass, null );
    getOwner().pushScriptPart( scriptPartId );
    GosuClassCompilingStack.pushCompilingType( gsClass );
    gsClass.setCompilingDeclarations( true );
    try
    {
      ClassStatement classStmt = (ClassStatement)gsClass.getClassStatement();
      try
      {
        setClassStatement( classStmt );
      }
      catch( Exception e )
      {
        throw GosuExceptionUtil.forceThrow( e, gsClass.getName() );
      }
      if( isTopLevelClass( gsClass ) || TypeLord.isEvalProgram( gsClass ) )
      {
        classStmt.getClassFileStatement().clearParseTreeInformation();
      }

      // Don't need an isolated scope here because class members are all dynamic
      // and, therefore, don't have to be indexed wrt an isolated scope.
      getSymbolTable().pushScope();
      try
      {
        //## todo: reparsing header with annotations this time, any chance we can do that the first time we parse the header, so we can avoid doing it twice?
        String strClassName = parseHeader(gsClass, false, false, true);
        if( gsClass instanceof IGosuEnhancementInternal )
        {
          parseEnhancementBodyDecl( gsClass );
        }
        else
        {
          parseClassBodyDecl( strClassName, gsClass );
        }
      }
      finally
      {
        getSymbolTable().popScope();

        pushStatement( classStmt );
        setLocation( _iClassOffset, _iClassLineNum, _iClassColumn, true );
        popStatement();

        if( isTopLevelClass( gsClass ) || TypeLord.isEvalProgram( gsClass ) )
        {
          pushStatement( classStmt.getClassFileStatement() );
          setLocation( 0, 1, _iClassColumn, true );
          popStatement();
        }
      }
      classStmt.compactParseTree();
    }
    finally
    {
      gsClass.setCompilingDeclarations( false );
      // Do not set decls compiled; we do that in parseClassBodyDecl(). Also the decls may not have actually been compiled
      //gsClass.setDeclarationsCompiled();
      GosuClassCompilingStack.popCompilingType();
      getOwner().popScriptPart( scriptPartId );
      popScopeIfNeeded( bPushedScope, gsClass );
      getTokenizer().popOffsetMarker( this );

      removeTypeVarsFromParserMap( gsClass );
    }
  }
523940
static ArrayTypeSignature parse(final Parser parser, final String definingClassName) throws ParseException {
        int numArrayDims = 0;
        while (parser.peek() == '[') {
            numArrayDims++;
            parser.next();
        }
        if (numArrayDims > 0) {
            final TypeSignature elementTypeSignature = TypeSignature.parse(parser, definingClassName);
            if (elementTypeSignature == null) {
                throw new ParseException(parser, "elementTypeSignature == null");
            }
            return new ArrayTypeSignature(elementTypeSignature, numArrayDims);
        } else {
            return null;
        }
    }
16813
@Override
    public Class defineClass( String name, byte [] code )
    {
        baseClassPath.setClassSource( name, new GeneratedClassSource( code ) );
        try {
            reloadClasses( new String [] { name } );
        } catch ( ClassPathException e ) {
            throw new bsh.InterpreterError("defineClass: "+e, e);
        }
        return classForName( name );
    }
345843
@Override
    public Parser newDelimitedParser(final InputStream dataSourceStream, final char delimiter, final char qualifier) {
        return new DelimiterParser(dataSourceStream, delimiter, qualifier, false);
    }
635081
public static <T> List<T> parseListFrom(JsonParser parser, Schema<T> schema,
            boolean numeric) throws IOException
    {
        if (parser.nextToken() != JsonToken.START_ARRAY)
        {
            throw new JsonInputException("Expected token: [ but was " +
                    parser.getCurrentToken() + " on message: " +
                    schema.messageFullName());
        }

        final JsonInput input = new JsonInput(parser, numeric);
        final List<T> list = new ArrayList<T>();
        for (JsonToken t = parser.nextToken(); t != JsonToken.END_ARRAY; t = parser.nextToken())
        {
            if (t != JsonToken.START_OBJECT)
            {
                throw new JsonInputException("Expected token: { but was " +
                        parser.getCurrentToken() + " on message " +
                        schema.messageFullName());
            }

            final T message = schema.newMessage();
            schema.mergeFrom(input, message);

            if (parser.getCurrentToken() != JsonToken.END_OBJECT)
            {
                throw new JsonInputException("Expected token: } but was " +
                        parser.getCurrentToken() + " on message " +
                        schema.messageFullName());
            }

            list.add(message);
            input.reset();
        }
        return list;
    }