macro

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

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

Go to latest
Published: Oct 25, 2021 License: MIT Imports: 9 Imported by: 1

README

gomacro

Go Documentation codecov license

Procedural macro toolbox for Golang.

Install

go get github.com/tdakkota/gomacro

Example

package main

import (
	"go/ast"
	"io/ioutil"
	"os"

	builders "github.com/tdakkota/astbuilders"
	macro "github.com/tdakkota/gomacro"
	"github.com/tdakkota/gomacro/runner"
)

// hello() -> println("Hello, ", "World")
// hello(arg) -> println("Hello, ", arg)
// hello(args...) -> println("Hello, ", args...)
func Macro() macro.Handler {
	return macro.OnlyFunction("hello", func(ctx macro.Context, call *ast.CallExpr) error {
		args := append([]ast.Expr{builders.StringLit("hello, ")}, call.Args...)
		if len(call.Args) == 0 {
			args = append(args, builders.StringLit("world"))
		}

		toReplace := builders.CallName("println", args...)
		ctx.Replace(toReplace)
		return nil
	})
}

const src = `
package main

//procm:use=runme
func main() {
	hello()
}
`

func writeTempFile(src string) (string, error) {
	f, err := ioutil.TempFile("", "src.*.go")
	if err != nil {
		return "", err
	}
	defer f.Close()

	_, err = f.WriteString(src)
	if err != nil {
		return "", err
	}

	return f.Name(), nil
}

func main() {
	srcPath, err := writeTempFile(src)
	if err != nil {
		panic(err)
	}

	err = runner.Print(srcPath, os.Stdout, macro.Macros{
		"runme": Macro(),
	})
	if err != nil {
		panic(err)
	}
}

Output:

package main        
                            
//procm:use=runme           
func main() {               
	println("hello, ", "world")          
}                           

Documentation

Overview

Package macro contains generic macro execution utilities.

Index

Constants

This section is empty.

Variables

View Source
var ErrStop = errors.New("macro exit")

ErrStop is special error to interrupt AST traversal.

Functions

This section is empty.

Types

type ASTInfo

type ASTInfo struct {
	// Current file.
	File *ast.File
	// Current token set.
	FileSet *token.FileSet
}

ASTInfo contains AST of Go source file.

func (ASTInfo) AddDecls

func (c ASTInfo) AddDecls(decls ...ast.Decl)

AddDecls adds declarations to current file.

func (ASTInfo) AddImports

func (c ASTInfo) AddImports(newImports ...*ast.ImportSpec)

AddImports adds new imports to file. If import already exists AddImports does nothing.

type Context

type Context struct {
	*astutil.Cursor
	Pre     bool
	Delayed Delayed
	Report  func(Report)
	// AST objects.
	ASTInfo
	// Type checker objects.
	TypeInfo
	// Parsed magic comments.
	Pragmas pragma.Pragmas
}

Context is a macro context.

func (Context) Reportf

func (c Context) Reportf(pos token.Pos, format string, args ...interface{})

Reportf reports macro error.

type Delayed

type Delayed map[string]DelayedTypes

Delayed is mapping from macro name to DelayedTypes

func (Delayed) Add

func (d Delayed) Add(pkg *packages.Package)

Add adds type names from package. If declaration have a magic comment, type name will be added.

func (Delayed) AddDecls

func (d Delayed) AddDecls(typesInfo *types.Info, decls []ast.Decl)

AddDecls adds type names from declarations. If declaration have a magic comment, type name will be added.

func (Delayed) AddTypeName

func (d Delayed) AddTypeName(macroName string, typeName *types.TypeName)

AddTypeName adds type name to list.

func (Delayed) Find

func (d Delayed) Find(macroName string, typeName *types.TypeName) bool

Find returns true if given typeName will be changed by macroName.

type DelayedTypes

type DelayedTypes map[string]struct{}

DelayedTypes is a list of types will be changed by macros.

func (DelayedTypes) AddTypeName

func (d DelayedTypes) AddTypeName(typeName *types.TypeName)

AddTypeName adds type name to list.

func (DelayedTypes) Find

func (d DelayedTypes) Find(typeName *types.TypeName) bool

Find returns true if given typeName will be changed by macro.

type Handler

type Handler interface {
	Handle(cursor Context, node ast.Node) error
}

Handler is macro handler.

func OnlyFunction

func OnlyFunction(name string, cb func(ctx Context, call *ast.CallExpr) error) Handler

OnlyFunction filter function call nodes using a name.

type HandlerFunc

type HandlerFunc func(cursor Context, node ast.Node) error

HandlerFunc is type adapter for Handler interface.

func (HandlerFunc) Handle

func (f HandlerFunc) Handle(cursor Context, node ast.Node) error

Handle implements Handler.

type Macros

type Macros map[string]Handler

Macros is name <-> macro handler table.

func (Macros) Get

func (m Macros) Get(names ...string) (result map[string]Handler)

Get returns available macros for given names.

type Report

type Report struct {
	Pos     token.Pos
	Message string
}

Report represents macro error report.

type TypeInfo

type TypeInfo struct {
	// Current package info.
	Package *types.Package
	// Type checker info.
	TypesInfo  *types.Info
	TypesSizes types.Sizes
}

TypeInfo is a type context of current package.

Directories

Path Synopsis
Package derive contains some utilities and helpers to build deriving macros.
Package derive contains some utilities and helpers to build deriving macros.
Package internal contains unexported implementation details of gomacro.
Package internal contains unexported implementation details of gomacro.
loader
Package loader contains Go source loading utilities.
Package loader contains Go source loading utilities.
rewriter
Package rewriter contains Go source rewriting utilities.
Package rewriter contains Go source rewriting utilities.
testutil
Package testutil contains testing utilities.
Package testutil contains testing utilities.
macros
derive/cursor
Package cursor contains derive_binary macro.
Package cursor contains derive_binary macro.
derive/deepcopy
Package deepcopy contains derive_copy macro.
Package deepcopy contains derive_copy macro.
derive/zero
Package zero contains derive_zero macro.
Package zero contains derive_zero macro.
Package pragma contains magic comment parser.
Package pragma contains magic comment parser.
Package runner contains macro runner implementation.
Package runner contains macro runner implementation.

Jump to

Keyboard shortcuts

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