Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go: introduce special GoOutputWriter and move generation of error check to it #299

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -485,12 +485,7 @@ class GoCompiler(typeProvider: ClassTypeProvider, config: RuntimeConfig)
override def instanceHeader(className: List[String], instName: InstanceIdentifier, dataType: DataType, isNullable: Boolean): Unit = {
out.puts(s"func (this *${types2class(className)}) ${publicMemberName(instName)}() (v ${kaitaiType2NativeType(dataType)}, err error) {")
out.inc
translator.returnRes = Some(dataType match {
case _: NumericType => "0"
case _: BooleanType => "false"
case _: StrType => "\"\""
case _ => "nil"
})
translator.returnRes = Some(defaultTypeValue(dataType))
}

override def instanceCalculate(instName: Identifier, dataType: DataType, value: Ast.expr): Unit = {
Expand Down Expand Up @@ -692,6 +687,13 @@ object GoCompiler extends LanguageCompilerStatic
def enumToStr(typeName: List[String], enumName: String): String =
types2class(typeName) + "__" + type2class(enumName)

def defaultTypeValue(dataType: DataType): String = dataType match {
case _: NumericType => "0"
case _: BooleanType => "false"
case _: StrType => "\"\""
case _ => "nil"
}

override def kstreamName: String = "kaitai.Stream"
override def kstructName: String = "kaitai.Struct"
override def ksErrorName(err: KSError): String = err match {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ class GoTranslator(out: StringLanguageOutputWriter, provider: TypeProvider, impo

import io.kaitai.struct.languages.GoCompiler._

/**
* Dummy return value that should be returned in case of error just because
* we cannot return nothing.
*/
var returnRes: Option[String] = None

override def translate(v: Ast.expr, extPrec: Int): String = resToStr(translateExpr(v, extPrec))
Expand Down Expand Up @@ -542,6 +546,10 @@ class GoTranslator(out: StringLanguageOutputWriter, provider: TypeProvider, impo

def localVarName(n: Int) = s"tmp$n"

/**
* Puts to the output code to check variable `err` for error value and emit
* a premature return with value of error.
*/
def outAddErrCheck(): Unit = {
out.puts("if err != nil {")
out.inc
Expand Down
Loading