param_impl_with_self.carbon 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. // RUN: %{explorer-run}
  7. // RUN: %{explorer-run-trace}
  8. // CHECK:STDOUT: result: 0
  9. package ExplorerTest api;
  10. interface Number {
  11. fn Zero() -> Self;
  12. fn Add[self: Self](other: Self) -> Self;
  13. }
  14. class Point(T:! Number) {
  15. var x: T;
  16. var y: T;
  17. }
  18. external impl i32 as Number {
  19. fn Zero() -> i32 { return 0; }
  20. fn Add[self: i32](other: i32) -> i32 { return self + other; }
  21. }
  22. external impl forall [U:! Number] Point(U) as Number {
  23. // Allowed: `Self` means `Point(U)` here.
  24. fn Zero() -> Self { return {.x = U.Zero(), .y = U.Zero() }; }
  25. fn Add[self: Self](other: Self) -> Self {
  26. return {.x = self.x.Add(other.x), .y = self.y.Add(other.y)};
  27. }
  28. }
  29. fn Sum[E:! Number](x: E, y: E) -> E {
  30. var total: E = E.Zero();
  31. total = total.Add(x);
  32. total = total.Add(y);
  33. return total;
  34. }
  35. fn Main() -> i32 {
  36. var p: Point(i32) = {.x = 1, .y = 2};
  37. var q: Point(i32) = {.x = 4, .y = 3};
  38. var r: Point(i32) = Sum(p, q);
  39. return r.x - r.y;
  40. }