Compare commits
69 Commits
WACC_Back-
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab895940bf | ||
|
9ba0e14eb5
|
|||
|
ab0c91463a
|
|||
| fda4e17327 | |||
|
bb1b6a3b23
|
|||
|
07afc2d59f
|
|||
|
8dd23f9e5c
|
|||
|
8b6e959d11
|
|||
|
|
df7a287801 | ||
|
|
fa399e7721 | ||
|
|
cf495e9d7f | ||
|
|
4d8064dc61 | ||
|
|
fde34e88b2 | ||
| 28ee7a2a32 | |||
|
68435207fe
|
|||
|
8f7c902ed5
|
|||
|
07f02e61d7
|
|||
|
|
af514b3363 | ||
|
|
447f29ce4c | ||
| 0368daef00 | |||
|
084081de7e
|
|||
|
46f526c680
|
|||
|
53d47fda63
|
|||
|
|
6ad1a9059d | ||
|
|
5778b3145d | ||
|
|
051ef02011 | ||
|
|
42515abf2a | ||
|
|
d44eb24086 | ||
| 191c5df824 | |||
|
|
68211fd877 | ||
|
a3895dca2c
|
|||
|
6e592e7d9b
|
|||
|
ee54a1201c
|
|||
|
c73b073f23
|
|||
|
8d8df3357d
|
|||
|
00df2dc546
|
|||
|
67e85688b2
|
|||
|
0497dd34a0
|
|||
|
6904aa37e4
|
|||
|
5141a2369f
|
|||
|
3fff9d3825
|
|||
|
f11fb9f881
|
|||
|
e881b736f8
|
|||
| 905a5e5b61 | |||
|
0d8be53ae4
|
|||
|
|
36ddd025b2 | ||
|
|
bad6e47e46 | ||
|
96ba81e24a
|
|||
|
|
54d6e7143b | ||
|
|
c2259334c1 | ||
|
|
94ee489faf | ||
|
|
f24aecffa3 | ||
| f896cbb0dd | |||
|
|
19e7ce4c11 | ||
|
|
473189342b | ||
|
|
f66f1ab3ac | ||
|
|
abb43b560d | ||
|
|
9a5ccea1f6 | ||
|
|
85a82aabb4 | ||
|
1b6d81dfca
|
|||
|
ae52fa653c
|
|||
|
|
01b38b1445 | ||
|
|
667fbf4949 | ||
|
|
d214723f35 | ||
|
|
d56be9249a | ||
|
|
1a72decf55 | ||
|
|
e54e5ce151 | ||
|
|
cf1028454d | ||
|
|
345c652a57 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -4,4 +4,3 @@
|
|||||||
.vscode/
|
.vscode/
|
||||||
wacc-examples/
|
wacc-examples/
|
||||||
.idea/
|
.idea/
|
||||||
|
|
||||||
|
|||||||
2
compile
2
compile
@@ -4,6 +4,6 @@
|
|||||||
# but do *not* change its name.
|
# but do *not* change its name.
|
||||||
|
|
||||||
# feel free to adjust to suit the specific internal flags of your compiler
|
# feel free to adjust to suit the specific internal flags of your compiler
|
||||||
./wacc-compiler "$@"
|
./wacc-compiler --output . "$@"
|
||||||
|
|
||||||
exit $?
|
exit $?
|
||||||
|
|||||||
10
extension/examples/invalid/semantics/badWacc.wacc
Normal file
10
extension/examples/invalid/semantics/badWacc.wacc
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
begin
|
||||||
|
int main() is
|
||||||
|
int a = 5 ;
|
||||||
|
string b = "Hello" ;
|
||||||
|
return a + b
|
||||||
|
end
|
||||||
|
|
||||||
|
int result = call main() ;
|
||||||
|
exit result
|
||||||
|
end
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import "./doesNotExist.wacc" (main)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int result = call main() ;
|
||||||
|
exit result
|
||||||
|
end
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import "../../../valid/sum.wacc" (mult)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int result = call mult(3, 2) ;
|
||||||
|
exit result
|
||||||
|
end
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import "../badWacc.wacc" (main)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int sum(int a, int b) is
|
||||||
|
return a + b
|
||||||
|
end
|
||||||
|
|
||||||
|
int result = call main() ;
|
||||||
|
exit result
|
||||||
|
end
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import "./importBadSem.wacc" (sum)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int result = call sum(1, 2) ;
|
||||||
|
exit result
|
||||||
|
end
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import "../../../valid/imports/basic.wacc" (sum)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int result = call sum(3, 2) ;
|
||||||
|
exit result
|
||||||
|
end
|
||||||
6
extension/examples/invalid/syntax/badWacc.wacc
Normal file
6
extension/examples/invalid/syntax/badWacc.wacc
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
int main() is
|
||||||
|
println "Hello World!" ;
|
||||||
|
return 0
|
||||||
|
end
|
||||||
|
|
||||||
|
skip
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import "../../../valid/sum.wacc" sum, main
|
||||||
|
|
||||||
|
begin
|
||||||
|
int result1 = call sum(5, 10) ;
|
||||||
|
int result2 = call main() ;
|
||||||
|
println result1 ;
|
||||||
|
println result2
|
||||||
|
end
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import "../../../valid/sum.wacc" ()
|
||||||
|
|
||||||
|
begin
|
||||||
|
exit 0
|
||||||
|
end
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import "../badWacc.wacc" (main)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int sum(int a, int b) is
|
||||||
|
return a + b
|
||||||
|
end
|
||||||
|
|
||||||
|
int result = call main() ;
|
||||||
|
exit result
|
||||||
|
end
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import "./importBadSyntax.wacc" (sum)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int result = call sum(1, 2) ;
|
||||||
|
exit result
|
||||||
|
end
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import "../../../valid/sum.wacc" (sum) ;
|
||||||
|
import "../../../valid/sum.wacc" (main) ;
|
||||||
|
|
||||||
|
begin
|
||||||
|
int result1 = call sum(5, 10) ;
|
||||||
|
int result2 = call main() ;
|
||||||
|
println result1 ;
|
||||||
|
println result2
|
||||||
|
end
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import "../../../valid/sum.wacc" *
|
||||||
|
|
||||||
|
begin
|
||||||
|
exit 0
|
||||||
|
end
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import "../../../valid/sum.wacc" (*)
|
||||||
|
|
||||||
|
begin
|
||||||
|
exit 0
|
||||||
|
end
|
||||||
7
extension/examples/valid/.gitignore
vendored
Normal file
7
extension/examples/valid/.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
*
|
||||||
|
|
||||||
|
!imports/
|
||||||
|
imports/*
|
||||||
|
|
||||||
|
!.gitignore
|
||||||
|
!*.wacc
|
||||||
22
extension/examples/valid/imports/alias.wacc
Normal file
22
extension/examples/valid/imports/alias.wacc
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
# import main from ../sum.wacc and ./basic.wacc
|
||||||
|
|
||||||
|
# Output:
|
||||||
|
# 15
|
||||||
|
# 0
|
||||||
|
# -33
|
||||||
|
#
|
||||||
|
|
||||||
|
# Exit:
|
||||||
|
# 0
|
||||||
|
|
||||||
|
# Program:
|
||||||
|
|
||||||
|
import "../sum.wacc" (main as sumMain)
|
||||||
|
import "./basic.wacc" (main)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int result1 = call sumMain() ;
|
||||||
|
int result2 = call main() ;
|
||||||
|
println result1 ;
|
||||||
|
println result2
|
||||||
|
end
|
||||||
21
extension/examples/valid/imports/basic.wacc
Normal file
21
extension/examples/valid/imports/basic.wacc
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
# import sum from ../sum.wacc
|
||||||
|
|
||||||
|
# Output:
|
||||||
|
# -33
|
||||||
|
#
|
||||||
|
|
||||||
|
# Exit:
|
||||||
|
# 0
|
||||||
|
|
||||||
|
# Program:
|
||||||
|
|
||||||
|
import "../sum.wacc" (sum)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int main() is
|
||||||
|
int result = call sum(-10, -23) ;
|
||||||
|
return result
|
||||||
|
end
|
||||||
|
int result = call main() ;
|
||||||
|
println result
|
||||||
|
end
|
||||||
33
extension/examples/valid/imports/manyMains.wacc
Normal file
33
extension/examples/valid/imports/manyMains.wacc
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
# import all the mains
|
||||||
|
|
||||||
|
# Output:
|
||||||
|
# 15
|
||||||
|
# -33
|
||||||
|
# 0
|
||||||
|
# -33
|
||||||
|
# 0
|
||||||
|
#
|
||||||
|
|
||||||
|
# Exit:
|
||||||
|
# 99
|
||||||
|
|
||||||
|
# Program:
|
||||||
|
|
||||||
|
import "../sum.wacc" (main as sumMain)
|
||||||
|
import "./basic.wacc" (main as basicMain)
|
||||||
|
import "./multiFunc.wacc" (main as multiFuncMain)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int main() is
|
||||||
|
int result1 = call sumMain() ;
|
||||||
|
int result2 = call basicMain() ;
|
||||||
|
int result3 = call multiFuncMain() ;
|
||||||
|
println result1 ;
|
||||||
|
println result2 ;
|
||||||
|
println result3 ;
|
||||||
|
return 99
|
||||||
|
end
|
||||||
|
|
||||||
|
int result = call main() ;
|
||||||
|
exit result
|
||||||
|
end
|
||||||
27
extension/examples/valid/imports/multiFunc.wacc
Normal file
27
extension/examples/valid/imports/multiFunc.wacc
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# import sum, main from ../sum.wacc
|
||||||
|
|
||||||
|
# Output:
|
||||||
|
# 15
|
||||||
|
# -33
|
||||||
|
# 0
|
||||||
|
# 0
|
||||||
|
#
|
||||||
|
|
||||||
|
# Exit:
|
||||||
|
# 0
|
||||||
|
|
||||||
|
# Program:
|
||||||
|
|
||||||
|
import "../sum.wacc" (sum, main as sumMain)
|
||||||
|
|
||||||
|
begin
|
||||||
|
int main() is
|
||||||
|
int result = call sum(-10, -23) ;
|
||||||
|
println result ;
|
||||||
|
return 0
|
||||||
|
end
|
||||||
|
int result1 = call sumMain() ;
|
||||||
|
int result2 = call main() ;
|
||||||
|
println result1 ;
|
||||||
|
println result2
|
||||||
|
end
|
||||||
27
extension/examples/valid/sum.wacc
Normal file
27
extension/examples/valid/sum.wacc
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
# simple sum program
|
||||||
|
|
||||||
|
# Output:
|
||||||
|
# 15
|
||||||
|
#
|
||||||
|
|
||||||
|
# Exit:
|
||||||
|
# 0
|
||||||
|
|
||||||
|
# Program:
|
||||||
|
|
||||||
|
begin
|
||||||
|
int sum(int a, int b) is
|
||||||
|
return a + b
|
||||||
|
end
|
||||||
|
|
||||||
|
int main() is
|
||||||
|
int a = 5 ;
|
||||||
|
int b = 10 ;
|
||||||
|
int result = call sum(a, b) ;
|
||||||
|
println result ;
|
||||||
|
return 0
|
||||||
|
end
|
||||||
|
|
||||||
|
int result = call main() ;
|
||||||
|
exit result
|
||||||
|
end
|
||||||
@@ -5,23 +5,20 @@
|
|||||||
//> using dep com.github.j-mie6::parsley::5.0.0-M10
|
//> using dep com.github.j-mie6::parsley::5.0.0-M10
|
||||||
//> using dep com.github.j-mie6::parsley-cats::1.5.0
|
//> using dep com.github.j-mie6::parsley-cats::1.5.0
|
||||||
//> using dep com.lihaoyi::os-lib::0.11.4
|
//> using dep com.lihaoyi::os-lib::0.11.4
|
||||||
//> using dep com.github.scopt::scopt::4.1.0
|
//> using dep org.typelevel::cats-core::2.13.0
|
||||||
|
//> using dep org.typelevel::cats-effect::3.5.7
|
||||||
|
//> using dep com.monovore::decline::2.5.0
|
||||||
|
//> using dep com.monovore::decline-effect::2.5.0
|
||||||
|
//> using dep org.typelevel::log4cats-slf4j::2.7.0
|
||||||
|
//> using dep org.slf4j:slf4j-simple:2.0.17
|
||||||
//> using test.dep org.scalatest::scalatest::3.2.19
|
//> using test.dep org.scalatest::scalatest::3.2.19
|
||||||
|
//> using dep org.typelevel::cats-effect-testing-scalatest::1.6.0
|
||||||
|
//> using dep "co.fs2::fs2-core:3.11.0"
|
||||||
|
//> using dep co.fs2::fs2-io:3.11.0
|
||||||
|
|
||||||
// these are all sensible defaults to catch annoying issues
|
// sensible defaults for warnings and compiler checks
|
||||||
//> using options -deprecation -unchecked -feature
|
//> using options -deprecation -unchecked -feature
|
||||||
//> using options -Wimplausible-patterns -Wunused:all
|
//> using options -Wimplausible-patterns -Wunused:all
|
||||||
//> using options -Yexplicit-nulls -Wsafe-init -Xkind-projector:underscores
|
//> using options -Yexplicit-nulls -Wsafe-init -Xkind-projector:underscores
|
||||||
|
|
||||||
// these will help ensure you have access to the latest parsley releases
|
// repositories for pre-release versions if needed
|
||||||
// even before they land on maven proper, or snapshot versions, if necessary.
|
|
||||||
// just in case they cause problems, however, keep them turned off unless you
|
|
||||||
// specifically need them.
|
|
||||||
// using repositories sonatype-s01:releases
|
|
||||||
// using repositories sonatype-s01:snapshots
|
|
||||||
|
|
||||||
// these are flags used by Scala native: if you aren't using scala-native, then they do nothing
|
|
||||||
// lto-thin has decent linking times, and release-fast does not too much optimisation.
|
|
||||||
// using nativeLto thin
|
|
||||||
// using nativeGc commix
|
|
||||||
// using nativeMode release-fast
|
|
||||||
|
|||||||
@@ -1,92 +1,177 @@
|
|||||||
package wacc
|
package wacc
|
||||||
|
|
||||||
import scala.collection.mutable
|
import cats.data.{Chain, NonEmptyList}
|
||||||
import cats.data.Chain
|
|
||||||
import parsley.{Failure, Success}
|
import parsley.{Failure, Success}
|
||||||
import scopt.OParser
|
|
||||||
import java.io.File
|
import java.nio.file.{Files, Path}
|
||||||
import java.io.PrintStream
|
import cats.syntax.all._
|
||||||
|
|
||||||
|
import cats.effect.IO
|
||||||
|
import cats.effect.ExitCode
|
||||||
|
|
||||||
|
import com.monovore.decline._
|
||||||
|
import com.monovore.decline.effect._
|
||||||
|
|
||||||
|
import org.typelevel.log4cats.slf4j.Slf4jLogger
|
||||||
|
import org.typelevel.log4cats.Logger
|
||||||
|
|
||||||
|
import fs2.Stream
|
||||||
|
|
||||||
import assemblyIR as asm
|
import assemblyIR as asm
|
||||||
|
import cats.data.ValidatedNel
|
||||||
|
import java.io.File
|
||||||
|
import cats.data.NonEmptySeq
|
||||||
|
|
||||||
case class CliConfig(
|
/*
|
||||||
file: File = new File(".")
|
TODO:
|
||||||
)
|
1) IO correctness
|
||||||
|
2) Errors can be handled more gracefully - currently, parallelised compilation is not fail fast as far as I am aware
|
||||||
|
3) splitting the file up and nicer refactoring
|
||||||
|
4) logging could be removed
|
||||||
|
5) general cleanup and comments (things like replacing home/<user> with ~ , and names of parameters and args, descriptions etc)
|
||||||
|
*/
|
||||||
|
|
||||||
val cliBuilder = OParser.builder[CliConfig]
|
private val SUCCESS = ExitCode.Success.code
|
||||||
val cliParser = {
|
private val ERROR = ExitCode.Error.code
|
||||||
import cliBuilder._
|
|
||||||
OParser.sequence(
|
given logger: Logger[IO] = Slf4jLogger.getLogger[IO]
|
||||||
programName("wacc-compiler"),
|
|
||||||
help('h', "help")
|
val logOpt: Opts[Boolean] =
|
||||||
.text("Prints this help message"),
|
Opts.flag("log", "Enable logging for additional compilation details", short = "l").orFalse
|
||||||
arg[File]("<file>")
|
|
||||||
.text("Input WACC source file")
|
def validateFile(path: Path): ValidatedNel[String, Path] = {
|
||||||
.required()
|
(for {
|
||||||
.action((f, c) => c.copy(file = f))
|
// TODO: redundant 2nd parameter :(
|
||||||
.validate(f =>
|
_ <- Either.cond(Files.exists(path), (), s"File '${path}' does not exist")
|
||||||
if (!f.exists) failure("File does not exist")
|
_ <- Either.cond(Files.isRegularFile(path), (), s"File '${path}' must be a regular file")
|
||||||
else if (!f.isFile) failure("File must be a regular file")
|
_ <- Either.cond(path.toString.endsWith(".wacc"), (), "File must have .wacc extension")
|
||||||
else if (!f.getName.endsWith(".wacc"))
|
} yield path).toValidatedNel
|
||||||
failure("File must have .wacc extension")
|
|
||||||
else success
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val filesOpt: Opts[NonEmptyList[Path]] =
|
||||||
|
Opts.arguments[Path]("files").mapValidated {
|
||||||
|
_.traverse(validateFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
val outputOpt: Opts[Option[Path]] =
|
||||||
|
Opts
|
||||||
|
.option[Path]("output", metavar = "path", help = "Output directory for compiled files.")
|
||||||
|
.validate("Must have permissions to create & access the output path") { path =>
|
||||||
|
try {
|
||||||
|
Files.createDirectories(path)
|
||||||
|
true
|
||||||
|
} catch {
|
||||||
|
case e: java.nio.file.AccessDeniedException =>
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.validate("Output path must be a directory") { path =>
|
||||||
|
Files.isDirectory(path)
|
||||||
|
}
|
||||||
|
.orNone
|
||||||
|
|
||||||
def frontend(
|
def frontend(
|
||||||
contents: String
|
contents: String,
|
||||||
)(using stdout: PrintStream): Either[microWacc.Program, Int] = {
|
file: File
|
||||||
|
): IO[Either[NonEmptySeq[Error], microWacc.Program]] =
|
||||||
parser.parse(contents) match {
|
parser.parse(contents) match {
|
||||||
case Success(prog) =>
|
case Failure(msg) => IO.pure(Left(NonEmptySeq.one(Error.SyntaxError(file, msg))))
|
||||||
given errors: mutable.Builder[Error, List[Error]] = List.newBuilder
|
case Success(fn) =>
|
||||||
val (names, funcs) = renamer.rename(prog)
|
val partialProg = fn(file)
|
||||||
given ctx: typeChecker.TypeCheckerCtx = typeChecker.TypeCheckerCtx(names, funcs, errors)
|
|
||||||
val typedProg = typeChecker.check(prog)
|
for {
|
||||||
if (errors.result.nonEmpty) {
|
(typedProg, errors) <- semantics.check(partialProg)
|
||||||
given errorContent: String = contents
|
res = NonEmptySeq.fromSeq(errors.iterator.toSeq).map(Left(_)).getOrElse(Right(typedProg))
|
||||||
Right(
|
} yield res
|
||||||
errors.result
|
}
|
||||||
.map { error =>
|
|
||||||
printError(error)
|
|
||||||
error match {
|
|
||||||
case _: Error.InternalError => 201
|
|
||||||
case _ => 200
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.max()
|
|
||||||
)
|
|
||||||
} else Left(typedProg)
|
|
||||||
case Failure(msg) =>
|
|
||||||
stdout.println(msg)
|
|
||||||
Right(100)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val s = "enter an integer to echo"
|
|
||||||
def backend(typedProg: microWacc.Program): Chain[asm.AsmLine] =
|
def backend(typedProg: microWacc.Program): Chain[asm.AsmLine] =
|
||||||
asmGenerator.generateAsm(typedProg)
|
asmGenerator.generateAsm(typedProg)
|
||||||
|
|
||||||
def compile(filename: String, outFile: Option[File] = None)(using
|
def compile(
|
||||||
stdout: PrintStream = Console.out
|
filePath: Path,
|
||||||
): Int =
|
outputDir: Option[Path],
|
||||||
frontend(os.read(os.Path(filename))) match {
|
log: Boolean
|
||||||
case Left(typedProg) =>
|
): IO[Int] = {
|
||||||
val asmFile = outFile.getOrElse(File(filename.stripSuffix(".wacc") + ".s"))
|
val logAction: String => IO[Unit] =
|
||||||
val asm = backend(typedProg)
|
if (log) logger.info(_)
|
||||||
writer.writeTo(asm, PrintStream(asmFile))
|
else (_ => IO.unit)
|
||||||
0
|
|
||||||
case Right(exitCode) => exitCode
|
|
||||||
}
|
|
||||||
|
|
||||||
def main(args: Array[String]): Unit =
|
def readSourceFile: IO[String] =
|
||||||
OParser.parse(cliParser, args, CliConfig()) match {
|
IO.blocking(os.read(os.Path(filePath)))
|
||||||
case Some(config) =>
|
|
||||||
System.exit(
|
// TODO: path, file , the names are confusing (when Path is the type but we are working with files)
|
||||||
compile(
|
def writeOutputFile(typedProg: microWacc.Program, outputPath: Path): IO[Unit] =
|
||||||
config.file.getAbsolutePath,
|
val backendStart = System.nanoTime()
|
||||||
outFile = Some(File(".", config.file.getName.stripSuffix(".wacc") + ".s"))
|
val asmLines = backend(typedProg)
|
||||||
)
|
val backendEnd = System.nanoTime()
|
||||||
|
writer.writeTo(asmLines, outputPath) *>
|
||||||
|
logAction(
|
||||||
|
s"Backend time (${filePath.toRealPath()}): ${(backendEnd - backendStart).toFloat / 1e6} ms"
|
||||||
|
) *>
|
||||||
|
IO.blocking(println(s"Success: ${outputPath.toRealPath()}"))
|
||||||
|
|
||||||
|
def processProgram(contents: String, file: File, outDir: Path): IO[Int] =
|
||||||
|
val frontendStart = System.nanoTime()
|
||||||
|
for {
|
||||||
|
frontendResult <- frontend(contents, file)
|
||||||
|
frontendEnd = System.nanoTime()
|
||||||
|
_ <- logAction(
|
||||||
|
s"Frontend time (${filePath.toRealPath()}): ${(frontendEnd - frontendStart).toFloat / 1e6} ms"
|
||||||
)
|
)
|
||||||
case None =>
|
res <- frontendResult match {
|
||||||
}
|
case Left(errors) =>
|
||||||
|
val code = errors.map(err => err.exitCode).toList.min
|
||||||
|
val errorMsg = errors.map(formatError).toIterable.mkString("\n")
|
||||||
|
for {
|
||||||
|
_ <- logAction(s"Compilation failed for $filePath\nExit code: $code")
|
||||||
|
_ <- IO.blocking(
|
||||||
|
// Explicit println since we want this to always show without logger thread info e.t.c.
|
||||||
|
println(s"Compilation failed for ${file.getCanonicalPath}:\n$errorMsg")
|
||||||
|
)
|
||||||
|
} yield code
|
||||||
|
|
||||||
|
case Right(typedProg) =>
|
||||||
|
val outputFile = outDir.resolve(filePath.getFileName.toString.stripSuffix(".wacc") + ".s")
|
||||||
|
writeOutputFile(typedProg, outputFile).as(SUCCESS)
|
||||||
|
}
|
||||||
|
} yield res
|
||||||
|
|
||||||
|
for {
|
||||||
|
contents <- readSourceFile
|
||||||
|
_ <- logAction(s"Compiling file: ${filePath.toAbsolutePath}")
|
||||||
|
exitCode <- processProgram(contents, filePath.toFile, outputDir.getOrElse(filePath.getParent))
|
||||||
|
} yield exitCode
|
||||||
|
}
|
||||||
|
|
||||||
|
def compileCommandParallel(
|
||||||
|
files: NonEmptyList[Path],
|
||||||
|
log: Boolean,
|
||||||
|
outDir: Option[Path]
|
||||||
|
): IO[ExitCode] =
|
||||||
|
Stream
|
||||||
|
.emits(files.toList)
|
||||||
|
.parEvalMapUnordered(Runtime.getRuntime.availableProcessors()) { file =>
|
||||||
|
compile(file.toAbsolutePath, outDir, log)
|
||||||
|
}
|
||||||
|
.compile
|
||||||
|
.toList
|
||||||
|
.map { exitCodes =>
|
||||||
|
exitCodes.filter(_ != 0) match {
|
||||||
|
case Nil => ExitCode.Success
|
||||||
|
case errorCodes => ExitCode(errorCodes.min)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
object Main
|
||||||
|
extends CommandIOApp(
|
||||||
|
name = "wacc",
|
||||||
|
header = "The ultimate WACC compiler",
|
||||||
|
version = "1.0"
|
||||||
|
) {
|
||||||
|
def main: Opts[IO[ExitCode]] =
|
||||||
|
(filesOpt, logOpt, outputOpt).mapN { (files, log, outDir) =>
|
||||||
|
compileCommandParallel(files, log, outDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package wacc
|
|||||||
|
|
||||||
import scala.collection.mutable
|
import scala.collection.mutable
|
||||||
import cats.data.Chain
|
import cats.data.Chain
|
||||||
|
import wacc.ast.Position
|
||||||
|
|
||||||
private class LabelGenerator {
|
private class LabelGenerator {
|
||||||
import assemblyIR._
|
import assemblyIR._
|
||||||
@@ -9,7 +10,9 @@ private class LabelGenerator {
|
|||||||
import asmGenerator.escaped
|
import asmGenerator.escaped
|
||||||
|
|
||||||
private val strings = mutable.HashMap[String, String]()
|
private val strings = mutable.HashMap[String, String]()
|
||||||
|
private val files = mutable.HashMap[String, Int]()
|
||||||
private var labelVal = -1
|
private var labelVal = -1
|
||||||
|
private var permittedFuncFile: Option[String] = None
|
||||||
|
|
||||||
/** Get an arbitrary label. */
|
/** Get an arbitrary label. */
|
||||||
def getLabel(): String = {
|
def getLabel(): String = {
|
||||||
@@ -18,7 +21,7 @@ private class LabelGenerator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private def getLabel(target: CallTarget | RuntimeError): String = target match {
|
private def getLabel(target: CallTarget | RuntimeError): String = target match {
|
||||||
case Ident(v, _) => s"wacc_$v"
|
case Ident(v, guid) => s"wacc_${v}_$guid"
|
||||||
case Builtin(name) => s"_$name"
|
case Builtin(name) => s"_$name"
|
||||||
case err: RuntimeError => s".L.${err.name}"
|
case err: RuntimeError => s".L.${err.name}"
|
||||||
}
|
}
|
||||||
@@ -39,6 +42,25 @@ private class LabelGenerator {
|
|||||||
def getLabelArg(src: String, name: String): LabelArg =
|
def getLabelArg(src: String, name: String): LabelArg =
|
||||||
LabelArg(strings.getOrElseUpdate(src, s".L.$name.str${strings.size}"))
|
LabelArg(strings.getOrElseUpdate(src, s".L.$name.str${strings.size}"))
|
||||||
|
|
||||||
|
/** Get a debug directive for a file. */
|
||||||
|
def getDebugFile(file: java.io.File): Int =
|
||||||
|
files.getOrElseUpdate(file.getCanonicalPath, files.size)
|
||||||
|
|
||||||
|
/** Get a debug directive for a function. */
|
||||||
|
def getDebugFunc(pos: Position, name: String, label: LabelDef): Chain[AsmLine] = {
|
||||||
|
permittedFuncFile match {
|
||||||
|
case Some(f) if f != pos.file.getCanonicalPath => Chain.empty
|
||||||
|
case _ =>
|
||||||
|
val customLabel = if name == "main" then Chain.empty else Chain(LabelDef(name))
|
||||||
|
permittedFuncFile = Some(pos.file.getCanonicalPath)
|
||||||
|
customLabel ++ Chain(
|
||||||
|
Directive.Location(getDebugFile(pos.file), pos.line, None),
|
||||||
|
Directive.Type(label, SymbolType.Function),
|
||||||
|
Directive.Func(name, label)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Generate the assembly labels for constants that were labelled using the LabelGenerator. */
|
/** Generate the assembly labels for constants that were labelled using the LabelGenerator. */
|
||||||
def generateConstants: Chain[AsmLine] =
|
def generateConstants: Chain[AsmLine] =
|
||||||
strings.foldLeft(Chain.empty) { case (acc, (str, label)) =>
|
strings.foldLeft(Chain.empty) { case (acc, (str, label)) =>
|
||||||
@@ -47,4 +69,10 @@ private class LabelGenerator {
|
|||||||
Directive.Asciz(str.escaped)
|
Directive.Asciz(str.escaped)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Generates debug directives that were created using the LabelGenerator. */
|
||||||
|
def generateDebug: Chain[AsmLine] =
|
||||||
|
files.foldLeft(Chain.empty) { case (acc, (file, no)) =>
|
||||||
|
acc :+ Directive.File(no, file)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ class Stack {
|
|||||||
|
|
||||||
/** Push an expression onto the stack. */
|
/** Push an expression onto the stack. */
|
||||||
def push(expr: mw.Expr, src: Register): AsmLine = {
|
def push(expr: mw.Expr, src: Register): AsmLine = {
|
||||||
stack += expr -> StackValue(src.size, sizeBytes)
|
stack += expr -> StackValue(expr.ty.size, sizeBytes)
|
||||||
Push(src)
|
Push(src)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,7 +81,7 @@ class Stack {
|
|||||||
|
|
||||||
/** Get an MemLocation for a variable in the stack. */
|
/** Get an MemLocation for a variable in the stack. */
|
||||||
def accessVar(ident: mw.Ident): MemLocation =
|
def accessVar(ident: mw.Ident): MemLocation =
|
||||||
MemLocation(RSP, sizeBytes - stack(ident).bottom)
|
MemLocation(RSP, sizeBytes - stack(ident).bottom, opSize = Some(stack(ident).size))
|
||||||
|
|
||||||
def contains(ident: mw.Ident): Boolean = stack.contains(ident)
|
def contains(ident: mw.Ident): Boolean = stack.contains(ident)
|
||||||
def head: MemLocation = MemLocation(RSP, opSize = Some(stack.last._2.size))
|
def head: MemLocation = MemLocation(RSP, opSize = Some(stack.last._2.size))
|
||||||
|
|||||||
@@ -36,11 +36,14 @@ object asmGenerator {
|
|||||||
given labelGenerator: LabelGenerator = LabelGenerator()
|
given labelGenerator: LabelGenerator = LabelGenerator()
|
||||||
val Program(funcs, main) = microProg
|
val Program(funcs, main) = microProg
|
||||||
|
|
||||||
val progAsm = Chain(LabelDef("main")).concatAll(
|
val mainLabel = LabelDef("main")
|
||||||
|
val mainAsm = labelGenerator.getDebugFunc(microProg.pos, "main", mainLabel) + mainLabel
|
||||||
|
val progAsm = mainAsm.concatAll(
|
||||||
funcPrologue(),
|
funcPrologue(),
|
||||||
main.foldMap(generateStmt(_)),
|
main.foldMap(generateStmt(_)),
|
||||||
Chain.one(Xor(RAX, RAX)),
|
Chain.one(Xor(RAX, RAX)),
|
||||||
funcEpilogue(),
|
funcEpilogue(),
|
||||||
|
Chain(Directive.Size(mainLabel, SizeExpr.Relative(mainLabel)), Directive.EndFunc),
|
||||||
generateBuiltInFuncs(),
|
generateBuiltInFuncs(),
|
||||||
RuntimeError.all.foldMap(_.generate),
|
RuntimeError.all.foldMap(_.generate),
|
||||||
funcs.foldMap(generateUserFunc(_))
|
funcs.foldMap(generateUserFunc(_))
|
||||||
@@ -51,6 +54,7 @@ object asmGenerator {
|
|||||||
Directive.Global("main"),
|
Directive.Global("main"),
|
||||||
Directive.RoData
|
Directive.RoData
|
||||||
).concatAll(
|
).concatAll(
|
||||||
|
labelGenerator.generateDebug,
|
||||||
labelGenerator.generateConstants,
|
labelGenerator.generateConstants,
|
||||||
Chain.one(Directive.Text),
|
Chain.one(Directive.Text),
|
||||||
progAsm
|
progAsm
|
||||||
@@ -75,7 +79,10 @@ object asmGenerator {
|
|||||||
// Setup the stack with param 7 and up
|
// Setup the stack with param 7 and up
|
||||||
func.params.drop(argRegs.size).foreach(stack.reserve(_))
|
func.params.drop(argRegs.size).foreach(stack.reserve(_))
|
||||||
stack.reserve(Size.Q64) // Reserve return pointer slot
|
stack.reserve(Size.Q64) // Reserve return pointer slot
|
||||||
var asm = Chain.one[AsmLine](labelGenerator.getLabelDef(func.name))
|
val funcLabel = labelGenerator.getLabelDef(func.name)
|
||||||
|
var asm = labelGenerator.getDebugFunc(func.pos, func.name.name, funcLabel)
|
||||||
|
val debugFunc = asm.size > 0
|
||||||
|
asm += funcLabel
|
||||||
asm ++= funcPrologue()
|
asm ++= funcPrologue()
|
||||||
// Push the rest of params onto the stack for simplicity
|
// Push the rest of params onto the stack for simplicity
|
||||||
argRegs.zip(func.params).foreach { (reg, param) =>
|
argRegs.zip(func.params).foreach { (reg, param) =>
|
||||||
@@ -83,6 +90,10 @@ object asmGenerator {
|
|||||||
}
|
}
|
||||||
asm ++= func.body.foldMap(generateStmt(_))
|
asm ++= func.body.foldMap(generateStmt(_))
|
||||||
// No need for epilogue here since all user functions must return explicitly
|
// No need for epilogue here since all user functions must return explicitly
|
||||||
|
if (debugFunc) {
|
||||||
|
asm += Directive.Size(funcLabel, SizeExpr.Relative(funcLabel))
|
||||||
|
asm += Directive.EndFunc
|
||||||
|
}
|
||||||
asm
|
asm
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,8 +170,8 @@ object asmGenerator {
|
|||||||
stack: Stack,
|
stack: Stack,
|
||||||
labelGenerator: LabelGenerator
|
labelGenerator: LabelGenerator
|
||||||
): Chain[AsmLine] = {
|
): Chain[AsmLine] = {
|
||||||
var asm = Chain.empty[AsmLine]
|
val fileNo = labelGenerator.getDebugFile(stmt.pos.file)
|
||||||
asm += Comment(stmt.toString)
|
var asm = Chain.one[AsmLine](Directive.Location(fileNo, stmt.pos.line, None))
|
||||||
stmt match {
|
stmt match {
|
||||||
case Assign(lhs, rhs) =>
|
case Assign(lhs, rhs) =>
|
||||||
lhs match {
|
lhs match {
|
||||||
@@ -261,7 +272,7 @@ object asmGenerator {
|
|||||||
asm += stack.push(KnownType.String.size, RAX)
|
asm += stack.push(KnownType.String.size, RAX)
|
||||||
case ty =>
|
case ty =>
|
||||||
asm ++= generateCall(
|
asm ++= generateCall(
|
||||||
microWacc.Call(Builtin.Malloc, List(IntLiter(array.heapSize))),
|
microWacc.Call(Builtin.Malloc, List(IntLiter(array.heapSize)))(array.pos),
|
||||||
isTail = false
|
isTail = false
|
||||||
)
|
)
|
||||||
asm += stack.push(KnownType.Array(?).size, RAX)
|
asm += stack.push(KnownType.Array(?).size, RAX)
|
||||||
|
|||||||
@@ -199,18 +199,49 @@ object assemblyIR {
|
|||||||
}
|
}
|
||||||
|
|
||||||
enum Directive extends AsmLine {
|
enum Directive extends AsmLine {
|
||||||
case IntelSyntax, RoData, Text
|
case IntelSyntax, RoData, Text, EndFunc
|
||||||
case Global(name: String)
|
case Global(name: String)
|
||||||
case Int(value: scala.Int)
|
case Int(value: scala.Int)
|
||||||
case Asciz(string: String)
|
case Asciz(string: String)
|
||||||
|
case File(no: scala.Int, file: String)
|
||||||
|
case Location(fileNo: scala.Int, lineNo: scala.Int, colNo: Option[scala.Int])
|
||||||
|
case Func(name: String, label: LabelDef)
|
||||||
|
case Type(label: LabelDef, symbolType: SymbolType)
|
||||||
|
case Size(label: LabelDef, expr: SizeExpr)
|
||||||
|
|
||||||
override def toString(): String = this match {
|
override def toString(): String = this match {
|
||||||
case IntelSyntax => ".intel_syntax noprefix"
|
case IntelSyntax => ".intel_syntax noprefix"
|
||||||
case Global(name) => s".globl $name"
|
case Global(name) => s".globl $name"
|
||||||
case Text => ".text"
|
case Text => ".text"
|
||||||
case RoData => ".section .rodata"
|
case RoData => ".section .rodata"
|
||||||
case Int(value) => s"\t.int $value"
|
case Int(value) => s"\t.int $value"
|
||||||
case Asciz(string) => s"\t.asciz \"$string\""
|
case Asciz(string) => s"\t.asciz \"$string\""
|
||||||
|
case File(no, file) => s".file $no \"${file}\""
|
||||||
|
case Location(fileNo, lineNo, colNo) =>
|
||||||
|
s"\t.loc $fileNo $lineNo" + colNo.map(c => s" $c").getOrElse("")
|
||||||
|
case Func(name, label) =>
|
||||||
|
s".func $name, ${label.name}"
|
||||||
|
case EndFunc => ".endfunc"
|
||||||
|
case Type(label, symbolType) =>
|
||||||
|
s".type ${label.name}, @${symbolType.toString}"
|
||||||
|
case Directive.Size(label, expr) =>
|
||||||
|
s".size ${label.name}, ${expr.toString}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SymbolType {
|
||||||
|
case Function
|
||||||
|
|
||||||
|
override def toString(): String = this match {
|
||||||
|
case Function => "function"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SizeExpr {
|
||||||
|
case Relative(label: LabelDef)
|
||||||
|
|
||||||
|
override def toString(): String = this match {
|
||||||
|
case Relative(label) => s".-${label.name}"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,42 @@
|
|||||||
package wacc
|
package wacc
|
||||||
|
|
||||||
import java.io.PrintStream
|
import cats.effect.Resource
|
||||||
|
import java.nio.charset.StandardCharsets
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.FileWriter
|
||||||
import cats.data.Chain
|
import cats.data.Chain
|
||||||
|
import cats.effect.IO
|
||||||
|
|
||||||
|
import org.typelevel.log4cats.Logger
|
||||||
|
import java.nio.file.Path
|
||||||
|
|
||||||
object writer {
|
object writer {
|
||||||
import assemblyIR._
|
import assemblyIR._
|
||||||
|
|
||||||
def writeTo(asmList: Chain[AsmLine], printStream: PrintStream): Unit = {
|
// TODO: Judging from documentation it seems as though IO.blocking is the correct choice
|
||||||
asmList.iterator.foreach(printStream.println)
|
// But needs checking
|
||||||
}
|
|
||||||
|
/** Creates a resource safe BufferedWriter */
|
||||||
|
private def bufferedWriter(outputPath: Path): Resource[IO, BufferedWriter] =
|
||||||
|
Resource.make {
|
||||||
|
IO.blocking(new BufferedWriter(new FileWriter(outputPath.toFile, StandardCharsets.UTF_8)))
|
||||||
|
} { writer =>
|
||||||
|
IO.blocking(writer.close())
|
||||||
|
.handleErrorWith(_ => IO.unit) // TODO: ensures writer is closed even if an error occurs
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Write line safely into a BufferedWriter */
|
||||||
|
private def writeLines(writer: BufferedWriter, lines: Chain[AsmLine]): IO[Unit] =
|
||||||
|
IO.blocking {
|
||||||
|
lines.iterator.foreach { line =>
|
||||||
|
writer.write(line.toString)
|
||||||
|
writer.newLine()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Main function to write assembly to a file */
|
||||||
|
def writeTo(asmList: Chain[AsmLine], outputPath: Path)(using logger: Logger[IO]): IO[Unit] =
|
||||||
|
bufferedWriter(outputPath).use {
|
||||||
|
writeLines(_, asmList)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ package wacc
|
|||||||
|
|
||||||
import wacc.ast.Position
|
import wacc.ast.Position
|
||||||
import wacc.types._
|
import wacc.types._
|
||||||
import java.io.PrintStream
|
import java.io.File
|
||||||
|
|
||||||
|
private val SYNTAX_ERROR = 100
|
||||||
|
private val SEMANTIC_ERROR = 200
|
||||||
|
|
||||||
/** Error types for semantic errors
|
/** Error types for semantic errors
|
||||||
*/
|
*/
|
||||||
@@ -15,6 +18,15 @@ enum Error {
|
|||||||
case SemanticError(pos: Position, msg: String)
|
case SemanticError(pos: Position, msg: String)
|
||||||
case TypeMismatch(pos: Position, expected: SemType, got: SemType, msg: String)
|
case TypeMismatch(pos: Position, expected: SemType, got: SemType, msg: String)
|
||||||
case InternalError(pos: Position, msg: String)
|
case InternalError(pos: Position, msg: String)
|
||||||
|
|
||||||
|
case SyntaxError(file: File, msg: String)
|
||||||
|
}
|
||||||
|
|
||||||
|
extension (e: Error) {
|
||||||
|
def exitCode: Int = e match {
|
||||||
|
case Error.SyntaxError(_, _) => SYNTAX_ERROR
|
||||||
|
case _ => SEMANTIC_ERROR
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Function to handle printing the details of a given semantic error
|
/** Function to handle printing the details of a given semantic error
|
||||||
@@ -24,71 +36,91 @@ enum Error {
|
|||||||
* @param errorContent
|
* @param errorContent
|
||||||
* Contents of the file to generate code snippets
|
* Contents of the file to generate code snippets
|
||||||
*/
|
*/
|
||||||
def printError(error: Error)(using errorContent: String, stdout: PrintStream): Unit = {
|
def formatError(error: Error): String = {
|
||||||
stdout.println("Semantic error:")
|
val sb = new StringBuilder()
|
||||||
error match {
|
|
||||||
case Error.DuplicateDeclaration(ident) =>
|
/** Format the file of an error
|
||||||
printPosition(ident.pos)
|
*
|
||||||
stdout.println(s"Duplicate declaration of identifier ${ident.v}")
|
* @param file
|
||||||
highlight(ident.pos, ident.v.length)
|
* File of the error
|
||||||
case Error.UndeclaredVariable(ident) =>
|
*/
|
||||||
printPosition(ident.pos)
|
def formatFile(file: File): Unit = {
|
||||||
stdout.println(s"Undeclared variable ${ident.v}")
|
sb.append(s"File: ${file.getCanonicalPath}\n")
|
||||||
highlight(ident.pos, ident.v.length)
|
|
||||||
case Error.UndefinedFunction(ident) =>
|
|
||||||
printPosition(ident.pos)
|
|
||||||
stdout.println(s"Undefined function ${ident.v}")
|
|
||||||
highlight(ident.pos, ident.v.length)
|
|
||||||
case Error.FunctionParamsMismatch(id, expected, got, funcType) =>
|
|
||||||
printPosition(id.pos)
|
|
||||||
stdout.println(s"Function expects $expected parameters, got $got")
|
|
||||||
stdout.println(
|
|
||||||
s"(function ${id.v} has type (${funcType.params.mkString(", ")}) -> ${funcType.returnType})"
|
|
||||||
)
|
|
||||||
highlight(id.pos, 1)
|
|
||||||
case Error.TypeMismatch(pos, expected, got, msg) =>
|
|
||||||
printPosition(pos)
|
|
||||||
stdout.println(s"Type mismatch: $msg\nExpected: $expected\nGot: $got")
|
|
||||||
highlight(pos, 1)
|
|
||||||
case Error.SemanticError(pos, msg) =>
|
|
||||||
printPosition(pos)
|
|
||||||
stdout.println(msg)
|
|
||||||
highlight(pos, 1)
|
|
||||||
case wacc.Error.InternalError(pos, msg) =>
|
|
||||||
printPosition(pos)
|
|
||||||
stdout.println(s"Internal error: $msg")
|
|
||||||
highlight(pos, 1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
/** Function to format the position of an error
|
||||||
|
*
|
||||||
/** Function to highlight a section of code for an error message
|
* @param pos
|
||||||
*
|
* Position of the error
|
||||||
* @param pos
|
*/
|
||||||
* Position of the error
|
def formatPosition(pos: Position): Unit = {
|
||||||
* @param size
|
formatFile(pos.file)
|
||||||
* Size(in chars) of section to highlight
|
sb.append(s"(line ${pos.line}, column ${pos.column}):\n")
|
||||||
* @param errorContent
|
}
|
||||||
* Contents of the file to generate code snippets
|
|
||||||
*/
|
/** Function to highlight a section of code for an error message
|
||||||
def highlight(pos: Position, size: Int)(using errorContent: String, stdout: PrintStream): Unit = {
|
*
|
||||||
val lines = errorContent.split("\n")
|
* @param pos
|
||||||
|
* Position of the error
|
||||||
val preLine = if (pos.line > 1) lines(pos.line - 2) else ""
|
* @param size
|
||||||
val midLine = lines(pos.line - 1)
|
* Size(in chars) of section to highlight
|
||||||
val postLine = if (pos.line < lines.size) lines(pos.line) else ""
|
*/
|
||||||
val linePointer = " " * (pos.column + 2) + ("^" * (size)) + "\n"
|
def formatHighlight(pos: Position, size: Int): Unit = {
|
||||||
|
val lines = os.read(os.Path(pos.file.getCanonicalPath)).split("\n")
|
||||||
stdout.println(
|
val preLine = if (pos.line > 1) lines(pos.line - 2) else ""
|
||||||
s" >$preLine\n >$midLine\n$linePointer >$postLine"
|
val midLine = lines(pos.line - 1)
|
||||||
)
|
val postLine = if (pos.line < lines.size) lines(pos.line) else ""
|
||||||
}
|
val linePointer = " " * (pos.column + 2) + ("^" * (size)) + "\n"
|
||||||
|
|
||||||
/** Function to print the position of an error
|
sb.append(
|
||||||
*
|
s" >$preLine\n >$midLine\n$linePointer >$postLine\netscape"
|
||||||
* @param pos
|
)
|
||||||
* Position of the error
|
}
|
||||||
*/
|
|
||||||
def printPosition(pos: Position)(using stdout: PrintStream): Unit = {
|
error match {
|
||||||
stdout.println(s"(line ${pos.line}, column ${pos.column}):")
|
case Error.SyntaxError(_, _) =>
|
||||||
|
sb.append("Syntax error:\n")
|
||||||
|
case _ =>
|
||||||
|
sb.append("Semantic error:\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
error match {
|
||||||
|
case Error.DuplicateDeclaration(ident) =>
|
||||||
|
formatPosition(ident.pos)
|
||||||
|
sb.append(s"Duplicate declaration of identifier ${ident.v}\n")
|
||||||
|
formatHighlight(ident.pos, ident.v.length)
|
||||||
|
case Error.UndeclaredVariable(ident) =>
|
||||||
|
formatPosition(ident.pos)
|
||||||
|
sb.append(s"Undeclared variable ${ident.v}\n")
|
||||||
|
formatHighlight(ident.pos, ident.v.length)
|
||||||
|
case Error.UndefinedFunction(ident) =>
|
||||||
|
formatPosition(ident.pos)
|
||||||
|
sb.append(s"Undefined function ${ident.v}\n")
|
||||||
|
formatHighlight(ident.pos, ident.v.length)
|
||||||
|
case Error.FunctionParamsMismatch(id, expected, got, funcType) =>
|
||||||
|
formatPosition(id.pos)
|
||||||
|
sb.append(s"Function expects $expected parameters, got $got\n")
|
||||||
|
sb.append(
|
||||||
|
s"(function ${id.v} has type (${funcType.params.mkString(", ")}) -> ${funcType.returnType})\n"
|
||||||
|
)
|
||||||
|
formatHighlight(id.pos, 1)
|
||||||
|
case Error.TypeMismatch(pos, expected, got, msg) =>
|
||||||
|
formatPosition(pos)
|
||||||
|
sb.append(s"Type mismatch: $msg\nExpected: $expected\nGot: $got\n")
|
||||||
|
formatHighlight(pos, 1)
|
||||||
|
case Error.SemanticError(pos, msg) =>
|
||||||
|
formatPosition(pos)
|
||||||
|
sb.append(msg + "\n")
|
||||||
|
formatHighlight(pos, 1)
|
||||||
|
case wacc.Error.InternalError(pos, msg) =>
|
||||||
|
formatPosition(pos)
|
||||||
|
sb.append(s"Internal error: $msg\n")
|
||||||
|
formatHighlight(pos, 1)
|
||||||
|
case Error.SyntaxError(file, msg) =>
|
||||||
|
formatFile(file)
|
||||||
|
sb.append(msg + "\n")
|
||||||
|
sb.append("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.toString()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
package wacc
|
package wacc
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
import parsley.Parsley
|
import parsley.Parsley
|
||||||
import parsley.generic.ErrorBridge
|
import parsley.generic.ErrorBridge
|
||||||
import parsley.ap._
|
import parsley.ap._
|
||||||
import parsley.position._
|
import parsley.position._
|
||||||
import parsley.syntax.zipped._
|
|
||||||
import cats.data.NonEmptyList
|
import cats.data.NonEmptyList
|
||||||
|
|
||||||
object ast {
|
object ast {
|
||||||
@@ -23,26 +23,42 @@ object ast {
|
|||||||
/* ============================ ATOMIC EXPRESSIONS ============================ */
|
/* ============================ ATOMIC EXPRESSIONS ============================ */
|
||||||
|
|
||||||
case class IntLiter(v: Int)(val pos: Position) extends Expr6
|
case class IntLiter(v: Int)(val pos: Position) extends Expr6
|
||||||
object IntLiter extends ParserBridgePos1[Int, IntLiter]
|
object IntLiter extends ParserBridgePos1Atom[Int, IntLiter]
|
||||||
case class BoolLiter(v: Boolean)(val pos: Position) extends Expr6
|
case class BoolLiter(v: Boolean)(val pos: Position) extends Expr6
|
||||||
object BoolLiter extends ParserBridgePos1[Boolean, BoolLiter]
|
object BoolLiter extends ParserBridgePos1Atom[Boolean, BoolLiter]
|
||||||
case class CharLiter(v: Char)(val pos: Position) extends Expr6
|
case class CharLiter(v: Char)(val pos: Position) extends Expr6
|
||||||
object CharLiter extends ParserBridgePos1[Char, CharLiter]
|
object CharLiter extends ParserBridgePos1Atom[Char, CharLiter]
|
||||||
case class StrLiter(v: String)(val pos: Position) extends Expr6
|
case class StrLiter(v: String)(val pos: Position) extends Expr6
|
||||||
object StrLiter extends ParserBridgePos1[String, StrLiter]
|
object StrLiter extends ParserBridgePos1Atom[String, StrLiter]
|
||||||
case class PairLiter()(val pos: Position) extends Expr6
|
case class PairLiter()(val pos: Position) extends Expr6
|
||||||
object PairLiter extends ParserBridgePos0[PairLiter]
|
object PairLiter extends ParserBridgePos0[PairLiter]
|
||||||
case class Ident(v: String, var uid: Int = -1)(val pos: Position) extends Expr6 with LValue
|
case class Ident(var v: String, var guid: Int = -1, var ty: types.RenamerType = types.?)(
|
||||||
object Ident extends ParserBridgePos1[String, Ident] {
|
val pos: Position
|
||||||
|
) extends Expr6
|
||||||
|
with LValue
|
||||||
|
object Ident extends ParserBridgePos1Atom[String, Ident] {
|
||||||
def apply(v: String)(pos: Position): Ident = new Ident(v)(pos)
|
def apply(v: String)(pos: Position): Ident = new Ident(v)(pos)
|
||||||
}
|
}
|
||||||
case class ArrayElem(name: Ident, indices: NonEmptyList[Expr])(val pos: Position)
|
case class ArrayElem(name: Ident, indices: NonEmptyList[Expr])(val pos: Position)
|
||||||
extends Expr6
|
extends Expr6
|
||||||
with LValue
|
with LValue
|
||||||
object ArrayElem extends ParserBridgePos1[NonEmptyList[Expr], Ident => ArrayElem] {
|
object ArrayElem extends ParserBridgePos2Chain[NonEmptyList[Expr], Ident, ArrayElem] {
|
||||||
def apply(a: NonEmptyList[Expr])(pos: Position): Ident => ArrayElem =
|
def apply(indices: NonEmptyList[Expr], name: Ident)(pos: Position): ArrayElem =
|
||||||
name => ArrayElem(name, a)(pos)
|
new ArrayElem(name, indices)(pos)
|
||||||
}
|
}
|
||||||
|
// object ArrayElem extends ParserBridgePos1[NonEmptyList[Expr], (File => Ident) => ArrayElem] {
|
||||||
|
// def apply(a: NonEmptyList[Expr])(pos: Position): (File => Ident) => ArrayElem =
|
||||||
|
// name => ArrayElem(name(pos.file), a)(pos)
|
||||||
|
// }
|
||||||
|
// object ArrayElem extends ParserSingletonBridgePos[(File => NonEmptyList[Expr]) => (File => Ident) => File => ArrayElem] {
|
||||||
|
// // def apply(indices: NonEmptyList[Expr]): (File => Ident) => File => ArrayElem =
|
||||||
|
// // name => file => new ArrayElem(name(file), )
|
||||||
|
// def apply(indices: Parsley[File => NonEmptyList[Expr]]): Parsley[(File => Ident) => File => ArrayElem] =
|
||||||
|
// // error(ap1(pos.map(con),))
|
||||||
|
|
||||||
|
// override final def con(pos: (Int, Int)): (File => NonEmptyList[Expr]) => => C =
|
||||||
|
// (a, b) => file => this.apply(a(file), b(file))(Position(pos._1, pos._2, file))
|
||||||
|
// }
|
||||||
case class Parens(expr: Expr)(val pos: Position) extends Expr6
|
case class Parens(expr: Expr)(val pos: Position) extends Expr6
|
||||||
object Parens extends ParserBridgePos1[Expr, Parens]
|
object Parens extends ParserBridgePos1[Expr, Parens]
|
||||||
|
|
||||||
@@ -120,8 +136,9 @@ object ast {
|
|||||||
case class ArrayType(elemType: Type, dimensions: Int)(val pos: Position)
|
case class ArrayType(elemType: Type, dimensions: Int)(val pos: Position)
|
||||||
extends Type
|
extends Type
|
||||||
with PairElemType
|
with PairElemType
|
||||||
object ArrayType extends ParserBridgePos1[Int, Type => ArrayType] {
|
object ArrayType extends ParserBridgePos2Chain[Int, Type, ArrayType] {
|
||||||
def apply(a: Int)(pos: Position): Type => ArrayType = elemType => ArrayType(elemType, a)(pos)
|
def apply(dimensions: Int, elemType: Type)(pos: Position): ArrayType =
|
||||||
|
ArrayType(elemType, dimensions)(pos)
|
||||||
}
|
}
|
||||||
case class PairType(fst: PairElemType, snd: PairElemType)(val pos: Position) extends Type
|
case class PairType(fst: PairElemType, snd: PairElemType)(val pos: Position) extends Type
|
||||||
object PairType extends ParserBridgePos2[PairElemType, PairElemType, PairType]
|
object PairType extends ParserBridgePos2[PairElemType, PairElemType, PairType]
|
||||||
@@ -132,6 +149,18 @@ object ast {
|
|||||||
|
|
||||||
/* ============================ PROGRAM STRUCTURE ============================ */
|
/* ============================ PROGRAM STRUCTURE ============================ */
|
||||||
|
|
||||||
|
case class ImportedFunc(sourceName: Ident, importName: Ident)(val pos: Position)
|
||||||
|
object ImportedFunc extends ParserBridgePos2[Ident, Option[Ident], ImportedFunc] {
|
||||||
|
def apply(a: Ident, b: Option[Ident])(pos: Position): ImportedFunc =
|
||||||
|
new ImportedFunc(a, b.getOrElse(a))(pos)
|
||||||
|
}
|
||||||
|
|
||||||
|
case class Import(source: StrLiter, funcs: NonEmptyList[ImportedFunc])(val pos: Position)
|
||||||
|
object Import extends ParserBridgePos2[StrLiter, NonEmptyList[ImportedFunc], Import]
|
||||||
|
|
||||||
|
case class PartialProgram(imports: List[Import], self: Program)(val pos: Position)
|
||||||
|
object PartialProgram extends ParserBridgePos2[List[Import], Program, PartialProgram]
|
||||||
|
|
||||||
case class Program(funcs: List[FuncDecl], main: NonEmptyList[Stmt])(val pos: Position)
|
case class Program(funcs: List[FuncDecl], main: NonEmptyList[Stmt])(val pos: Position)
|
||||||
object Program extends ParserBridgePos2[List[FuncDecl], NonEmptyList[Stmt], Program]
|
object Program extends ParserBridgePos2[List[FuncDecl], NonEmptyList[Stmt], Program]
|
||||||
|
|
||||||
@@ -144,15 +173,15 @@ object ast {
|
|||||||
body: NonEmptyList[Stmt]
|
body: NonEmptyList[Stmt]
|
||||||
)(val pos: Position)
|
)(val pos: Position)
|
||||||
object FuncDecl
|
object FuncDecl
|
||||||
extends ParserBridgePos2[
|
extends ParserBridgePos2Chain[
|
||||||
List[Param],
|
(List[Param], NonEmptyList[Stmt]),
|
||||||
NonEmptyList[Stmt],
|
((Type, Ident)),
|
||||||
((Type, Ident)) => FuncDecl
|
FuncDecl
|
||||||
] {
|
] {
|
||||||
def apply(params: List[Param], body: NonEmptyList[Stmt])(
|
def apply(paramsBody: (List[Param], NonEmptyList[Stmt]), retTyName: (Type, Ident))(
|
||||||
pos: Position
|
pos: Position
|
||||||
): ((Type, Ident)) => FuncDecl =
|
): FuncDecl =
|
||||||
(returnType, name) => FuncDecl(returnType, name, params, body)(pos)
|
new FuncDecl(retTyName._1, retTyName._2, paramsBody._1, paramsBody._2)(pos)
|
||||||
}
|
}
|
||||||
|
|
||||||
case class Param(paramType: Type, name: Ident)(val pos: Position)
|
case class Param(paramType: Type, name: Ident)(val pos: Position)
|
||||||
@@ -160,7 +189,9 @@ object ast {
|
|||||||
|
|
||||||
/* ============================ STATEMENTS ============================ */
|
/* ============================ STATEMENTS ============================ */
|
||||||
|
|
||||||
sealed trait Stmt
|
sealed trait Stmt {
|
||||||
|
val pos: Position
|
||||||
|
}
|
||||||
case class Skip()(val pos: Position) extends Stmt
|
case class Skip()(val pos: Position) extends Stmt
|
||||||
object Skip extends ParserBridgePos0[Skip]
|
object Skip extends ParserBridgePos0[Skip]
|
||||||
case class VarDecl(varType: Type, name: Ident, value: RValue)(val pos: Position) extends Stmt
|
case class VarDecl(varType: Type, name: Ident, value: RValue)(val pos: Position) extends Stmt
|
||||||
@@ -192,7 +223,9 @@ object ast {
|
|||||||
val pos: Position
|
val pos: Position
|
||||||
}
|
}
|
||||||
|
|
||||||
sealed trait RValue
|
sealed trait RValue {
|
||||||
|
val pos: Position
|
||||||
|
}
|
||||||
case class ArrayLiter(elems: List[Expr])(val pos: Position) extends RValue
|
case class ArrayLiter(elems: List[Expr])(val pos: Position) extends RValue
|
||||||
object ArrayLiter extends ParserBridgePos1[List[Expr], ArrayLiter]
|
object ArrayLiter extends ParserBridgePos1[List[Expr], ArrayLiter]
|
||||||
case class NewPair(fst: Expr, snd: Expr)(val pos: Position) extends RValue
|
case class NewPair(fst: Expr, snd: Expr)(val pos: Position) extends RValue
|
||||||
@@ -208,7 +241,7 @@ object ast {
|
|||||||
|
|
||||||
/* ============================ PARSER BRIDGES ============================ */
|
/* ============================ PARSER BRIDGES ============================ */
|
||||||
|
|
||||||
case class Position(line: Int, column: Int)
|
case class Position(line: Int, column: Int, file: File)
|
||||||
|
|
||||||
trait ParserSingletonBridgePos[+A] extends ErrorBridge {
|
trait ParserSingletonBridgePos[+A] extends ErrorBridge {
|
||||||
protected def con(pos: (Int, Int)): A
|
protected def con(pos: (Int, Int)): A
|
||||||
@@ -216,38 +249,63 @@ object ast {
|
|||||||
final def <#(op: Parsley[?]): Parsley[A] = this from op
|
final def <#(op: Parsley[?]): Parsley[A] = this from op
|
||||||
}
|
}
|
||||||
|
|
||||||
trait ParserBridgePos0[+A] extends ParserSingletonBridgePos[A] {
|
trait ParserBridgePos0[+A] extends ParserSingletonBridgePos[File => A] {
|
||||||
def apply()(pos: Position): A
|
def apply()(pos: Position): A
|
||||||
|
|
||||||
override final def con(pos: (Int, Int)): A =
|
override final def con(pos: (Int, Int)): File => A =
|
||||||
apply()(Position(pos._1, pos._2))
|
file => apply()(Position(pos._1, pos._2, file))
|
||||||
}
|
}
|
||||||
|
|
||||||
trait ParserBridgePos1[-A, +B] extends ParserSingletonBridgePos[A => B] {
|
trait ParserBridgePos1Atom[-A, +B] extends ParserSingletonBridgePos[A => File => B] {
|
||||||
def apply(a: A)(pos: Position): B
|
def apply(a: A)(pos: Position): B
|
||||||
def apply(a: Parsley[A]): Parsley[B] = error(ap1(pos.map(con), a))
|
def apply(a: Parsley[A]): Parsley[File => B] = error(ap1(pos.map(con), a))
|
||||||
|
|
||||||
override final def con(pos: (Int, Int)): A => B =
|
override final def con(pos: (Int, Int)): A => File => B =
|
||||||
this.apply(_)(Position(pos._1, pos._2))
|
a => file => this.apply(a)(Position(pos._1, pos._2, file))
|
||||||
}
|
}
|
||||||
|
|
||||||
trait ParserBridgePos2[-A, -B, +C] extends ParserSingletonBridgePos[(A, B) => C] {
|
trait ParserBridgePos1[-A, +B] extends ParserSingletonBridgePos[(File => A) => File => B] {
|
||||||
|
def apply(a: A)(pos: Position): B
|
||||||
|
def apply(a: Parsley[File => A]): Parsley[File => B] = error(ap1(pos.map(con), a))
|
||||||
|
|
||||||
|
override final def con(pos: (Int, Int)): (File => A) => File => B =
|
||||||
|
a => file => this.apply(a(file))(Position(pos._1, pos._2, file))
|
||||||
|
}
|
||||||
|
|
||||||
|
trait ParserBridgePos2Chain[-A, -B, +C]
|
||||||
|
extends ParserSingletonBridgePos[(File => A) => (File => B) => File => C] {
|
||||||
def apply(a: A, b: B)(pos: Position): C
|
def apply(a: A, b: B)(pos: Position): C
|
||||||
def apply(a: Parsley[A], b: => Parsley[B]): Parsley[C] = error(
|
def apply(a: Parsley[File => A]): Parsley[(File => B) => File => C] = error(
|
||||||
|
ap1(pos.map(con), a)
|
||||||
|
)
|
||||||
|
|
||||||
|
override final def con(pos: (Int, Int)): (File => A) => (File => B) => File => C =
|
||||||
|
a => b => file => this.apply(a(file), b(file))(Position(pos._1, pos._2, file))
|
||||||
|
}
|
||||||
|
|
||||||
|
trait ParserBridgePos2[-A, -B, +C]
|
||||||
|
extends ParserSingletonBridgePos[(File => A, File => B) => File => C] {
|
||||||
|
def apply(a: A, b: B)(pos: Position): C
|
||||||
|
def apply(a: Parsley[File => A], b: => Parsley[File => B]): Parsley[File => C] = error(
|
||||||
ap2(pos.map(con), a, b)
|
ap2(pos.map(con), a, b)
|
||||||
)
|
)
|
||||||
|
|
||||||
override final def con(pos: (Int, Int)): (A, B) => C =
|
override final def con(pos: (Int, Int)): (File => A, File => B) => File => C =
|
||||||
apply(_, _)(Position(pos._1, pos._2))
|
(a, b) => file => this.apply(a(file), b(file))(Position(pos._1, pos._2, file))
|
||||||
}
|
}
|
||||||
|
|
||||||
trait ParserBridgePos3[-A, -B, -C, +D] extends ParserSingletonBridgePos[(A, B, C) => D] {
|
trait ParserBridgePos3[-A, -B, -C, +D]
|
||||||
|
extends ParserSingletonBridgePos[(File => A, File => B, File => C) => File => D] {
|
||||||
def apply(a: A, b: B, c: C)(pos: Position): D
|
def apply(a: A, b: B, c: C)(pos: Position): D
|
||||||
def apply(a: Parsley[A], b: => Parsley[B], c: => Parsley[C]): Parsley[D] = error(
|
def apply(
|
||||||
|
a: Parsley[File => A],
|
||||||
|
b: => Parsley[File => B],
|
||||||
|
c: => Parsley[File => C]
|
||||||
|
): Parsley[File => D] = error(
|
||||||
ap3(pos.map(con), a, b, c)
|
ap3(pos.map(con), a, b, c)
|
||||||
)
|
)
|
||||||
|
|
||||||
override final def con(pos: (Int, Int)): (A, B, C) => D =
|
override final def con(pos: (Int, Int)): (File => A, File => B, File => C) => File => D =
|
||||||
apply(_, _, _)(Position(pos._1, pos._2))
|
(a, b, c) => file => apply(a(file), b(file), c(file))(Position(pos._1, pos._2, file))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
package wacc
|
package wacc
|
||||||
|
|
||||||
|
import cats.data.Chain
|
||||||
|
|
||||||
object microWacc {
|
object microWacc {
|
||||||
|
import wacc.ast.Position
|
||||||
import wacc.types._
|
import wacc.types._
|
||||||
|
|
||||||
sealed trait CallTarget(val retTy: SemType)
|
sealed trait CallTarget(val retTy: SemType)
|
||||||
@@ -11,7 +14,7 @@ object microWacc {
|
|||||||
case class IntLiter(v: Int) extends Expr(KnownType.Int)
|
case class IntLiter(v: Int) extends Expr(KnownType.Int)
|
||||||
case class BoolLiter(v: Boolean) extends Expr(KnownType.Bool)
|
case class BoolLiter(v: Boolean) extends Expr(KnownType.Bool)
|
||||||
case class CharLiter(v: Char) extends Expr(KnownType.Char)
|
case class CharLiter(v: Char) extends Expr(KnownType.Char)
|
||||||
case class ArrayLiter(elems: List[Expr])(ty: SemType) extends Expr(ty)
|
case class ArrayLiter(elems: List[Expr])(ty: SemType, val pos: Position) extends Expr(ty)
|
||||||
case class NullLiter()(ty: SemType) extends Expr(ty)
|
case class NullLiter()(ty: SemType) extends Expr(ty)
|
||||||
case class Ident(name: String, uid: Int)(identTy: SemType)
|
case class Ident(name: String, uid: Int)(identTy: SemType)
|
||||||
extends Expr(identTy)
|
extends Expr(identTy)
|
||||||
@@ -63,7 +66,9 @@ object microWacc {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Statements
|
// Statements
|
||||||
sealed trait Stmt
|
sealed trait Stmt {
|
||||||
|
val pos: Position
|
||||||
|
}
|
||||||
|
|
||||||
case class Builtin(val name: String)(retTy: SemType) extends CallTarget(retTy) {
|
case class Builtin(val name: String)(retTy: SemType) extends CallTarget(retTy) {
|
||||||
override def toString(): String = name
|
override def toString(): String = name
|
||||||
@@ -77,13 +82,16 @@ object microWacc {
|
|||||||
object PrintCharArray extends Builtin("printCharArray")(?)
|
object PrintCharArray extends Builtin("printCharArray")(?)
|
||||||
}
|
}
|
||||||
|
|
||||||
case class Assign(lhs: LValue, rhs: Expr) extends Stmt
|
case class Assign(lhs: LValue, rhs: Expr)(val pos: Position) extends Stmt
|
||||||
case class If(cond: Expr, thenBranch: List[Stmt], elseBranch: List[Stmt]) extends Stmt
|
case class If(cond: Expr, thenBranch: Chain[Stmt], elseBranch: Chain[Stmt])(val pos: Position)
|
||||||
case class While(cond: Expr, body: List[Stmt]) extends Stmt
|
extends Stmt
|
||||||
case class Call(target: CallTarget, args: List[Expr]) extends Stmt with Expr(target.retTy)
|
case class While(cond: Expr, body: Chain[Stmt])(val pos: Position) extends Stmt
|
||||||
case class Return(expr: Expr) extends Stmt
|
case class Call(target: CallTarget, args: List[Expr])(val pos: Position)
|
||||||
|
extends Stmt
|
||||||
|
with Expr(target.retTy)
|
||||||
|
case class Return(expr: Expr)(val pos: Position) extends Stmt
|
||||||
|
|
||||||
// Program
|
// Program
|
||||||
case class FuncDecl(name: Ident, params: List[Ident], body: List[Stmt])
|
case class FuncDecl(name: Ident, params: List[Ident], body: Chain[Stmt])(val pos: Position)
|
||||||
case class Program(funcs: List[FuncDecl], stmts: List[Stmt])
|
case class Program(funcs: Chain[FuncDecl], stmts: Chain[Stmt])(val pos: Position)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,18 +1,22 @@
|
|||||||
package wacc
|
package wacc
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
import parsley.Result
|
import parsley.Result
|
||||||
import parsley.Parsley
|
import parsley.Parsley
|
||||||
import parsley.Parsley.{atomic, many, notFollowedBy, pure, unit}
|
import parsley.Parsley.{atomic, many, notFollowedBy, pure, unit}
|
||||||
import parsley.combinator.{countSome, sepBy}
|
import parsley.combinator.{countSome, sepBy, option}
|
||||||
import parsley.expr.{precedence, SOps, InfixL, InfixN, InfixR, Prefix, Atoms}
|
import parsley.expr.{precedence, SOps, InfixL, InfixN, InfixR, Prefix, Atoms}
|
||||||
import parsley.errors.combinator._
|
import parsley.errors.combinator._
|
||||||
import parsley.errors.patterns.VerifiedErrors
|
import parsley.errors.patterns.VerifiedErrors
|
||||||
import parsley.syntax.zipped._
|
import parsley.syntax.zipped._
|
||||||
import parsley.cats.combinator.{some}
|
import parsley.cats.combinator.{some, sepBy1}
|
||||||
|
import cats.syntax.all._
|
||||||
import cats.data.NonEmptyList
|
import cats.data.NonEmptyList
|
||||||
import parsley.errors.DefaultErrorBuilder
|
import parsley.errors.DefaultErrorBuilder
|
||||||
import parsley.errors.ErrorBuilder
|
import parsley.errors.ErrorBuilder
|
||||||
import parsley.errors.tokenextractors.LexToken
|
import parsley.errors.tokenextractors.LexToken
|
||||||
|
import parsley.expr.GOps
|
||||||
|
import cats.Functor
|
||||||
|
|
||||||
object parser {
|
object parser {
|
||||||
import lexer.implicits.implicitSymbol
|
import lexer.implicits.implicitSymbol
|
||||||
@@ -52,13 +56,24 @@ object parser {
|
|||||||
implicit val builder: ErrorBuilder[String] = new DefaultErrorBuilder with LexToken {
|
implicit val builder: ErrorBuilder[String] = new DefaultErrorBuilder with LexToken {
|
||||||
def tokens = errTokens
|
def tokens = errTokens
|
||||||
}
|
}
|
||||||
def parse(input: String): Result[String, Program] = parser.parse(input)
|
def parse(input: String): Result[String, File => PartialProgram] = parser.parse(input)
|
||||||
private val parser = lexer.fully(`<program>`)
|
private val parser = lexer.fully(`<partial-program>`)
|
||||||
|
|
||||||
|
private type FParsley[A] = Parsley[File => A]
|
||||||
|
|
||||||
|
private def fParsley[A](p: Parsley[A]): FParsley[A] =
|
||||||
|
p map { a => file => a }
|
||||||
|
|
||||||
|
private def fPair[A, B](p: Parsley[(File => A, File => B)]): FParsley[(A, B)] =
|
||||||
|
p map { case (a, b) => file => (a(file), b(file)) }
|
||||||
|
|
||||||
|
private def fMap[A, F[_]: Functor](p: Parsley[F[File => A]]): FParsley[F[A]] =
|
||||||
|
p map { funcs => file => funcs.map(_(file)) }
|
||||||
|
|
||||||
// Expressions
|
// Expressions
|
||||||
private lazy val `<expr>`: Parsley[Expr] = precedence {
|
private lazy val `<expr>`: FParsley[Expr] = precedence {
|
||||||
SOps(InfixR)(Or from "||") +:
|
GOps(InfixR)(Or from "||") +:
|
||||||
SOps(InfixR)(And from "&&") +:
|
GOps(InfixR)(And from "&&") +:
|
||||||
SOps(InfixN)(Eq from "==", Neq from "!=") +:
|
SOps(InfixN)(Eq from "==", Neq from "!=") +:
|
||||||
SOps(InfixN)(
|
SOps(InfixN)(
|
||||||
Less from "<",
|
Less from "<",
|
||||||
@@ -83,32 +98,33 @@ object parser {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Atoms
|
// Atoms
|
||||||
private lazy val `<atom>`: Atoms[Expr6] = Atoms(
|
private lazy val `<atom>`: Atoms[File => Expr6] = Atoms(
|
||||||
IntLiter(integer).label("integer literal"),
|
IntLiter(integer).label("integer literal"),
|
||||||
BoolLiter(("true" as true) | ("false" as false)).label("boolean literal"),
|
BoolLiter(("true" as true) | ("false" as false)).label("boolean literal"),
|
||||||
CharLiter(charLit).label("character literal"),
|
CharLiter(charLit).label("character literal"),
|
||||||
StrLiter(stringLit).label("string literal"),
|
`<str-liter>`.label("string literal"),
|
||||||
PairLiter from "null",
|
PairLiter from "null",
|
||||||
`<ident-or-array-elem>`,
|
`<ident-or-array-elem>`,
|
||||||
Parens("(" ~> `<expr>` <~ ")")
|
Parens("(" ~> `<expr>` <~ ")")
|
||||||
)
|
)
|
||||||
private val `<ident>` =
|
private lazy val `<str-liter>` = StrLiter(stringLit)
|
||||||
|
private lazy val `<ident>` =
|
||||||
Ident(ident) | some("*" | "&").verifiedExplain("pointer operators are not allowed")
|
Ident(ident) | some("*" | "&").verifiedExplain("pointer operators are not allowed")
|
||||||
private lazy val `<ident-or-array-elem>` =
|
private lazy val `<ident-or-array-elem>` =
|
||||||
(`<ident>` <~ ("(".verifiedExplain(
|
(`<ident>` <~ ("(".verifiedExplain(
|
||||||
"functions can only be called using 'call' keyword"
|
"functions can only be called using 'call' keyword"
|
||||||
) | unit)) <**> (`<array-indices>` </> identity)
|
) | unit)) <**> (`<array-indices>` </> identity)
|
||||||
private val `<array-indices>` = ArrayElem(some("[" ~> `<expr>` <~ "]"))
|
private lazy val `<array-indices>` = ArrayElem(fMap(some("[" ~> `<expr>` <~ "]")))
|
||||||
|
|
||||||
// Types
|
// Types
|
||||||
private lazy val `<type>`: Parsley[Type] =
|
private lazy val `<type>`: FParsley[Type] =
|
||||||
(`<base-type>` | (`<pair-type>` ~> `<pair-elems-type>`)) <**> (`<array-type>` </> identity)
|
(`<base-type>` | (`<pair-type>` ~> `<pair-elems-type>`)) <**> (`<array-type>` </> identity)
|
||||||
private val `<base-type>` =
|
private val `<base-type>` =
|
||||||
(IntType from "int") | (BoolType from "bool") | (CharType from "char") | (StringType from "string")
|
(IntType from "int") | (BoolType from "bool") | (CharType from "char") | (StringType from "string")
|
||||||
private lazy val `<array-type>` =
|
private lazy val `<array-type>` =
|
||||||
ArrayType(countSome("[" ~> "]"))
|
ArrayType(fParsley(countSome("[" ~> "]")))
|
||||||
private val `<pair-type>` = "pair"
|
private val `<pair-type>` = "pair"
|
||||||
private val `<pair-elems-type>`: Parsley[PairType] = PairType(
|
private val `<pair-elems-type>`: FParsley[PairType] = PairType(
|
||||||
"(" ~> `<pair-elem-type>` <~ ",",
|
"(" ~> `<pair-elem-type>` <~ ",",
|
||||||
`<pair-elem-type>` <~ ")"
|
`<pair-elem-type>` <~ ")"
|
||||||
)
|
)
|
||||||
@@ -116,7 +132,7 @@ object parser {
|
|||||||
(`<base-type>` <**> (`<array-type>` </> identity)) |
|
(`<base-type>` <**> (`<array-type>` </> identity)) |
|
||||||
((UntypedPairType from `<pair-type>`) <**>
|
((UntypedPairType from `<pair-type>`) <**>
|
||||||
((`<pair-elems-type>` <**> `<array-type>`)
|
((`<pair-elems-type>` <**> `<array-type>`)
|
||||||
.map(arr => (_: UntypedPairType) => arr) </> identity))
|
.map(arr => (_: File => UntypedPairType) => arr) </> identity))
|
||||||
|
|
||||||
/* Statements
|
/* Statements
|
||||||
Atomic is used in two places here:
|
Atomic is used in two places here:
|
||||||
@@ -127,13 +143,30 @@ object parser {
|
|||||||
invalid syntax check, this only happens at most once per program so this is not a major
|
invalid syntax check, this only happens at most once per program so this is not a major
|
||||||
concern.
|
concern.
|
||||||
*/
|
*/
|
||||||
|
private lazy val `<partial-program>` = PartialProgram(
|
||||||
|
fMap(many(`<import>`)),
|
||||||
|
`<program>`
|
||||||
|
)
|
||||||
|
private lazy val `<import>` = Import(
|
||||||
|
"import" ~> `<import-filename>`,
|
||||||
|
"(" ~> fMap(sepBy1(`<imported-func>`, ",")) <~ ")"
|
||||||
|
)
|
||||||
|
private lazy val `<import-filename>` = `<str-liter>`.label("import file name")
|
||||||
|
private lazy val `<imported-func>` = ImportedFunc(
|
||||||
|
`<ident>`.label("imported function name"),
|
||||||
|
fMap(option("as" ~> `<ident>`)).label("imported function alias")
|
||||||
|
)
|
||||||
private lazy val `<program>` = Program(
|
private lazy val `<program>` = Program(
|
||||||
"begin" ~> (
|
"begin" ~> (
|
||||||
many(
|
fMap(
|
||||||
atomic(
|
many(
|
||||||
`<type>`.label("function declaration") <~> `<ident>` <~ "("
|
fPair(
|
||||||
) <**> `<partial-func-decl>`
|
atomic(
|
||||||
).label("function declaration") |
|
`<type>`.label("function declaration") <~> `<ident>` <~ "("
|
||||||
|
)
|
||||||
|
) <**> `<partial-func-decl>`
|
||||||
|
).label("function declaration")
|
||||||
|
) |
|
||||||
atomic(`<ident>` <~ "(").verifiedExplain("function declaration is missing return type")
|
atomic(`<ident>` <~ "(").verifiedExplain("function declaration is missing return type")
|
||||||
),
|
),
|
||||||
`<stmt>`.label(
|
`<stmt>`.label(
|
||||||
@@ -142,17 +175,23 @@ object parser {
|
|||||||
)
|
)
|
||||||
private lazy val `<partial-func-decl>` =
|
private lazy val `<partial-func-decl>` =
|
||||||
FuncDecl(
|
FuncDecl(
|
||||||
sepBy(`<param>`, ",") <~ ")" <~ "is",
|
fPair(
|
||||||
`<stmt>`.guardAgainst {
|
(fMap(sepBy(`<param>`, ",")) <~ ")" <~ "is") <~>
|
||||||
case stmts if !stmts.isReturning => Seq("all functions must end in a returning statement")
|
(`<stmt>`.guardAgainst {
|
||||||
} <~ "end"
|
// TODO: passing in an arbitrary file works but is ugly
|
||||||
|
case stmts if !(stmts(File("."))).isReturning =>
|
||||||
|
Seq("all functions must end in a returning statement")
|
||||||
|
} <~ "end")
|
||||||
|
)
|
||||||
)
|
)
|
||||||
private lazy val `<param>` = Param(`<type>`, `<ident>`)
|
private lazy val `<param>` = Param(`<type>`, `<ident>`)
|
||||||
private lazy val `<stmt>`: Parsley[NonEmptyList[Stmt]] =
|
private lazy val `<stmt>`: FParsley[NonEmptyList[Stmt]] =
|
||||||
(
|
fMap(
|
||||||
`<basic-stmt>`.label("main program body"),
|
(
|
||||||
(many(";" ~> `<basic-stmt>`.label("statement after ';'"))) </> Nil
|
`<basic-stmt>`.label("main program body"),
|
||||||
).zipped(NonEmptyList.apply)
|
(many(";" ~> `<basic-stmt>`.label("statement after ';'"))) </> Nil
|
||||||
|
).zipped(NonEmptyList.apply)
|
||||||
|
)
|
||||||
|
|
||||||
private lazy val `<basic-stmt>` =
|
private lazy val `<basic-stmt>` =
|
||||||
(Skip from "skip")
|
(Skip from "skip")
|
||||||
@@ -160,8 +199,8 @@ object parser {
|
|||||||
| Free("free" ~> `<expr>`.labelAndExplain(LabelType.Expr))
|
| Free("free" ~> `<expr>`.labelAndExplain(LabelType.Expr))
|
||||||
| Return("return" ~> `<expr>`.labelAndExplain(LabelType.Expr))
|
| Return("return" ~> `<expr>`.labelAndExplain(LabelType.Expr))
|
||||||
| Exit("exit" ~> `<expr>`.labelAndExplain(LabelType.Expr))
|
| Exit("exit" ~> `<expr>`.labelAndExplain(LabelType.Expr))
|
||||||
| Print("print" ~> `<expr>`.labelAndExplain(LabelType.Expr), pure(false))
|
| Print("print" ~> `<expr>`.labelAndExplain(LabelType.Expr), fParsley(pure(false)))
|
||||||
| Print("println" ~> `<expr>`.labelAndExplain(LabelType.Expr), pure(true))
|
| Print("println" ~> `<expr>`.labelAndExplain(LabelType.Expr), fParsley(pure(true)))
|
||||||
| If(
|
| If(
|
||||||
"if" ~> `<expr>`.labelWithType(LabelType.Expr) <~ "then",
|
"if" ~> `<expr>`.labelWithType(LabelType.Expr) <~ "then",
|
||||||
`<stmt>` <~ "else",
|
`<stmt>` <~ "else",
|
||||||
@@ -185,9 +224,9 @@ object parser {
|
|||||||
("call" ~> `<ident>`).verifiedExplain(
|
("call" ~> `<ident>`).verifiedExplain(
|
||||||
"function calls' results must be assigned to a variable"
|
"function calls' results must be assigned to a variable"
|
||||||
)
|
)
|
||||||
private lazy val `<lvalue>`: Parsley[LValue] =
|
private lazy val `<lvalue>`: FParsley[LValue] =
|
||||||
`<pair-elem>` | `<ident-or-array-elem>`
|
`<pair-elem>` | `<ident-or-array-elem>`
|
||||||
private lazy val `<rvalue>`: Parsley[RValue] =
|
private lazy val `<rvalue>`: FParsley[RValue] =
|
||||||
`<array-liter>` |
|
`<array-liter>` |
|
||||||
NewPair(
|
NewPair(
|
||||||
"newpair" ~> "(" ~> `<expr>` <~ ",",
|
"newpair" ~> "(" ~> `<expr>` <~ ",",
|
||||||
@@ -196,13 +235,13 @@ object parser {
|
|||||||
`<pair-elem>` |
|
`<pair-elem>` |
|
||||||
Call(
|
Call(
|
||||||
"call" ~> `<ident>` <~ "(",
|
"call" ~> `<ident>` <~ "(",
|
||||||
sepBy(`<expr>`, ",") <~ ")"
|
fMap(sepBy(`<expr>`, ",")) <~ ")"
|
||||||
) | `<expr>`.labelWithType(LabelType.Expr)
|
) | `<expr>`.labelWithType(LabelType.Expr)
|
||||||
private lazy val `<pair-elem>` =
|
private lazy val `<pair-elem>` =
|
||||||
Fst("fst" ~> `<lvalue>`.label("valid pair"))
|
Fst("fst" ~> `<lvalue>`.label("valid pair"))
|
||||||
| Snd("snd" ~> `<lvalue>`.label("valid pair"))
|
| Snd("snd" ~> `<lvalue>`.label("valid pair"))
|
||||||
private lazy val `<array-liter>` = ArrayLiter(
|
private lazy val `<array-liter>` = ArrayLiter(
|
||||||
"[" ~> sepBy(`<expr>`, ",") <~ "]"
|
"[" ~> fMap(sepBy(`<expr>`, ",")) <~ "]"
|
||||||
)
|
)
|
||||||
|
|
||||||
extension (stmts: NonEmptyList[Stmt]) {
|
extension (stmts: NonEmptyList[Stmt]) {
|
||||||
|
|||||||
@@ -1,126 +1,276 @@
|
|||||||
package wacc
|
package wacc
|
||||||
|
|
||||||
|
import java.io.File
|
||||||
import scala.collection.mutable
|
import scala.collection.mutable
|
||||||
|
import cats.effect.IO
|
||||||
|
import cats.implicits._
|
||||||
|
import cats.data.Chain
|
||||||
|
import cats.data.NonEmptyList
|
||||||
|
import parsley.{Failure, Success}
|
||||||
|
|
||||||
object renamer {
|
object renamer {
|
||||||
import ast._
|
import ast._
|
||||||
import types._
|
import types._
|
||||||
|
|
||||||
private enum IdentType {
|
val MAIN = "$main"
|
||||||
|
|
||||||
|
enum IdentType {
|
||||||
case Func
|
case Func
|
||||||
case Var
|
case Var
|
||||||
}
|
}
|
||||||
|
|
||||||
private class Scope(
|
case class ScopeKey(path: String, name: String, identType: IdentType)
|
||||||
val current: mutable.Map[(String, IdentType), Ident],
|
case class ScopeValue(id: Ident, public: Boolean)
|
||||||
val parent: Map[(String, IdentType), Ident]
|
|
||||||
|
class Scope(
|
||||||
|
private val current: mutable.Map[ScopeKey, ScopeValue],
|
||||||
|
private val parent: Map[ScopeKey, ScopeValue],
|
||||||
|
guidStart: Int = 0,
|
||||||
|
val guidInc: Int = 1
|
||||||
) {
|
) {
|
||||||
|
private var guid = guidStart
|
||||||
|
private var immutable = false
|
||||||
|
|
||||||
|
private def nextGuid(): Int = {
|
||||||
|
val id = guid
|
||||||
|
guid += guidInc
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
private def verifyMutable(): Unit = {
|
||||||
|
if (immutable) throw new IllegalStateException("Cannot modify an immutable scope")
|
||||||
|
}
|
||||||
|
|
||||||
/** Create a new scope with the current scope as its parent.
|
/** Create a new scope with the current scope as its parent.
|
||||||
|
*
|
||||||
|
* To be used for single-threaded applications.
|
||||||
*
|
*
|
||||||
* @return
|
* @return
|
||||||
* A new scope with an empty current scope, and this scope flattened into the parent scope.
|
* A new scope with an empty current scope, and this scope flattened into the parent scope.
|
||||||
*/
|
*/
|
||||||
def subscope: Scope =
|
def withSubscope[T](f: Scope => T): T = {
|
||||||
Scope(mutable.Map.empty, Map.empty.withDefault(current.withDefault(parent)))
|
val subscope =
|
||||||
|
Scope(mutable.Map.empty, Map.empty.withDefault(current.withDefault(parent)), guid, guidInc)
|
||||||
|
immutable = true
|
||||||
|
val result = f(subscope)
|
||||||
|
guid = subscope.guid // Sync GUID
|
||||||
|
immutable = false
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Create new scopes with the current scope as its parent and GUID numbering adjusted
|
||||||
|
* correctly.
|
||||||
|
*
|
||||||
|
* This will permanently mark the current scope as immutable, for thread safety.
|
||||||
|
*
|
||||||
|
* To be used for multi-threaded applications.
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
* New scopes with an empty current scope, and this scope flattened into the parent scope.
|
||||||
|
*/
|
||||||
|
def subscopes(n: Int): Seq[Scope] = {
|
||||||
|
verifyMutable()
|
||||||
|
immutable = true
|
||||||
|
(0 until n).map { i =>
|
||||||
|
Scope(
|
||||||
|
mutable.Map.empty,
|
||||||
|
Map.empty.withDefault(current.withDefault(parent)),
|
||||||
|
guid + i * guidInc,
|
||||||
|
guidInc * n
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Attempt to add a new identifier to the current scope. If the identifier already exists in
|
/** Attempt to add a new identifier to the current scope. If the identifier already exists in
|
||||||
* the current scope, add an error to the error list.
|
* the current scope, add an error to the error list.
|
||||||
*
|
*
|
||||||
* @param ty
|
|
||||||
* The semantic type of the variable identifier, or function identifier type.
|
|
||||||
* @param name
|
* @param name
|
||||||
* The name of the identifier.
|
* The name of the identifier.
|
||||||
* @param globalNames
|
* @return
|
||||||
* The global map of identifiers to semantic types - the identifier will be added to this
|
* An error, if one occurred.
|
||||||
* map.
|
|
||||||
* @param globalNumbering
|
|
||||||
* The global map of identifier names to the number of times they have been declared - will
|
|
||||||
* used to rename this identifier, and will be incremented.
|
|
||||||
* @param errors
|
|
||||||
* The list of errors to append to.
|
|
||||||
*/
|
*/
|
||||||
def add(ty: SemType | FuncType, name: Ident)(using
|
def add(name: Ident, public: Boolean = false): Chain[Error] = {
|
||||||
globalNames: mutable.Map[Ident, SemType],
|
verifyMutable()
|
||||||
globalFuncs: mutable.Map[Ident, FuncType],
|
val path = name.pos.file.getCanonicalPath
|
||||||
globalNumbering: mutable.Map[String, Int],
|
val identType = name.ty match {
|
||||||
errors: mutable.Builder[Error, List[Error]]
|
|
||||||
) = {
|
|
||||||
val identType = ty match {
|
|
||||||
case _: SemType => IdentType.Var
|
case _: SemType => IdentType.Var
|
||||||
case _: FuncType => IdentType.Func
|
case _: FuncType => IdentType.Func
|
||||||
}
|
}
|
||||||
current.get((name.v, identType)) match {
|
val key = ScopeKey(path, name.v, identType)
|
||||||
case Some(Ident(_, uid)) =>
|
current.get(key) match {
|
||||||
errors += Error.DuplicateDeclaration(name)
|
case Some(ScopeValue(Ident(_, id, _), _)) =>
|
||||||
name.uid = uid
|
name.guid = id
|
||||||
|
Chain.one(Error.DuplicateDeclaration(name))
|
||||||
case None =>
|
case None =>
|
||||||
val uid = globalNumbering.getOrElse(name.v, 0)
|
name.guid = nextGuid()
|
||||||
name.uid = uid
|
current(key) = ScopeValue(name, public)
|
||||||
current((name.v, identType)) = name
|
Chain.empty
|
||||||
|
|
||||||
ty match {
|
|
||||||
case semType: SemType =>
|
|
||||||
globalNames(name) = semType
|
|
||||||
case funcType: FuncType =>
|
|
||||||
globalFuncs(name) = funcType
|
|
||||||
}
|
|
||||||
globalNumbering(name.v) = uid + 1
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private def get(name: String, identType: IdentType): Option[Ident] =
|
/** Attempt to add a new identifier as an alias to another to the existing scope.
|
||||||
|
*
|
||||||
|
* @param alias
|
||||||
|
* The (new) alias identifier.
|
||||||
|
* @param orig
|
||||||
|
* The (existing) original identifier.
|
||||||
|
*
|
||||||
|
* @return
|
||||||
|
* An error, if one occurred.
|
||||||
|
*/
|
||||||
|
def addAlias(alias: Ident, orig: ScopeValue, public: Boolean = false): Chain[Error] = {
|
||||||
|
verifyMutable()
|
||||||
|
val path = alias.pos.file.getCanonicalPath
|
||||||
|
val identType = alias.ty match {
|
||||||
|
case _: SemType => IdentType.Var
|
||||||
|
case _: FuncType => IdentType.Func
|
||||||
|
}
|
||||||
|
val key = ScopeKey(path, alias.v, identType)
|
||||||
|
current.get(key) match {
|
||||||
|
case Some(ScopeValue(Ident(_, id, _), _)) =>
|
||||||
|
alias.guid = id
|
||||||
|
Chain.one(Error.DuplicateDeclaration(alias))
|
||||||
|
case None =>
|
||||||
|
alias.guid = nextGuid()
|
||||||
|
current(key) = ScopeValue(orig.id, public)
|
||||||
|
Chain.empty
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def get(path: String, name: String, identType: IdentType): Option[ScopeValue] =
|
||||||
// Unfortunately map defaults only work with `.apply()`, which throws an error when the key is not found.
|
// Unfortunately map defaults only work with `.apply()`, which throws an error when the key is not found.
|
||||||
// Neither is there a way to check whether a default exists, so we have to use a try-catch.
|
// Neither is there a way to check whether a default exists, so we have to use a try-catch.
|
||||||
try {
|
try {
|
||||||
Some(current.withDefault(parent)((name, identType)))
|
Some(current.withDefault(parent)(ScopeKey(path, name, identType)))
|
||||||
} catch {
|
} catch {
|
||||||
case _: NoSuchElementException => None
|
case _: NoSuchElementException => None
|
||||||
}
|
}
|
||||||
|
|
||||||
def getVar(name: String): Option[Ident] = get(name, IdentType.Var)
|
def getVar(name: Ident): Option[Ident] =
|
||||||
def getFunc(name: String): Option[Ident] = get(name, IdentType.Func)
|
get(name.pos.file.getCanonicalPath, name.v, IdentType.Var).map(_.id)
|
||||||
|
def getFunc(name: Ident): Option[Ident] =
|
||||||
|
get(name.pos.file.getCanonicalPath, name.v, IdentType.Func).map(_.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Check scoping of all variables and functions in the program. Also generate semantic types for
|
def prepareGlobalScope(
|
||||||
* all identifiers.
|
partialProg: PartialProgram
|
||||||
*
|
)(using scope: Scope): IO[(FuncDecl, Chain[FuncDecl], Chain[Error])] = {
|
||||||
* @param prog
|
def readImportFile(file: File): IO[String] =
|
||||||
* AST of the program
|
IO.blocking(os.read(os.Path(file.getCanonicalPath)))
|
||||||
* @param errors
|
|
||||||
* List of errors to append to
|
def prepareImport(contents: String, file: File)(using
|
||||||
* @return
|
scope: Scope
|
||||||
* Map of all (renamed) identifies to their semantic types
|
): IO[(Chain[FuncDecl], Chain[Error])] = {
|
||||||
*/
|
parser.parse(contents) match {
|
||||||
def rename(prog: Program)(using
|
case Failure(msg) =>
|
||||||
errors: mutable.Builder[Error, List[Error]]
|
IO.pure(Chain.empty, Chain.one(Error.SyntaxError(file, msg)))
|
||||||
): (Map[Ident, SemType], Map[Ident, FuncType]) = {
|
case Success(fn) =>
|
||||||
given globalNames: mutable.Map[Ident, SemType] = mutable.Map.empty
|
val partialProg = fn(file)
|
||||||
given globalFuncs: mutable.Map[Ident, FuncType] = mutable.Map.empty
|
for {
|
||||||
given globalNumbering: mutable.Map[String, Int] = mutable.Map.empty
|
(main, chunks, errors) <- prepareGlobalScope(partialProg)
|
||||||
val scope = Scope(mutable.Map.empty, Map.empty)
|
} yield (main +: chunks, errors)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
def addImportsToScope(importFile: File, funcs: NonEmptyList[ImportedFunc])(using
|
||||||
|
scope: Scope
|
||||||
|
): Chain[Error] =
|
||||||
|
funcs.foldMap { case ImportedFunc(srcName, aliasName) =>
|
||||||
|
scope.get(importFile.getCanonicalPath, srcName.v, IdentType.Func) match {
|
||||||
|
case Some(src) if src.public =>
|
||||||
|
aliasName.ty = src.id.ty
|
||||||
|
scope.addAlias(aliasName, src)
|
||||||
|
case _ =>
|
||||||
|
Chain.one(Error.UndefinedFunction(srcName))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val PartialProgram(imports, prog) = partialProg
|
||||||
|
|
||||||
|
// First prepare this file's functions...
|
||||||
val Program(funcs, main) = prog
|
val Program(funcs, main) = prog
|
||||||
funcs
|
val (funcChunks, funcErrors) = funcs.foldLeft((Chain.empty[FuncDecl], Chain.empty[Error])) {
|
||||||
// First add all function declarations to the scope
|
case ((chunks, errors), func @ FuncDecl(retType, name, params, body)) =>
|
||||||
.map { case FuncDecl(retType, name, params, body) =>
|
|
||||||
val paramTypes = params.map { param =>
|
val paramTypes = params.map { param =>
|
||||||
val paramType = SemType(param.paramType)
|
val paramType = SemType(param.paramType)
|
||||||
|
param.name.ty = paramType
|
||||||
paramType
|
paramType
|
||||||
}
|
}
|
||||||
scope.add(FuncType(SemType(retType), paramTypes), name)
|
name.ty = FuncType(SemType(retType), paramTypes)
|
||||||
(params zip paramTypes, body)
|
(chunks :+ func, errors ++ scope.add(name, public = true))
|
||||||
|
}
|
||||||
|
// ...and main body.
|
||||||
|
val mainBodyIdent = Ident(MAIN, ty = FuncType(?, Nil))(main.head.pos)
|
||||||
|
val mainBodyErrors = scope.add(mainBodyIdent, public = false)
|
||||||
|
val mainBodyChunk = FuncDecl(IntType()(prog.pos), mainBodyIdent, Nil, main)(prog.pos)
|
||||||
|
|
||||||
|
// Now handle imports
|
||||||
|
val file = prog.pos.file
|
||||||
|
val preparedImports = imports.foldLeftM[IO, (Chain[FuncDecl], Chain[Error])](
|
||||||
|
(Chain.empty[FuncDecl], Chain.empty[Error])
|
||||||
|
) { case ((chunks, errors), Import(name, funcs)) =>
|
||||||
|
val importFile = File(file.getParent, name.v)
|
||||||
|
if (!importFile.exists()) {
|
||||||
|
IO.pure(
|
||||||
|
(
|
||||||
|
chunks,
|
||||||
|
errors :+ Error.SemanticError(
|
||||||
|
name.pos,
|
||||||
|
s"File not found: ${importFile.getCanonicalPath}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} else if (!importFile.canRead()) {
|
||||||
|
IO.pure(
|
||||||
|
(
|
||||||
|
chunks,
|
||||||
|
errors :+ Error.SemanticError(
|
||||||
|
name.pos,
|
||||||
|
s"File not readable: ${importFile.getCanonicalPath}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} else if (importFile.getCanonicalPath == file.getCanonicalPath) {
|
||||||
|
IO.pure(
|
||||||
|
(
|
||||||
|
chunks,
|
||||||
|
errors :+ Error.SemanticError(
|
||||||
|
name.pos,
|
||||||
|
s"Cannot import self: ${importFile.getCanonicalPath}"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} else if (scope.get(importFile.getCanonicalPath, MAIN, IdentType.Func).isDefined) {
|
||||||
|
IO.pure(chunks, errors ++ addImportsToScope(importFile, funcs))
|
||||||
|
} else {
|
||||||
|
for {
|
||||||
|
contents <- readImportFile(importFile)
|
||||||
|
(importChunks, importErrors) <- prepareImport(contents, importFile)
|
||||||
|
importAliasErrors = addImportsToScope(importFile, funcs)
|
||||||
|
} yield (chunks ++ importChunks, errors ++ importErrors)
|
||||||
}
|
}
|
||||||
// Only then rename the function bodies
|
}
|
||||||
// (functions can call one-another regardless of order of declaration)
|
|
||||||
.foreach { case (params, body) =>
|
for {
|
||||||
val functionScope = scope.subscope
|
(importChunks, importErrors) <- preparedImports
|
||||||
params.foreach { case (param, paramType) =>
|
allChunks = importChunks ++ funcChunks
|
||||||
functionScope.add(paramType, param.name)
|
allErrors = importErrors ++ funcErrors ++ mainBodyErrors
|
||||||
}
|
} yield (mainBodyChunk, allChunks, allErrors)
|
||||||
body.toList.foreach(rename(functionScope.subscope)) // body can shadow function params
|
}
|
||||||
}
|
|
||||||
main.toList.foreach(rename(scope))
|
/** Check scoping of all variables and flatten a program. Also generates semantic types and parses
|
||||||
(globalNames.toMap, globalFuncs.toMap)
|
* any imported files.
|
||||||
|
*
|
||||||
|
* @param partialProg
|
||||||
|
* AST of the program
|
||||||
|
* @return
|
||||||
|
* (flattenedProg, errors)
|
||||||
|
*/
|
||||||
|
def renameFunction(funcScopePair: (FuncDecl, Scope)): IO[Chain[Error]] = {
|
||||||
|
val (FuncDecl(_, _, params, body), subscope) = funcScopePair
|
||||||
|
val paramErrors = params.foldMap(param => subscope.add(param.name))
|
||||||
|
IO(subscope.withSubscope { s => body.foldMap(rename(s)) })
|
||||||
|
.map(bodyErrors => paramErrors ++ bodyErrors)
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Check scoping of all identifies in a given AST node.
|
/** Check scoping of all identifies in a given AST node.
|
||||||
@@ -129,91 +279,90 @@ object renamer {
|
|||||||
* The current scope and flattened parent scope.
|
* The current scope and flattened parent scope.
|
||||||
* @param node
|
* @param node
|
||||||
* The AST node.
|
* The AST node.
|
||||||
* @param globalNames
|
|
||||||
* The global map of identifiers to semantic types - renamed identifiers will be added to this
|
|
||||||
* map.
|
|
||||||
* @param globalNumbering
|
|
||||||
* The global map of identifier names to the number of times they have been declared - used and
|
|
||||||
* updated during identifier renaming.
|
|
||||||
* @param errors
|
|
||||||
*/
|
*/
|
||||||
private def rename(scope: Scope)(
|
private def rename(scope: Scope)(node: Ident | Stmt | LValue | RValue | Expr): Chain[Error] =
|
||||||
node: Ident | Stmt | LValue | RValue | Expr
|
node match {
|
||||||
)(using
|
// These cases are more interes/globting because the involve making subscopes
|
||||||
globalNames: mutable.Map[Ident, SemType],
|
// or modifying the current scope.
|
||||||
globalFuncs: mutable.Map[Ident, FuncType],
|
case VarDecl(synType, name, value) => {
|
||||||
globalNumbering: mutable.Map[String, Int],
|
// Order matters here. Variable isn't declared until after the value is evaluated.
|
||||||
errors: mutable.Builder[Error, List[Error]]
|
val errors = rename(scope)(value)
|
||||||
): Unit = node match {
|
// Attempt to add the new variable to the current scope.
|
||||||
// These cases are more interesting because the involve making subscopes
|
name.ty = SemType(synType)
|
||||||
// or modifying the current scope.
|
errors ++ scope.add(name)
|
||||||
case VarDecl(synType, name, value) => {
|
}
|
||||||
// Order matters here. Variable isn't declared until after the value is evaluated.
|
case If(cond, thenStmt, elseStmt) => {
|
||||||
rename(scope)(value)
|
val condErrors = rename(scope)(cond)
|
||||||
// Attempt to add the new variable to the current scope.
|
// then and else both have their own scopes
|
||||||
scope.add(SemType(synType), name)
|
val thenErrors = scope.withSubscope(s => thenStmt.foldMap(rename(s)))
|
||||||
}
|
val elseErrors = scope.withSubscope(s => elseStmt.foldMap(rename(s)))
|
||||||
case If(cond, thenStmt, elseStmt) => {
|
condErrors ++ thenErrors ++ elseErrors
|
||||||
rename(scope)(cond)
|
}
|
||||||
// then and else both have their own scopes
|
case While(cond, body) => {
|
||||||
thenStmt.toList.foreach(rename(scope.subscope))
|
val condErrors = rename(scope)(cond)
|
||||||
elseStmt.toList.foreach(rename(scope.subscope))
|
// while bodies have their own scopes
|
||||||
}
|
val bodyErrors = scope.withSubscope(s => body.foldMap(rename(s)))
|
||||||
case While(cond, body) => {
|
condErrors ++ bodyErrors
|
||||||
rename(scope)(cond)
|
}
|
||||||
// while bodies have their own scopes
|
// begin-end blocks have their own scopes
|
||||||
body.toList.foreach(rename(scope.subscope))
|
case Block(body) => scope.withSubscope(s => body.foldMap(rename(s)))
|
||||||
}
|
|
||||||
// begin-end blocks have their own scopes
|
|
||||||
case Block(body) => body.toList.foreach(rename(scope.subscope))
|
|
||||||
|
|
||||||
// These cases are simpler, mostly just recursive calls to rename()
|
// These cases are simpler, mostly just recursive calls to rename()
|
||||||
case Assign(lhs, value) => {
|
case Assign(lhs, value) => {
|
||||||
// Variables may be reassigned with their value in the rhs, so order doesn't matter here.
|
// Variables may be reassigned with their value in the rhs, so order doesn't matter here.
|
||||||
rename(scope)(lhs)
|
rename(scope)(lhs) ++ rename(scope)(value)
|
||||||
rename(scope)(value)
|
|
||||||
}
|
|
||||||
case Read(lhs) => rename(scope)(lhs)
|
|
||||||
case Free(expr) => rename(scope)(expr)
|
|
||||||
case Return(expr) => rename(scope)(expr)
|
|
||||||
case Exit(expr) => rename(scope)(expr)
|
|
||||||
case Print(expr, _) => rename(scope)(expr)
|
|
||||||
case NewPair(fst, snd) => {
|
|
||||||
rename(scope)(fst)
|
|
||||||
rename(scope)(snd)
|
|
||||||
}
|
|
||||||
case Call(name, args) => {
|
|
||||||
scope.getFunc(name.v) match {
|
|
||||||
case Some(Ident(_, uid)) => name.uid = uid
|
|
||||||
case None =>
|
|
||||||
errors += Error.UndefinedFunction(name)
|
|
||||||
scope.add(FuncType(?, args.map(_ => ?)), name)
|
|
||||||
}
|
}
|
||||||
args.foreach(rename(scope))
|
case Read(lhs) => rename(scope)(lhs)
|
||||||
}
|
case Free(expr) => rename(scope)(expr)
|
||||||
case Fst(elem) => rename(scope)(elem)
|
case Return(expr) => rename(scope)(expr)
|
||||||
case Snd(elem) => rename(scope)(elem)
|
case Exit(expr) => rename(scope)(expr)
|
||||||
case ArrayLiter(elems) => elems.foreach(rename(scope))
|
case Print(expr, _) => rename(scope)(expr)
|
||||||
case ArrayElem(name, indices) => {
|
case NewPair(fst, snd) => {
|
||||||
rename(scope)(name)
|
rename(scope)(fst) ++ rename(scope)(snd)
|
||||||
indices.toList.foreach(rename(scope))
|
|
||||||
}
|
|
||||||
case Parens(expr) => rename(scope)(expr)
|
|
||||||
case op: UnaryOp => rename(scope)(op.x)
|
|
||||||
case op: BinaryOp => {
|
|
||||||
rename(scope)(op.x)
|
|
||||||
rename(scope)(op.y)
|
|
||||||
}
|
|
||||||
// Default to variables. Only `call` uses IdentType.Func.
|
|
||||||
case id: Ident => {
|
|
||||||
scope.getVar(id.v) match {
|
|
||||||
case Some(Ident(_, uid)) => id.uid = uid
|
|
||||||
case None =>
|
|
||||||
errors += Error.UndeclaredVariable(id)
|
|
||||||
scope.add(?, id)
|
|
||||||
}
|
}
|
||||||
|
case Call(name, args) => {
|
||||||
|
val nameErrors = scope.getFunc(name) match {
|
||||||
|
case Some(Ident(realName, guid, ty)) =>
|
||||||
|
name.v = realName
|
||||||
|
name.ty = ty
|
||||||
|
name.guid = guid
|
||||||
|
Chain.empty
|
||||||
|
case None =>
|
||||||
|
name.ty = FuncType(?, args.map(_ => ?))
|
||||||
|
scope.add(name)
|
||||||
|
Chain.one(Error.UndefinedFunction(name))
|
||||||
|
}
|
||||||
|
val argsErrors = args.foldMap(rename(scope))
|
||||||
|
nameErrors ++ argsErrors
|
||||||
|
}
|
||||||
|
case Fst(elem) => rename(scope)(elem)
|
||||||
|
case Snd(elem) => rename(scope)(elem)
|
||||||
|
case ArrayLiter(elems) => elems.foldMap(rename(scope))
|
||||||
|
case ArrayElem(name, indices) => {
|
||||||
|
val nameErrors = rename(scope)(name)
|
||||||
|
val indicesErrors = indices.foldMap(rename(scope))
|
||||||
|
nameErrors ++ indicesErrors
|
||||||
|
}
|
||||||
|
case Parens(expr) => rename(scope)(expr)
|
||||||
|
case op: UnaryOp => rename(scope)(op.x)
|
||||||
|
case op: BinaryOp => {
|
||||||
|
rename(scope)(op.x) ++ rename(scope)(op.y)
|
||||||
|
}
|
||||||
|
// Default to variables. Only `call` uses IdentType.Func.
|
||||||
|
case id: Ident => {
|
||||||
|
scope.getVar(id) match {
|
||||||
|
case Some(Ident(_, guid, ty)) =>
|
||||||
|
id.ty = ty
|
||||||
|
id.guid = guid
|
||||||
|
Chain.empty
|
||||||
|
case None =>
|
||||||
|
id.ty = ?
|
||||||
|
scope.add(id)
|
||||||
|
Chain.one(Error.UndeclaredVariable(id))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// These literals cannot contain identifies, exit immediately.
|
||||||
|
case IntLiter(_) | BoolLiter(_) | CharLiter(_) | StrLiter(_) | PairLiter() | Skip() =>
|
||||||
|
Chain.empty
|
||||||
}
|
}
|
||||||
// These literals cannot contain identifies, exit immediately.
|
|
||||||
case IntLiter(_) | BoolLiter(_) | CharLiter(_) | StrLiter(_) | PairLiter() | Skip() => ()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
42
src/main/wacc/frontend/semantics.scala
Normal file
42
src/main/wacc/frontend/semantics.scala
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package wacc
|
||||||
|
|
||||||
|
import scala.collection.mutable
|
||||||
|
import cats.implicits._
|
||||||
|
import cats.data.Chain
|
||||||
|
import cats.effect.IO
|
||||||
|
|
||||||
|
object semantics {
|
||||||
|
import renamer.{Scope, prepareGlobalScope, renameFunction}
|
||||||
|
import typeChecker.checkFuncDecl
|
||||||
|
|
||||||
|
private def checkFunc(
|
||||||
|
funcDecl: ast.FuncDecl,
|
||||||
|
scope: Scope
|
||||||
|
): IO[(microWacc.FuncDecl, Chain[Error])] = {
|
||||||
|
for {
|
||||||
|
renamerErrors <- renameFunction(funcDecl, scope)
|
||||||
|
(microWaccFunc, typeErrors) = checkFuncDecl(funcDecl)
|
||||||
|
} yield (microWaccFunc, renamerErrors ++ typeErrors)
|
||||||
|
}
|
||||||
|
|
||||||
|
def check(partialProg: ast.PartialProgram): IO[(microWacc.Program, Chain[Error])] = {
|
||||||
|
given scope: Scope = Scope(mutable.Map.empty, Map.empty)
|
||||||
|
|
||||||
|
for {
|
||||||
|
(main, chunks, globalErrors) <- prepareGlobalScope(partialProg)
|
||||||
|
toRename = (main +: chunks).toList
|
||||||
|
res <- toRename
|
||||||
|
.zip(scope.subscopes(toRename.size))
|
||||||
|
.parTraverse(checkFunc)
|
||||||
|
(typedChunks, errors) = res.foldLeft((Chain.empty[microWacc.FuncDecl], Chain.empty[Error])) {
|
||||||
|
case ((acc, err), (funcDecl, errors)) =>
|
||||||
|
(acc :+ funcDecl, err ++ errors)
|
||||||
|
}
|
||||||
|
(typedMain, funcs) = typedChunks.uncons match {
|
||||||
|
case Some((head, tail)) => (head.body, tail)
|
||||||
|
case None => (Chain.empty, Chain.empty)
|
||||||
|
}
|
||||||
|
} yield (microWacc.Program(funcs, typedMain)(main.pos), globalErrors ++ errors)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,25 +1,12 @@
|
|||||||
package wacc
|
package wacc
|
||||||
|
|
||||||
import cats.syntax.all._
|
import cats.syntax.all._
|
||||||
import scala.collection.mutable
|
|
||||||
import cats.data.NonEmptyList
|
import cats.data.NonEmptyList
|
||||||
|
import cats.data.Chain
|
||||||
|
|
||||||
object typeChecker {
|
object typeChecker {
|
||||||
import wacc.types._
|
import wacc.types._
|
||||||
|
|
||||||
case class TypeCheckerCtx(
|
|
||||||
globalNames: Map[ast.Ident, SemType],
|
|
||||||
globalFuncs: Map[ast.Ident, FuncType],
|
|
||||||
errors: mutable.Builder[Error, List[Error]]
|
|
||||||
) {
|
|
||||||
def typeOf(ident: ast.Ident): SemType = globalNames(ident)
|
|
||||||
def funcType(ident: ast.Ident): FuncType = globalFuncs(ident)
|
|
||||||
|
|
||||||
def error(err: Error): SemType =
|
|
||||||
errors += err
|
|
||||||
?
|
|
||||||
}
|
|
||||||
|
|
||||||
private enum Constraint {
|
private enum Constraint {
|
||||||
case Unconstrained
|
case Unconstrained
|
||||||
// Allows weakening in one direction
|
// Allows weakening in one direction
|
||||||
@@ -43,31 +30,29 @@ object typeChecker {
|
|||||||
* @return
|
* @return
|
||||||
* The type if the constraint was satisfied, or ? if it was not.
|
* The type if the constraint was satisfied, or ? if it was not.
|
||||||
*/
|
*/
|
||||||
private def satisfies(constraint: Constraint, pos: ast.Position)(using
|
private def satisfies(constraint: Constraint, pos: ast.Position): (SemType, Chain[Error]) =
|
||||||
ctx: TypeCheckerCtx
|
|
||||||
): SemType =
|
|
||||||
(ty, constraint) match {
|
(ty, constraint) match {
|
||||||
case (KnownType.Array(KnownType.Char), Constraint.Is(KnownType.String, _)) =>
|
case (KnownType.Array(KnownType.Char), Constraint.Is(KnownType.String, _)) =>
|
||||||
KnownType.String
|
(KnownType.String, Chain.empty)
|
||||||
case (
|
case (
|
||||||
KnownType.String,
|
KnownType.String,
|
||||||
Constraint.IsSymmetricCompatible(KnownType.Array(KnownType.Char), _)
|
Constraint.IsSymmetricCompatible(KnownType.Array(KnownType.Char), _)
|
||||||
) =>
|
) =>
|
||||||
KnownType.String
|
(KnownType.String, Chain.empty)
|
||||||
case (ty, Constraint.IsSymmetricCompatible(ty2, msg)) =>
|
case (ty, Constraint.IsSymmetricCompatible(ty2, msg)) =>
|
||||||
ty.satisfies(Constraint.Is(ty2, msg), pos)
|
ty.satisfies(Constraint.Is(ty2, msg), pos)
|
||||||
// Change to IsUnweakenable to disallow recursive weakening
|
// Change to IsUnweakenable to disallow recursive weakening
|
||||||
case (ty, Constraint.Is(ty2, msg)) => ty.satisfies(Constraint.IsUnweakenable(ty2, msg), pos)
|
case (ty, Constraint.Is(ty2, msg)) => ty.satisfies(Constraint.IsUnweakenable(ty2, msg), pos)
|
||||||
case (ty, Constraint.Unconstrained) => ty
|
case (ty, Constraint.Unconstrained) => (ty, Chain.empty)
|
||||||
case (ty, Constraint.Never(msg)) =>
|
case (ty, Constraint.Never(msg)) =>
|
||||||
ctx.error(Error.SemanticError(pos, msg))
|
(?, Chain.one(Error.SemanticError(pos, msg)))
|
||||||
case (ty, Constraint.IsEither(ty1, ty2, msg)) =>
|
case (ty, Constraint.IsEither(ty1, ty2, msg)) =>
|
||||||
(ty moreSpecific ty1).orElse(ty moreSpecific ty2).getOrElse {
|
(ty moreSpecific ty1).orElse(ty moreSpecific ty2).map((_, Chain.empty)).getOrElse {
|
||||||
ctx.error(Error.TypeMismatch(pos, ty1, ty, msg))
|
(?, Chain.one(Error.TypeMismatch(pos, ty1, ty, msg)))
|
||||||
}
|
}
|
||||||
case (ty, Constraint.IsUnweakenable(ty2, msg)) =>
|
case (ty, Constraint.IsUnweakenable(ty2, msg)) =>
|
||||||
(ty moreSpecific ty2).getOrElse {
|
(ty moreSpecific ty2).map((_, Chain.empty)).getOrElse {
|
||||||
ctx.error(Error.TypeMismatch(pos, ty2, ty, msg))
|
(?, Chain.one(Error.TypeMismatch(pos, ty2, ty, msg)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,36 +76,29 @@ object typeChecker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Type-check a WACC program.
|
/** Type-check a function declaration.
|
||||||
*
|
*
|
||||||
* @param prog
|
* @param func
|
||||||
* The AST of the program to type-check.
|
* The AST of the function to type-check.
|
||||||
* @param ctx
|
|
||||||
* The type checker context which includes the global names and functions, and an errors
|
|
||||||
* builder.
|
|
||||||
*/
|
*/
|
||||||
def check(prog: ast.Program)(using
|
def checkFuncDecl(func: ast.FuncDecl): (microWacc.FuncDecl, Chain[Error]) = {
|
||||||
ctx: TypeCheckerCtx
|
val ast.FuncDecl(_, name, params, stmts) = func
|
||||||
): microWacc.Program =
|
val FuncType(retType, paramTypes) = name.ty.asInstanceOf[FuncType]
|
||||||
microWacc.Program(
|
val returnConstraint =
|
||||||
// Ignore function syntax types for return value and params, since those have been converted
|
if func.name.v == renamer.MAIN then Constraint.Never("main body must not return")
|
||||||
// to SemTypes by the renamer.
|
else Constraint.Is(retType, s"function ${name.v} must return $retType")
|
||||||
prog.funcs.map { case ast.FuncDecl(_, name, params, stmts) =>
|
val (body, bodyErrors) = stmts.foldMap(checkStmt(_, returnConstraint))
|
||||||
val FuncType(retType, paramTypes) = ctx.funcType(name)
|
(
|
||||||
microWacc.FuncDecl(
|
microWacc.FuncDecl(
|
||||||
microWacc.Ident(name.v, name.uid)(retType),
|
microWacc.Ident(name.v, name.guid)(retType),
|
||||||
params.zip(paramTypes).map { case (ast.Param(_, ident), ty) =>
|
params.zip(paramTypes).map { case (ast.Param(_, ident), ty) =>
|
||||||
microWacc.Ident(ident.v, ident.uid)(ty)
|
microWacc.Ident(ident.v, ident.guid)(ty)
|
||||||
},
|
},
|
||||||
stmts.toList
|
body
|
||||||
.flatMap(
|
)(func.pos),
|
||||||
checkStmt(_, Constraint.Is(retType, s"function ${name.v} must return $retType"))
|
bodyErrors
|
||||||
)
|
|
||||||
)
|
|
||||||
},
|
|
||||||
prog.main.toList
|
|
||||||
.flatMap(checkStmt(_, Constraint.Never("main function must not return")))
|
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/** Type-check an AST statement node.
|
/** Type-check an AST statement node.
|
||||||
*
|
*
|
||||||
@@ -129,40 +107,54 @@ object typeChecker {
|
|||||||
* @param returnConstraint
|
* @param returnConstraint
|
||||||
* The constraint that any `return <expr>` statements must satisfy.
|
* The constraint that any `return <expr>` statements must satisfy.
|
||||||
*/
|
*/
|
||||||
private def checkStmt(stmt: ast.Stmt, returnConstraint: Constraint)(using
|
private def checkStmt(
|
||||||
ctx: TypeCheckerCtx
|
stmt: ast.Stmt,
|
||||||
): List[microWacc.Stmt] = stmt match {
|
returnConstraint: Constraint
|
||||||
|
): (Chain[microWacc.Stmt], Chain[Error]) = stmt match {
|
||||||
// Ignore the type of the variable, since it has been converted to a SemType by the renamer.
|
// Ignore the type of the variable, since it has been converted to a SemType by the renamer.
|
||||||
case ast.VarDecl(_, name, value) =>
|
case ast.VarDecl(_, name, value) =>
|
||||||
val expectedTy = ctx.typeOf(name)
|
val expectedTy = name.ty
|
||||||
val typedValue = checkValue(
|
val (typedValue, valueErrors) = checkValue(
|
||||||
value,
|
value,
|
||||||
Constraint.Is(
|
Constraint.Is(
|
||||||
expectedTy,
|
expectedTy.asInstanceOf[SemType],
|
||||||
s"variable ${name.v} must be assigned a value of type $expectedTy"
|
s"variable ${name.v} must be assigned a value of type $expectedTy"
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
List(microWacc.Assign(microWacc.Ident(name.v, name.uid)(expectedTy), typedValue))
|
(
|
||||||
|
Chain.one(
|
||||||
|
microWacc.Assign(
|
||||||
|
microWacc.Ident(name.v, name.guid)(expectedTy.asInstanceOf[SemType]),
|
||||||
|
typedValue
|
||||||
|
)(stmt.pos)
|
||||||
|
),
|
||||||
|
valueErrors
|
||||||
|
)
|
||||||
case ast.Assign(lhs, rhs) =>
|
case ast.Assign(lhs, rhs) =>
|
||||||
val lhsTyped = checkLValue(lhs, Constraint.Unconstrained)
|
val (lhsTyped, lhsErrors) = checkLValue(lhs, Constraint.Unconstrained)
|
||||||
val rhsTyped =
|
val (rhsTyped, rhsErrors) =
|
||||||
checkValue(rhs, Constraint.Is(lhsTyped.ty, s"assignment must have type ${lhsTyped.ty}"))
|
checkValue(rhs, Constraint.Is(lhsTyped.ty, s"assignment must have type ${lhsTyped.ty}"))
|
||||||
(lhsTyped.ty, rhsTyped.ty) match {
|
val unknownError = (lhsTyped.ty, rhsTyped.ty) match {
|
||||||
case (?, ?) =>
|
case (?, ?) =>
|
||||||
ctx.error(
|
Chain.one(
|
||||||
Error.SemanticError(lhs.pos, "assignment with both sides of unknown type is illegal")
|
Error.SemanticError(lhs.pos, "assignment with both sides of unknown type is illegal")
|
||||||
)
|
)
|
||||||
case _ => ()
|
case _ => Chain.empty
|
||||||
}
|
}
|
||||||
List(microWacc.Assign(lhsTyped, rhsTyped))
|
(
|
||||||
|
Chain.one(microWacc.Assign(lhsTyped, rhsTyped)(stmt.pos)),
|
||||||
|
lhsErrors ++ rhsErrors ++ unknownError
|
||||||
|
)
|
||||||
case ast.Read(dest) =>
|
case ast.Read(dest) =>
|
||||||
val destTyped = checkLValue(dest, Constraint.Unconstrained)
|
val (destTyped, destErrors) = checkLValue(dest, Constraint.Unconstrained)
|
||||||
val destTy = destTyped.ty match {
|
val (destTy, destTyErrors) = destTyped.ty match {
|
||||||
case ? =>
|
case ? =>
|
||||||
ctx.error(
|
(
|
||||||
Error.SemanticError(dest.pos, "cannot read into a destination with an unknown type")
|
?,
|
||||||
|
Chain.one(
|
||||||
|
Error.SemanticError(dest.pos, "cannot read into a destination with an unknown type")
|
||||||
|
)
|
||||||
)
|
)
|
||||||
?
|
|
||||||
case destTy =>
|
case destTy =>
|
||||||
destTy.satisfies(
|
destTy.satisfies(
|
||||||
Constraint.IsEither(
|
Constraint.IsEither(
|
||||||
@@ -173,49 +165,44 @@ object typeChecker {
|
|||||||
dest.pos
|
dest.pos
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
List(
|
(
|
||||||
microWacc.Assign(
|
Chain.one(
|
||||||
destTyped,
|
microWacc.Assign(
|
||||||
microWacc.Call(
|
destTyped,
|
||||||
microWacc.Builtin.Read,
|
microWacc.Call(
|
||||||
List(
|
microWacc.Builtin.Read,
|
||||||
destTy match {
|
List(
|
||||||
case KnownType.Int => " %d".toMicroWaccCharArray
|
destTy match {
|
||||||
case KnownType.Char | _ => " %c".toMicroWaccCharArray
|
case KnownType.Int => " %d".toMicroWaccCharArray(stmt.pos)
|
||||||
},
|
case KnownType.Char | _ => " %c".toMicroWaccCharArray(stmt.pos)
|
||||||
destTyped
|
},
|
||||||
)
|
destTyped
|
||||||
)
|
)
|
||||||
)
|
)(dest.pos)
|
||||||
|
)(stmt.pos)
|
||||||
|
),
|
||||||
|
destErrors ++ destTyErrors
|
||||||
)
|
)
|
||||||
case ast.Free(lhs) =>
|
case ast.Free(lhs) =>
|
||||||
List(
|
val (lhsTyped, lhsErrors) = checkValue(
|
||||||
microWacc.Call(
|
lhs,
|
||||||
microWacc.Builtin.Free,
|
Constraint.IsEither(
|
||||||
List(
|
KnownType.Array(?),
|
||||||
checkValue(
|
KnownType.Pair(?, ?),
|
||||||
lhs,
|
"free must be applied to an array or pair"
|
||||||
Constraint.IsEither(
|
|
||||||
KnownType.Array(?),
|
|
||||||
KnownType.Pair(?, ?),
|
|
||||||
"free must be applied to an array or pair"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
(Chain.one(microWacc.Call(microWacc.Builtin.Free, List(lhsTyped))(stmt.pos)), lhsErrors)
|
||||||
case ast.Return(expr) =>
|
case ast.Return(expr) =>
|
||||||
List(microWacc.Return(checkValue(expr, returnConstraint)))
|
val (exprTyped, exprErrors) = checkValue(expr, returnConstraint)
|
||||||
|
(Chain.one(microWacc.Return(exprTyped)(stmt.pos)), exprErrors)
|
||||||
case ast.Exit(expr) =>
|
case ast.Exit(expr) =>
|
||||||
List(
|
val (exprTyped, exprErrors) =
|
||||||
microWacc.Call(
|
checkValue(expr, Constraint.Is(KnownType.Int, "exit value must be int"))
|
||||||
microWacc.Builtin.Exit,
|
(Chain.one(microWacc.Call(microWacc.Builtin.Exit, List(exprTyped))(stmt.pos)), exprErrors)
|
||||||
List(checkValue(expr, Constraint.Is(KnownType.Int, "exit value must be int")))
|
|
||||||
)
|
|
||||||
)
|
|
||||||
case ast.Print(expr, newline) =>
|
case ast.Print(expr, newline) =>
|
||||||
// This constraint should never fail, the scope-checker should have caught it already
|
// This constraint should never fail, the scope-checker should have caught it already
|
||||||
val exprTyped = checkValue(expr, Constraint.Unconstrained)
|
val (exprTyped, exprErrors) = checkValue(expr, Constraint.Unconstrained)
|
||||||
val exprFormat = exprTyped.ty match {
|
val exprFormat = exprTyped.ty match {
|
||||||
case KnownType.Bool | KnownType.String => "%s"
|
case KnownType.Bool | KnownType.String => "%s"
|
||||||
case KnownType.Array(KnownType.Char) => "%.*s"
|
case KnownType.Array(KnownType.Char) => "%.*s"
|
||||||
@@ -224,46 +211,48 @@ object typeChecker {
|
|||||||
case KnownType.Pair(_, _) | KnownType.Array(_) | ? => "%p"
|
case KnownType.Pair(_, _) | KnownType.Array(_) | ? => "%p"
|
||||||
}
|
}
|
||||||
val printfCall = { (func: microWacc.Builtin, value: microWacc.Expr) =>
|
val printfCall = { (func: microWacc.Builtin, value: microWacc.Expr) =>
|
||||||
List(
|
Chain.one(
|
||||||
microWacc.Call(
|
microWacc.Call(
|
||||||
func,
|
func,
|
||||||
List(
|
List(
|
||||||
s"$exprFormat${if newline then "\n" else ""}".toMicroWaccCharArray,
|
s"$exprFormat${if newline then "\n" else ""}".toMicroWaccCharArray(stmt.pos),
|
||||||
value
|
value
|
||||||
)
|
)
|
||||||
)
|
)(stmt.pos)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
exprTyped.ty match {
|
(
|
||||||
case KnownType.Bool =>
|
exprTyped.ty match {
|
||||||
List(
|
case KnownType.Bool =>
|
||||||
microWacc.If(
|
Chain.one(
|
||||||
exprTyped,
|
microWacc.If(
|
||||||
printfCall(microWacc.Builtin.Printf, "true".toMicroWaccCharArray),
|
exprTyped,
|
||||||
printfCall(microWacc.Builtin.Printf, "false".toMicroWaccCharArray)
|
printfCall(microWacc.Builtin.Printf, "true".toMicroWaccCharArray(stmt.pos)),
|
||||||
|
printfCall(microWacc.Builtin.Printf, "false".toMicroWaccCharArray(stmt.pos))
|
||||||
|
)(stmt.pos)
|
||||||
)
|
)
|
||||||
)
|
case KnownType.Array(KnownType.Char) =>
|
||||||
case KnownType.Array(KnownType.Char) =>
|
printfCall(microWacc.Builtin.PrintCharArray, exprTyped)
|
||||||
printfCall(microWacc.Builtin.PrintCharArray, exprTyped)
|
case _ => printfCall(microWacc.Builtin.Printf, exprTyped)
|
||||||
case _ => printfCall(microWacc.Builtin.Printf, exprTyped)
|
},
|
||||||
}
|
exprErrors
|
||||||
|
)
|
||||||
case ast.If(cond, thenStmt, elseStmt) =>
|
case ast.If(cond, thenStmt, elseStmt) =>
|
||||||
List(
|
val (condTyped, condErrors) =
|
||||||
microWacc.If(
|
checkValue(cond, Constraint.Is(KnownType.Bool, "if condition must be a bool"))
|
||||||
checkValue(cond, Constraint.Is(KnownType.Bool, "if condition must be a bool")),
|
val (thenStmtTyped, thenErrors) = thenStmt.foldMap(checkStmt(_, returnConstraint))
|
||||||
thenStmt.toList.flatMap(checkStmt(_, returnConstraint)),
|
val (elseStmtTyped, elseErrors) = elseStmt.foldMap(checkStmt(_, returnConstraint))
|
||||||
elseStmt.toList.flatMap(checkStmt(_, returnConstraint))
|
(
|
||||||
)
|
Chain.one(microWacc.If(condTyped, thenStmtTyped, elseStmtTyped)(cond.pos)),
|
||||||
|
condErrors ++ thenErrors ++ elseErrors
|
||||||
)
|
)
|
||||||
case ast.While(cond, body) =>
|
case ast.While(cond, body) =>
|
||||||
List(
|
val (condTyped, condErrors) =
|
||||||
microWacc.While(
|
checkValue(cond, Constraint.Is(KnownType.Bool, "while condition must be a bool"))
|
||||||
checkValue(cond, Constraint.Is(KnownType.Bool, "while condition must be a bool")),
|
val (bodyTyped, bodyErrors) = body.foldMap(checkStmt(_, returnConstraint))
|
||||||
body.toList.flatMap(checkStmt(_, returnConstraint))
|
(Chain.one(microWacc.While(condTyped, bodyTyped)(cond.pos)), condErrors ++ bodyErrors)
|
||||||
)
|
case ast.Block(body) => body.foldMap(checkStmt(_, returnConstraint))
|
||||||
)
|
case skip @ ast.Skip() => (Chain.empty, Chain.empty)
|
||||||
case ast.Block(body) => body.toList.flatMap(checkStmt(_, returnConstraint))
|
|
||||||
case skip @ ast.Skip() => List.empty
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Type-check an AST LValue, RValue or Expr node. This function does all 3 since these traits
|
/** Type-check an AST LValue, RValue or Expr node. This function does all 3 since these traits
|
||||||
@@ -276,127 +265,145 @@ object typeChecker {
|
|||||||
* @return
|
* @return
|
||||||
* The most specific type of the value if it could be determined, or ? if it could not.
|
* The most specific type of the value if it could be determined, or ? if it could not.
|
||||||
*/
|
*/
|
||||||
private def checkValue(value: ast.LValue | ast.RValue | ast.Expr, constraint: Constraint)(using
|
private def checkValue(
|
||||||
ctx: TypeCheckerCtx
|
value: ast.LValue | ast.RValue | ast.Expr,
|
||||||
): microWacc.Expr = value match {
|
constraint: Constraint
|
||||||
|
): (microWacc.Expr, Chain[Error]) = value match {
|
||||||
case l @ ast.IntLiter(v) =>
|
case l @ ast.IntLiter(v) =>
|
||||||
KnownType.Int.satisfies(constraint, l.pos)
|
val (_, errors) = KnownType.Int.satisfies(constraint, l.pos)
|
||||||
microWacc.IntLiter(v)
|
(microWacc.IntLiter(v), errors)
|
||||||
case l @ ast.BoolLiter(v) =>
|
case l @ ast.BoolLiter(v) =>
|
||||||
KnownType.Bool.satisfies(constraint, l.pos)
|
val (_, errors) = KnownType.Bool.satisfies(constraint, l.pos)
|
||||||
microWacc.BoolLiter(v)
|
(microWacc.BoolLiter(v), errors)
|
||||||
case l @ ast.CharLiter(v) =>
|
case l @ ast.CharLiter(v) =>
|
||||||
KnownType.Char.satisfies(constraint, l.pos)
|
val (_, errors) = KnownType.Char.satisfies(constraint, l.pos)
|
||||||
microWacc.CharLiter(v)
|
(microWacc.CharLiter(v), errors)
|
||||||
case l @ ast.StrLiter(v) =>
|
case l @ ast.StrLiter(v) =>
|
||||||
KnownType.String.satisfies(constraint, l.pos)
|
val (_, errors) = KnownType.String.satisfies(constraint, l.pos)
|
||||||
v.toMicroWaccCharArray
|
(v.toMicroWaccCharArray(l.pos), errors)
|
||||||
case l @ ast.PairLiter() =>
|
case l @ ast.PairLiter() =>
|
||||||
microWacc.NullLiter()(KnownType.Pair(?, ?).satisfies(constraint, l.pos))
|
val (ty, errors) = KnownType.Pair(?, ?).satisfies(constraint, l.pos)
|
||||||
|
(microWacc.NullLiter()(ty), errors)
|
||||||
case ast.Parens(expr) => checkValue(expr, constraint)
|
case ast.Parens(expr) => checkValue(expr, constraint)
|
||||||
case l @ ast.ArrayLiter(elems) =>
|
case l @ ast.ArrayLiter(elems) =>
|
||||||
val (elemTy, elemsTyped) = elems.mapAccumulate[SemType, microWacc.Expr](?) {
|
val ((elemTy, elemsErrors), elemsTyped) =
|
||||||
case (acc, elem) =>
|
elems.mapAccumulate[(SemType, Chain[Error]), microWacc.Expr]((?, Chain.empty)) {
|
||||||
val elemTyped = checkValue(
|
case ((acc, errors), elem) =>
|
||||||
elem,
|
val (elemTyped, elemErrors) = checkValue(
|
||||||
Constraint.IsSymmetricCompatible(acc, s"array elements must have the same type")
|
elem,
|
||||||
)
|
Constraint.IsSymmetricCompatible(acc, s"array elements must have the same type")
|
||||||
(elemTyped.ty, elemTyped)
|
)
|
||||||
}
|
((elemTyped.ty, errors ++ elemErrors), elemTyped)
|
||||||
val arrayTy = KnownType
|
}
|
||||||
|
val (arrayTy, arrayErrors) = KnownType
|
||||||
// Start with an unknown param type, make it more specific while checking the elements.
|
// Start with an unknown param type, make it more specific while checking the elements.
|
||||||
.Array(elemTy)
|
.Array(elemTy)
|
||||||
.satisfies(constraint, l.pos)
|
.satisfies(constraint, l.pos)
|
||||||
microWacc.ArrayLiter(elemsTyped)(arrayTy)
|
(microWacc.ArrayLiter(elemsTyped)(arrayTy, l.pos), elemsErrors ++ arrayErrors)
|
||||||
case l @ ast.NewPair(fst, snd) =>
|
case l @ ast.NewPair(fst, snd) =>
|
||||||
val fstTyped = checkValue(fst, Constraint.Unconstrained)
|
val (fstTyped, fstErrors) = checkValue(fst, Constraint.Unconstrained)
|
||||||
val sndTyped = checkValue(snd, Constraint.Unconstrained)
|
val (sndTyped, sndErrors) = checkValue(snd, Constraint.Unconstrained)
|
||||||
microWacc.ArrayLiter(List(fstTyped, sndTyped))(
|
val (pairTy, pairErrors) =
|
||||||
KnownType.Pair(fstTyped.ty, sndTyped.ty).satisfies(constraint, l.pos)
|
KnownType.Pair(fstTyped.ty, sndTyped.ty).satisfies(constraint, l.pos)
|
||||||
|
(
|
||||||
|
microWacc.ArrayLiter(List(fstTyped, sndTyped))(pairTy, l.pos),
|
||||||
|
fstErrors ++ sndErrors ++ pairErrors
|
||||||
)
|
)
|
||||||
case ast.Call(id, args) =>
|
case ast.Call(id, args) =>
|
||||||
val funcTy @ FuncType(retTy, paramTys) = ctx.funcType(id)
|
val funcTy @ FuncType(retTy, paramTys) = id.ty.asInstanceOf[FuncType]
|
||||||
if (args.length != paramTys.length) {
|
val lenError =
|
||||||
ctx.error(Error.FunctionParamsMismatch(id, paramTys.length, args.length, funcTy))
|
if (args.length == paramTys.length) then Chain.empty
|
||||||
}
|
else Chain.one(Error.FunctionParamsMismatch(id, paramTys.length, args.length, funcTy))
|
||||||
// Even if the number of arguments is wrong, we still check the types of the arguments
|
// Even if the number of arguments is wrong, we still check the types of the arguments
|
||||||
// in the best way we can (by taking a zip).
|
// in the best way we can (by taking a zip).
|
||||||
val argsTyped = args.zip(paramTys).map { case (arg, paramTy) =>
|
val (argsErrors, argsTyped) =
|
||||||
checkValue(arg, Constraint.Is(paramTy, s"argument type mismatch in function ${id.v}"))
|
args.zip(paramTys).mapAccumulate(Chain.empty[Error]) { case (errors, (arg, paramTy)) =>
|
||||||
}
|
val (argTyped, argErrors) =
|
||||||
microWacc.Call(microWacc.Ident(id.v, id.uid)(retTy.satisfies(constraint, id.pos)), argsTyped)
|
checkValue(arg, Constraint.Is(paramTy, s"argument type mismatch in function ${id.v}"))
|
||||||
|
(errors ++ argErrors, argTyped)
|
||||||
|
}
|
||||||
|
val (retTyChecked, retErrors) = retTy.satisfies(constraint, id.pos)
|
||||||
|
(
|
||||||
|
microWacc.Call(microWacc.Ident(id.v, id.guid)(retTyChecked), argsTyped)(id.pos),
|
||||||
|
lenError ++ argsErrors ++ retErrors
|
||||||
|
)
|
||||||
|
|
||||||
// Unary operators
|
// Unary operators
|
||||||
case ast.Negate(x) =>
|
case ast.Negate(x) =>
|
||||||
microWacc.UnaryOp(
|
val (argTyped, argErrors) =
|
||||||
checkValue(x, Constraint.Is(KnownType.Int, "negation must be applied to an int")),
|
checkValue(x, Constraint.Is(KnownType.Int, "negation must be applied to an int"))
|
||||||
microWacc.UnaryOperator.Negate
|
val (retTy, retErrors) = KnownType.Int.satisfies(constraint, x.pos)
|
||||||
)(KnownType.Int.satisfies(constraint, x.pos))
|
(microWacc.UnaryOp(argTyped, microWacc.UnaryOperator.Negate)(retTy), argErrors ++ retErrors)
|
||||||
case ast.Not(x) =>
|
case ast.Not(x) =>
|
||||||
microWacc.UnaryOp(
|
val (argTyped, argErrors) =
|
||||||
checkValue(x, Constraint.Is(KnownType.Bool, "logical not must be applied to a bool")),
|
checkValue(x, Constraint.Is(KnownType.Bool, "logical not must be applied to a bool"))
|
||||||
microWacc.UnaryOperator.Not
|
val (retTy, retErrors) = KnownType.Bool.satisfies(constraint, x.pos)
|
||||||
)(KnownType.Bool.satisfies(constraint, x.pos))
|
(microWacc.UnaryOp(argTyped, microWacc.UnaryOperator.Not)(retTy), argErrors ++ retErrors)
|
||||||
case ast.Len(x) =>
|
case ast.Len(x) =>
|
||||||
microWacc.UnaryOp(
|
val (argTyped, argErrors) =
|
||||||
checkValue(x, Constraint.Is(KnownType.Array(?), "len must be applied to an array")),
|
checkValue(x, Constraint.Is(KnownType.Array(?), "len must be applied to an array"))
|
||||||
microWacc.UnaryOperator.Len
|
val (retTy, retErrors) = KnownType.Int.satisfies(constraint, x.pos)
|
||||||
)(KnownType.Int.satisfies(constraint, x.pos))
|
(microWacc.UnaryOp(argTyped, microWacc.UnaryOperator.Len)(retTy), argErrors ++ retErrors)
|
||||||
case ast.Ord(x) =>
|
case ast.Ord(x) =>
|
||||||
microWacc.UnaryOp(
|
val (argTyped, argErrors) =
|
||||||
checkValue(x, Constraint.Is(KnownType.Char, "ord must be applied to a char")),
|
checkValue(x, Constraint.Is(KnownType.Char, "ord must be applied to a char"))
|
||||||
microWacc.UnaryOperator.Ord
|
val (retTy, retErrors) = KnownType.Int.satisfies(constraint, x.pos)
|
||||||
)(KnownType.Int.satisfies(constraint, x.pos))
|
(microWacc.UnaryOp(argTyped, microWacc.UnaryOperator.Ord)(retTy), argErrors ++ retErrors)
|
||||||
case ast.Chr(x) =>
|
case ast.Chr(x) =>
|
||||||
microWacc.UnaryOp(
|
val (argTyped, argErrors) =
|
||||||
checkValue(x, Constraint.Is(KnownType.Int, "chr must be applied to an int")),
|
checkValue(x, Constraint.Is(KnownType.Int, "chr must be applied to an int"))
|
||||||
microWacc.UnaryOperator.Chr
|
val (retTy, retErrors) = KnownType.Char.satisfies(constraint, x.pos)
|
||||||
)(KnownType.Char.satisfies(constraint, x.pos))
|
(microWacc.UnaryOp(argTyped, microWacc.UnaryOperator.Chr)(retTy), argErrors ++ retErrors)
|
||||||
|
|
||||||
// Binary operators
|
// Binary operators
|
||||||
case op: (ast.Add | ast.Sub | ast.Mul | ast.Div | ast.Mod) =>
|
case op: (ast.Add | ast.Sub | ast.Mul | ast.Div | ast.Mod) =>
|
||||||
val operand = Constraint.Is(KnownType.Int, s"${op.name} operator must be applied to an int")
|
val operand = Constraint.Is(KnownType.Int, s"${op.name} operator must be applied to an int")
|
||||||
microWacc.BinaryOp(
|
val (xTyped, xErrors) = checkValue(op.x, operand)
|
||||||
checkValue(op.x, operand),
|
val (yTyped, yErrors) = checkValue(op.y, operand)
|
||||||
checkValue(op.y, operand),
|
val (retTy, retErrors) = KnownType.Int.satisfies(constraint, op.pos)
|
||||||
microWacc.BinaryOperator.fromAst(op)
|
(
|
||||||
)(KnownType.Int.satisfies(constraint, op.pos))
|
microWacc.BinaryOp(xTyped, yTyped, microWacc.BinaryOperator.fromAst(op))(retTy),
|
||||||
|
xErrors ++ yErrors ++ retErrors
|
||||||
|
)
|
||||||
case op: (ast.Eq | ast.Neq) =>
|
case op: (ast.Eq | ast.Neq) =>
|
||||||
val xTyped = checkValue(op.x, Constraint.Unconstrained)
|
val (xTyped, xErrors) = checkValue(op.x, Constraint.Unconstrained)
|
||||||
microWacc.BinaryOp(
|
val (yTyped, yErrors) = checkValue(
|
||||||
xTyped,
|
op.y,
|
||||||
checkValue(
|
Constraint.Is(xTyped.ty, s"${op.name} operator must be applied to values of the same type")
|
||||||
op.y,
|
)
|
||||||
Constraint
|
val (retTy, retErrors) = KnownType.Bool.satisfies(constraint, op.pos)
|
||||||
.Is(xTyped.ty, s"${op.name} operator must be applied to values of the same type")
|
(
|
||||||
),
|
microWacc.BinaryOp(xTyped, yTyped, microWacc.BinaryOperator.fromAst(op))(retTy),
|
||||||
microWacc.BinaryOperator.fromAst(op)
|
xErrors ++ yErrors ++ retErrors
|
||||||
)(KnownType.Bool.satisfies(constraint, op.pos))
|
)
|
||||||
case op: (ast.Less | ast.LessEq | ast.Greater | ast.GreaterEq) =>
|
case op: (ast.Less | ast.LessEq | ast.Greater | ast.GreaterEq) =>
|
||||||
val xConstraint = Constraint.IsEither(
|
val xConstraint = Constraint.IsEither(
|
||||||
KnownType.Int,
|
KnownType.Int,
|
||||||
KnownType.Char,
|
KnownType.Char,
|
||||||
s"${op.name} operator must be applied to an int or char"
|
s"${op.name} operator must be applied to an int or char"
|
||||||
)
|
)
|
||||||
val xTyped = checkValue(op.x, xConstraint)
|
val (xTyped, xErrors) = checkValue(op.x, xConstraint)
|
||||||
// If x type-check failed, we still want to check y is an Int or Char (rather than ?)
|
// If x type-check failed, we still want to check y is an Int or Char (rather than ?)
|
||||||
val yConstraint = xTyped.ty match {
|
val yConstraint = xTyped.ty match {
|
||||||
case ? => xConstraint
|
case ? => xConstraint
|
||||||
case xTy =>
|
case xTy =>
|
||||||
Constraint.Is(xTy, s"${op.name} operator must be applied to values of the same type")
|
Constraint.Is(xTy, s"${op.name} operator must be applied to values of the same type")
|
||||||
}
|
}
|
||||||
microWacc.BinaryOp(
|
val (yTyped, yErrors) = checkValue(op.y, yConstraint)
|
||||||
xTyped,
|
val (retTy, retErrors) = KnownType.Bool.satisfies(constraint, op.pos)
|
||||||
checkValue(op.y, yConstraint),
|
(
|
||||||
microWacc.BinaryOperator.fromAst(op)
|
microWacc.BinaryOp(xTyped, yTyped, microWacc.BinaryOperator.fromAst(op))(retTy),
|
||||||
)(KnownType.Bool.satisfies(constraint, op.pos))
|
xErrors ++ yErrors ++ retErrors
|
||||||
|
)
|
||||||
case op: (ast.And | ast.Or) =>
|
case op: (ast.And | ast.Or) =>
|
||||||
val operand = Constraint.Is(KnownType.Bool, s"${op.name} operator must be applied to a bool")
|
val operand = Constraint.Is(KnownType.Bool, s"${op.name} operator must be applied to a bool")
|
||||||
microWacc.BinaryOp(
|
val (xTyped, xErrors) = checkValue(op.x, operand)
|
||||||
checkValue(op.x, operand),
|
val (yTyped, yErrors) = checkValue(op.y, operand)
|
||||||
checkValue(op.y, operand),
|
val (retTy, retErrors) = KnownType.Bool.satisfies(constraint, op.pos)
|
||||||
microWacc.BinaryOperator.fromAst(op)
|
(
|
||||||
)(KnownType.Bool.satisfies(constraint, op.pos))
|
microWacc.BinaryOp(xTyped, yTyped, microWacc.BinaryOperator.fromAst(op))(retTy),
|
||||||
|
xErrors ++ yErrors ++ retErrors
|
||||||
|
)
|
||||||
|
|
||||||
case lvalue: ast.LValue => checkLValue(lvalue, constraint)
|
case lvalue: ast.LValue => checkLValue(lvalue, constraint)
|
||||||
}
|
}
|
||||||
@@ -413,70 +420,73 @@ object typeChecker {
|
|||||||
* @return
|
* @return
|
||||||
* The most specific type of the value if it could be determined, or ? if it could not.
|
* The most specific type of the value if it could be determined, or ? if it could not.
|
||||||
*/
|
*/
|
||||||
private def checkLValue(value: ast.LValue, constraint: Constraint)(using
|
private def checkLValue(
|
||||||
ctx: TypeCheckerCtx
|
value: ast.LValue,
|
||||||
): microWacc.LValue = value match {
|
constraint: Constraint
|
||||||
case id @ ast.Ident(name, uid) =>
|
): (microWacc.LValue, Chain[Error]) = value match {
|
||||||
microWacc.Ident(name, uid)(ctx.typeOf(id).satisfies(constraint, id.pos))
|
case id @ ast.Ident(name, guid, ty) =>
|
||||||
|
val (idTy, idErrors) = ty.asInstanceOf[SemType].satisfies(constraint, id.pos)
|
||||||
|
(microWacc.Ident(name, guid)(idTy), idErrors)
|
||||||
case ast.ArrayElem(id, indices) =>
|
case ast.ArrayElem(id, indices) =>
|
||||||
val arrayTy = ctx.typeOf(id)
|
val arrayTy = id.ty.asInstanceOf[SemType]
|
||||||
val (elemTy, indicesTyped) = indices.mapAccumulate(arrayTy) { (acc, elem) =>
|
val ((elemTy, elemErrors), indicesTyped) =
|
||||||
val idxTyped = checkValue(elem, Constraint.Is(KnownType.Int, "array index must be an int"))
|
indices.mapAccumulate((arrayTy.asInstanceOf[SemType], Chain.empty[Error])) {
|
||||||
val next = acc match {
|
case ((acc, errors), elem) =>
|
||||||
case KnownType.Array(innerTy) => innerTy
|
val (idxTyped, idxErrors) =
|
||||||
case ? => ? // we can keep indexing an unknown type
|
checkValue(elem, Constraint.Is(KnownType.Int, "array index must be an int"))
|
||||||
case nonArrayTy =>
|
val (next, nextError) = acc match {
|
||||||
ctx.error(
|
case KnownType.Array(innerTy) => (innerTy, Chain.empty)
|
||||||
Error.TypeMismatch(
|
case ? => (?, Chain.empty) // we can keep indexing an unknown type
|
||||||
elem.pos,
|
case nonArrayTy =>
|
||||||
KnownType.Array(?),
|
(
|
||||||
acc,
|
?,
|
||||||
"cannot index into a non-array"
|
Chain.one(
|
||||||
)
|
Error.TypeMismatch(
|
||||||
)
|
elem.pos,
|
||||||
?
|
KnownType.Array(?),
|
||||||
|
acc,
|
||||||
|
"cannot index into a non-array"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
((next, errors ++ idxErrors ++ nextError), idxTyped)
|
||||||
}
|
}
|
||||||
(next, idxTyped)
|
val (retTy, retErrors) = elemTy.satisfies(constraint, value.pos)
|
||||||
}
|
|
||||||
val firstArrayElem = microWacc.ArrayElem(
|
val firstArrayElem = microWacc.ArrayElem(
|
||||||
microWacc.Ident(id.v, id.uid)(arrayTy),
|
microWacc.Ident(id.v, id.guid)(arrayTy),
|
||||||
indicesTyped.head
|
indicesTyped.head
|
||||||
)(elemTy.satisfies(constraint, value.pos))
|
)(retTy)
|
||||||
val arrayElem = indicesTyped.tail.foldLeft(firstArrayElem) { (acc, idx) =>
|
val arrayElem = indicesTyped.tail.foldLeft(firstArrayElem) { (acc, idx) =>
|
||||||
microWacc.ArrayElem(acc, idx)(KnownType.Array(acc.ty))
|
microWacc.ArrayElem(acc, idx)(KnownType.Array(acc.ty))
|
||||||
}
|
}
|
||||||
// Need to type-check the final arrayElem with the constraint
|
// Need to type-check the final arrayElem with the constraint
|
||||||
microWacc.ArrayElem(arrayElem.value, arrayElem.index)(elemTy.satisfies(constraint, value.pos))
|
// TODO: What
|
||||||
|
(microWacc.ArrayElem(arrayElem.value, arrayElem.index)(retTy), elemErrors ++ retErrors)
|
||||||
case ast.Fst(elem) =>
|
case ast.Fst(elem) =>
|
||||||
val elemTyped = checkLValue(
|
val (elemTyped, elemErrors) = checkLValue(
|
||||||
elem,
|
elem,
|
||||||
Constraint.Is(KnownType.Pair(?, ?), "fst must be applied to a pair")
|
Constraint.Is(KnownType.Pair(?, ?), "fst must be applied to a pair")
|
||||||
)
|
)
|
||||||
microWacc.ArrayElem(
|
val (retTy, retErrors) = elemTyped.ty match {
|
||||||
elemTyped,
|
case KnownType.Pair(left, _) => left.satisfies(constraint, elem.pos)
|
||||||
microWacc.IntLiter(0)
|
case _ => (?, Chain.one(Error.InternalError(elem.pos, "fst must be applied to a pair")))
|
||||||
)(elemTyped.ty match {
|
}
|
||||||
case KnownType.Pair(left, _) =>
|
(microWacc.ArrayElem(elemTyped, microWacc.IntLiter(0))(retTy), elemErrors ++ retErrors)
|
||||||
left.satisfies(constraint, elem.pos)
|
|
||||||
case _ => ctx.error(Error.InternalError(elem.pos, "fst must be applied to a pair"))
|
|
||||||
})
|
|
||||||
case ast.Snd(elem) =>
|
case ast.Snd(elem) =>
|
||||||
val elemTyped = checkLValue(
|
val (elemTyped, elemErrors) = checkLValue(
|
||||||
elem,
|
elem,
|
||||||
Constraint.Is(KnownType.Pair(?, ?), "snd must be applied to a pair")
|
Constraint.Is(KnownType.Pair(?, ?), "snd must be applied to a pair")
|
||||||
)
|
)
|
||||||
microWacc.ArrayElem(
|
val (retTy, retErrors) = elemTyped.ty match {
|
||||||
elemTyped,
|
case KnownType.Pair(_, right) => right.satisfies(constraint, elem.pos)
|
||||||
microWacc.IntLiter(1)
|
case _ => (?, Chain.one(Error.InternalError(elem.pos, "snd must be applied to a pair")))
|
||||||
)(elemTyped.ty match {
|
}
|
||||||
case KnownType.Pair(_, right) =>
|
(microWacc.ArrayElem(elemTyped, microWacc.IntLiter(1))(retTy), elemErrors ++ retErrors)
|
||||||
right.satisfies(constraint, elem.pos)
|
|
||||||
case _ => ctx.error(Error.InternalError(elem.pos, "snd must be applied to a pair"))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extension (s: String) {
|
extension (s: String) {
|
||||||
def toMicroWaccCharArray: microWacc.ArrayLiter =
|
def toMicroWaccCharArray(pos: ast.Position): microWacc.ArrayLiter =
|
||||||
microWacc.ArrayLiter(s.map(microWacc.CharLiter(_)).toList)(KnownType.String)
|
microWacc.ArrayLiter(s.map(microWacc.CharLiter(_)).toList)(KnownType.String, pos)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,9 @@ package wacc
|
|||||||
object types {
|
object types {
|
||||||
import ast._
|
import ast._
|
||||||
|
|
||||||
sealed trait SemType {
|
sealed trait RenamerType
|
||||||
|
|
||||||
|
sealed trait SemType extends RenamerType {
|
||||||
override def toString(): String = this match {
|
override def toString(): String = this match {
|
||||||
case KnownType.Int => "int"
|
case KnownType.Int => "int"
|
||||||
case KnownType.Bool => "bool"
|
case KnownType.Bool => "bool"
|
||||||
@@ -41,5 +43,5 @@ object types {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
case class FuncType(returnType: SemType, params: List[SemType])
|
case class FuncType(returnType: SemType, params: List[SemType]) extends RenamerType
|
||||||
}
|
}
|
||||||
|
|||||||
66
src/test/wacc/backend/extensionsSpec.scala
Normal file
66
src/test/wacc/backend/extensionsSpec.scala
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
package wacc
|
||||||
|
|
||||||
|
import org.scalatest.flatspec.AnyFlatSpec
|
||||||
|
import org.scalatest.Inspectors.forEvery
|
||||||
|
import cats.data.Chain
|
||||||
|
|
||||||
|
class ExtensionsSpec extends AnyFlatSpec {
|
||||||
|
import asmGenerator.concatAll
|
||||||
|
import asmGenerator.escaped
|
||||||
|
|
||||||
|
behavior of "concatAll"
|
||||||
|
|
||||||
|
it should "handle int chains" in {
|
||||||
|
val chain = Chain(1, 2, 3).concatAll(
|
||||||
|
Chain(4, 5, 6),
|
||||||
|
Chain.empty,
|
||||||
|
Chain.one(-1)
|
||||||
|
)
|
||||||
|
assert(chain == Chain(1, 2, 3, 4, 5, 6, -1))
|
||||||
|
}
|
||||||
|
|
||||||
|
it should "handle AsmLine chains" in {
|
||||||
|
object lines {
|
||||||
|
import assemblyIR._
|
||||||
|
import assemblyIR.commonRegisters._
|
||||||
|
val main = LabelDef("main")
|
||||||
|
val pop = Pop(RAX)
|
||||||
|
val add = Add(RAX, ImmediateVal(1))
|
||||||
|
val push = Push(RAX)
|
||||||
|
val ret = Return()
|
||||||
|
}
|
||||||
|
val chain = Chain(lines.main).concatAll(
|
||||||
|
Chain.empty,
|
||||||
|
Chain.one(lines.pop),
|
||||||
|
Chain(lines.add, lines.push),
|
||||||
|
Chain.one(lines.ret)
|
||||||
|
)
|
||||||
|
assert(chain == Chain(lines.main, lines.pop, lines.add, lines.push, lines.ret))
|
||||||
|
}
|
||||||
|
|
||||||
|
behavior of "escaped"
|
||||||
|
|
||||||
|
val escapedStrings = Map(
|
||||||
|
"hello" -> "hello",
|
||||||
|
"world" -> "world",
|
||||||
|
"hello\nworld" -> "hello\\nworld",
|
||||||
|
"hello\tworld" -> "hello\\tworld",
|
||||||
|
"hello\\world" -> "hello\\\\world",
|
||||||
|
"hello\"world" -> "hello\\\"world",
|
||||||
|
"hello'world" -> "hello\\'world",
|
||||||
|
"hello\\nworld" -> "hello\\\\nworld",
|
||||||
|
"hello\\tworld" -> "hello\\\\tworld",
|
||||||
|
"hello\\\\world" -> "hello\\\\\\\\world",
|
||||||
|
"hello\\\"world" -> "hello\\\\\\\"world",
|
||||||
|
"hello\\'world" -> "hello\\\\\\'world",
|
||||||
|
"hello\\n\\t\\'world" -> "hello\\\\n\\\\t\\\\\\'world",
|
||||||
|
"hello\u0000world" -> "hello\\0world",
|
||||||
|
"hello\bworld" -> "hello\\bworld",
|
||||||
|
"hello\fworld" -> "hello\\fworld"
|
||||||
|
)
|
||||||
|
forEvery(escapedStrings) { (input, expected) =>
|
||||||
|
it should s"return $expected" in {
|
||||||
|
assert(input.escaped == expected)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
85
src/test/wacc/backend/labelGeneratorSpec.scala
Normal file
85
src/test/wacc/backend/labelGeneratorSpec.scala
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
package wacc
|
||||||
|
|
||||||
|
import org.scalatest.flatspec.AnyFlatSpec
|
||||||
|
|
||||||
|
class LabelGeneratorSpec extends AnyFlatSpec {
|
||||||
|
import microWacc._
|
||||||
|
import assemblyIR.{LabelDef, LabelArg, Directive}
|
||||||
|
import types.?
|
||||||
|
|
||||||
|
"getLabel" should "return unique labels" in {
|
||||||
|
val labelGenerator = new LabelGenerator
|
||||||
|
val labels = (1 to 10).map(_ => labelGenerator.getLabel())
|
||||||
|
assert(labels.distinct.length == labels.length)
|
||||||
|
}
|
||||||
|
|
||||||
|
"getLabelDef" should "return unique labels" in {
|
||||||
|
assert(
|
||||||
|
LabelDef("test") == LabelDef("test") &&
|
||||||
|
LabelDef("test").hashCode == LabelDef("test").hashCode,
|
||||||
|
"Sanity check: LabelDef should be case-classes"
|
||||||
|
)
|
||||||
|
|
||||||
|
val labelGenerator = new LabelGenerator
|
||||||
|
val labels = (List(
|
||||||
|
Builtin.Exit,
|
||||||
|
Builtin.Printf,
|
||||||
|
Ident("exit", 0)(?),
|
||||||
|
Ident("test", 0)(?)
|
||||||
|
) ++ RuntimeError.all.toList).map(labelGenerator.getLabelDef(_))
|
||||||
|
assert(labels.distinct.length == labels.length)
|
||||||
|
}
|
||||||
|
|
||||||
|
"getLabelArg" should "return unique labels" in {
|
||||||
|
assert(
|
||||||
|
LabelArg("test") == LabelArg("test") &&
|
||||||
|
LabelArg("test").hashCode == LabelArg("test").hashCode,
|
||||||
|
"Sanity check: LabelArg should be case-classes"
|
||||||
|
)
|
||||||
|
|
||||||
|
val labelGenerator = new LabelGenerator
|
||||||
|
val labels = (List(
|
||||||
|
Builtin.Exit,
|
||||||
|
Builtin.Printf,
|
||||||
|
Ident("exit", 0)(?),
|
||||||
|
Ident("test", 0)(?),
|
||||||
|
"test",
|
||||||
|
"test",
|
||||||
|
"test3"
|
||||||
|
) ++ RuntimeError.all.toList).map {
|
||||||
|
case s: String => labelGenerator.getLabelArg(s)
|
||||||
|
case t: (CallTarget | RuntimeError) => labelGenerator.getLabelArg(t)
|
||||||
|
}
|
||||||
|
assert(labels.distinct.length == labels.distinct.length)
|
||||||
|
}
|
||||||
|
|
||||||
|
it should "return consistent labels to getLabelDef" in {
|
||||||
|
val labelGenerator = new LabelGenerator
|
||||||
|
val targets = (List(
|
||||||
|
Builtin.Exit,
|
||||||
|
Builtin.Printf,
|
||||||
|
Ident("exit", 0)(?),
|
||||||
|
Ident("test", 0)(?)
|
||||||
|
) ++ RuntimeError.all.toList)
|
||||||
|
val labelDefs = targets.map(labelGenerator.getLabelDef(_).toString.dropRight(1)).toSet
|
||||||
|
val labelArgs = targets.map(labelGenerator.getLabelArg(_).toString).toSet
|
||||||
|
assert(labelDefs == labelArgs)
|
||||||
|
}
|
||||||
|
|
||||||
|
"generateConstants" should "generate de-duplicated labels for strings" in {
|
||||||
|
val labelGenerator = new LabelGenerator
|
||||||
|
val strings = List("hello", "world", "hello\u0000world", "hello", "Hello")
|
||||||
|
val distincts = strings.distinct.length
|
||||||
|
val labels = strings.map(labelGenerator.getLabelArg(_).toString).toSet
|
||||||
|
val asmLines = labelGenerator.generateConstants
|
||||||
|
assert(
|
||||||
|
asmLines.collect { case LabelDef(name) =>
|
||||||
|
name
|
||||||
|
}.length == distincts
|
||||||
|
)
|
||||||
|
assert(
|
||||||
|
asmLines.collect { case Directive.Asciz(str) => str }.length == distincts
|
||||||
|
)
|
||||||
|
assert(asmLines.collect { case LabelDef(name) => name }.toList.toSet == labels)
|
||||||
|
}
|
||||||
|
}
|
||||||
140
src/test/wacc/backend/stackSpec.scala
Normal file
140
src/test/wacc/backend/stackSpec.scala
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
package wacc
|
||||||
|
|
||||||
|
import org.scalatest.flatspec.AnyFlatSpec
|
||||||
|
import cats.data.Chain
|
||||||
|
|
||||||
|
class StackSpec extends AnyFlatSpec {
|
||||||
|
import microWacc._
|
||||||
|
import assemblyIR._
|
||||||
|
import assemblyIR.Size._
|
||||||
|
import assemblyIR.commonRegisters._
|
||||||
|
import types.{KnownType, ?}
|
||||||
|
import sizeExtensions.size
|
||||||
|
|
||||||
|
private val RSP = Register(Q64, RegName.SP)
|
||||||
|
|
||||||
|
"size" should "be 0 initially" in {
|
||||||
|
val stack = new Stack
|
||||||
|
assert(stack.size == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
"push" should "add an expression to the stack" in {
|
||||||
|
val stack = new Stack
|
||||||
|
val expr = Ident("x", 0)(?)
|
||||||
|
val result = stack.push(expr, RAX)
|
||||||
|
assert(stack.size == 1)
|
||||||
|
assert(result == Push(RAX))
|
||||||
|
}
|
||||||
|
|
||||||
|
it should "add 2 expressions to the stack" in {
|
||||||
|
val stack = new Stack
|
||||||
|
val expr1 = Ident("x", 0)(?)
|
||||||
|
val expr2 = Ident("x", 1)(?)
|
||||||
|
val result1 = stack.push(expr1, RAX)
|
||||||
|
val result2 = stack.push(expr2, RCX)
|
||||||
|
assert(stack.size == 2)
|
||||||
|
assert(result1 == Push(RAX))
|
||||||
|
assert(result2 == Push(RCX))
|
||||||
|
}
|
||||||
|
|
||||||
|
it should "add a value to the stack" in {
|
||||||
|
val stack = new Stack
|
||||||
|
val result = stack.push(D32, RAX)
|
||||||
|
assert(stack.size == 1)
|
||||||
|
assert(result == Push(RAX))
|
||||||
|
}
|
||||||
|
|
||||||
|
"reserve" should "reserve space for an identifier" in {
|
||||||
|
val stack = new Stack
|
||||||
|
val ident = Ident("x", 0)(KnownType.Int)
|
||||||
|
val result = stack.reserve(ident)
|
||||||
|
assert(stack.size == 1)
|
||||||
|
assert(result == Subtract(RSP, ImmediateVal(Q64.toInt)))
|
||||||
|
}
|
||||||
|
|
||||||
|
it should "reserve space for a register" in {
|
||||||
|
val stack = new Stack
|
||||||
|
val result = stack.reserve(RAX)
|
||||||
|
assert(stack.size == 1)
|
||||||
|
assert(result == Subtract(RSP, ImmediateVal(Q64.toInt)))
|
||||||
|
}
|
||||||
|
|
||||||
|
it should "reserve space for multiple values" in {
|
||||||
|
val stack = new Stack
|
||||||
|
val result = stack.reserve(D32, Q64, B8)
|
||||||
|
assert(stack.size == 3)
|
||||||
|
assert(result == Subtract(RSP, ImmediateVal(Q64.toInt * 3)))
|
||||||
|
}
|
||||||
|
|
||||||
|
"pop" should "remove the last value from the stack" in {
|
||||||
|
val stack = new Stack
|
||||||
|
stack.push(D32, RAX)
|
||||||
|
val result = stack.pop(RAX)
|
||||||
|
assert(stack.size == 0)
|
||||||
|
assert(result == Pop(RAX))
|
||||||
|
}
|
||||||
|
|
||||||
|
"drop" should "remove the last 2 value from the stack" in {
|
||||||
|
val stack = new Stack
|
||||||
|
stack.push(D32, RAX)
|
||||||
|
stack.push(Q64, RAX)
|
||||||
|
stack.push(B8, RAX)
|
||||||
|
val result = stack.drop(2)
|
||||||
|
assert(stack.size == 1)
|
||||||
|
assert(result == Add(RSP, ImmediateVal(Q64.toInt * 2)))
|
||||||
|
}
|
||||||
|
|
||||||
|
"withScope" should "reset stack after block" in {
|
||||||
|
val stack = new Stack
|
||||||
|
stack.push(D32, RAX)
|
||||||
|
stack.push(Q64, RCX)
|
||||||
|
stack.push(B8, RDX)
|
||||||
|
val result = stack.withScope(() =>
|
||||||
|
Chain(
|
||||||
|
stack.push(Q64, RSI),
|
||||||
|
stack.push(B8, RDI),
|
||||||
|
stack.push(B8, RBP)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assert(stack.size == 3)
|
||||||
|
assert(
|
||||||
|
result == Chain(
|
||||||
|
Push(RSI),
|
||||||
|
Push(RDI),
|
||||||
|
Push(RBP),
|
||||||
|
Add(RSP, ImmediateVal(Q64.toInt * 3))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
"accessVar" should "return the correctly-sized memory location for the identifier" in {
|
||||||
|
val stack = new Stack
|
||||||
|
val id = Ident("x", 0)(KnownType.Int)
|
||||||
|
stack.push(Q64, RAX)
|
||||||
|
stack.push(id, RCX)
|
||||||
|
stack.push(B8, RDX)
|
||||||
|
stack.push(D32, RSI)
|
||||||
|
val result = stack.accessVar(Ident("x", 0)(KnownType.Int))
|
||||||
|
assert(result == MemLocation(RSP, Q64.toInt * 2, opSize = Some(KnownType.Int.size)))
|
||||||
|
}
|
||||||
|
|
||||||
|
"contains" should "return true if the stack contains the identifier" in {
|
||||||
|
val stack = new Stack
|
||||||
|
val id = Ident("x", 0)(KnownType.Int)
|
||||||
|
stack.push(D32, RAX)
|
||||||
|
stack.push(id, RCX)
|
||||||
|
stack.push(B8, RDX)
|
||||||
|
assert(stack.contains(id))
|
||||||
|
assert(!stack.contains(Ident("x", 1)(KnownType.Int)))
|
||||||
|
}
|
||||||
|
|
||||||
|
"head" should "return the correct memory location for the last element" in {
|
||||||
|
val stack = new Stack
|
||||||
|
val id = Ident("x", 0)(KnownType.Int)
|
||||||
|
stack.push(D32, RAX)
|
||||||
|
stack.push(id, RCX)
|
||||||
|
stack.push(B8, RDX)
|
||||||
|
val result = stack.head
|
||||||
|
assert(result == MemLocation(RSP, opSize = Some(B8)))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +1,19 @@
|
|||||||
package wacc
|
package wacc
|
||||||
|
|
||||||
import org.scalatest.BeforeAndAfterAll
|
import org.scalatest.BeforeAndAfterAll
|
||||||
import org.scalatest.flatspec.AnyFlatSpec
|
|
||||||
import org.scalatest.Inspectors.forEvery
|
import org.scalatest.Inspectors.forEvery
|
||||||
|
import org.scalatest.matchers.should.Matchers._
|
||||||
|
import org.scalatest.freespec.AsyncFreeSpec
|
||||||
|
import cats.effect.testing.scalatest.AsyncIOSpec
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import java.nio.file.Path
|
||||||
import sys.process._
|
import sys.process._
|
||||||
import java.io.PrintStream
|
|
||||||
import scala.io.Source
|
import scala.io.Source
|
||||||
|
import cats.effect.IO
|
||||||
|
import wacc.{compile as compileWacc}
|
||||||
|
|
||||||
|
class ParallelExamplesSpec extends AsyncFreeSpec with AsyncIOSpec with BeforeAndAfterAll {
|
||||||
|
|
||||||
class ParallelExamplesSpec extends AnyFlatSpec with BeforeAndAfterAll {
|
|
||||||
val files =
|
val files =
|
||||||
allWaccFiles("wacc-examples/valid").map { p =>
|
allWaccFiles("wacc-examples/valid").map { p =>
|
||||||
(p.toString, List(0))
|
(p.toString, List(0))
|
||||||
@@ -21,97 +26,119 @@ class ParallelExamplesSpec extends AnyFlatSpec with BeforeAndAfterAll {
|
|||||||
} ++
|
} ++
|
||||||
allWaccFiles("wacc-examples/invalid/whack").map { p =>
|
allWaccFiles("wacc-examples/invalid/whack").map { p =>
|
||||||
(p.toString, List(100, 200))
|
(p.toString, List(100, 200))
|
||||||
|
} ++
|
||||||
|
allWaccFiles("extension/examples/valid").map { p =>
|
||||||
|
(p.toString, List(0))
|
||||||
|
} ++
|
||||||
|
allWaccFiles("extension/examples/invalid/syntax").map { p =>
|
||||||
|
(p.toString, List(100))
|
||||||
|
} ++
|
||||||
|
allWaccFiles("extension/examples/invalid/semantics").map { p =>
|
||||||
|
(p.toString, List(200))
|
||||||
}
|
}
|
||||||
|
|
||||||
// tests go here
|
|
||||||
forEvery(files) { (filename, expectedResult) =>
|
forEvery(files) { (filename, expectedResult) =>
|
||||||
val baseFilename = filename.stripSuffix(".wacc")
|
val baseFilename = filename.stripSuffix(".wacc")
|
||||||
given stdout: PrintStream = PrintStream(File(baseFilename + ".out"))
|
|
||||||
|
|
||||||
s"$filename" should "be compiled with correct result" in {
|
s"$filename" - {
|
||||||
val result = compile(filename)
|
"should be compiled with correct result" in {
|
||||||
assert(expectedResult.contains(result))
|
if (fileIsPendingFrontend(filename))
|
||||||
}
|
IO.pure(pending)
|
||||||
|
|
||||||
if (expectedResult == List(0)) it should "run with correct result" in {
|
|
||||||
if (fileIsDisallowedBackend(filename)) pending
|
|
||||||
|
|
||||||
// Retrieve contents to get input and expected output + exit code
|
|
||||||
val contents = scala.io.Source.fromFile(File(filename)).getLines.toList
|
|
||||||
val inputLine =
|
|
||||||
contents
|
|
||||||
.find(_.matches("^# ?[Ii]nput:.*$"))
|
|
||||||
.map(_.split(":").last.strip + "\n")
|
|
||||||
.getOrElse("")
|
|
||||||
val outputLineIdx = contents.indexWhere(_.matches("^# ?[Oo]utput:.*$"))
|
|
||||||
val expectedOutput =
|
|
||||||
if (outputLineIdx == -1) ""
|
|
||||||
else
|
else
|
||||||
contents
|
compileWacc(Path.of(filename), outputDir = None, log = false).map { result =>
|
||||||
.drop(outputLineIdx + 1)
|
expectedResult should contain(result)
|
||||||
.takeWhile(_.startsWith("#"))
|
}
|
||||||
.map(_.stripPrefix("#").stripLeading)
|
}
|
||||||
.mkString("\n")
|
|
||||||
|
|
||||||
val exitLineIdx = contents.indexWhere(_.matches("^# ?[Ee]xit:.*$"))
|
if (expectedResult == List(0)) {
|
||||||
val expectedExit =
|
"should run with correct result" in {
|
||||||
if (exitLineIdx == -1) 0
|
if (fileIsDisallowedBackend(filename))
|
||||||
else contents(exitLineIdx + 1).stripPrefix("#").strip.toInt
|
IO.pure(succeed)
|
||||||
|
else if (fileIsPendingBackend(filename))
|
||||||
|
IO.pure(pending)
|
||||||
|
else
|
||||||
|
for {
|
||||||
|
contents <- IO(Source.fromFile(File(filename)).getLines.toList)
|
||||||
|
inputLine = extractInput(contents)
|
||||||
|
expectedOutput = extractOutput(contents)
|
||||||
|
expectedExit = extractExit(contents)
|
||||||
|
|
||||||
// Assembly and link using gcc
|
asmFilename = baseFilename + ".s"
|
||||||
val asmFilename = baseFilename + ".s"
|
execFilename = baseFilename
|
||||||
val execFilename = baseFilename
|
gccResult <- IO(s"gcc -o $execFilename -z noexecstack $asmFilename".!)
|
||||||
val gccResult = s"gcc -o $execFilename -z noexecstack $asmFilename".!
|
|
||||||
assert(gccResult == 0)
|
|
||||||
|
|
||||||
// Run the executable with the provided input
|
_ = assert(gccResult == 0)
|
||||||
val stdout = new StringBuilder
|
|
||||||
val process = s"timeout 5s $execFilename" run ProcessIO(
|
|
||||||
in = w => {
|
|
||||||
w.write(inputLine.getBytes)
|
|
||||||
w.close()
|
|
||||||
},
|
|
||||||
out = Source.fromInputStream(_).addString(stdout),
|
|
||||||
err = _ => ()
|
|
||||||
)
|
|
||||||
|
|
||||||
assert(process.exitValue == expectedExit)
|
stdout <- IO.pure(new StringBuilder)
|
||||||
assert(
|
process <- IO {
|
||||||
stdout.toString
|
s"timeout 5s $execFilename" run ProcessIO(
|
||||||
.replaceAll("0x[0-9a-f]+", "#addrs#")
|
in = w => {
|
||||||
.replaceAll("fatal error:.*", "#runtime_error#\u0000")
|
w.write(inputLine.getBytes)
|
||||||
.takeWhile(_ != '\u0000')
|
w.close()
|
||||||
== expectedOutput
|
},
|
||||||
)
|
out = Source.fromInputStream(_).addString(stdout),
|
||||||
|
err = _ => ()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
exitCode <- IO.pure(process.exitValue)
|
||||||
|
|
||||||
|
} yield {
|
||||||
|
exitCode shouldBe expectedExit
|
||||||
|
normalizeOutput(stdout.toString) shouldBe expectedOutput
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
def allWaccFiles(dir: String): IndexedSeq[os.Path] =
|
def allWaccFiles(dir: String): IndexedSeq[os.Path] =
|
||||||
val d = java.io.File(dir)
|
val d = java.io.File(dir)
|
||||||
os.walk(os.Path(d.getAbsolutePath)).filter { _.ext == "wacc" }
|
os.walk(os.Path(d.getAbsolutePath)).filter(_.ext == "wacc")
|
||||||
|
|
||||||
def fileIsDisallowedBackend(filename: String): Boolean =
|
private def fileIsDisallowedBackend(filename: String): Boolean =
|
||||||
Seq(
|
filename.matches("^.*wacc-examples/valid/advanced.*$")
|
||||||
// format: off
|
|
||||||
// disable formatting to avoid binPack
|
private def fileIsPendingFrontend(filename: String): Boolean =
|
||||||
"^.*wacc-examples/valid/advanced.*$",
|
List(
|
||||||
// "^.*wacc-examples/valid/array.*$",
|
// "^.*extension/examples/invalid/syntax/imports/importBadSyntax.*$",
|
||||||
// "^.*wacc-examples/valid/basic/exit.*$",
|
// "^.*extension/examples/invalid/semantics/imports.*$",
|
||||||
// "^.*wacc-examples/valid/basic/skip.*$",
|
// "^.*extension/examples/valid/imports.*$"
|
||||||
// "^.*wacc-examples/valid/expressions.*$",
|
).exists(filename.matches)
|
||||||
// "^.*wacc-examples/valid/function/nested_functions.*$",
|
|
||||||
// "^.*wacc-examples/valid/function/simple_functions.*$",
|
private def fileIsPendingBackend(filename: String): Boolean =
|
||||||
// "^.*wacc-examples/valid/if.*$",
|
List(
|
||||||
// "^.*wacc-examples/valid/IO/print.*$",
|
// "^.*extension/examples/invalid/syntax/imports.*$",
|
||||||
// "^.*wacc-examples/valid/IO/read.*$",
|
// "^.*extension/examples/invalid/semantics/imports.*$",
|
||||||
// "^.*wacc-examples/valid/IO/IOLoop.wacc.*$",
|
// "^.*extension/examples/valid/imports.*$"
|
||||||
// "^.*wacc-examples/valid/IO/IOSequence.wacc.*$",
|
).exists(filename.matches)
|
||||||
// "^.*wacc-examples/valid/pairs.*$",
|
|
||||||
//"^.*wacc-examples/valid/runtimeErr.*$",
|
private def extractInput(contents: List[String]): String =
|
||||||
// "^.*wacc-examples/valid/scope.*$",
|
contents
|
||||||
// "^.*wacc-examples/valid/sequence.*$",
|
.find(_.matches("^# ?[Ii]nput:.*$"))
|
||||||
// "^.*wacc-examples/valid/variables.*$",
|
.map(_.split(":").last.strip + "\n")
|
||||||
// "^.*wacc-examples/valid/while.*$",
|
.getOrElse("")
|
||||||
// format: on
|
|
||||||
).find(filename.matches).isDefined
|
private def extractOutput(contents: List[String]): String = {
|
||||||
|
val outputLineIdx = contents.indexWhere(_.matches("^# ?[Oo]utput:.*$"))
|
||||||
|
if (outputLineIdx == -1) ""
|
||||||
|
else
|
||||||
|
contents
|
||||||
|
.drop(outputLineIdx + 1)
|
||||||
|
.takeWhile(_.startsWith("#"))
|
||||||
|
.map(_.stripPrefix("#").stripLeading)
|
||||||
|
.mkString("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
private def extractExit(contents: List[String]): Int = {
|
||||||
|
val exitLineIdx = contents.indexWhere(_.matches("^# ?[Ee]xit:.*$"))
|
||||||
|
if (exitLineIdx == -1) 0
|
||||||
|
else contents(exitLineIdx + 1).stripPrefix("#").strip.toInt
|
||||||
|
}
|
||||||
|
|
||||||
|
private def normalizeOutput(output: String): String =
|
||||||
|
output
|
||||||
|
.replaceAll("0x[0-9a-f]+", "#addrs#")
|
||||||
|
.replaceAll("fatal error:.*", "#runtime_error#\u0000")
|
||||||
|
.takeWhile(_ != '\u0000')
|
||||||
}
|
}
|
||||||
|
|||||||
4
wacc-syntax/.vscodeignore
Normal file
4
wacc-syntax/.vscodeignore
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
.vscode/**
|
||||||
|
.vscode-test/**
|
||||||
|
.gitignore
|
||||||
|
vsc-extension-quickstart.md
|
||||||
9
wacc-syntax/CHANGELOG.md
Normal file
9
wacc-syntax/CHANGELOG.md
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
# Change Log
|
||||||
|
|
||||||
|
All notable changes to the "wacc-syntax" extension will be documented in this file.
|
||||||
|
|
||||||
|
Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
- Initial release
|
||||||
7
wacc-syntax/README.md
Normal file
7
wacc-syntax/README.md
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
### INTELLIWACC
|
||||||
|
|
||||||
|
This is the IntelliWACC extension for WACC code development; featuring syntax highlighting, error messages/highlighting and imports.
|
||||||
|
|
||||||
|
This extension was developed as a part of the "WACC Extensions" milestone 2025.
|
||||||
|
|
||||||
|
Authored by Alex L, Gleb K, Guy C and Jonny T
|
||||||
BIN
wacc-syntax/README.pdf
Normal file
BIN
wacc-syntax/README.pdf
Normal file
Binary file not shown.
71
wacc-syntax/extension.js
Normal file
71
wacc-syntax/extension.js
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
// Developed using the VSC language extension tutorial
|
||||||
|
// https://code.visualstudio.com/api/language-extensions/overview
|
||||||
|
|
||||||
|
const vscode = require('vscode');
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
const { parse } = require('path');
|
||||||
|
|
||||||
|
function activate(context) {
|
||||||
|
console.log('IntelliWACC is now active!');
|
||||||
|
|
||||||
|
let diagnosticCollection = vscode.languages.createDiagnosticCollection('wacc');
|
||||||
|
context.subscriptions.push(diagnosticCollection);
|
||||||
|
|
||||||
|
vscode.workspace.onDidSaveTextDocument((document) => {
|
||||||
|
if (document.languageId !== 'wacc') return;
|
||||||
|
|
||||||
|
let diagnostics = [];
|
||||||
|
let errors = generateErrors(document.getText(), document.fileName);
|
||||||
|
errors.forEach(error => {
|
||||||
|
console.log(error);
|
||||||
|
let range = new vscode.Range(error.line - 1 , error.column - 1, error.line - 1, error.column + error.size);
|
||||||
|
let diagnostic = new vscode.Diagnostic(range, error.errorMessage, vscode.DiagnosticSeverity.Error);
|
||||||
|
diagnostics.push(diagnostic);
|
||||||
|
});
|
||||||
|
|
||||||
|
diagnosticCollection.set(document.uri, diagnostics);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function deactivate() {
|
||||||
|
console.log('IntelliWACC is deactivating...');
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateErrors(code, filePath) {
|
||||||
|
try {
|
||||||
|
console.log("generating errors")
|
||||||
|
const fs = require('fs');
|
||||||
|
const tmpFilePath = parse(filePath).dir + '/.temp_wacc_file.wacc';
|
||||||
|
fs.writeFileSync(tmpFilePath, code);
|
||||||
|
|
||||||
|
let output;
|
||||||
|
try {
|
||||||
|
const waccExePath = `${__dirname}/wacc-compiler`;
|
||||||
|
output = execSync(`${waccExePath} ${tmpFilePath}`, { encoding: 'utf8', shell: true, stdio: 'pipe'});
|
||||||
|
} catch (err) {
|
||||||
|
console.log("Error running compiler");
|
||||||
|
output = err.stdout;
|
||||||
|
console.log(output);
|
||||||
|
}
|
||||||
|
let errors = [];
|
||||||
|
errorRegex = /\(line ([\d]+), column ([\d]+)\):\n([^>]+)([^\^]+)([\^]+)\n([^\n]+)([^\(]*)/g
|
||||||
|
while((match = errorRegex.exec(output)) !== null) {
|
||||||
|
console.log(match[5]);
|
||||||
|
errors.push({
|
||||||
|
line: parseInt(match[1], 10),
|
||||||
|
column: parseInt(match[2], 10),
|
||||||
|
errorMessage: match[3].trim(),
|
||||||
|
size: match[5].length - 1
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return errors;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error running compiler:', err);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
activate,
|
||||||
|
deactivate
|
||||||
|
};
|
||||||
BIN
wacc-syntax/icon.png
Normal file
BIN
wacc-syntax/icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 571 KiB |
28
wacc-syntax/language-configuration.json
Normal file
28
wacc-syntax/language-configuration.json
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
{
|
||||||
|
"comments": {
|
||||||
|
// symbol used for single line comment. Remove this entry if your language does not support line comments
|
||||||
|
"lineComment": "#",
|
||||||
|
},
|
||||||
|
// symbols used as brackets
|
||||||
|
"brackets": [
|
||||||
|
["{", "}"],
|
||||||
|
["[", "]"],
|
||||||
|
["(", ")"]
|
||||||
|
],
|
||||||
|
// symbols that are auto closed when typing
|
||||||
|
"autoClosingPairs": [
|
||||||
|
["{", "}"],
|
||||||
|
["[", "]"],
|
||||||
|
["(", ")"],
|
||||||
|
["\"", "\""],
|
||||||
|
["'", "'"]
|
||||||
|
],
|
||||||
|
// symbols that can be used to surround a selection
|
||||||
|
"surroundingPairs": [
|
||||||
|
["{", "}"],
|
||||||
|
["[", "]"],
|
||||||
|
["(", ")"],
|
||||||
|
["\"", "\""],
|
||||||
|
["'", "'"]
|
||||||
|
]
|
||||||
|
}
|
||||||
15
wacc-syntax/package-lock.json
generated
Normal file
15
wacc-syntax/package-lock.json
generated
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
{
|
||||||
|
"name": "wacc-syntax",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "wacc-syntax",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"engines": {
|
||||||
|
"vscode": "^1.97.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
40
wacc-syntax/package.json
Normal file
40
wacc-syntax/package.json
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
{
|
||||||
|
"name": "wacc-syntax",
|
||||||
|
"displayName": "intelliWACC",
|
||||||
|
"description": "WACC language support features",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"publisher": "WACC-37-2025",
|
||||||
|
"icon": "icon.png",
|
||||||
|
"engines": {
|
||||||
|
"vscode": "^1.97.0"
|
||||||
|
},
|
||||||
|
"categories": [
|
||||||
|
"Programming Languages"
|
||||||
|
],
|
||||||
|
"contributes": {
|
||||||
|
"languages": [{
|
||||||
|
"id": "wacc",
|
||||||
|
"aliases": ["WACC", "wacc"],
|
||||||
|
"extensions": [".wacc"],
|
||||||
|
"configuration": "./language-configuration.json"
|
||||||
|
}],
|
||||||
|
"grammars": [{
|
||||||
|
"language": "wacc",
|
||||||
|
"scopeName": "source.wacc",
|
||||||
|
"path": "./syntaxes/wacc.tmLanguage.json"
|
||||||
|
}],
|
||||||
|
"properties": {
|
||||||
|
"files.exclude": {
|
||||||
|
"type": "object",
|
||||||
|
"default": {
|
||||||
|
"**/.temp_wacc_file.*": true
|
||||||
|
},
|
||||||
|
"description": "Configure patterns for excluding files and folders."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"build": "vsce package"
|
||||||
|
},
|
||||||
|
"main": "./extension.js"
|
||||||
|
}
|
||||||
56
wacc-syntax/syntaxes/wacc.tmLanguage.json
Normal file
56
wacc-syntax/syntaxes/wacc.tmLanguage.json
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
|
||||||
|
"name": "WACC",
|
||||||
|
"scopeName": "source.wacc",
|
||||||
|
"fileTypes": [
|
||||||
|
"wacc"
|
||||||
|
],
|
||||||
|
"patterns": [
|
||||||
|
{
|
||||||
|
"match": "\\b(true|false)\\b",
|
||||||
|
"name": "keyword.constant.wacc"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "\\b(int|bool|char|string|pair|null)\\b",
|
||||||
|
"name": "storage.type.wacc"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "\".*?\"",
|
||||||
|
"name": "string.quoted.double.mylang"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "\\b(begin|end)\\b",
|
||||||
|
"name": "keyword.other.unit"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "\\b(if|then|else|fi|while|do|done|skip|is)\\b",
|
||||||
|
"name": "keyword.control.wacc"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "\\b(read|free|print|println|newpair|call|fst|snd|ord|chr|len)\\b",
|
||||||
|
"name": "keyword.operator.function.wacc"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "\\b(return|exit)\\b",
|
||||||
|
"name": "keyword.operator.wacc"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "'[^']{1}'",
|
||||||
|
"name": "constant.character.wacc"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "\\b([a-zA-Z_][a-zA-Z0-9_]*)\\s*(?=\\()",
|
||||||
|
"name": "variable.function.wacc"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b",
|
||||||
|
"name": "variable.other.wacc"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"match": "#.*$",
|
||||||
|
"name": "comment.line"
|
||||||
|
}
|
||||||
|
|
||||||
|
]
|
||||||
|
|
||||||
|
}
|
||||||
29
wacc-syntax/vsc-extension-quickstart.md
Normal file
29
wacc-syntax/vsc-extension-quickstart.md
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# Welcome to your VS Code Extension
|
||||||
|
|
||||||
|
## What's in the folder
|
||||||
|
|
||||||
|
* This folder contains all of the files necessary for your extension.
|
||||||
|
* `package.json` - this is the manifest file in which you declare your language support and define the location of the grammar file that has been copied into your extension.
|
||||||
|
* `syntaxes/wacc.tmLanguage.json` - this is the Text mate grammar file that is used for tokenization.
|
||||||
|
* `language-configuration.json` - this is the language configuration, defining the tokens that are used for comments and brackets.
|
||||||
|
|
||||||
|
## Get up and running straight away
|
||||||
|
|
||||||
|
* Make sure the language configuration settings in `language-configuration.json` are accurate.
|
||||||
|
* Press `F5` to open a new window with your extension loaded.
|
||||||
|
* Create a new file with a file name suffix matching your language.
|
||||||
|
* Verify that syntax highlighting works and that the language configuration settings are working.
|
||||||
|
|
||||||
|
## Make changes
|
||||||
|
|
||||||
|
* You can relaunch the extension from the debug toolbar after making changes to the files listed above.
|
||||||
|
* You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes.
|
||||||
|
|
||||||
|
## Add more language features
|
||||||
|
|
||||||
|
* To add features such as IntelliSense, hovers and validators check out the VS Code extenders documentation at https://code.visualstudio.com/docs
|
||||||
|
|
||||||
|
## Install your extension
|
||||||
|
|
||||||
|
* To start using your extension with Visual Studio Code copy it into the `<user home>/.vscode/extensions` folder and restart Code.
|
||||||
|
* To share your extension with the world, read on https://code.visualstudio.com/docs about publishing an extension.
|
||||||
Reference in New Issue
Block a user