Base "abstract" Avro union type.
192230
function UnionType(schema, opts) {
  Type.call(this);

  if (!Array.isArray(schema)) {
    throw new Error(f('non-array union schema: %j', schema));
  }
  if (!schema.length) {
    throw new Error('empty union');
  }
  this.types = Object.freeze(schema.map(function (obj) {
    return Type.forSchema(obj, opts);
  }));

  this._branchIndices = {};
  this.types.forEach(function (type, i) {
    if (Type.isType(type, 'union')) {
      throw new Error('unions cannot be directly nested');
    }
    var branch = type.branchName;
    if (this._branchIndices[branch] !== undefined) {
      throw new Error(f('duplicate union branch name: %j', branch));
    }
    this._branchIndices[branch] = i;
  }, this);
}
66956
def simplify_recursive(typ):
    # type: (AbstractType) -> AbstractType
    """"""
    if isinstance(typ, UnionType):
        return combine_types(typ.items)
    elif isinstance(typ, ClassType):
        simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])
        args = simplified.args
        if (simplified.name == 'Dict' and len(args) == 2
                and isinstance(args[0], ClassType) and args[0].name in ('str', 'Text')
                and isinstance(args[1], UnionType) and not is_optional(args[1])):
            # Looks like a potential case for TypedDict, which we don't properly support yet.
            return ClassType('Dict', [args[0], AnyType()])
        return simplified
    elif isinstance(typ, TupleType):
        return TupleType([simplify_recursive(item) for item in typ.items])
    return typ
491618
function getUnionTypeFromSortedList(types, aliasSymbol, aliasTypeArguments) {
            if (types.length === 0) {
                return neverType;
            }
            if (types.length === 1) {
                return types[0];
            }
            var id = getTypeListId(types);
            var type = unionTypes[id];
            if (!type) {
                var propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 6144 /* Nullable */);
                type = unionTypes[id] = createObjectType(524288 /* Union */ | propagatedFlags);
                type.types = types;
                type.aliasSymbol = aliasSymbol;
                type.aliasTypeArguments = aliasTypeArguments;
            }
            return type;
        }
127894
def _generate_union_class(self, ns, data_type):
        # type: (ApiNamespace, Union) -> None
        """"""
        self.emit(self._class_declaration_for_type(ns, data_type))
        with self.indent():
            self.emit('"""')
            if data_type.doc:
                self.emit_wrapped_text(
                    self.process_doc(data_type.doc, self._docf))
                self.emit()

            self.emit_wrapped_text(
                'This class acts as a tagged union. Only one of the ``is_*`` '
                'methods will return true. To get the associated value of a '
                'tag (if one exists), use the corresponding ``get_*`` method.')

            if data_type.has_documented_fields():
                self.emit()

            for field in data_type.fields:
                if not field.doc:
                    continue
                if is_void_type(field.data_type):
                    ivar_doc = ':ivar {}: {}'.format(
                        fmt_namespaced_var(ns.name, data_type.name, field.name),
                        self.process_doc(field.doc, self._docf))
                elif is_user_defined_type(field.data_type):
                    if data_type.namespace.name != ns.name:
                        formatted_var = fmt_namespaced_var(ns.name, data_type.name, field.name)
                    else:
                        formatted_var = '{}.{}'.format(data_type.name, fmt_var(field.name))
                    ivar_doc = ':ivar {} {}: {}'.format(
                        fmt_class(field.data_type.name),
                        formatted_var,
                        self.process_doc(field.doc, self._docf))
                else:
                    ivar_doc = ':ivar {} {}: {}'.format(
                        self._python_type_mapping(ns, field.data_type),
                        fmt_namespaced_var(ns.name, data_type.name, field.name), field.doc)
                self.emit_wrapped_text(ivar_doc, subsequent_prefix='    ')
            self.emit('"""')
            self.emit()

            self._generate_union_class_vars(data_type)
            self._generate_union_class_variant_creators(ns, data_type)
            self._generate_union_class_is_set(data_type)
            self._generate_union_class_get_helpers(ns, data_type)
            self._generate_union_class_custom_annotations(ns, data_type)
            self._generate_union_class_repr(data_type)
        self.emit('{0}_validator = bv.Union({0})'.format(
            class_name_for_data_type(data_type)
        ))
        self.emit()
78874
def _issubclass_Union(subclass, superclass, bound_Generic, bound_typevars,
            bound_typevars_readonly, follow_fwd_refs, _recursion_check):
    
    if not follow_fwd_refs:
        return _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars,
            bound_typevars_readonly, follow_fwd_refs, _recursion_check)
    try:
        # try to succeed fast, before we go the expensive way involving recursion checks
        return _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars,
            bound_typevars_readonly, False, _recursion_check)
    except pytypes.ForwardRefError:
        return _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars,
            bound_typevars_readonly, follow_fwd_refs, _recursion_check)
935375
def _unionload(l: Loader, value, type_) -> Any:
    
    try:
        args = uniontypes(type_)
    except AttributeError:
        raise TypedloadAttributeError('The typing API for this Python version is unknown')

    # Do not convert basic types, if possible
    if type(value) in args.intersection(l.basictypes):
        return value

    exceptions = []

    # Try all types
    for t in args:
        try:
            return l.load(value, t, annotation=Annotation(AnnotationType.UNION, t))
        except Exception as e:
            exceptions.append(e)
    raise TypedloadValueError(
        'Value could not be loaded into %s' % type_,
            value=value,
            type_=type_,
            exceptions=exceptions
    )
43440
@Override
    public R visitUnionType(UnionTypeTree node, P p) {
        return scan(node.getTypeAlternatives(), p);
    }
752601
def register_annotype_converter(cls, types, is_array=False,
                                    is_mapping=False):
        # type: (Union[Sequence[type], type], bool, bool) -> Any
        """"""
        if not isinstance(types, Sequence):
            types = [types]

        def decorator(subclass):
            for typ in types:
                cls._annotype_lookup[(typ, is_array, is_mapping)] = subclass
            return subclass

        return decorator
973488
public List<Symbol> getAllSymbolsForType(JSType type) {
    if (type == null) {
      return ImmutableList.of();
    }

    UnionType unionType = type.toMaybeUnionType();
    if (unionType != null) {
      List<Symbol> result = new ArrayList<>(2);
      for (JSType alt : unionType.getAlternates()) {
        // Our type system never has nested unions.
        Symbol altSym = getSymbolForTypeHelper(alt, true);
        if (altSym != null) {
          result.add(altSym);
        }
      }
      return result;
    }
    Symbol result = getSymbolForTypeHelper(type, true);
    return result == null ? ImmutableList.of() : ImmutableList.of(result);
  }
928989
def surface_or_abstract(cls, predstr):
        """"""
        if predstr.strip('"').lstrip("'").startswith('_'):
            return cls.surface(predstr)
        else:
            return cls.abstract(predstr)
1163752
def v_type_base(ctx, stmt, no_error_report=False):
    """"""
    # Find the identity
    name = stmt.arg
    stmt.i_identity = None
    if name.find(":") == -1:
        prefix = None
    else:
        [prefix, name] = name.split(':', 1)
    if prefix is None or stmt.i_module.i_prefix == prefix:
        # check local identities
        pmodule = stmt.i_module
    else:
        # this is a prefixed name, check the imported modules
        pmodule = prefix_to_module(stmt.i_module, prefix, stmt.pos, ctx.errors)
        if pmodule is None:
            return
    if name in pmodule.i_identities:
        i = pmodule.i_identities[name]
        if prefix is None and not is_submodule_included(stmt, i):
            pass
        else:
            stmt.i_identity = i
            v_type_identity(ctx, stmt.i_identity)
    if stmt.i_identity is None and no_error_report == False:
        err_add(ctx.errors, stmt.pos,
                'IDENTITY_NOT_FOUND', (name, pmodule.arg))
316501
def _generate_union_class_variant_creators(self, ns, data_type):
        
        for field in data_type.fields:
            if not is_void_type(field.data_type):
                field_name = fmt_func(field.name)
                field_name_reserved_check = fmt_func(field.name, check_reserved=True)
                if is_nullable_type(field.data_type):
                    field_dt = field.data_type.data_type
                else:
                    field_dt = field.data_type
                self.emit('@classmethod')
                self.emit('def {}(cls, val):'.format(field_name_reserved_check))
                with self.indent():
                    self.emit('"""')
                    self.emit_wrapped_text(
                        'Create an instance of this class set to the ``%s`` '
                        'tag with value ``val``.' % field_name)
                    self.emit()
                    self.emit(':param {} val:'.format(
                        self._python_type_mapping(ns, field_dt)))
                    self.emit(':rtype: {}'.format(
                        self._python_type_mapping(ns, data_type)))
                    self.emit('"""')
                    self.emit("return cls('{}', val)".format(field_name))
                self.emit()
698736
def _find_base_type(data_type):
    
    bases = type(data_type).__mro__
    for base in bases:
        if base in _ALL:
            return base

    return None
755679
function combine(types, opts) {
  if (!types.length) {
    throw new Error('no types to combine');
  }
  if (types.length === 1) {
    return types[0]; // Nothing to do.
  }
  opts = opts || {};

  // Extract any union types, with special care for wrapped unions (see below).
  var expanded = [];
  var numWrappedUnions = 0;
  var isValidWrappedUnion = true;
  types.forEach(function (type) {
    switch (type.getTypeName()) {
      case 'union:unwrapped':
        isValidWrappedUnion = false;
        expanded = expanded.concat(type.getTypes());
        break;
      case 'union:wrapped':
        numWrappedUnions++;
        expanded = expanded.concat(type.getTypes());
        break;
      case 'null':
        expanded.push(type);
        break;
      default:
        isValidWrappedUnion = false;
        expanded.push(type);
    }
  });
  if (numWrappedUnions) {
    if (!isValidWrappedUnion) {
      // It is only valid to combine wrapped unions when no other type is
      // present other than wrapped unions and nulls (otherwise the values of
      // others wouldn't be valid in the resulting union).
      throw new Error('cannot combine wrapped union');
    }
    var branchTypes = {};
    expanded.forEach(function (type) {
      var name = type.getName(true);
      var branchType = branchTypes[name];
      if (!branchType) {
        branchTypes[name] = type;
      } else if (!type.equals(branchType)) {
        throw new Error('inconsistent branch type');
      }
    });
    var wrapUnions = opts.wrapUnions;
    var unionType;
    opts.wrapUnions = true;
    try {
      unionType = createType(Object.keys(branchTypes).map(function (name) {
        return branchTypes[name];
      }), opts);
    } catch (err) {
      opts.wrapUnions = wrapUnions;
      throw err;
    }
    opts.wrapUnions = wrapUnions;
    return unionType;
  }

  // Group types by category, similar to the logic for unwrapped unions.
  var bucketized = {};
  expanded.forEach(function (type) {
    var bucket = getTypeBucket(type);
    var bucketTypes = bucketized[bucket];
    if (!bucketTypes) {
      bucketized[bucket] = bucketTypes = [];
    }
    bucketTypes.push(type);
  });

  // Generate the "augmented" type for each group.
  var buckets = Object.keys(bucketized);
  var augmented = buckets.map(function (bucket) {
    var bucketTypes = bucketized[bucket];
    if (bucketTypes.length === 1) {
      return bucketTypes[0];
    } else {
      switch (bucket) {
        case 'null':
        case 'boolean':
          return bucketTypes[0];
        case 'number':
          return combineNumbers(bucketTypes);
        case 'string':
          return combineStrings(bucketTypes, opts);
        case 'buffer':
          return combineBuffers(bucketTypes, opts);
        case 'array':
          // Remove any sentinel arrays (used when inferring from empty arrays)
          // to avoid making things nullable when they shouldn't be.
          bucketTypes = bucketTypes.filter(function (t) {
            return t !== EMPTY_ARRAY_TYPE;
          });
          if (!bucketTypes.length) {
            // We still don't have a real type, just return the sentinel.
            return EMPTY_ARRAY_TYPE;
          }
          return createType({
            type: 'array',
            items: combine(bucketTypes.map(function (t) {
              return t.getItemsType();
            }))
          }, opts);
        default:
          return combineObjects(bucketTypes, opts);
      }
    }
  });

  if (augmented.length === 1) {
    return augmented[0];
  } else {
    // We return an (unwrapped) union of all augmented types.
    return createType(augmented, opts);
  }
}
198820
function baseTypeStrictlyMatches(left, right) {
    let leftTypes, rightTypes;

    if (t.isIdentifier(left)) {
      leftTypes = customTypeAnnotation(left);
    } else if (t.isIdentifier(right)) {
      rightTypes = customTypeAnnotation(right);
    }

    // Early exit
    if (t.isAnyTypeAnnotation(leftTypes) || t.isAnyTypeAnnotation(rightTypes)) {
      return false;
    }

    leftTypes = [].concat(leftTypes, left.getTypeAnnotation());
    rightTypes = [].concat(rightTypes, right.getTypeAnnotation());

    leftTypes = t.createUnionTypeAnnotation(leftTypes);
    rightTypes = t.createUnionTypeAnnotation(rightTypes);

    if (
      !t.isAnyTypeAnnotation(leftTypes) &&
      t.isFlowBaseAnnotation(leftTypes)
    ) {
      return leftTypes.type === rightTypes.type;
    }
  }
1105404
def basicsize(obj, **opts):
    '''
    '''
    v = _typedefof(obj, **opts)
    if v:
        v = v.base
    return v
1188246
def uniontypes(type_: Type[Any]) -> Set[Type[Any]]:
    '''
    
    '''
    if not is_union(type_):
        raise ValueError('Not a Union: ' + str(type_))

    if hasattr(type_, '__args__'):
        return set(type_.__args__)
    elif hasattr(type_, '__union_params__'):
        return set(type_.__union_params__)
    raise AttributeError('The typing API for this Python version is unknown')