Skip to content
/ expr Public

An expression parser supporting multiple types

License

Notifications You must be signed in to change notification settings

torrentg/expr

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

39 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

expr

An expression parser supporting multiple types.

Key Features:

  • Multiple types (number, bool, datetime, string and error)
  • Memory managed by user (no allocs)
  • Iterator based interface
  • Supporting variables
  • Stateless
  • Expressions can be compiled (RPN stack)
  • Fully compile-time checked syntax
  • Documented grammar
  • Standard C11 code
  • No dependencies

Examples

# Numerical calculations
sin((-1 + 2) * PI)

# Dates
datetrunc(now(), "day")

# Strings
"hi " + upper("bob")  + trim("  !  ")

# Conditionals
ifelse(1 < 5 && length($alphabet) > 25, "case1", "case2")

# Find the missing letter
replace($alphabet, substr($alphabet, 25 - random(0, length($alphabet)), 1), "")

Usage

#include <stdio.h>
#include <string.h>
#include "expr.h"

int main()
{
    yy_token_t data[64] = {0};
    yy_stack_t stack = {.data = data, .reserved = 64};

    const char *txt = "1 + 1";
    yy_token_t result = yy_eval_number(txt, txt + strlen(txt), &stack, NULL, NULL);

    printf("%s = %g\n", txt, result.number_val);
}

Compile previous code using:

gcc -o example example.c expr.c -lm

Build

Follow these steps to compile and run the tests and examples.

make
cd build
tests
calc

Contributors

Name Contribution
Gerard Torrent Initial work
Code maintainer
skeeto Fuzzer analysis (reddit post)

License

This project is licensed under the MIT License - see the LICENSE file for details.