Convert Figma logo to code with AI

google logostarlark-go

Starlark in Go: the Starlark configuration language, implemented in Go

2,301
209
2,301
56

Top Related Projects

Starlark Language

1,187

Skylark in Go: the Skylark configuration language, implemented in Go [MOVED to go.starlark.net]

22,963

a fast, scalable, multi-language and extensible build system

5,227

HCL is the HashiCorp configuration language.

42,146

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.

Quick Overview

Starlark-go is an implementation of the Starlark language in Go. Starlark is a dialect of Python intended for use as a configuration language, designed to be simple, thread-safe, and deterministic. This project provides a Go library for embedding Starlark in Go programs, allowing for dynamic configuration and scripting capabilities.

Pros

  • Familiar Python-like syntax, making it easy for developers to adopt
  • Thread-safe and deterministic execution, ideal for configuration purposes
  • Sandboxed environment, ensuring security when executing untrusted code
  • Extensible with custom Go functions and types

Cons

  • Limited standard library compared to full Python
  • Performance may be slower than native Go code
  • Learning curve for Go developers unfamiliar with Python syntax
  • Lack of dynamic imports, limiting modularity in larger configurations

Code Examples

  1. Basic Starlark execution:
package main

import (
    "fmt"
    "go.starlark.net/starlark"
)

func main() {
    thread := &starlark.Thread{Name: "example"}
    globals, err := starlark.ExecFile(thread, "example.star", `
x = 5
y = 7
print(x + y)
    `, nil)
    if err != nil {
        panic(err)
    }
    fmt.Println(globals["x"], globals["y"])
}
  1. Extending Starlark with Go functions:
package main

import (
    "fmt"
    "go.starlark.net/starlark"
)

func add(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
    var x, y int
    if err := starlark.UnpackArgs(b.Name(), args, kwargs, "x", &x, "y", &y); err != nil {
        return nil, err
    }
    return starlark.MakeInt(x + y), nil
}

func main() {
    thread := &starlark.Thread{Name: "example"}
    predeclared := starlark.StringDict{
        "add": starlark.NewBuiltin("add", add),
    }
    globals, err := starlark.ExecFile(thread, "example.star", `
result = add(x=5, y=7)
print(result)
    `, predeclared)
    if err != nil {
        panic(err)
    }
    fmt.Println(globals["result"])
}
  1. Working with Starlark data structures:
package main

import (
    "fmt"
    "go.starlark.net/starlark"
)

func main() {
    thread := &starlark.Thread{Name: "example"}
    globals, err := starlark.ExecFile(thread, "example.star", `
my_list = [1, 2, 3]
my_dict = {"a": 1, "b": 2}
my_set = set(["x", "y", "z"])
    `, nil)
    if err != nil {
        panic(err)
    }
    fmt.Println(globals["my_list"])
    fmt.Println(globals["my_dict"])
    fmt.Println(globals["my_set"])
}

Getting Started

To use Starlark-go in your Go project:

  1. Install the package:

    go get go.starlark.net/starlark
    
  2. Import the package in your Go code:

    import "go.starlark.net/starlark"
    
  3. Create a Starlark thread and execute Starlark code:

    thread := &starlark.Thread{Name: "example"}
    globals, err := starlark.ExecFile(thread, "example.star", "print('Hello, Starlark!')", nil)
    if err != nil {
        panic(err)
    }
    

Competitor Comparisons

Starlark Language

Pros of Starlark (bazelbuild)

  • More comprehensive documentation and examples
  • Closer integration with Bazel build system
  • Includes additional features like load() for importing modules

Cons of Starlark (bazelbuild)

  • Less frequently updated compared to starlark-go
  • Potentially more complex to use outside of Bazel ecosystem
  • May have some Bazel-specific implementations that are not universally applicable

Code Comparison

starlark-go:

load("@io_bazel_rules_go//go:def.bzl", "go_library")

go_library(
    name = "go_default_library",
    srcs = ["file.go"],
    importpath = "github.com/example/project",
    visibility = ["//visibility:public"],
)

Starlark (bazelbuild):

load("@rules_python//python:defs.bzl", "py_library")

py_library(
    name = "my_library",
    srcs = ["file.py"],
    deps = [
        "//some/other:library",
    ],
)

Both repositories implement the Starlark language, but they have different focuses. starlark-go is a more general-purpose implementation, while Starlark (bazelbuild) is tailored for use with Bazel. The code examples show how they might be used in different contexts, with starlark-go being more Go-centric and Starlark (bazelbuild) being more Python and Bazel-oriented.

1,187

Skylark in Go: the Skylark configuration language, implemented in Go [MOVED to go.starlark.net]

Pros of Skylark

  • Older repository with a longer history of development
  • May have more established community and resources
  • Potentially more stable and battle-tested codebase

Cons of Skylark

  • No longer actively maintained or updated
  • May lack newer features or improvements found in Starlark-go
  • Could have unresolved issues or bugs that won't be addressed

Code Comparison

Skylark:

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

Starlark-go:

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

Summary

Skylark and Starlark-go are closely related projects, with Starlark-go being the successor to Skylark. While Skylark may have a longer history, Starlark-go is the actively maintained version and is recommended for new projects. The syntax and functionality are largely similar, making migration from Skylark to Starlark-go relatively straightforward. Users should consider Starlark-go for ongoing development and support, while existing Skylark implementations may still be functional but lack future updates and improvements.

22,963

a fast, scalable, multi-language and extensible build system

Pros of Bazel

  • Comprehensive build system with advanced features like remote caching and execution
  • Supports multiple programming languages and platforms
  • Large ecosystem with extensive documentation and community support

Cons of Bazel

  • Steeper learning curve and more complex setup compared to Starlark-go
  • Heavier resource usage, especially for smaller projects
  • Can be overkill for simple applications or single-language projects

Code Comparison

Starlark-go (simple function definition):

def greet(name):
    return "Hello, " + name + "!"

Bazel (BUILD file example):

py_binary(
    name = "hello",
    srcs = ["hello.py"],
    main = "hello.py",
)

Summary

Starlark-go is a lightweight implementation of the Starlark language, suitable for embedding in Go programs. It's simpler to use and integrate but lacks the full-featured build system capabilities of Bazel.

Bazel, on the other hand, is a complete build and test tool that uses Starlark as its configuration language. It offers more advanced features and multi-language support but comes with increased complexity and resource requirements.

Choose Starlark-go for simple scripting needs within Go projects, and Bazel for large-scale, multi-language build management.

5,227

HCL is the HashiCorp configuration language.

Pros of HCL

  • Designed specifically for configuration, with a focus on human-readability
  • Native support for complex data structures like maps and lists
  • Extensive use in HashiCorp ecosystem (Terraform, Vault, etc.)

Cons of HCL

  • Less flexible as a general-purpose language compared to Starlark
  • Limited built-in functions and standard library
  • Steeper learning curve for users not familiar with HashiCorp tools

Code Comparison

HCL:

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = {
    Name = "ExampleInstance"
  }
}

Starlark:

def create_instance(ami, instance_type, name):
    return {
        "ami": ami,
        "instance_type": instance_type,
        "tags": {"Name": name},
    }

example = create_instance("ami-0c55b159cbfafe1f0", "t2.micro", "ExampleInstance")

Both HCL and Starlark serve different purposes. HCL is tailored for configuration management, particularly in the HashiCorp ecosystem, while Starlark is a more versatile scripting language designed for extensibility in various applications. The choice between them depends on the specific use case and integration requirements of your project.

42,146

Terraform enables you to safely and predictably create, change, and improve infrastructure. It is a source-available tool that codifies APIs into declarative configuration files that can be shared amongst team members, treated as code, edited, reviewed, and versioned.

Pros of Terraform

  • Comprehensive infrastructure-as-code solution for managing cloud resources
  • Large ecosystem with extensive provider support for various cloud platforms
  • Powerful state management and resource dependency handling

Cons of Terraform

  • Steeper learning curve due to its domain-specific language (HCL)
  • More complex setup and configuration compared to Starlark's simplicity
  • Heavier resource footprint and slower execution for large infrastructures

Code Comparison

Terraform (HCL):

resource "aws_instance" "example" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
}

Starlark:

def create_instance(ami, instance_type):
    return aws.instance(
        ami=ami,
        instance_type=instance_type
    )

Summary

Terraform is a powerful infrastructure-as-code tool with broad cloud provider support, while Starlark is a simpler, more flexible configuration language. Terraform excels in managing complex cloud resources but has a steeper learning curve. Starlark offers a more familiar Python-like syntax and is easier to integrate into existing systems, but lacks the comprehensive infrastructure management features of Terraform. The choice between them depends on the specific needs of your project and the complexity of your infrastructure requirements.

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

Starlark in Go

Go Tests Go Reference

This is the home of the Starlark in Go project. Starlark in Go is an interpreter for Starlark, implemented in Go. Starlark was formerly known as Skylark. The new import path for Go packages is "go.starlark.net/starlark".

Starlark is a dialect of Python intended for use as a configuration language. Like Python, it is an untyped dynamic language with high-level data types, first-class functions with lexical scope, and garbage collection. Unlike CPython, independent Starlark threads execute in parallel, so Starlark workloads scale well on parallel machines. Starlark is a small and simple language with a familiar and highly readable syntax. You can use it as an expressive notation for structured data, defining functions to eliminate repetition, or you can use it to add scripting capabilities to an existing application.

A Starlark interpreter is typically embedded within a larger application, and the application may define additional domain-specific functions and data types beyond those provided by the core language. For example, Starlark was originally developed for the Bazel build tool. Bazel uses Starlark as the notation both for its BUILD files (like Makefiles, these declare the executables, libraries, and tests in a directory) and for its macro language, through which Bazel is extended with custom logic to support new languages and compilers.

Documentation

Getting started

Build the code:

# check out the code and dependencies,
# and install interpreter in $GOPATH/bin
$ go install go.starlark.net/cmd/starlark@latest

Run the interpreter:

$ cat coins.star
coins = {
  'dime': 10,
  'nickel': 5,
  'penny': 1,
  'quarter': 25,
}
print('By name:\t' + ', '.join(sorted(coins.keys())))
print('By value:\t' + ', '.join(sorted(coins.keys(), key=coins.get)))

$ starlark coins.star
By name:	dime, nickel, penny, quarter
By value:	penny, nickel, dime, quarter

Interact with the read-eval-print loop (REPL):

$ starlark
>>> def fibonacci(n):
...    res = list(range(n))
...    for i in res[2:]:
...        res[i] = res[i-2] + res[i-1]
...    return res
...
>>> fibonacci(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>>

When you have finished, type Ctrl-D to close the REPL's input stream.

Embed the interpreter in your Go program:

import "go.starlark.net/starlark"

// Execute Starlark program in a file.
thread := &starlark.Thread{Name: "my thread"}
globals, err := starlark.ExecFile(thread, "fibonacci.star", nil, nil)
if err != nil { ... }

// Retrieve a module global.
fibonacci := globals["fibonacci"]

// Call Starlark function from Go.
v, err := starlark.Call(thread, fibonacci, starlark.Tuple{starlark.MakeInt(10)}, nil)
if err != nil { ... }
fmt.Printf("fibonacci(10) = %v\n", v) // fibonacci(10) = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

See starlark/example_test.go for more examples.

Contributing

We welcome submissions but please let us know what you're working on if you want to change or add to the Starlark repository.

Before undertaking to write something new for the Starlark project, please file an issue or claim an existing issue. All significant changes to the language or to the interpreter's Go API must be discussed before they can be accepted. This gives all participants a chance to validate the design and to avoid duplication of effort.

Despite some differences, the Go implementation of Starlark strives to match the behavior of the Java implementation used by Bazel and maintained by the Bazel team. For that reason, proposals to change the language itself should generally be directed to the Starlark site, not to the maintainers of this project. Only once there is consensus that a language change is desirable may its Go implementation proceed.

We use GitHub pull requests for contributions.

Please complete Google's contributor license agreement (CLA) before sending your first change to the project. If you are the copyright holder, you will need to agree to the individual contributor license agreement, which can be completed online. If your organization is the copyright holder, the organization will need to agree to the corporate contributor license agreement. If the copyright holder for your contribution has already completed the agreement in connection with another Google open source project, it does not need to be completed again.

Stability

We reserve the right to make breaking language and API changes at this stage in the project, although we will endeavor to keep them to a minimum. Once the Bazel team has finalized the version 1 language specification, we will be more rigorous with interface stability.

We aim to support the most recent four (go1.x) releases of the Go toolchain. For example, if the latest release is go1.20, we support it along with go1.19, go1.18, and go1.17, but not go1.16.

Credits

Starlark was designed and implemented in Java by Jon Brandvein, Alan Donovan, Laurent Le Brun, Dmitry Lomov, Vladimir Moskva, François-René Rideau, Gergely Svigruha, and Florian Weikert, standing on the shoulders of the Python community. The Go implementation was written by Alan Donovan and Jay Conrod; its scanner was derived from one written by Russ Cox.

Legal

Starlark in Go is Copyright (c) 2018 The Bazel Authors. All rights reserved.

It is provided under a 3-clause BSD license: LICENSE.

Starlark in Go is not an official Google product.