generic_with_two_params.carbon 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 Vector {
  11. fn Add[self: Self](b: Self) -> Self;
  12. fn Scale[self: Self](v: i32) -> Self;
  13. }
  14. class Point1 {
  15. var x: i32;
  16. var y: i32;
  17. impl Point1 as Vector {
  18. fn Add[self: Point1](b: Point1) -> Point1 {
  19. return {.x = self.x + b.x, .y = self.y + b.y};
  20. }
  21. fn Scale[self: Point1](v: i32) -> Point1 {
  22. return {.x = self.x * v, .y = self.y * v};
  23. }
  24. }
  25. }
  26. class Point2 {
  27. var x: i32;
  28. var y: i32;
  29. impl Point2 as Vector {
  30. fn Add[self: Point2](b: Point2) -> Point2 {
  31. return {.x = self.x + b.x + 1, .y = self.y + b.y + 1};
  32. }
  33. fn Scale[self: Point2](v: i32) -> Point2 {
  34. return {.x = self.x * v * 2, .y = self.y * v * 2};
  35. }
  36. }
  37. }
  38. fn ScaleGeneric[U:! Vector](c: U, s: i32) -> U {
  39. return c.Scale(s);
  40. }
  41. fn AddAndScaleGeneric[T:! Vector, V:! Vector](a: T, b: V, s: i32) -> (T, V) {
  42. return (ScaleGeneric(a.Add(a), s),
  43. ScaleGeneric(b.Add(b), s));
  44. }
  45. fn Main() -> i32 {
  46. var a: Point1 = {.x = 1, .y = 1};
  47. var b: Point2 = {.x = 2, .y = 3};
  48. var (p: Point1, q: Point2) = AddAndScaleGeneric(a, b, 5);
  49. return q.x - p.x - 40;
  50. }