Convert Figma logo to code with AI

bouk logomonkey

Monkey patching in Go

3,339
370
3,339
2

Quick Overview

The bouk/monkey repository is a Go library that provides a simple and lightweight implementation of the Monkey programming language. Monkey is a dynamically-typed, interpreted language with a syntax inspired by languages like JavaScript and Ruby.

Pros

  • Simplicity: The Monkey language and its implementation in this library are designed to be straightforward and easy to understand, making it a great learning resource for those interested in programming language design.
  • Extensibility: The library is designed to be modular and extensible, allowing developers to easily add new features or modify existing ones.
  • Educational Value: The project serves as a valuable educational resource for those interested in understanding the inner workings of programming languages and interpreters.
  • Portability: The library is written in Go, which is a cross-platform language, making the Monkey interpreter easily deployable on various operating systems.

Cons

  • Limited Features: As a relatively simple language, Monkey may lack some of the more advanced features found in other programming languages, which could limit its practical applications.
  • Lack of Documentation: The project's documentation, while present, could be more comprehensive and user-friendly, making it potentially challenging for newcomers to get started.
  • Niche Audience: As a relatively obscure language, Monkey may not have a large and active community, which could make it difficult to find support or resources for learning and development.
  • Performance Concerns: Interpreted languages like Monkey may not be as performant as compiled languages, which could be a concern for certain use cases.

Code Examples

Here are a few examples of how to use the bouk/monkey library:

  1. Evaluating a Simple Expression:
package main

import (
    "fmt"
    "github.com/bouk/monkey/ast"
    "github.com/bouk/monkey/lexer"
    "github.com/bouk/monkey/parser"
)

func main() {
    input := "5 + 5;"
    l := lexer.New(input)
    p := parser.New(l)
    program := p.ParseProgram()

    if len(p.Errors()) != 0 {
        fmt.Println(p.Errors())
        return
    }

    evaluated := Eval(program)
    fmt.Println(evaluated)
}

func Eval(node ast.Node) object.Object {
    // Implement the evaluation logic here
}
  1. Defining a Custom Function:
package main

import (
    "fmt"
    "github.com/bouk/monkey/ast"
    "github.com/bouk/monkey/lexer"
    "github.com/bouk/monkey/object"
    "github.com/bouk/monkey/parser"
)

func main() {
    input := `
        let square = fn(x) { x * x; };
        square(5);
    `
    l := lexer.New(input)
    p := parser.New(l)
    program := p.ParseProgram()

    if len(p.Errors()) != 0 {
        fmt.Println(p.Errors())
        return
    }

    evaluated := Eval(program)
    fmt.Println(evaluated)
}

func Eval(node ast.Node) object.Object {
    // Implement the evaluation logic here
}
  1. Handling Errors:
package main

import (
    "fmt"
    "github.com/bouk/monkey/ast"
    "github.com/bouk/monkey/lexer"
    "github.com/bouk/monkey/object"
    "github.com/bouk/monkey/parser"
)

func main() {
    input := `
        let x = 5 + "foo";
    `
    l := lexer.New(input)
    p := parser.New(l)
    program := p.ParseProgram()

    if len(p.Errors()) != 0 {
        fmt.Println(p.Errors())
        return
    }

    evaluated := Eval(program)
    fmt.Println(evaluated)
}

func Eval(node ast.Node) object.Object {

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Go monkeypatching :monkey_face: :monkey:

Actual arbitrary monkeypatching for Go. Yes really.

Read this blogpost for an explanation on how it works: https://bou.ke/blog/monkey-patching-in-go/

I thought that monkeypatching in Go is impossible?

It's not possible through regular language constructs, but we can always bend computers to our will! Monkey implements monkeypatching by rewriting the running executable at runtime and inserting a jump to the function you want called instead. This is as unsafe as it sounds and I don't recommend anyone do it outside of a testing environment.

Make sure you read the notes at the bottom of the README if you intend to use this library.

Using monkey

Monkey's API is very simple and straightfoward. Call monkey.Patch(<target function>, <replacement function>) to replace a function. For example:

package main

import (
	"fmt"
	"os"
	"strings"

	"bou.ke/monkey"
)

func main() {
	monkey.Patch(fmt.Println, func(a ...interface{}) (n int, err error) {
		s := make([]interface{}, len(a))
		for i, v := range a {
			s[i] = strings.Replace(fmt.Sprint(v), "hell", "*bleep*", -1)
		}
		return fmt.Fprintln(os.Stdout, s...)
	})
	fmt.Println("what the hell?") // what the *bleep*?
}

You can then call monkey.Unpatch(<target function>) to unpatch the method again. The replacement function can be any function value, whether it's anonymous, bound or otherwise.

If you want to patch an instance method you need to use monkey.PatchInstanceMethod(<type>, <name>, <replacement>). You get the type by using reflect.TypeOf, and your replacement function simply takes the instance as the first argument. To disable all network connections, you can do as follows for example:

package main

import (
	"fmt"
	"net"
	"net/http"
	"reflect"

	"bou.ke/monkey"
)

func main() {
	var d *net.Dialer // Has to be a pointer to because `Dial` has a pointer receiver
	monkey.PatchInstanceMethod(reflect.TypeOf(d), "Dial", func(_ *net.Dialer, _, _ string) (net.Conn, error) {
		return nil, fmt.Errorf("no dialing allowed")
	})
	_, err := http.Get("http://google.com")
	fmt.Println(err) // Get http://google.com: no dialing allowed
}

Note that patching the method for just one instance is currently not possible, PatchInstanceMethod will patch it for all instances. Don't bother trying monkey.Patch(instance.Method, replacement), it won't work. monkey.UnpatchInstanceMethod(<type>, <name>) will undo PatchInstanceMethod.

If you want to remove all currently applied monkeypatches simply call monkey.UnpatchAll. This could be useful in a test teardown function.

If you want to call the original function from within the replacement you need to use a monkey.PatchGuard. A patchguard allows you to easily remove and restore the patch so you can call the original function. For example:

package main

import (
	"fmt"
	"net/http"
	"reflect"
	"strings"

	"bou.ke/monkey"
)

func main() {
	var guard *monkey.PatchGuard
	guard = monkey.PatchInstanceMethod(reflect.TypeOf(http.DefaultClient), "Get", func(c *http.Client, url string) (*http.Response, error) {
		guard.Unpatch()
		defer guard.Restore()

		if !strings.HasPrefix(url, "https://") {
			return nil, fmt.Errorf("only https requests allowed")
		}

		return c.Get(url)
	})

	_, err := http.Get("http://google.com")
	fmt.Println(err) // only https requests allowed
	resp, err := http.Get("https://google.com")
	fmt.Println(resp.Status, err) // 200 OK <nil>
}

Notes

  1. Monkey sometimes fails to patch a function if inlining is enabled. Try running your tests with inlining disabled, for example: go test -gcflags=-l. The same command line argument can also be used for build.
  2. Monkey won't work on some security-oriented operating system that don't allow memory pages to be both write and execute at the same time. With the current approach there's not really a reliable fix for this.
  3. Monkey is not threadsafe. Or any kind of safe.
  4. I've tested monkey on OSX 10.10.2 and Ubuntu 14.04. It should work on any unix-based x86 or x86-64 system.

© Bouke van der Bijl