procm

package module
v0.0.0-...-e03b1fb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 2, 2020 License: MIT Imports: 0 Imported by: 0

README

procm

Go Documentation codecov license

procedural macros for Go

API is unstable. Work in progress.

Install

go get github.com/tdakkota/procm

Example

Declare eval macro

eval.go

func eval(expr string) (types.TypeAndValue, error) {
	fset := token.NewFileSet()
	pack := types.NewPackage(".", ".")

	return types.Eval(fset, pack, 0, expr)
}

//procm:macro=eval
func Eval(cursor macro.Context, node ast.Node) error {
	if cursor.Pre {
		return nil
	}

	return macro.OnlyFunction("eval", func(ctx macro.Context, call *ast.CallExpr) error {
		for i := range call.Args {
			switch v := call.Args[i].(type) {
			case *ast.BasicLit:
				value, err := eval(v.Value[1 : len(v.Value)-1])
				if err != nil {
					return err
				}

				cursor.Replace(&ast.BasicLit{
					ValuePos: v.Pos(),
					Kind:     token.INT,
					Value:    value.Value.ExactString(),
				})
			}
		}

		return nil
	}).Handle(cursor, node)
}

Input:

eval.go

package main

import "fmt"

//procm:use=eval
func evalTest() {
	n := eval(`
		1 + 1
    `)
	fmt.Print(n)
}

func main() {
	evalTest()
}

Output:

package main

import "fmt"

//procm:use=eval
func evalTest() {
	n := 2

	fmt.Print(n)
}

func main() {
	evalTest()
}

Also

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL