A funny project to help you test your BNF syntax

Overview

Readme

The idea of this project is to implement a BNF expression compiler.

We could use BNF to design some syntax like Arithmetic expression.

<factor> ::= <int> | "(" <expr> ")"
<int> ::= [0-9]+
<term> ::= <factor> (("*" | "/" ) <factor>)*
<expr> ::= <term> (("+" | "-") <term>)*

It matches any simple arithmetic expression such as

68/(8*((34+3+89)))
9*(94*57)/9*30-5*9-48+(557)

However, You have to write your interpreter.

So I was thinking, It probably exciting to write a compiler for the BNF expression, and that's it.

Here is the syntax list for BNF

<text> ::= ([a-z] | [0-9] | "*" | "/" | "+" | "-" | "(" | ")")+
<quantifier> ::= "?" | "+" | "*"
<exp_name> ::= "<" <text> ">"
<var> ::= "\"" <text> "\""
<var_group> ::= "[" <text> "-" <text> "]"
<factor> ::= <var> | <exp_name> | <var_group> | "(" <exp_list> ")"
<exp> ::= <factor> <quantifier>?
<exp_list> ::= <exp> "|"? <exp_list> | <exp>
<declaration> ::= <exp_name> "::=" <exp_list>
<program> ::= <declaration> <program> | <declaration>

I turned the syntax to an AST (abstract syntax tree) and converted the AST to NFA. So we could allow you to design your syntax.

Here is the test case for arithmetic expression

@Test
fun testNFASearch() {
    val text = """
    <int> ::= [0-9]+
    <factor> ::= <int> | "(" <expr> ")"
    <term> ::= <factor> (("*" | "/" ) <factor>)*
    <expr> ::= <term> (("+" | "-") <term>)*
    """.trimIndent()
    //Initial the NFA symbol table.
    val symbolTableNodeVisitor = SymbolTableNodeVisitor(ExpressionParser(Lexer(text)))
    symbolTableNodeVisitor.visitNode()
    val symbolTable = symbolTableNodeVisitor.getSymbolTable()

    val nodeVisitor = NFANodeVisitor(symbolTable, ExpressionParser(Lexer(text)))
    val programNode = nodeVisitor.visitNode()
    val subProgram = programNode.getSubProgram("expr")
    val matcher = NFAEngine(subProgram)
    val str =
        "(((1+660)/8313)-((((5*(4*6))/6)-27/25981/9)+6*5-7)*(((26)/2-5+(5414-267)))/((648))/((4)/46)-71)*0+(925)/(66)"
    val pathList = matcher.search(str)
    for (path in pathList) {
        val subStr = str.substring(path.start, path.end)
        println(subStr + " Matcher:" + path.state.matcher)
    }
    val path = pathList.last()
    Assertions.assertEquals(path.end, str.length)
}

We can use this engine to track or match any text by using your syntax.

Here are some pictures that I turned the AST to NFA

image image image image

Test cases

How I design the quantifiers

  • For symbol '+'
[0-9]+

image

  • For symbol '*'
[0-9]*

image

  • For symbol '?'
[0-9]?

image

About Dot

I use the class: DotGenerator help me to generate the dot file.

digraph astgraph {
  node [fontsize=36, height=1];rankdir = "LR";labelloc = "t";label = "dot_expression1";
	node0 [label = "program"]
	node0 -> node1
	node1 [label = "int"]
	node1 -> node2
	node2 [label = "ε-0"]
	node2 -> node3
	node3 [label = "text<ab>"]
	node3 -> node4
	node4 [label = "ε-1"]
	node4 -> node5
	node5 [label = "range<0-9>"]
	node5 -> node6
	node6 [label = "ε-2"]
	node6 -> node4
	node6 -> node7
	node4 [label = "ε-1"]
	node7 [label = "ε-3"]
	node7 -> node8
	node8 [label = "text<c>"]
	node8 -> node9
	node9 [label = "ε-4"]
	node9 -> node10
	node10 [label = "END"]
}

You can download the IDEA plugin: dot-plugin or use the website: GraphvizOnline to visualize the graph.

References

You might also like...
A project that takes advantage of docker and makes the load test easier

Performance Test It's a project that takes advantage of docker and makes the load test easier. Also, it collects metrics from each running container.

This is a template to help you get started building amazing Kotlin applications and libraries.

Welcome to the Starter This is a template to help you get started building amazing Kotlin applications and libraries. Over time, examples will be comp

A toy port scanner to help me (and you!) learn Kotlin + Akka.

kotlin-akka-portscan A toy program to help me (and you!) learn Kotlin + Akka. butwhy.gif When I want to learn a new language, I've found it helpful to

BindsAdapter is an Android library to help you create and maintain Adapter class easier via ksp( Kotlin Symbol Processing).

BindsAdapter BindsAdapter is an Android library to help you create and maintain Adapter class easier via ksp( Kotlin Symbol Processing). Installation

Backend aio - A project made to help all newbie programmers that are approaching backend development

BackendAIO A ktor based ready to use backend BackendAIO is a project made to hel

An Android template you can use to build your project with gradle kotlin dsl

Android Gradle KTS An Android template you can use to build your project with gradle kotlin dsl Build.gradle.kts You can use your project's build.grad

Simple view which allow you to customise your pizza's toppings and size as per your choice.
Simple view which allow you to customise your pizza's toppings and size as per your choice.

TwistedPizzaToppingsView Overview Simple view which allows options to customize your pizza toppings and size as per your choice. Features Android 12 s

Binding your extras more easier, more simpler for your Android project

Ktan Ktan make your intent / arguments more easier and readable. And most important, will help you bind all extras for your activity / fragment. And a

Sample demonstrates use of Flow, StateFlow & how we can test Flow

FlowSample This sample demonstrates use of Flow, StateFlow & how we can test Flow. In Kotlin, Coroutine is just the scheduler part of RxJava but now w

Owner
Jack Chen
Jack Chen
Kotlin-koans - Kotlin Koans are a series of exercises to get you familiar with the Kotlin Syntax

kotlin-koans-edu Kotlin Koans are a series of exercises to get you familiar with

null 1 Jan 11, 2022
A very simple Android app which shows you random memes with the help of meme-api which you can share with your friends!

Meme Share A very simple Android app which shows you random memes with the help of meme-api which you can share with your friends! Tech stack 100% wri

Stɑrry Shivɑm 8 Aug 10, 2022
Scala 3 Standard Library with bracket syntax.

Scala 3 Library with braces Scala adds a terrible new feature, optional braces, which allow use indentation instead of braces. The new syntax is widel

Glavo 10 Dec 30, 2021
An introductory dynamics to Test Driven Development (TDD)An introductory dynamics to Test Driven Development (TDD)

tdd-demo Nesse hands-on teremos uma dinâmica introdutória a Test Driven Development (TDD), ou desenvolvimento orientado por testes. instruções 1 - Clo

Plataforma Impact 1 Jan 15, 2022
Gha-central-test - GitHub Actions Maven Central Test

GitHub Actions Maven Central Test Pushing a tag does a release. Local Maven Depl

James Ward 1 Jan 19, 2022
A sample Music Player project that help you learn about Compose in Android

Music App Compose UI A sample Music Player project that help you learn about Compose in Android. Note that this app only contain UI and has no logic.

Hamidreza Sahraei 25 Dec 13, 2022
LinkHub is a simple and effective link management application that can help you to easily manage your app with no ads!

LinkHub LinkHub is a simple and effective link management application that can help you to easily manage your own links with no ads! Download Screensh

Amr Hesham 71 Dec 17, 2022
Simple FOSS android app to help you plan and manage your savings goals easily and establish the habit of saving money.

GreenStash GreenStash is a simple FOSS android app to help you plan and manage your savings goals easily and establish the habit of saving money. ?? S

Pool-Of-Tears 112 Dec 3, 2022
To help to promote your android app by prompting users to rate your app in a bottom Sheet.

RateBottomSheet This an Android library to help to promote your Android App by prompting users to rate your app in the Google Play Store with a materi

Farham Hosseini 5 Jul 8, 2022
sample project that shows you how you can use Ktor to creat a server for real Project.

Ktor-Sample This is a sample project that shows you how you can use Ktor to creat a server for real Project. What is done Save data to database (Get a

Mohamed Emad 4 Dec 23, 2022