param_impl_with_self.carbon 1.3 KB

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