• Stars
    star
    116
  • Rank 303,894 (Top 6 %)
  • Language
    Rust
  • License
    MIT License
  • Created over 3 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A hybrid programming language written in Rust.

boson

An interpreted, dynamically-typed, multi-threaded, general purpose hobby programming language written in Rust.

Check out the live web server written in boson-lang:

To experiment with the capabilities of boson, I wrote a simple TCP single threaded web server which serves a sample HTML document. Check out this URL (The static web server is packaged as a container image and is deployed on Heroku)

Features:

  1. Multiple Data Types: char, int, float, string, array, hashtable, bytes and buffer
  2. Airthmetic, Logical operations
  3. Variables and Constants
  4. Control and Looping structures
  5. Functions and Lambda expressions
  6. Many built-in functions
  7. Threads and Multi-threading
  8. Shell operator to run shell commands within the language statements
  9. Some basic built-in functions
  10. Iterators (psuedo iterators)
  11. Byte code generation, serialization and loading
  12. Dynamic modules - can load rust modules at runtime as addons
  13. System calls

Note: The documentation of this project is still in early stages.

Installation:

Building the language from source requires a working rust toolchain installed on the host machine. Check out the tutorial here to set-up Rust and Cargo.

  1. Grab the source code:
git clone [email protected]:Narasimha1997/boson-lang.git
  1. Build boson:
./build.sh

The build script should install Boson suite of tools on your system. Explore different options supported by this script.

  1. Run sample source code
boson-eval examples/hello.np

This should print hello, world! on screen.

Using the tools

If compilation is successful, it should generate four binary tools, these are:

  1. boson: This is the REPL of boson lang, you can execute boson language statements in the CLI.
Welcome to Boson REPL
This is a REPL binary for boson - a general purpose programming language written in rust. (Ctrl + C to quit)
Boson v0.0.1
VM Check - Passed.
>> println(10 + 20)
30
  1. boson-dis: This tool generates stringified representation of the compiled version of source file.
boson-dis examples/hello.np

This should generate the output:

Instructions: 
00000000 IConstant 0
00000003 ILoadBuiltIn 2
00000006 ICall 1

Constants: 
00000000 hello, world!
  1. boson-compile: This tool generates the compiled bytecode of the source file, which can then be executed.
boson-eval ./examples/hello.np

This should generates a file called hello.np.b in the same folder hello.np was present, i.e examples/hello.np.b. This file has the binary representation of the compiled bytecode.

  1. boson-eval: Evaluates the source file or the bytecode file and stdouts the result.
boson-eval ./examples/hello.np

Language examples:

  1. Hello, world
println('hello,world')
  1. Keyboard input and display
const ip = input()
const ip2 = input();
const greeting = "Hello! " + ip2 + " " + ip;
println(greeting);
  1. Arithmetic operators
const d = a + b + c;
const e = a * b - c;
const f = ((a + b) * c * d) / (a + b);

const g = (a + b) % c;

println(a, b, c, d, e, f, g); # 1 2 3 6 -1 18 0
  1. Bitwise operators
const x = 10;
const y = 20;

var z = ((x & 0) | y);
println(~z) # -21
  1. Logical operators
const m = 10;
const n = 20;

println(m > n, n < m, n > m + 5) # false, false, true
println(m == n - 10, !0, !(m == n - 10)) # true true false
  1. Arrays
var array = [1, 2, 3, 4, "Hello", 6.455]
println(array[0] + 2) # 3
println(array[4] + ", world") # Hello, world
println(array) # Array([1, 2, 3, 4, Hello, 6.455])

array[4] = 9678967;
println(array) # Array([1, 2, 3, 4, 9678967, 6.455])
  1. Hash tables
var myHashMap = {
    "name": "Prasanna",
    "age": 24,
    "country": "India"
}

println(myHashMap) # HashTable({age: 24, country: India, name: Prasanna})
println(myHashMap["age"] + 2) # 26

const key = "name"
println("Hey! " + myHashMap[key]) # Hey! Prasanna

myHashMap["city"] = "Bengaluru"
println(myHashMap["city"]) # Bengaluru
  1. While loop
const N = 100;

var n0 = 0;
var n1 = 1;
var n2 = 0;
var idx = 2;

while (idx <= N ) {
    n2 = n0 + n1;
    n0 = n1;
    n1 = n2;
    idx = idx + 1;
}

println(n1);
  1. If else:
const x = 10;

if (x > 20) {
    println("X > 20");
} else {
    println("X < 20"); # this will be executed
}
  1. Functions:
func fib(N) {
    
    if (N == 0) {
        return 0;
    }

    if (N == 1) {
        return 1;
    }

    return fib(N - 1) + fib(N - 2);
}

const result = fib(10);
println('got result: ', result);
  1. Shell operator:

Shell operator can be used to execute shell commands within the program statements.

# count the number of files in the given directory
func count_files() {
    const res = $ "ls | wc -l";
    return int(res[1]);
}

# call the function and print it's output
println(count_files());

# count the number of occurences of a given pattern in the given file
func count_occurences(file, pattern) {
    const res = $ "cat "+file+" | grep -c "+pattern; 
    return int(res[1])
}

const res = count_occurences("LICENSE", "GPL")
println(res);
  1. Lambda functions:
# define a adder that takes two parameters
const lambda_adder = lambda x, y => x + y
println(lambda_adder(10, 20)) # 30
  1. Functions as objects:
# here the adder function accepts a function as argument and executes it
func adder_exec(fn, x, y) {
    return fn(x, y)
}

# adder function is defined here
func adder(x, y) {
    return x + y
}

# adder function is passed as the parameter
const result = adder_exec(adder, 10, 20)
println(result) # 30
  1. Closures:
# this is the wrapper function that returns a adder function with enclosed local variables
func wrap_adder(x, y) {
    const z = 30
    func adder() {
        return x + y + z
    }

    return adder
}

# call the wrapper and obtain the inner child
const adder = wrap_adder(10, 20)

# call the inner child adder function
const result = adder()
println(result) # result = 60
  1. Iterators:

Note: Iterators are yet to be tested completely

const arr = [1, 2, 3, 4]
const iterator = iter(arr)
while (has_next(iterator)) {
    println(next(iterator))
}
  1. Multithreading:
# this function prints Hello, world from <thread> every 3 seconds 
func print_periodic(name) {
    while (true) {
        println("Hello, world from ", name);
        sleep_sec(3);
    }
}

# spawn thread1 and spawn thread2
const th1 = thread print_periodic("thread1");
const th2 = thread print_periodic("thread2");

# wait for thread 1 and thread 2 to complete
wait(th1)
wait(th2)

Threads and global variables: In boson, every thread gets it's own copy of global variables space, so when a thread mutates a global variable, it mutates it's local variable copy and not the one in global space.

Native modules

Boson has a support for native modules written in Rust, every module has to implement a set of functions as per the standard function signatures shown below:

pub type OpenFunctionSymbol = unsafe extern "Rust" fn(Rc<Object>) -> DynamicModuleResult;
pub type CloseFunctionSymbol = unsafe extern "Rust" fn(Rc<Object>) -> DynamicModuleResult;
pub type ReadFunctionSymbol = unsafe extern "Rust" fn(Rc<Object>) -> DynamicModuleResult;
pub type WriteFunctionSymbol = unsafe extern "Rust" fn(Rc<Object>) -> DynamicModuleResult;
pub type ExecFunctionSymbol = unsafe extern "Rust" fn(String, &Vec<Rc<Object>>) -> DynamicModuleResult;

Any cargo crate that implements these functions can be loaded and used as a dynamic module. Look at the hello-world module for reference. Make sure you add the following lines to Cargo.toml of the cargo crate you are trying to build as a module:

[lib]
crate-type = ["rlib", "cdylib"]

The native modules that are under modules/ directory will be installed at /usr/local/lib/boson and can be loaded using mopen:

# you can pass init parameters also while calling `mopen`
const regex = mopen("std::re", none)[0];

This will look for libre.so in /usr/local/lib/boson, in general it will look at /usr/local/bin/boson/lib{{module-name}}.so. However you can also load modules directly by their file-paths like:

const regex = mopen("/usr/local/lib/boson/libre.so", none)[0];

System calls

System call methods are provided as builtin functions in boson. get_syscalls method returns a list of all the system calls supported on the target architecture and syscall method executes the system call. Look at the example below:

const no = get_syscalls();
const fd = syscall(no.OPEN, "hello.txt", 0)

if (fd < 0) {
    println("file hello.txt not found")
    exit(fd)
}

const buffer = create_buffer(10)

syscall(
    no.READ,
    fd, 
    buffer,
    10
)

println(string(buffer))

Embedding Boson:

Boson language compiler + VM can be easily integrated into other projects using the API. As of now, any Rust codebase can import statically the Boson crate or use foreign function interface (FFI) to load Boson shared library by manually defining the ABI. We are yet to test CXXABI compatibility of the boson crate, so it can be considered unsafe to import boson in Non-Rust codebases as of now.

Here is how you can embed boson in other rust projects:

extern crate boson;

use boson::api::BosonLang;

pub fn main() {
    let result = BosonLang::eval_buffer(
        "10 + 3 / 2"
            .as_bytes()
            .to_vec()
    );

    println!("eval result: {}", result);
    // will output "eval result: Some(Float(11.5))"
}

Running tests

You can use cargo test tools to run the test

cargo test

Benchmarks

Benchmarks are still under implementation

Credits

  1. Monkey lang
  2. Monkey lang rust version

TODO:

  1. Web assembly port
  2. Proper documentation
  3. Proper test cases
  4. Bug fixes

Contributing

Feel free to raise any issues, make Pull Requests, suggest changes, clone the project and make your own changes.

More Repositories

1

fake-sms

A simple command line tool using which you can skip phone number based SMS verification by using a temporary phone number that acts like a proxy.
Go
2,695
star
2

ratelimiter

A concurrent rate limiter library for Golang based on Sliding-Window rate limiter algorithm.
Go
239
star
3

py4jshell

Simulating Log4j Remote Code Execution (RCE) vulnerability in a flask web server using python's logging library with custom formatter that simulates lookup substitution by executing remote exploit code.
Python
86
star
4

r3

A tiny x86_64 kernel written in Rust.
Rust
80
star
5

sig-716i

A CLI tool that can be used to disrupt wireless connectivity in your area by jamming all the wireless devices connected to multiple access points.
Go
79
star
6

MarvinOS

A hobby Operating System developed from scratch using C/C++ and assembly
C
67
star
7

smartreply

Unofficial port of Google's smart reply runtime (powers gmail and assistant) model to python, allowing developers to leverage intelligent smart reply as an API in Web and embedded systems that supports Linux, a loader (ld.so), a fully POSIX C++ Runtime and Python interpreter.
C++
56
star
8

pyMigrate

A tool for automatically migrating any python source code to a virtual environment with all dependencies automatically identified and installed. You can also use this tool to generate requirements.txt for your python code base, in general, this tool will help you to bring your old/hobby python codebase to production/distribution.
Python
52
star
9

rust-kernel-barebones

A minimal 64-bit rust kernel and a bunch of configuration scripts that can be used to bootstrap Operating system development using Nightly-Rust compiler.
Shell
45
star
10

clfu

Implementation of Constant Time LFU (least frequently used) cache in Go with concurrency safety.
Go
38
star
11

tor-proxy

An experimental Tor-Proxy serivce written in Go using Go-proxy and Go-libtor.
Go
35
star
12

gopg

A minimal microservice written in Go that executes Go programs. This microservice can be used to set-up local go learning environment at your workspace/school. You can also use the provided zero-configuration docker-image for quick deployments.
Go
29
star
13

aio-eth

A simple python library that can be used to run large Web3 queries on Ethereum blockchain concurrently as per Ethereum JSON-RPC specification.
Python
28
star
14

pavlos

A light-weight container runtime for Linux with NVIDIA gpu support, allows developers to quicky setup development environments for dev and test. Pavlos can emulate any Linux rootfs image as a container.
Go
26
star
15

wavenet-stt

An end-to-end speech recognition system with Wavenet. Built using C++ and python.
Python
21
star
16

PyThreads

A simple python library that makes creation of threads easier. It makes functions asynchronous with only one extra line of code.
Python
21
star
17

redis-pydict

A python dictionary that uses Redis as in-memory storage backend to facilitate distributed computing applications development.
Python
19
star
18

py_cpu

Python bindings for Google's cpu_features library. Allows python developers to enable hardware specific optimizations at runtime.
C++
19
star
19

bzCompute

bzCompute is a computation graph library with built-in support for domain-decomposition and prallel computation. The library can be used for expressing and executing large number of mathematical and text-processing operations using Data-Flow graphs, (Educational version of tensorflow), written in pure python code with numpy support.
Python
16
star
20

py-smartreply

Python bindings for Google's Smart Reply (AI based chat suggestions) Tensorflow Lite model.
C++
13
star
21

httppool

A simple asynchronous worker pool and concurrent job queue for Golang's HTTP Server, inspired from Node.js asynchronous http server design.
Go
8
star
22

exif_service

A C++ microservice used to extract location and other forensic information from JPEG images.
C++
8
star
23

StackMachine

A simple educational virtual computer machine that can execute simple arithmetic and logical programs, This Virtual Machine has it's own memory model, instruction queue, virtual CPU and a compiler that comes with a parser.
Java
7
star
24

go-cowin

Unofficial GO SDK for Indian Government's Co-WIN API Platform. This SDK helps developers to easily integrate Co-WIN APIs with their existing eco-system.
Go
7
star
25

C-Dict

A tiny library that brings the support of dictionaries to C programming language with a fast lookup using hash tables. dict type can be used to associate large arrays with string keys.
C
7
star
26

bit_vector

A header-only bit vector library for C . This can be used for implementing dynamic bit-vectors for building Bloom-Filters and Hyper-Logs .
C
6
star
27

cc-builder

Live compilation and linking tool for C/C++ projects written in Go.
Go
6
star
28

BloodCell-Identification-tfjs-client

Blood Cell Identification system is a web app built using React and Tensorflow js, The CNN model trained to classify blood cell images using python and is ported to Browser Client using tensorflow model converter.
JavaScript
6
star
29

IronServer

A simple, amazingly fast static web server written in C. Supports faster MIME type resolution and caching.
C
5
star
30

Blood-Cell-type-identification-using-CNN-classifier

Notebook providing solution for kaggle dataset to classify blood cell types (Built using Convolution Neural Network)
Jupyter Notebook
5
star
31

PyQ

A python library for expressing computations using Message passing queues.
Python
4
star
32

socketio-cgi

A cgi layer that allows any process / program to stream data across world wide web.
Go
4
star
33

ptw

A minimal boilerplate for building frontends using Preact, TypeScript and Web Assembly.
JavaScript
4
star
34

dipmp

A decentralized package registry for python built on top of IPFS and Ethereum - using python, solidity and pinata. dipmp can be used with pip.
Python
3
star
35

GroupChat-C

A simple group chat server that one can write using C/C++, with the support of external websocket router.
C
3
star
36

Inception-On-Device-inference

An android application for on-device machine learning using TensorFlow and GoogleNet (Inception v3)
Java
3
star
37

DirtyPointer-Hack

A hackaround on C++ private class members and methods to access them outside the class even though they are private. (GNU GCC compiler, Linux)
C++
3
star
38

encoder-aas

An architecture providing Universal Sentence Encoder as a service by exploiting job-level parallelism of multi-core architectures. The service can be used as a transformer model for downstream NLP and NLU tasks like Language modelling, Sentiment Classification, Question Answering, Semantic Search and more.
Python
3
star
39

packed-encoder

A tiny rust crate that can be used to encode data of different types into a packed byte array which can be passed over network, system calls or FFI.
Rust
3
star
40

VSNET_2

Image-Recognition system using Client(android app) and Server(TensorFlow with Flask) model.
Java
2
star
41

Narasimha1997

My profile README
2
star
42

Sento---Online-Sentiment-Analysis-tool

Sento is a free online sentiment analysis tool .
JavaScript
2
star
43

360Player

A 360 image and Video player based on Google Cardboard Platform, It's just like an example of how to use VrViews in android
Java
2
star
44

pnuemonia_classification_onnx

Pnuemonia classification at scale using ONNX runtime and an inference server with batching support.
Jupyter Notebook
2
star
45

VegAnalytics

A dashboard tool that provides end-to-end solution for local marts and vegetable sellers.
JavaScript
1
star
46

Mark_2

A Django platform to transfer large files between your Phone and your Personal Computer.
Python
1
star
47

FaceRecognition-tool

FaceRecognition is a simple and modular face recognition tool built using OpenFace and face_recognition.
Python
1
star
48

NewsMaster

a react app for real-time news on any device (First stage build)
HTML
1
star
49

GameChanger

Java
1
star
50

Speech-net

Online text-to-speech platform
HTML
1
star
51

ProjectHub

DBMS mini project !
JavaScript
1
star
52

LiteNet

A simple CNN architecture to solve simple computer vision problems.
Python
1
star
53

OS-Development-Tutorial

A step by step, cumulative guide for building an Operating System for x86 and it's variants.
1
star
54

Visualnet

Simple image recognition server using TensorFlow inception v3
Python
1
star
55

Narasimha1997.github.io

JavaScript
1
star
56

FastVideo-transformation

A Python backend architecture for fast video processing by Machine Learning models based on Producer - Consumer model and Message Passing Queues
Python
1
star
57

ObjectCode-Executor

Object code generator and executor built for C, Python program takes C file as input, generates Object code and another C file that executes it.
Python
1
star
58

News-Bot

An artifically intelligent news and weather bot for Facebook messenger
Python
1
star
59

blog

Source tree of my blog
1
star
60

Simple-Service-Broadcast

A simple UDP broadcast protocol used for service discovery in a local network
Python
1
star
61

bls-server

A gRPC server written in python that provides BLS (Boneh–Lynn–Shacham) signatures related functionalities like signing, verification and signatures aggregation - used in production at some places.
Python
1
star
62

klogger

A C++ CLI tool for linux that streams kernel logs and events over a light-weight UDP socket to remote machines. You can use this tool for debugging while developing Linux kernel extensions and custom Linux kernel modules, especially for embedded systems that don't have built-in display. (Cross compile for aarch64 and others).
C++
1
star
63

libIgnition-dev

A byte-stream based File-Encryption library built using Python and C (using Fernet encryption algorithm)
HTML
1
star