'Combines the enforced `valid_types` with any from the search string
itself and updates the query.
For example, a name of \'a,b:foo\' and valid_types of b,c will search for
only `b`s named "foo".
Returns `(name, merged_valid_types, term)`, where `name` has had any type
prefix stripped, `merged_valid_types` combines the original
`valid_types` with the type prefix, and `term` is a query term for
limited to just the allowed types.  If there are no type restrictions
at all, `term` will be None.'

def _apply_valid_types(self, name, valid_types):

    user_valid_types = []
    if (':' in name):
        (prefix_chunk, name) = name.split(':', 1)
        name = name.strip()
        prefixes = prefix_chunk.split(',')
        user_valid_types = []
        for prefix in prefixes:
            prefix = prefix.strip()
            if prefix:
                user_valid_types.append(prefix)
            if (prefix == 'pokemon'):
                user_valid_types.append('pokemon_species')
                user_valid_types.append('pokemon_form')
    def merge_requirements(func):
        user = list(filter(func, user_valid_types))
        system = list(filter(func, valid_types))
        if (user and system):
            merged = list((set(user) & set(system)))
            if merged:
                return merged
            else:
                return system
        else:
            return (user or system)
    lang_requirements = merge_requirements((lambda req: (req[0] == u'@')))
    type_requirements = merge_requirements((lambda req: (req[0] != u'@')))
    all_requirements = (lang_requirements + type_requirements)
    lang_terms = []
    for lang in lang_requirements:
        lang_code = lang[1:]
        lang_terms.append(whoosh.query.Term(u'iso639', lang_code))
        lang_terms.append(whoosh.query.Term(u'iso3166', lang_code))
    type_terms = []
    for type in type_requirements:
        table_name = self._parse_table_name(type)
        if table_name:
            type_terms.append(whoosh.query.Term(u'table', table_name))
    all_terms = []
    if type_terms:
        all_terms.append(whoosh.query.Or(type_terms))
    if lang_terms:
        all_terms.append(whoosh.query.Or(lang_terms))
    return (name, all_requirements, whoosh.query.And(all_terms))
