Convert Figma logo to code with AI

expr-lang logoexpr

Expression language and expression evaluation for Go

6,112
393
6,112
47

Top Related Projects

9,556

A small C compiler

A readable lisp in less than 1k lines of C

6,127

A Small C Compiler

Quick Overview

The expr-lang/expr repository is a programming language that allows users to write and evaluate mathematical expressions. It is designed to be a simple and lightweight language that can be easily integrated into other projects.

Pros

  • Simplicity: The language is designed to be easy to learn and use, with a straightforward syntax and a small set of core features.
  • Flexibility: The language can be used to evaluate a wide range of mathematical expressions, from simple arithmetic to more complex functions and operations.
  • Extensibility: The language is designed to be easily extensible, with the ability to add new functions and operators as needed.
  • Portability: The language is implemented in Rust, which allows it to be easily integrated into a variety of projects and platforms.

Cons

  • Limited Functionality: While the language is designed to be flexible, it may not have the same level of functionality as more complex mathematical programming languages.
  • Lack of Documentation: The project's documentation could be more comprehensive, which may make it more difficult for new users to get started.
  • Niche Use Case: The language is primarily designed for evaluating mathematical expressions, which may limit its usefulness for other types of programming tasks.
  • Potential Performance Issues: Depending on the complexity of the expressions being evaluated, the language may not be as performant as other options.

Code Examples

Here are a few examples of how to use the expr-lang/expr language:

// Evaluate a simple arithmetic expression
let result = expr::eval("2 + 3 * 4").unwrap();
println!("Result: {}", result); // Output: Result: 14

// Use a custom function
expr::register_function("square", |x| x * x);
let result = expr::eval("square(5)").unwrap();
println!("Result: {}", result); // Output: Result: 25

// Evaluate an expression with variables
let mut context = expr::Context::new();
context.set_variable("x", 3.0);
context.set_variable("y", 4.0);
let result = expr::eval_with_context("x * y", &context).unwrap();
println!("Result: {}", result); // Output: Result: 12.0

Getting Started

To get started with the expr-lang/expr language, you can follow these steps:

  1. Install Rust, if you haven't already. You can download it from the official Rust website: https://www.rust-lang.org/tools/install
  2. Clone the expr-lang/expr repository:
    git clone https://github.com/expr-lang/expr.git
    
  3. Navigate to the project directory:
    cd expr
    
  4. Build the project:
    cargo build
    
  5. Run the example code:
    cargo run --example basic
    

This will execute a simple example that evaluates the expression 2 + 3 * 4 and prints the result.

You can also use the expr crate in your own Rust projects by adding it as a dependency in your Cargo.toml file:

[dependencies]
expr = "0.1.0"

Then, you can use the expr crate in your Rust code, as shown in the code examples above.

Competitor Comparisons

9,556

A small C compiler

Pros of chibicc

  • chibicc is a more mature and well-documented project, with a clear and concise codebase.
  • chibicc has a more comprehensive test suite, ensuring better code quality and stability.
  • chibicc supports a wider range of C language features, making it a more robust and feature-rich compiler.

Cons of chibicc

  • chibicc has a more complex and larger codebase, which may be less approachable for beginners.
  • chibicc has a more limited set of target architectures, focusing primarily on x86-64.

Code Comparison

Here's a brief comparison of the code for parsing a simple expression in expr-lang/expr and rui314/chibicc:

expr-lang/expr:

fn parse_expr(input: &str) -> Result<Expr, ParseError> {
    let mut parser = Parser::new(input);
    parser.parse_expr()
}

fn parse_term(parser: &mut Parser) -> Result<Expr, ParseError> {
    let mut expr = parser.parse_primary()?;
    while let Ok(op) = parser.parse_op() {
        let rhs = parser.parse_primary()?;
        expr = Expr::Binary(op, Box::new(expr), Box::new(rhs));
    }
    Ok(expr)
}

rui314/chibicc:

Node *expr(void) {
    Node *node = assign();
    return node;
}

Node *assign(void) {
    Node *node = equality();
    if (consume("="))
        node = new_binary(ND_ASSIGN, node, assign());
    return node;
}

A readable lisp in less than 1k lines of C

Pros of minilisp

  • Smaller codebase and simpler implementation compared to expr-lang/expr
  • Provides a basic Lisp interpreter with a focus on simplicity
  • Includes a REPL (Read-Eval-Print Loop) for interactive development

Cons of minilisp

  • Limited functionality compared to expr-lang/expr, with fewer built-in functions and features
  • May not be as actively maintained or have as large a community as expr-lang/expr
  • Lacks some of the advanced features and flexibility of expr-lang/expr

Code Comparison

Here's a brief comparison of the code for a simple addition function in both projects:

minilisp:

(define (add x y)
  (+ x y))

expr-lang/expr:

fn add(args: &[Expr]) -> Result<Expr, EvalError> {
    let x = try_get_number(&args[0])?;
    let y = try_get_number(&args[1])?;
    Ok(Expr::Number(x + y))
}

The minilisp implementation is more concise and straightforward, while the expr-lang/expr version is more verbose but provides more error handling and flexibility.

6,127

A Small C Compiler

Pros of 8cc

  • 8cc is a complete C compiler, while expr-lang/expr is a domain-specific language for mathematical expressions.
  • 8cc has a more mature and feature-rich codebase, with support for a wider range of C language features.
  • 8cc has been actively maintained for several years, with regular updates and improvements.

Cons of 8cc

  • 8cc is a larger and more complex project, which may make it more difficult to understand and contribute to for newcomers.
  • 8cc is primarily focused on C language support, while expr-lang/expr is designed for a more specific use case.
  • 8cc may have a steeper learning curve for developers who are primarily interested in expression parsing and evaluation.

Code Comparison

Here's a brief comparison of the code for parsing a simple expression in both projects:

expr-lang/expr:

expr_t *expr = expr_parse("2 + 3 * 4");
int result = expr_eval(expr);
printf("Result: %d\n", result); // Output: Result: 14

8cc:

#include <stdio.h>

int main() {
    printf("2 + 3 * 4 = %d\n", 2 + 3 * 4); // Output: 2 + 3 * 4 = 14
    return 0;
}

As you can see, the expr-lang/expr code is more focused on the expression parsing and evaluation, while the 8cc code is a complete C program that performs the calculation directly.

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

Zx logo Expr

[!IMPORTANT] The repository github.com/antonmedv/expr moved to github.com/expr-lang/expr.

test Go Report Card Fuzzing Status GoDoc

Expr is a Go-centric expression language designed to deliver dynamic configurations with unparalleled accuracy, safety, and speed. Expr combines simple syntax with powerful features for ease of use:

// Allow only admins and moderators to moderate comments.
user.Group in ["admin", "moderator"] || user.Id == comment.UserId
// Determine whether the request is in the permitted time window.
request.Time - resource.Age < duration("24h")
// Ensure all tweets are less than 240 characters.
all(tweets, len(.Content) <= 240)

Features

Expr is a safe, fast, and intuitive expression evaluator optimized for the Go language. Here are its standout features:

Safety and Isolation

  • Memory-Safe: Expr is designed with a focus on safety, ensuring that programs do not access unrelated memory or introduce memory vulnerabilities.
  • Side-Effect-Free: Expressions evaluated in Expr only compute outputs from their inputs, ensuring no side-effects that can change state or produce unintended results.
  • Always Terminating: Expr is designed to prevent infinite loops, ensuring that every program will conclude in a reasonable amount of time.

Go Integration

  • Seamless with Go: Integrate Expr into your Go projects without the need to redefine types.

Static Typing

  • Ensures type correctness and prevents runtime type errors.
    out, err := expr.Compile(`name + age`)
    // err: invalid operation + (mismatched types string and int)
    // | name + age
    // | .....^
    

User-Friendly

  • Provides user-friendly error messages to assist with debugging and development.

Flexibility and Utility

  • Rich Operators: Offers a reasonable set of basic operators for a variety of applications.
  • Built-in Functions: Functions like all, none, any, one, filter, and map are provided out-of-the-box.

Performance

  • Optimized for Speed: Expr stands out in its performance, utilizing an optimizing compiler and a bytecode virtual machine. Check out these benchmarks for more details.

Install

go get github.com/expr-lang/expr

Documentation

Examples

Play Online

package main

import (
	"fmt"
	"github.com/expr-lang/expr"
)

func main() {
	env := map[string]interface{}{
		"greet":   "Hello, %v!",
		"names":   []string{"world", "you"},
		"sprintf": fmt.Sprintf,
	}

	code := `sprintf(greet, names[0])`

	program, err := expr.Compile(code, expr.Env(env))
	if err != nil {
		panic(err)
	}

	output, err := expr.Run(program, env)
	if err != nil {
		panic(err)
	}

	fmt.Println(output)
}

Play Online

package main

import (
	"fmt"
	"github.com/expr-lang/expr"
)

type Tweet struct {
	Len int
}

type Env struct {
	Tweets []Tweet
}

func main() {
	code := `all(Tweets, {.Len <= 240})`

	program, err := expr.Compile(code, expr.Env(Env{}))
	if err != nil {
		panic(err)
	}

	env := Env{
		Tweets: []Tweet{{42}, {98}, {69}},
	}
	output, err := expr.Run(program, env)
	if err != nil {
		panic(err)
	}

	fmt.Println(output)
}

Who uses Expr?

  • Google uses Expr as one of its expression languages on the Google Cloud Platform.
  • Uber uses Expr to allow customization of its Uber Eats marketplace.
  • GoDaddy employs Expr for the customization of its GoDaddy Pro product.
  • ByteDance incorporates Expr into its internal business rule engine.
  • Aviasales utilizes Expr as a business rule engine for its flight search engine.
  • Wish.com employs Expr in its decision-making rule engine for the Wish Assistant.
  • Argo integrates Expr into Argo Rollouts and Argo Workflows for Kubernetes.
  • OpenTelemetry integrates Expr into the OpenTelemetry Collector.
  • Philips Labs employs Expr in Tabia, a tool designed to collect insights on their code bases.
  • CrowdSec incorporates Expr into its security automation tool.
  • CoreDNS uses Expr in CoreDNS, which is a DNS server.
  • qiniu implements Expr in its trade systems.
  • Junglee Games uses Expr for its in-house marketing retention tool, Project Audience.
  • Faceit uses Expr to enhance customization of its eSports matchmaking algorithm.
  • Chaos Mesh incorporates Expr into Chaos Mesh, a cloud-native Chaos Engineering platform.
  • Visually.io employs Expr as a business rule engine for its personalization targeting algorithm.
  • Akvorado utilizes Expr to classify exporters and interfaces in network flows.
  • keda.sh uses Expr to allow customization of its Kubernetes-based event-driven autoscaling.
  • Span Digital uses Expr in it's Knowledge Management products.
  • Xiaohongshu combining yaml with Expr for dynamically policies delivery.
  • Melrōse uses Expr to implement its music programming language.
  • Tork integrates Expr into its workflow execution.

Add your company too

License

MIT

NPM DownloadsLast 30 Days