cleanup: fix spelling errors and some compiler warnings/suggestions

This commit is contained in:
Irmen de Jong 2021-10-10 23:35:02 +02:00
parent 7de4e9e66a
commit 3557d38ce0
26 changed files with 58 additions and 63 deletions

View File

@ -37,7 +37,7 @@ class ModuleImporter(private val program: Program,
else -> candidates.first() // TODO: report error if more than 1 candidate?
}
var logMsg = "importing '${filePath.nameWithoutExtension}' (from $srcPath)"
val logMsg = "importing '${filePath.nameWithoutExtension}' (from $srcPath)"
println(logMsg)
return importModule(SourceCode.fromPath(srcPath))

View File

@ -12,8 +12,6 @@ import prog8.compiler.IErrorReporter
import prog8.compiler.ZeropageType
import prog8.compiler.functions.BuiltinFunctions
import prog8.compiler.functions.builtinFunctionReturnType
import prog8.compiler.target.C64Target
import prog8.compiler.target.Cx16Target
import prog8.compiler.target.ICompilationTarget
import java.io.CharConversionException
import java.io.File
@ -1014,7 +1012,7 @@ internal class AstChecker(private val program: Program,
if(target is BuiltinFunctionStatementPlaceholder) {
if(target.name=="swap") {
// swap() is a bit weird because this one is translated into a operations directly, instead of being a function call
// swap() is a bit weird because this one is translated into an operations directly, instead of being a function call
val dt1 = args[0].inferType(program)
val dt2 = args[1].inferType(program)
if (dt1 != dt2)
@ -1170,13 +1168,11 @@ internal class AstChecker(private val program: Program,
}
private fun checkFunctionOrLabelExists(target: IdentifierReference, statement: Statement): Statement? {
val targetStatement = target.targetStatement(program)
if(targetStatement is Label || targetStatement is Subroutine || targetStatement is BuiltinFunctionStatementPlaceholder)
return targetStatement
else if(targetStatement==null)
errors.err("undefined function or subroutine: ${target.nameInSource.joinToString(".")}", statement.position)
else
errors.err("cannot call that: ${target.nameInSource.joinToString(".")}", statement.position)
when (val targetStatement = target.targetStatement(program)) {
is Label, is Subroutine, is BuiltinFunctionStatementPlaceholder -> return targetStatement
null -> errors.err("undefined function or subroutine: ${target.nameInSource.joinToString(".")}", statement.position)
else -> errors.err("cannot call that: ${target.nameInSource.joinToString(".")}", statement.position)
}
return null
}

View File

@ -130,9 +130,9 @@ internal fun Program.checkIdentifiers(errors: IErrorReporter, options: Compilati
// TODO: move check for unique module names to earlier stage and/or to unit tests
val namesToModules = mapOf<String, MutableList<prog8.ast.Module>>().toMutableMap()
for (m in modules) {
var others = namesToModules[m.name]
val others = namesToModules[m.name]
if (others == null) {
namesToModules.put(m.name, listOf(m).toMutableList())
namesToModules[m.name] = listOf(m).toMutableList()
} else {
others.add(m)
}
@ -141,7 +141,7 @@ internal fun Program.checkIdentifiers(errors: IErrorReporter, options: Compilati
.map { Pair(it, namesToModules[it]!!.size) }
.filter { it.second > 1 }
.map { "\"${it.first}\" (x${it.second})"}
if (nonUniqueNames.size > 0) {
if (nonUniqueNames.isNotEmpty()) {
throw FatalAstException("modules must have unique names; of the ttl ${modules.size} these have not: $nonUniqueNames")
}
}

View File

@ -16,7 +16,7 @@ internal class LiteralsToAutoVars(private val program: Program) : AstWalker() {
override fun after(string: StringLiteralValue, parent: Node): Iterable<IAstModification> {
if(string.parent !is VarDecl && string.parent !is WhenChoice) {
// replace the literal string by a identifier reference to the interned string
// replace the literal string by an identifier reference to the interned string
val scopedName = program.internString(string)
val identifier = IdentifierReference(scopedName, string.position)
return listOf(IAstModification.ReplaceNode(string, identifier, parent))

View File

@ -24,7 +24,7 @@ internal class StatementReorderer(val program: Program, val errors: IErrorReport
// - (syntax desugaring) a vardecl with a non-const initializer value is split into a regular vardecl and an assignment statement.
// - in-place assignments are reordered a bit so that they are mostly of the form A = A <operator> <rest>
// - sorts the choices in when statement.
// - insert AddressOf (&) expression where required (string params to a UWORD function param etc).
// - insert AddressOf (&) expression where required (string params to a UWORD function param etc.).
private val directivesToMove = setOf("%output", "%launcher", "%zeropage", "%zpreserved", "%address", "%option")
@ -93,7 +93,7 @@ internal class StatementReorderer(val program: Program, val errors: IErrorReport
// ConstValue <associativeoperator> X --> X <associativeoperator> ConstValue
// (this should be done by the ExpressionSimplifier when optimizing is enabled,
// but the current assembly code generator for IF statements now also depends on it so we do it here regardless of optimization.)
// but the current assembly code generator for IF statements now also depends on it, so we do it here regardless of optimization.)
if (expr.left.constValue(program) != null && expr.operator in associativeOperators && expr.right.constValue(program) == null)
return listOf(IAstModification.SwapOperands(expr))

View File

@ -315,7 +315,7 @@ private fun builtinSizeof(args: List<Expression>, position: Position, program: P
@Suppress("UNUSED_PARAMETER")
private fun builtinLen(args: List<Expression>, position: Position, program: Program, memsizer: IMemSizer): NumericLiteralValue {
// note: in some cases the length is > 255 and then we have to return a UWORD type instead of a UBYTE.
// note: in some cases the length is > 255, and then we have to return a UWORD type instead of a UBYTE.
if(args.size!=1)
throw SyntaxError("len requires one argument", position)

View File

@ -113,7 +113,7 @@ internal object C64MachineDefinition: IMachineDefinition {
}
if (options.zeropage == ZeropageType.FLOATSAFE) {
// remove the zero page locations used for floating point operations from the free list
// remove the zeropage locations used for floating point operations from the free list
free.removeAll(listOf(
0x22, 0x23, 0x24, 0x25,
0x10, 0x11, 0x12, 0x26, 0x27, 0x28, 0x29, 0x2a,

View File

@ -1051,7 +1051,7 @@ object Petscii {
private val encodingScreencodeUppercase = decodingScreencodeUppercase.withIndex().associate{it.value to it.index}
private fun replaceSpecial(chr: Char): Char =
// characters often used in C like source code can be translated with a little bit of fantasy:
// characters often used in C like source code can be translated with a little fantasy:
when(chr) {
'^' -> '↑'
'_' -> '▁'

View File

@ -551,8 +551,7 @@ internal class AsmGen(private val program: Program,
internal fun loadByteFromPointerIntoA(pointervar: IdentifierReference): Pair<Boolean, String> {
// returns if the pointer is already on the ZP itself or not (in the latter case SCRATCH_W1 is used as intermediary)
val target = pointervar.targetStatement(program)
when (target) {
when (val target = pointervar.targetStatement(program)) {
is Label -> {
val sourceName = asmSymbolName(pointervar)
out(" lda $sourceName")
@ -1076,7 +1075,7 @@ internal class AsmGen(private val program: Program,
// note: A/Y must have been loaded with the number of iterations!
if(constIterations==0)
return
// no need to explicitly test for 0 iterations as this is done in the count down logic below
// no need to explicitly test for 0 iterations as this is done in the countdown logic below
val counterVar: String = createRepeatCounterVar(DataType.UWORD, constIterations, stmt)
out("""
@ -1097,7 +1096,7 @@ $repeatLabel lda $counterVar
}
private fun repeatByteCountInA(constIterations: Int?, repeatLabel: String, endLabel: String, stmt: RepeatLoop) {
// note: A must have been loaded with the number of iterations!
// note: A must be loaded with the number of iterations!
if(constIterations==0)
return
@ -1458,7 +1457,7 @@ $label nop""")
if(constIdx!=null && constIdx.number.toInt()>=0 && constIdx.number.toInt()<=255) {
return Pair(pointerOffsetExpr.left, NumericLiteralValue(DataType.UBYTE, constIdx.number, constIdx.position))
}
// could be that the index was type casted into uword, check that
// could be that the index was typecasted into uword, check that
val rightTc = pointerOffsetExpr.right as? TypecastExpression
if(rightTc!=null && rightTc.expression.inferType(program).istype(DataType.UBYTE))
return Pair(pointerOffsetExpr.left, rightTc.expression)
@ -1492,8 +1491,7 @@ $label nop""")
val ptrAndIndex = pointerViaIndexRegisterPossible(expr)
if(ptrAndIndex!=null) {
val pointervar = ptrAndIndex.first as? IdentifierReference
val target = pointervar?.targetStatement(program)
when(target) {
when(pointervar?.targetStatement(program)) {
is Label -> {
assignExpressionToRegister(ptrAndIndex.second, RegisterOrPair.Y)
out(" lda ${asmSymbolName(pointervar)},y")

View File

@ -74,7 +74,7 @@ private fun getLinesBy(lines: MutableList<String>, windowSize: Int) =
lines.withIndex().filter { it.value.isNotBlank() && !it.value.trimStart().startsWith(';') }.windowed(windowSize, partialWindows = false)
private fun optimizeCmpSequence(linesByFour: List<List<IndexedValue<String>>>): List<Modification> {
// the when statement (on bytes) generates a sequence of:
// when statement (on bytes) generates a sequence of:
// lda $ce01,x
// cmp #$20
// beq check_prog8_s72choice_32

View File

@ -858,8 +858,7 @@ internal class BuiltinFunctionsAsmGen(private val program: Program, private val
}
}
val datatype = first.inferType(program).typeOrElse(DataType.UNDEFINED)
when(datatype) {
when(val datatype: DataType = first.inferType(program).typeOrElse(DataType.UNDEFINED)) {
in ByteDatatypes, in WordDatatypes -> {
asmgen.assignExpressionToVariable(first, "P8ZP_SCRATCH_W1", datatype, null)
asmgen.assignExpressionToVariable(second, "P8ZP_SCRATCH_W2", datatype, null)

View File

@ -49,7 +49,7 @@ internal class FunctionCallAsmGen(private val program: Program, private val asmg
}
internal fun translateFunctionCall(stmt: IFunctionCall) {
// Output only the code to setup the parameters and perform the actual call
// Output only the code to set up the parameters and perform the actual call
// NOTE: does NOT output the code to deal with the result values!
// NOTE: does NOT output code to save/restore the X register for this call! Every caller should deal with this in their own way!!
// (you can use subroutine.shouldSaveX() and saveX()/restoreX() routines as a help for this)

View File

@ -398,7 +398,7 @@ internal class AssignmentAsmGen(private val program: Program, private val asmgen
RegisterOrPair.A,
RegisterOrPair.X,
RegisterOrPair.Y -> {
// 'cast' a ubyte value to a byte register; no cast needed at all
// 'cast' an ubyte value to a byte register; no cast needed at all
return assignExpressionToRegister(value, target.register)
}
RegisterOrPair.AX,

View File

@ -1010,8 +1010,7 @@ internal class AugmentableAssignmentAsmGen(private val program: Program,
private fun inplaceModification_word_variable_to_variable(name: String, dt: DataType, operator: String, ident: IdentifierReference) {
val otherName = asmgen.asmVariableName(ident)
val valueDt = ident.targetVarDecl(program)!!.datatype
when (valueDt) {
when (val valueDt = ident.targetVarDecl(program)!!.datatype) {
in ByteDatatypes -> {
// the other variable is a BYTE type so optimize for that
when (operator) {
@ -1697,7 +1696,7 @@ internal class AugmentableAssignmentAsmGen(private val program: Program,
if (innerCastDt == null) {
// simple typecast where the value is the target
when (target.datatype) {
DataType.UBYTE, DataType.BYTE -> { /* byte target can't be casted to anything else at all */ }
DataType.UBYTE, DataType.BYTE -> { /* byte target can't be typecasted to anything else at all */ }
DataType.UWORD, DataType.WORD -> {
when (outerCastDt) {
DataType.UBYTE, DataType.BYTE -> {

View File

@ -14,7 +14,7 @@ import prog8.compiler.astprocessing.toConstantIntegerRange
import prog8.compiler.target.ICompilationTarget
// Fix up the literal value's type to match that of the vardecl
// (also check range literal operands types before they get expanded to arrays for instance)
// (also check range literal operands types before they get expanded into arrays for instance)
internal class VarConstantValueTypeAdjuster(private val program: Program, private val errors: IErrorReporter) : AstWalker() {
override fun after(decl: VarDecl, parent: Node): Iterable<IAstModification> {

View File

@ -290,7 +290,7 @@ internal class ExpressionSimplifier(private val program: Program) : AstWalker()
if(arg is TypecastExpression) {
val valueDt = arg.expression.inferType(program)
if (valueDt.istype(DataType.BYTE) || valueDt.istype(DataType.UBYTE)) {
// useless lsb() of byte value that was casted to word
// useless lsb() of byte value that was typecasted to word
return listOf(IAstModification.ReplaceNode(functionCall, arg.expression, parent))
}
} else {
@ -306,7 +306,7 @@ internal class ExpressionSimplifier(private val program: Program) : AstWalker()
if(arg is TypecastExpression) {
val valueDt = arg.expression.inferType(program)
if (valueDt.istype(DataType.BYTE) || valueDt.istype(DataType.UBYTE)) {
// useless msb() of byte value that was casted to word, replace with 0
// useless msb() of byte value that was typecasted to word, replace with 0
return listOf(IAstModification.ReplaceNode(
functionCall,
NumericLiteralValue(valueDt.typeOrElse(DataType.UBYTE), 0, arg.expression.position),

View File

@ -47,8 +47,7 @@ internal class StatementOptimizer(private val program: Program,
if(subroutine!=null) {
val first = subroutine.statements.asSequence().filterNot { it is VarDecl || it is Directive }.firstOrNull()
if(first is Return && first.value?.isSimple==true) {
val orig = first.value!!
val copy = when(orig) {
val copy = when(val orig = first.value!!) {
is AddressOf -> {
val scoped = scopePrefix(orig.identifier, subroutine)
AddressOf(scoped, orig.position)

View File

@ -12,7 +12,7 @@ import prog8.ast.walk.IAstVisitor
/**
* Produces Prog8 source text from a [Program] (AST node),
* passing it as a String to the specified receiver function.
* TODO: rename/refactor to make proper sense in the presence of class [prog8.SourceCode]
* TODO: rename/refactor to make proper sense in the presence of class [prog8.parser.SourceCode]
*/
class AstToSourceCode(val output: (text: String) -> Unit, val program: Program): IAstVisitor {
private var scopelevel = 0

View File

@ -340,7 +340,7 @@ class Program(val name: String,
open class Module(override val name: String,
override var statements: MutableList<Statement>,
override val position: Position,
final override val position: Position,
val source: SourceCode?) : Node, INameScope {
override lateinit var parent: Node

View File

@ -25,7 +25,7 @@ private fun ParserRuleContext.toPosition() : Position {
*/
val filename = start.inputStream.sourceName
// note: be ware of TAB characters in the source text, they count as 1 column...
// note: beware of TAB characters in the source text, they count as 1 column...
return Position(filename, start.line, start.charPositionInLine, stop.charPositionInLine + stop.text.length)
}

View File

@ -165,7 +165,7 @@ val Cx16VirtualRegisters = listOf(
// find the parent node of a specific type or interface
// (useful to figure out in what namespace/block something is defined, etc)
// (useful to figure out in what namespace/block something is defined, etc.)
inline fun <reified T> findParentNode(node: Node): T? {
var candidate = node.parent
while(candidate !is T && candidate !is ParentSentinel)

View File

@ -515,7 +515,7 @@ class CharLiteral(val value: Char,
override fun referencesIdentifier(vararg scopedName: String) = false
override fun constValue(program: Program): NumericLiteralValue? = null // TODO: CharLiteral.constValue can't be NumericLiteralValue...
override fun accept(visitor: IAstVisitor) = visitor.visit(this)
override fun accept(walker: AstWalker, parent: Node) = walker.visit(this, parent)
override fun accept(visitor: AstWalker, parent: Node) = visitor.visit(this, parent)
override fun toString(): String = "'${escape(value.toString())}'"
override fun inferType(program: Program): InferredTypes.InferredType = InferredTypes.knownFor(DataType.UNDEFINED) // FIXME: CharLiteral.inferType
@ -645,7 +645,7 @@ class ArrayLiteralValue(val type: InferredTypes.InferredType, // inferred be
val castArray = value.map{
val num = it as? NumericLiteralValue
if(num==null) {
// an array of UWORDs could possibly also contain AddressOfs, other stuff can't be casted
// an array of UWORDs could possibly also contain AddressOfs, other stuff can't be typecasted
if (elementType != DataType.UWORD || it !is AddressOf)
return null // can't cast a value of the array, abort
it

View File

@ -114,7 +114,7 @@ data class Label(override val name: String, override val position: Position) : S
}
}
open class Return(var value: Expression?, override val position: Position) : Statement() {
open class Return(var value: Expression?, final override val position: Position) : Statement() {
override lateinit var parent: Node
override fun linkParents(parent: Node) {
@ -165,7 +165,7 @@ open class VarDecl(val type: VarDeclType,
val isArray: Boolean,
val autogeneratedDontRemove: Boolean,
val sharedWithAsm: Boolean,
override val position: Position) : Statement(), ISymbolStatement {
final override val position: Position) : Statement(), ISymbolStatement {
override lateinit var parent: Node
var allowInitializeWithZero = true
@ -285,7 +285,7 @@ class ArrayIndex(var indexExpr: Expression,
fun copy() = ArrayIndex(indexExpr, position)
}
open class Assignment(var target: AssignTarget, var value: Expression, override val position: Position) : Statement() {
open class Assignment(var target: AssignTarget, var value: Expression, final override val position: Position) : Statement() {
override lateinit var parent: Node
override fun linkParents(parent: Node) {
@ -670,7 +670,7 @@ class Subroutine(override val name: String,
open class SubroutineParameter(val name: String,
val type: DataType,
override val position: Position) : Node {
final override val position: Position) : Node {
override lateinit var parent: Node
override fun linkParents(parent: Node) {
@ -869,7 +869,7 @@ class WhenStatement(var condition: Expression,
else {
val values = choice.values!!.map {
val cv = it.constValue(program)
cv?.number?.toInt() ?: it.hashCode() // the hashcode is a nonsensical number but it avoids weird AST validation errors later
cv?.number?.toInt() ?: it.hashCode() // the hashcode is a nonsensical number, but it avoids weird AST validation errors later
}
result.add(values to choice)
}

View File

@ -53,7 +53,6 @@ object Prog8Parser {
position = Position(source.origin, 1, 0, 0),
source
) {
val provenance = Pair(source, Triple(1, 0, 0))
/**
* Adds a [Directive] to [statements] and
@ -112,13 +111,12 @@ object Prog8Parser {
}
}
private fun RecognitionException.getPosition(file: String) : Position {
private fun RecognitionException.getPosition(file: String): Position {
val offending = this.offendingToken
val line = offending.line
val beginCol = offending.charPositionInLine
val endCol = beginCol + offending.stopIndex - offending.startIndex // TODO: point to col *after* token?
val pos = Position(file, line, beginCol, endCol)
return pos
return Position(file, line, beginCol, endCol)
}
}

View File

@ -120,9 +120,8 @@ abstract class SourceCode {
override val isFromResources = true
override val origin = "@embedded@$normalized"
override fun getCharStream(): CharStream {
val inpStr = object{}.javaClass.getResourceAsStream(normalized)
val chars = CharStreams.fromStream(inpStr)
return chars
val inpStr = object {}.javaClass.getResourceAsStream(normalized)
return CharStreams.fromStream(inpStr)
}
}
}

View File

@ -4,10 +4,10 @@ import org.takes.Request
import org.takes.Response
import org.takes.Take
import org.takes.facets.fork.FkMethods
import org.takes.http.Exit;
import org.takes.http.FtBasic;
import org.takes.facets.fork.FkRegex;
import org.takes.facets.fork.TkFork;
import org.takes.http.Exit
import org.takes.http.FtBasic
import org.takes.facets.fork.FkRegex
import org.takes.facets.fork.TkFork
import org.takes.rq.form.RqFormBase
import org.takes.rs.RsJson
import org.takes.tk.TkSlf4j
@ -29,7 +29,14 @@ class RequestParser : Take {
val form = RqFormBase(request)
val names = form.names()
val a = form.param("a").single()
val compilationResult = compileProgram(Path.of(a), true, true, true, "c64", emptyList<String>(), Path.of("."))
val compilationResult = compileProgram(Path.of(a),
optimize = true,
writeAssembly = true,
slowCodegenWarnings = true,
compilationTarget = "c64",
libdirs = emptyList(),
outputDir = Path.of(".")
)
return RsJson(Jsonding())
}
}