Slime is an interpreter made in Java :)

Overview

Slime

Slime is a node-based interpreter

// Create a space to store things
final Space space = new Space();

// Define the slime interpreter
final Slime slime = new Slime(space);

// Execute
slime.exec(scanner.nextLine());

// Demo tests

// print result of 1 + 1 - (7 + 5)       
slime.exec("print 1 + 1 - (7 + 5)")

Process

The process:

Lexing -  Breaking down into tokens
Parsing - Parsed the tokens
Node Creator - Create a node tree
NodeReader/processor - Read the nodes and process them into result

Variable

Asign a value to a variable (a-zA-Z) characters are allowed.

a = 'The Android Java';

The variable can be a number or a string.

// example inputs

a = 70 + (10 + 20)
        
print a is 100 // true
a = 'The number is ' + a

Print

Use the print method to print a variable or a thing.

// prints value from variable 'a' 
// with value 'The number is 100'

print a
print 50 + (1 + 1) // 52
        
// prints 2.1        
print .1 + 2

Basic Operators

Slime can understand +, -, / and * math operators, is and or boolean operator including braces.

You will have to request the interpreter line by line.


Custom methods

You can also declare your methods!

For that, you will need to create a class that extends SlimeMethods and then do change accordingly, an example:

class MyMethods extends SlimeMethods {
    public void trim(final Object text) {
        System.out.println(String.valueOf(text).trim());
    }
}

Declare a constructor as passing your own SlimeMethods instance as the second parameter.

final Space space = new Space();
final Slime slime = new Slime(space, new MyMethods());

Define

You can also define variable with your own values with slime, you just need to call define(name, expression) or define(name, value) to define a constant.

slime.define("pie", valueOf(Math.PI));
slime.defineConstant("cakes", "50")

Dynamic operators

You can also add a dynamic operator, doing additional things!
For that you have to call setOperator on Slime and pass an operator and the operator handler. This will call the handle(Object, Object) method.
You have to perform any operator and return the result.

// Dynamically adding a boolean operator `<?> is <?>`
slime.setOperator("is", new Operator() {
            @Override
            public Object handle(Object first, Object second) {
                // checks and returns if first == second
                return Objects.equals(valueOf(first), valueOf(second));
            }
        });

slime.exec("a = (70 + (10 + 20)) is 100")
slime.exec("print a"); // prints true

Function

Yeah! You can also add functions!
There are two inbuilt functions named max and min.
To access this feature, you will have to use execBlock as replacement for exec command method.

// creates a variable named cakeName 
// with the value 'Chocolate Cake!'

slime.execBlock("cakeName = 'Chocolate Cake!'");

// prints 'CHOCOLATE CAKE!'
slime.execBlock("print case(cakeName, 'upper')");

// prints 'chocolate cake!'
slime.execBlock("print case(cakeName, 'lower')");

// find the max and  in the args provided
        
// prints the number 7     
slime.execBlock("print max(PI, 7)");

// prints the number 1

slime.execBlock("print min(PI, 7, 1)")

A complicated example to define a function with by calling the method defineFunction(MethodName, Function) on Slime object.

defineFunction("case", new Function() {
                @Override
                public Object handle(ArrayList<Object> parms) {
                    if (parms.size() != 2)
                        throw new IllegalArgumentException("Expected only two parameter!");
                    final Object toCase = parms.get(1);
                    if (toCase == "true" || toCase.equals("lower"))
                        return valueOf(parms.get(0)).toLowerCase();
                    else if (toCase == "false" || toCase.equals("upper"))
                        return valueOf(parms.get(0)).toUpperCase();
                    throw new IllegalArgumentException("Not a valid argument '" + toCase + "'");
                }
            });

This was made to learn.
Feel free to fork and contribute back 🙂
You might also like...

Log analyser / visualiser for Java HotSpot JIT compiler. Inspect inlining decisions, hot methods, bytecode, and assembly. View results in the JavaFX user interface.

JITWatch Log analyser and visualiser for the HotSpot JIT compiler. Video introduction to JITWatch video Slides from my LJC lightning talk on JITWatch

Jan 3, 2023

Java monitoring for the command-line, profiler included

jvmtop is a lightweight console application to monitor all accessible, running jvms on a machine. In a top-like manner, it displays JVM internal metri

Jan 6, 2023

A java agent to generate method mappings to use with the linux `perf` tool

perf-map-agent A java agent to generate /tmp/perf-pid.map files for just-in-time(JIT)-compiled methods for use with the Linux perf tools. Build Make

Jan 1, 2023

PerfJ is a wrapper of linux perf for java programs.

PerfJ is a wrapper of linux perf for java programs.

PerfJ PerfJ is a wrapper of linux perf for java programs. As Brendan Gregg's words In order to profile java programs, you need a profiler that can sam

Jan 2, 2023

OOM diagnostics for Java.

Polarbear A tool to help diagnose OutOfMemoryError conditions. Polarbear helps track down the root cause of OutOfMemoryError exceptions in Java. When

May 14, 2019

Inline raw ASM instructions in Java

asm-inline At first I thought: Oh, I can make an optimization transformer for Proguard And then this happened. Example: public class Test { public

Dec 8, 2022

Some utility classes around java records

record-util Some utility classes around java records On the menu MapTrait Transform any record to a java.util.Map just by implementing the interface M

Apr 6, 2022

Terminal UI JMX (Java management extension) viewer

Terminal UI JMX (Java management extension) viewer

JMXViewer Terminal UI JMX (Java management extension) viewer Usage java -jar jmxviewer.jar [pid] The PID is optional. If it is not provided, the appli

Sep 15, 2022

The Java agent for Apache SkyWalking

Apache SkyWalking Java Agent SkyWalking-Java: The Java Agent for Apache SkyWalking, which provides the native tracing/metrics/logging abilities for Ja

Jan 5, 2023
Owner
Kumaraswamy B G
Kumaraswamy B G
One file java script for visualizing JDK flight recorder execution logs as flamegraphs without any dependencies except Java and a browser.

Flamegraph from JFR logs Simple one file Java script to generate flamegraphs from Java flight recordings without installing Perl and the Brendan Gregg

Billy Sjöberg 17 Oct 2, 2022
JVM Explorer is a Java desktop application for browsing loaded class files inside locally running Java Virtual Machines.

JVM Explorer JVM Explorer is a Java desktop application for browsing loaded class files inside locally running Java Virtual Machines. Features Browse

null 109 Nov 30, 2022
A Java agent that rewrites bytecode to instrument allocation sites

The Allocation Instrumenter is a Java agent written using the java.lang.instrument API and ASM. Each allocation in your Java program is instrumented;

Google 438 Dec 19, 2022
Java memory allocation profiler

Aprof - Java Memory Allocation Profiler What is it? The Aprof project is a Java Memory Allocation Profiler with very low performance impact on profile

Devexperts 211 Dec 15, 2022
Sampling CPU and HEAP profiler for Java featuring AsyncGetCallTrace + perf_events

async-profiler This project is a low overhead sampling profiler for Java that does not suffer from Safepoint bias problem. It features HotSpot-specifi

null 5.8k Jan 3, 2023
BTrace - a safe, dynamic tracing tool for the Java platform

btrace A safe, dynamic tracing tool for the Java platform Version 2.1.0 Quick Summary BTrace is a safe, dynamic tracing tool for the Java platform. BT

btrace.io 5.3k Jan 9, 2023
Fork of tagtraum industries' GCViewer. Tagtraum stopped development in 2008, I aim to improve support for Sun's / Oracle's java 1.6+ garbage collector logs (including G1 collector)

GCViewer 1.36 GCViewer is a little tool that visualizes verbose GC output generated by Sun / Oracle, IBM, HP and BEA Java Virtual Machines. It is free

null 4.1k Jan 4, 2023
Java Agent for Memory Measurements

Overview Jamm provides MemoryMeter, a Java agent for all Java versions to measure actual object memory use including JVM overhead. Use To use MemoryMe

Jonathan Ellis 624 Dec 28, 2022
Get Method Sampling from Java Flight Recorder Dump and convert to FlameGraph compatible format.

Note: Travis has removed the support for Oracle JDK 8. Therefore the build status is removed temporarily. Converting JFR Method Profiling Samples to F

M. Isuru Tharanga Chrishantha Perera 248 Dec 16, 2022
Tool for creating reports from Java Flight Recorder dumps

jfr-report-tool Tool for creating reports from Java Flight Recorder dumps. Influenced by https://github.com/chrishantha/jfr-flame-graph . Kudos to @ch

Lari Hotari 50 Oct 28, 2022