Build Abstract Syntax Trees and tree-walking models quickly in Rust.

Overview

astmaker

Build Abstract Syntax Trees and tree-walking models quickly in Rust.

Example

This example creates an AST for simple math expressions, and an interpreter to evaluate the result:

use astmaker::{ast, model};

#[derive(Debug, Clone, PartialEq)]
pub enum BinOp {
  Add,
  Sub,
  Mul,
  Div,
}

#[derive(Debug, Clone, PartialEq)]
pub enum UnOp {
  Add,
  Sub,
}

ast!{
  location = ();

  pub node Expression =
    | BinOp -> Node<BinaryOperation>
    | UnOp -> Node<UnaryOperation>
    | Num -> Node<Number>
    ;

  pub node BinaryOperation = {
    lhs: Node<Expression>,
    op: BinOp,
    rhs: Node<Expression>,
  }

  pub node UnaryOperation = {
    op: UnOp,
    expr: Node<Expression>,
  }

  pub node Number = {
    value: f64,
  }
}

pub struct Interpreter;

model!{
  for Interpreter -> f64 {
    where Expression => {
      match node.data.as_mut() {
        Expression::BinOp(child_node) => context.visit(child_node),
        Expression::UnOp(child_node) => context.visit(child_node),
        Expression::Num(child_node) => context.visit(child_node),
      }
    },
    where BinaryOperation => {
      let lhs = context.visit(&mut node.data.lhs);
      let rhs = context.visit(&mut node.data.rhs);

      match node.data.op {
        BinOp::Add => lhs + rhs,
        BinOp::Sub => lhs - rhs,
        BinOp::Mul => lhs * rhs,
        BinOp::Div => lhs / rhs,
      }
    },
    where UnaryOperation => {
      let val = context.visit(&mut node.data.expr);

      match node.data.op {
        UnOp::Add => val,
        UnOp::Sub => -val,
      }
    },
    where Number => node.data.value,
  }
}

#[test]
fn eval() {
  let mut tree = Node::new((), Expression::BinOp(
    Node::new((), BinaryOperation {
      lhs: Node::new((), Expression::Num(
        Node::new((), Number { value: 1.0 })
      )),
      op: BinOp::Add,
      rhs: Node::new((), Expression::Num(
        Node::new((), Number { value: 2.0 })
      ))
    })
  ));

  let mut interpreter = Interpreter;

  assert_eq!(interpreter.visit(&mut tree), 3.0);
}

Roadmap

  • πŸ“ Documentation
  • ✨ Generics support
  • ✨ Lifetimes support
  • πŸ‘· Github workflows to build, test & publish crate

License

This project is released under the terms of the MIT License.

You might also like...
πŸ¦€Rust + Large Language Models - Make AI Services Freely and Easily. Inspired by LangChain

llmchain: Modern Data Transformations with LLM πŸ¦€ + Large Language Models, inspired by LangChain. Features Models: LLMs & Chat Models & Embedding Mode

Simple OpenAI CLI wrapper written in Rust, feat. configurable prompts and models

Quick Start git clone https://github.com/ryantinder/ask-rs cd ask cargo install --path . Example ask tell me about the Lockheed Martin SR71 The Loc

A Rust LLaMA project to load, serve and extend LLM models

OpenLLaMA Overview A Rust LLaMA project to load, serve and extend LLM models. Key Objectives Support both GGML and HF(HuggingFace) models Support a st

command line tools for coprolite research (paleontology and archaeology): estimate the producer's body mass based on coprolite diameter by the use of regression models
command line tools for coprolite research (paleontology and archaeology): estimate the producer's body mass based on coprolite diameter by the use of regression models

OVERVIEW OF COPROSIZE coprosize employs power, exponential and cubic regression models allowing to estimate the producer's body mass based on coprolit

Core Fiberplane data models and methods for transforming them (templates, providers, markdown conversion)

fiberplane This repository is a monorepo for Rust code that is used throughout Fiberplane's product. Overview base64uuid - A utility for working with

Striving to create a great Application with full functions of learning languages by ChatGPT, TTS, STT and other awesome AI models
Striving to create a great Application with full functions of learning languages by ChatGPT, TTS, STT and other awesome AI models

Striving to create a great Application with full functions of learning languages by ChatGPT, TTS, STT and other awesome AI models, supports talking, speaking assessment, memorizing words with contexts, Listening test, so on.

Terminal UI to chat with large language models (LLM) using different model backends, and integrations with your favourite editors!
Terminal UI to chat with large language models (LLM) using different model backends, and integrations with your favourite editors!

Oatmeal Terminal UI to chat with large language models (LLM) using different model backends, and integrations with your favourite editors! Overview In

auto-rust is an experimental project that aims to automatically generate Rust code with LLM (Large Language Models) during compilation, utilizing procedural macros.
auto-rust is an experimental project that aims to automatically generate Rust code with LLM (Large Language Models) during compilation, utilizing procedural macros.

Auto Rust auto-rust is an experimental project that aims to automatically generate Rust code with LLM (Large Language Models) during compilation, util

Solving context limits when working with AI LLM models by implementing a "chunkable" attribute on your prompt structs.

Promptize Promptize attempts to solve the issues with context limits when working with AI systems. It allows a user to add an attribute to their struc

Releases(v0.1.1)
Owner
David Delassus
Autodidact Python, Erlang and C developer since 2005, really interested in Artificial Intelligence and Data Science.
David Delassus
Traversal of tree-sitter Trees and any arbitrary tree with a TreeCursor-like interface

tree-sitter-traversal Traversal of tree-sitter Trees and any arbitrary tree with a TreeCursor-like interface. Using cursors, iteration over the tree c

Sebastian Mendez 12 Jan 8, 2023
An abstract, safe, and concise color conversion library for rust nightly This requires the feature adt_const_params

colortypes A type safe color conversion library This crate provides many methods for converting between color types. Everything is implemented abstrac

Jacob 13 Dec 7, 2022
A syntax highlighter for Node powered by Tree Sitter. Written in Rust.

tree-sitter-highlight A syntax highlighter for Node.js powered by Tree Sitter. Written in Rust. Usage The following will output HTML: const treeSitter

Devon Govett 211 Dec 20, 2022
As-tree - Print a list of paths as a tree of paths 🌳

as-tree Print a list of paths as a tree of paths. For example, given: dir1/foo.txt dir1/bar.txt dir2/qux.txt it will print: . β”œβ”€β”€ dir1 β”‚ β”œβ”€β”€ foo.tx

Jake Zimmerman 396 Dec 10, 2022
Quickly build cool CLI apps in Rust.

QuiCLI Quickly build cool CLI apps in Rust. Getting started Read the Getting Started guide! Thanks This is only possible because of all the awesome li

Pascal Hertleif 538 Dec 5, 2022
A tool crate to quickly build rust command line application.

Falsework A tool crate to quickly build rust command line application.

Leon Ding 103 Dec 12, 2022
A fun rust terminal program so you can make Christmas trees!

Xmastree 2021 A fun christmas tree where you can add ornaments! Then, you can export the file into either: a rust file a txt file About Taking a break

Junhao 2 Dec 21, 2021
Memory usage monitor for process trees

gotta-watch-em-all Executes a process with given arguments and monitors, logs when memory usage grows to a new peak. Example: cargo run -- cargo -- bu

Aaron Friel 8 Dec 8, 2022
Build Java applications without fighting your build tool. Drink some espresso.

Espresso Build Java applications without fighting your build tool. Drink some espresso. Features Modern Look & Feel Command line interface inspired by

Hunter LaFaille 5 Apr 2, 2024
Utility library for some Lenovo IdeaPad laptops. Supports IdeaPad Intel and AMD Models (15IIL05 and 15ARE05)

ideapad A Rust utility library for some Lenovo IdeaPad specific functionality. A Fair Warning This crate calls raw ACPI methods, which on the best cas

ALinuxPerson 2 Aug 31, 2022