example.ml 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. open EvalValue
  2. open Type
  3. class plugin =
  4. object (self)
  5. (**
  6. Prints greeting to stdout.
  7. Takes no arguments, returns Void.
  8. *)
  9. method hello () : value =
  10. print_endline "Hello from plugin";
  11. (*
  12. Plugin architecture requires to return something even for methods typed Void on Haxe side.
  13. Return `null`
  14. *)
  15. vnull
  16. (**
  17. Takes `haxe.macro.Position` and returns a string of that position in the same format used for
  18. compiler errors
  19. *)
  20. method stringify_position (pos:value) : value =
  21. let pos = EvalDecode.decode_pos pos in
  22. let str = Lexer.get_error_pos (Printf.sprintf "%s:%d:") pos in
  23. EvalEncode.encode_string str
  24. (**
  25. Change all static methods named "test" to throw "Hello from plugin".
  26. This is an example how to modify typed syntax tree.
  27. *)
  28. method hijack_static_test () : value =
  29. let compiler = (EvalContext.get_ctx()).curapi in
  30. (**
  31. Add a callback like `haxe.macro.Context.onAfterTyping`
  32. *)
  33. compiler.after_typing (fun haxe_types ->
  34. List.iter
  35. (fun hx_type ->
  36. match hx_type with
  37. | TClassDecl cls ->
  38. List.iter
  39. (fun field ->
  40. match field.cf_name, field.cf_expr with
  41. | "test", Some e ->
  42. let hello = {
  43. eexpr = TConst (TString "Hello from plugin");
  44. etype = (compiler.get_com()).basic.tstring;
  45. epos = Globals.null_pos;
  46. } in
  47. field.cf_expr <- Some { e with eexpr = TThrow hello }
  48. | _ -> ()
  49. )
  50. cls.cl_ordered_statics
  51. | _ -> ()
  52. )
  53. haxe_types
  54. );
  55. vnull
  56. end
  57. ;;
  58. let api = new plugin in
  59. (**
  60. Register our plugin API.
  61. This code is executed upon `eval.vm.Context.loadPlugin` call.
  62. *)
  63. EvalStdLib.StdContext.register [
  64. ("hello", EvalEncode.vfun0 api#hello);
  65. ("stringifyPosition", EvalEncode.vfun1 api#stringify_position);
  66. ("hijackStaticTest", EvalEncode.vfun0 api#hijack_static_test);
  67. ]