lookup_in_rewrite.carbon 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. //
  5. // AUTOUPDATE
  6. package ExplorerTest api;
  7. interface Hashable {
  8. fn Hash[self: Self]() -> i32;
  9. }
  10. class Potato {
  11. impl as Hashable {
  12. fn Hash[self: Self]() -> i32 {
  13. Print("Potato.(Hashable.Hash)");
  14. return 1;
  15. }
  16. }
  17. fn Hash[self: Self]() -> i32 {
  18. Print("Potato.Hash");
  19. return 2;
  20. }
  21. }
  22. interface Maker {
  23. let Result:! Hashable;
  24. fn Make() -> Result;
  25. }
  26. impl i32 as Hashable {
  27. fn Hash[self: Self]() -> i32 {
  28. Print("i32.Hash");
  29. return self;
  30. }
  31. }
  32. fn F[T:! Maker where .Result = i32](x: T) -> i32 {
  33. // OK, can treat T.Make() as an i32.
  34. return T.Make() + 1;
  35. }
  36. fn G[T:! Maker](x: T) -> i32 {
  37. // OK, Potato.(Hashable.Hash), not Potato.Hash.
  38. return T.Make().Hash();
  39. }
  40. fn H[T:! Maker where .Result = Potato](x: T) -> i32 {
  41. // OK, Potato.Hash, not Potato.(Hashable.Hash).
  42. return T.Make().Hash();
  43. }
  44. fn I[T:! Maker where .Result = Potato](x: T) -> i32 {
  45. var p: Potato = {};
  46. // OK, Potato.Hash, not Potato.(Hashable.Hash), even though we know Potato is
  47. // Hashable here.
  48. return p.Hash();
  49. }
  50. class IntFactory {
  51. extend impl as Maker where .Result = i32 {
  52. fn Make() -> i32 { return 0; }
  53. }
  54. }
  55. class PotatoFactory {
  56. extend impl as Maker where .Result = Potato {
  57. fn Make() -> Potato { return {}; }
  58. }
  59. }
  60. fn Main() -> i32 {
  61. var f: IntFactory = {};
  62. var g: PotatoFactory = {};
  63. Print("{0}", F(f));
  64. Print("{0}", G(f));
  65. Print("{0}", G(g));
  66. Print("{0}", H(g));
  67. Print("{0}", I(g));
  68. return 0;
  69. }
  70. // CHECK:STDOUT: 1
  71. // CHECK:STDOUT: i32.Hash
  72. // CHECK:STDOUT: 0
  73. // CHECK:STDOUT: Potato.(Hashable.Hash)
  74. // CHECK:STDOUT: 1
  75. // CHECK:STDOUT: Potato.Hash
  76. // CHECK:STDOUT: 2
  77. // CHECK:STDOUT: Potato.Hash
  78. // CHECK:STDOUT: 2
  79. // CHECK:STDOUT: result: 0