Last active
April 3, 2018 23:22
-
-
Save AndyG/bee8744ae18bd5fdd128b6f7a2dfba12 to your computer and use it in GitHub Desktop.
Basic Recursive Parser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Parser(private val rules: List<Rule>) { | |
fun parse(source: CharSequence): List<Node> { | |
val ast = ArrayList<Node>() | |
var mutableSource = source | |
while (mutableSource.isNotEmpty()) { | |
// Find a rule that matches the source. | |
for (rule in rules) { | |
val matcher = rule.pattern.matcher(mutableSource) | |
if (matcher.find()) { | |
// Grab the text that matched the rule. | |
// This looks like **...text...** for the bold rule. | |
val match = matcher.group() | |
// Trim off the part of the source that matches the rule. | |
// This step is why Rules must only match the beginning of the source! | |
mutableSource = mutableSource.subSequence(match.length, mutableSource.length) | |
// Pass the matched text to the rule for further processing. | |
// Then add the generated node to the result. | |
val node = rule.parse(matcher, this) | |
ast.add(node) | |
// We have matched a rule and modified the source. | |
// Start our search for a matching rule from the beginning. | |
break | |
} | |
} | |
} | |
return ast | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment