added flat mapping to symboltable

This commit is contained in:
Irmen de Jong 2022-03-06 18:05:38 +01:00
parent 0a04e626d7
commit 48d782c69c
3 changed files with 25 additions and 4 deletions

View File

@ -26,19 +26,19 @@ internal class SymbolTableMaker: IAstVisitor {
override fun visit(block: Block) {
val node = StNode(block.name, StNodeType.BLOCK, block.position)
st.add(node)
scopestack.push(node)
super.visit(block)
scopestack.pop()
st.add(node)
// st.origAstLinks[block] = node
}
override fun visit(subroutine: Subroutine) {
val node = StNode(subroutine.name, StNodeType.SUBROUTINE, subroutine.position)
scopestack.peek().add(node)
scopestack.push(node)
super.visit(subroutine)
scopestack.pop()
scopestack.peek().add(node)
// st.origAstLinks[subroutine] = node
}

View File

@ -16,10 +16,17 @@ class TestSymbolTable: FunSpec({
st.position shouldBe Position.DUMMY
}
test("symboltable flatten") {
val st = makeSt()
st.flat[listOf("zzzzz")] shouldBe null
st.flat.getValue(listOf("sin")).type shouldBe StNodeType.BUILTINFUNC
st.flat.getValue(listOf("block2")).type shouldBe StNodeType.BLOCK
st.flat.getValue(listOf("block2", "sub2", "subsub", "label")).type shouldBe StNodeType.LABEL
st.flat[listOf("block2", "sub2", "subsub", "label", "zzzz")] shouldBe null
}
test("symboltable global lookups") {
val st = makeSt()
st.print()
st.lookup("undefined") shouldBe null
st.lookup(listOf("undefined")) shouldBe null
var default = st.lookupOrElse("undefined") { StNode("default", StNodeType.LABEL, Position.DUMMY) }

View File

@ -9,6 +9,20 @@ class SymbolTable : StNode("", StNodeType.GLOBAL, Position.DUMMY) {
fun print() = printIndented(0)
override fun printProperties() { }
/**
* The table as a flat mapping of scoped names to the StNode.
* This gives the fastest lookup possible (no need to traverse tree nodes)
*/
val flat: Map<List<String>, StNode> by lazy {
val result = mutableMapOf<List<String>, StNode>()
fun flatten(node: StNode) {
result[node.scopedName] = node
node.children.values.forEach { flatten(it) }
}
children.values.forEach { flatten(it) }
result
}
}