default.carbon 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. package Core library "prelude/default";
  5. import library "prelude/types/bool";
  6. import library "prelude/types/int_literal";
  7. // Provides the default value of an object. If implemented for a type `T`, this
  8. // is used to initialize declarations without an explicit initializer, such as
  9. // `var x: T;`, and leaves them in a fully-formed state.
  10. interface Default { fn Op() -> Self; }
  11. // Indicates that a type permits unformed initialization, which leaves the
  12. // object in a state where calling the destructor is valid but optional, and no
  13. // other operations on the object except for reinitialization are permitted.
  14. interface UnformedInit {
  15. // TODO: This should probably be:
  16. // let StructT:! type;
  17. // fn Op() -> StructT;
  18. // and should be able to initialize a subset of the fields. For now we always
  19. // leave the object uninitialized when it is in an unformed state.
  20. // See https://github.com/carbon-language/carbon-lang/pull/5913
  21. }
  22. // Implementations for some builtin types. These need to be here to satisfy the
  23. // orphan rule because these builtin types have no associated library of their
  24. // own.
  25. impl bool as UnformedInit {}
  26. impl forall [T:! type] T* as UnformedInit {}
  27. impl forall [T:! UnformedInit, N:! IntLiteral()] array(T, N) as UnformedInit {}
  28. // TODO: Generalize these to apply to tuples and structs containing only
  29. // `UnformedInit` types.
  30. impl () as UnformedInit {}
  31. impl {} as UnformedInit {}
  32. // Provides a default, possibly unformed, value of an object. This should not be
  33. // implemented directly. Instead, implement `Default` to provide a fully-formed
  34. // state or (eventually) `UnformedInit` to provide an unformed state.
  35. interface DefaultOrUnformed {
  36. // TODO: This should return `MaybeUnformed(Self)` once that is supported.
  37. fn Op() -> Self;
  38. }
  39. final impl forall [T:! Default] T as DefaultOrUnformed {
  40. fn Op() -> Self {
  41. return T.Op();
  42. }
  43. }
  44. impl forall [T:! UnformedInit] T as DefaultOrUnformed {
  45. fn Op() -> Self = "make_uninitialized";
  46. }