mirror of
https://github.com/DanilaFe/abacus
synced 2026-09-22 03:12:33 +00:00
Rewrite the parsing interfaces in Kotlin.
This commit is contained in:
24
core/src/main/kotlin/org/nwapw/abacus/parsing/Parser.kt
Normal file
24
core/src/main/kotlin/org/nwapw/abacus/parsing/Parser.kt
Normal file
@@ -0,0 +1,24 @@
|
||||
package org.nwapw.abacus.parsing
|
||||
|
||||
import org.nwapw.abacus.tree.TreeNode
|
||||
|
||||
/**
|
||||
* Converter from tokens into a parse tree.
|
||||
*
|
||||
* An interface that provides the ability to convert a list of tokens
|
||||
* into a parse tree.
|
||||
*
|
||||
* @param <T> the type of tokens accepted by this parser.
|
||||
*/
|
||||
|
||||
interface Parser<in T> {
|
||||
|
||||
/**
|
||||
* Constructs a tree out of the given tokens.
|
||||
*
|
||||
* @param tokens the tokens to construct a tree from.
|
||||
* @return the constructed tree, or null on error.
|
||||
*/
|
||||
fun constructTree(tokens: List<T>): TreeNode
|
||||
|
||||
}
|
||||
21
core/src/main/kotlin/org/nwapw/abacus/parsing/Tokenizer.kt
Normal file
21
core/src/main/kotlin/org/nwapw/abacus/parsing/Tokenizer.kt
Normal file
@@ -0,0 +1,21 @@
|
||||
package org.nwapw.abacus.parsing
|
||||
|
||||
/**
|
||||
* Converter from string to tokens.
|
||||
*
|
||||
* Interface that converts a string into a list
|
||||
* of tokens of a certain type.
|
||||
*
|
||||
* @param <T> the type of the tokens produced.
|
||||
*/
|
||||
interface Tokenizer<out T> {
|
||||
|
||||
/**
|
||||
* Converts a string into tokens.
|
||||
*
|
||||
* @param string the string to convert.
|
||||
* @return the list of tokens, or null on error.
|
||||
*/
|
||||
fun tokenizeString(string: String): List<T>
|
||||
|
||||
}
|
||||
26
core/src/main/kotlin/org/nwapw/abacus/parsing/TreeBuilder.kt
Normal file
26
core/src/main/kotlin/org/nwapw/abacus/parsing/TreeBuilder.kt
Normal file
@@ -0,0 +1,26 @@
|
||||
package org.nwapw.abacus.parsing
|
||||
|
||||
import org.nwapw.abacus.tree.TreeNode
|
||||
|
||||
/**
|
||||
* Class to combine a [Tokenizer] and a [Parser]
|
||||
*
|
||||
* TreeBuilder class used to piece together a Tokenizer and
|
||||
* Parser of the same kind. This is used to essentially avoid
|
||||
* working with any parameters at all, and the generics
|
||||
* in this class are used only to ensure the tokenizer and parser
|
||||
* are of the same type.
|
||||
*
|
||||
* @param <T> the type of tokens created by the tokenizer and used by the parser.
|
||||
*/
|
||||
class TreeBuilder<T>(private val tokenizer: Tokenizer<T>, private val parser: Parser<T>) {
|
||||
|
||||
/**
|
||||
* Parses the given [string] into a tree.
|
||||
*
|
||||
* @param string the string to parse into a tree.
|
||||
* @return the resulting tree.
|
||||
*/
|
||||
fun fromString(string: String): TreeNode = parser.constructTree(tokenizer.tokenizeString(string))
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user