constrained_parameter.carbon 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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: %{executable_semantics} %s 2>&1 | \
  6. // RUN: %{FileCheck} --match-full-lines --allow-unused-prefixes=false %s
  7. // RUN: %{executable_semantics} --parser_debug --trace_file=- %s 2>&1 | \
  8. // RUN: %{FileCheck} --match-full-lines --allow-unused-prefixes %s
  9. // AUTOUPDATE: %{executable_semantics} %s
  10. // CHECK: result: 0
  11. package ExecutableSemanticsTest api;
  12. interface AddMul {
  13. fn Add[me: Self](o: Self) -> Self;
  14. fn Mul[me: Self](o: Self) -> Self;
  15. }
  16. external impl i32 as AddMul {
  17. fn Add[me: i32](o: i32) -> i32 {
  18. return me + o;
  19. }
  20. fn Mul[me: i32](o: i32) -> i32 {
  21. return me * o;
  22. }
  23. }
  24. class Holder(T:! AddMul) {
  25. var v: T;
  26. }
  27. interface Vector(Scalar:! AddMul) {
  28. fn Zero() -> Self;
  29. fn Add[me: Self](b: Self) -> Self;
  30. fn Scale[me: Self](v: Scalar) -> Self;
  31. fn Hold[me: Self](v: Scalar) -> Holder(Scalar);
  32. }
  33. class Point {
  34. var x: i32;
  35. var y: i32;
  36. impl Point as Vector(i32) {
  37. fn Zero() -> Point {
  38. return {.x = 0, .y = 0};
  39. }
  40. fn Add[me: Point](b: Point) -> Point {
  41. return {.x = me.x + b.x, .y = me.y + b.y};
  42. }
  43. fn Scale[me: Point](v: i32) -> Point {
  44. return {.x = me.x * v, .y = me.y * v};
  45. }
  46. fn Hold[me: Point](v: i32) -> Holder(i32) {
  47. return {.v = v};
  48. }
  49. }
  50. }
  51. fn AddAndScaleGeneric[T:! AddMul, U:! Vector(T)](a: U, s: T) -> U {
  52. return a.Add(U.Zero()).Scale(a.Hold(s).v);
  53. }
  54. fn Main() -> i32 {
  55. var a: Point = {.x = 2, .y = 1};
  56. var p: Point = AddAndScaleGeneric(a, 5);
  57. return p.x - 10;
  58. }