项目作者: tdakkota

项目描述 :
Procedural macro toolbox for Golang.
高级语言: Go
项目地址: git://github.com/tdakkota/gomacro.git
创建时间: 2020-08-10T05:42:25Z
项目社区:https://github.com/tdakkota/gomacro

开源协议:MIT License

下载


gomacro

Go
Documentation
codecov
license

Procedural macro toolbox for Golang.

Install

  1. go get github.com/tdakkota/gomacro

Example

  1. package main
  2. import (
  3. "go/ast"
  4. "io/ioutil"
  5. "os"
  6. builders "github.com/tdakkota/astbuilders"
  7. macro "github.com/tdakkota/gomacro"
  8. "github.com/tdakkota/gomacro/runner"
  9. )
  10. // hello() -> println("Hello, ", "World")
  11. // hello(arg) -> println("Hello, ", arg)
  12. // hello(args...) -> println("Hello, ", args...)
  13. func Macro() macro.Handler {
  14. return macro.OnlyFunction("hello", func(ctx macro.Context, call *ast.CallExpr) error {
  15. args := append([]ast.Expr{builders.StringLit("hello, ")}, call.Args...)
  16. if len(call.Args) == 0 {
  17. args = append(args, builders.StringLit("world"))
  18. }
  19. toReplace := builders.CallName("println", args...)
  20. ctx.Replace(toReplace)
  21. return nil
  22. })
  23. }
  24. const src = `
  25. package main
  26. //procm:use=runme
  27. func main() {
  28. hello()
  29. }
  30. `
  31. func writeTempFile(src string) (string, error) {
  32. f, err := ioutil.TempFile("", "src.*.go")
  33. if err != nil {
  34. return "", err
  35. }
  36. defer f.Close()
  37. _, err = f.WriteString(src)
  38. if err != nil {
  39. return "", err
  40. }
  41. return f.Name(), nil
  42. }
  43. func main() {
  44. srcPath, err := writeTempFile(src)
  45. if err != nil {
  46. panic(err)
  47. }
  48. err = runner.Print(srcPath, os.Stdout, macro.Macros{
  49. "runme": Macro(),
  50. })
  51. if err != nil {
  52. panic(err)
  53. }
  54. }

Output:

  1. package main
  2. //procm:use=runme
  3. func main() {
  4. println("hello, ", "world")
  5. }