Split out all code into modules.

This commit is contained in:
2023-09-04 01:56:24 -07:00
parent d46ea1e307
commit 128f40bcf4
53 changed files with 119 additions and 81 deletions

10
frontend/build.gradle.kts Normal file
View File

@ -0,0 +1,10 @@
plugins {
pork_module
}
dependencies {
api(project(":ast"))
api(project(":parser"))
implementation(project(":common"))
}

View File

@ -0,0 +1,8 @@
package gay.pizza.pork.frontend
import gay.pizza.pork.parser.CharSource
interface ContentSource {
fun loadAsCharSource(path: String): CharSource
fun stableContentIdentity(path: String): String
}

View File

@ -0,0 +1,23 @@
package gay.pizza.pork.frontend
import gay.pizza.pork.parser.StringCharSource
import java.nio.file.Path
import kotlin.io.path.absolutePathString
import kotlin.io.path.readText
class FsContentSource(val root: Path) : ContentSource {
override fun loadAsCharSource(path: String): gay.pizza.pork.parser.CharSource =
StringCharSource(asFsPath(path).readText())
override fun stableContentIdentity(path: String): String =
asFsPath(path).absolutePathString()
private fun asFsPath(path: String): Path {
val fsPath = root.resolve(path)
val absoluteRootPath = root.absolutePathString() + root.fileSystem.separator
if (!fsPath.absolutePathString().startsWith(absoluteRootPath)) {
throw RuntimeException("Unable to load path outside of the root: $fsPath (root is ${root})")
}
return fsPath
}
}

View File

@ -0,0 +1,41 @@
package gay.pizza.pork.frontend
import gay.pizza.pork.ast.CompilationUnit
import gay.pizza.pork.ast.ImportDeclaration
import gay.pizza.pork.parser.Parser
import gay.pizza.pork.parser.TokenStreamSource
import gay.pizza.pork.parser.Tokenizer
class World(val contentSource: ContentSource) {
private val units = mutableMapOf<String, CompilationUnit>()
private fun loadOneUnit(path: String): CompilationUnit {
val stableIdentity = contentSource.stableContentIdentity(path)
val cached = units[stableIdentity]
if (cached != null) {
return cached
}
val charSource = contentSource.loadAsCharSource(path)
val tokenizer = Tokenizer(charSource)
val tokenStream = tokenizer.tokenize()
val parser = Parser(TokenStreamSource(tokenStream), gay.pizza.pork.parser.DiscardNodeAttribution)
return parser.readCompilationUnit()
}
private fun resolveAllImports(unit: CompilationUnit): Set<CompilationUnit> {
val units = mutableSetOf<CompilationUnit>()
for (declaration in unit.declarations.filterIsInstance<ImportDeclaration>()) {
val importedUnit = loadOneUnit(declaration.path.text)
units.add(importedUnit)
}
return units
}
fun load(path: String): CompilationUnit {
val unit = loadOneUnit(path)
resolveAllImports(unit)
return unit
}
fun units(path: String): Set<CompilationUnit> = resolveAllImports(loadOneUnit(path))
}