impl_with_self.carbon 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 Vector {
  13. fn Zero() -> Self;
  14. fn Add[me: Self](b: Self) -> Self;
  15. fn Scale[me: Self](v: i32) -> Self;
  16. }
  17. class Point(T:! Type) {
  18. var x: T;
  19. var y: T;
  20. }
  21. external impl Point(i32) as Vector {
  22. // Allowed: `Self` means `Point(i32)` here.
  23. fn Zero() -> Self {
  24. return {.x = 0, .y = 0};
  25. }
  26. fn Add[me: Self](b: Self) -> Self {
  27. return {.x = me.x + b.x, .y = me.y + b.y};
  28. }
  29. fn Scale[me: Self](v: i32) -> Self {
  30. return {.x = me.x * v, .y = me.y * v};
  31. }
  32. }
  33. fn AddAndScaleGeneric[T:! Vector](a: T, s: i32) -> T {
  34. return a.Add(T.Zero()).Scale(s);
  35. }
  36. fn Main() -> i32 {
  37. var a: Point(i32) = {.x = 2, .y = 1};
  38. var p: Point(i32) = AddAndScaleGeneric(a, 5);
  39. return p.x - 10;
  40. }