diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 59fc2729..a3e55e79 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -2,7 +2,7 @@ on: [push, pull_request] name: Build jobs: build-linux: - runs-on: ubuntu-18.04 + runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 with: @@ -10,7 +10,7 @@ jobs: - run: ./build.sh working-directory: ./Build build-macos: - runs-on: macos-10.15 + runs-on: macos-11 steps: - uses: actions/checkout@v2 with: diff --git a/Build/build.bat b/Build/build.bat index 9298216f..a125fd34 100644 --- a/Build/build.bat +++ b/Build/build.bat @@ -3,7 +3,7 @@ set startingDir="%CD%" set basepath="%~dp0" cd %basepath%\..\Source -set Sources=actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildimplementationcpp.go buildbindingjava.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go +set Sources=actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildimplementationcpp.go buildbindingjava.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go buildimplementationjs.go buildimplementationts.go set GOOS=windows set GOARCH=amd64 @@ -16,42 +16,42 @@ echo "Patching properties of act.win64.exe" set GOOS=windows set GOARCH=386 echo "Build act.win32.exe" -go build -o ..\act.win32.exe %Sources% +REM go build -o ..\act.win32.exe %Sources% echo "Patching properties of act.win32.exe" -..\build\verpatch ..\act.win32.exe /high /va 1.8.0 /pv "1.8.0-develop" /s copyright "(c) 2018-2019 ACT Developers" /s desc "ACT is a code generator for software components" /s productName "Automatic Component Toolkit" +REM ..\build\verpatch ..\act.win32.exe /high /va 1.8.0 /pv "1.8.0-develop" /s copyright "(c) 2018-2019 ACT Developers" /s desc "ACT is a code generator for software components" /s productName "Automatic Component Toolkit" set GOOS=linux set GOARCH=amd64 echo "Build act.linux64" -go build -o ..\act.linux64 %Sources% +REM go build -o ..\act.linux64 %Sources% set GOOS=linux set GOARCH=386 echo "Build act.linux32" -go build -o ..\act.linux32 %Sources% +REM go build -o ..\act.linux32 %Sources% set GOOS=darwin set GOARCH=amd64 echo "Build act.darwin" -go build -o ..\act.darwin %Sources% +REM go build -o ..\act.darwin %Sources% set GOOS=darwin set GOARCH=arm set GOARM=5 echo "Build act.arm.darwin" -go build -o ..\act.arm.darwin %Sources% +REM go build -o ..\act.arm.darwin %Sources% set GOOS=linux set GOARCH=arm set GOARM=5 -go build -o ..\act.arm.linux32 %Sources% +REM go build -o ..\act.arm.linux32 %Sources% set GOOS=linux set GOARCH=arm64 set GOARM=5 echo "Build act.arm.linux64" -go build -o ..\act.arm.linux64 %Sources% +REM go build -o ..\act.arm.linux64 %Sources% copy ..\act.win64.exe ..\act.exe /Y copy ..\act.linux64 ..\act.linux /Y diff --git a/Build/build.sh b/Build/build.sh index 5d4b9e49..4050a422 100755 --- a/Build/build.sh +++ b/Build/build.sh @@ -6,7 +6,7 @@ startingpath="$(pwd)" basepath="$(cd "$(dirname "$0")" && pwd)" cd "$basepath/../Source" -Sources="actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go" +Sources="actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go buildimplementationjs.go buildimplementationts.go" echo "Build act.win64.exe" export GOARCH="amd64" diff --git a/Source/actutils.go b/Source/actutils.go index d503143b..43b41ef2 100644 --- a/Source/actutils.go +++ b/Source/actutils.go @@ -38,7 +38,7 @@ import ( ) // FileExists returns true if and only if the file in a given path exists -func FileExists(path string) (bool) { - _, err := os.Stat(path); - return !os.IsNotExist(err); -} \ No newline at end of file +func FileExists(path string) bool { + _, err := os.Stat(path) + return !os.IsNotExist(err) +} diff --git a/Source/automaticcomponenttoolkit.go b/Source/automaticcomponenttoolkit.go index 760a3167..135c9f1f 100644 --- a/Source/automaticcomponenttoolkit.go +++ b/Source/automaticcomponenttoolkit.go @@ -48,14 +48,14 @@ const ( eACTModeDiff = 1 ) -func createComponent(component ComponentDefinition, outfolderBase string, bindingsDirectoryOverride string, interfacesDirectoryOverride string, stubDirectoryOverride string, suppressBindings bool, suppressStub bool, suppressInterfaces bool, suppressSubcomponents bool, suppressLicense bool, suppressExamples bool) (error) { +func createComponent(component ComponentDefinition, outfolderBase string, bindingsDirectoryOverride string, interfacesDirectoryOverride string, stubDirectoryOverride string, suppressBindings bool, suppressStub bool, suppressInterfaces bool, suppressSubcomponents bool, suppressLicense bool, suppressExamples bool) error { log.Printf("Creating Component \"%s\"", component.LibraryName) - - if (!suppressSubcomponents) { + + if !suppressSubcomponents { for _, subComponent := range component.ImportedComponentDefinitions { err := createComponent(subComponent, outfolderBase, "", "", "", suppressBindings, suppressStub, suppressInterfaces, suppressSubcomponents, suppressLicense, suppressExamples) - if (err != nil) { + if err != nil { return err } } @@ -66,9 +66,9 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin outputFolderExamples := path.Join(outputFolder, "Examples") outputFolderDocumentation := path.Join(outputFolder, "Documentations") outputFolderImplementations := path.Join(outputFolder, "Implementations") - + if bindingsDirectoryOverride != "" { - outputFolderBindings = bindingsDirectoryOverride; + outputFolderBindings = bindingsDirectoryOverride } err := os.MkdirAll(outputFolder, os.ModePerm) @@ -76,7 +76,7 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin return err } - if (!suppressLicense) { + if !suppressLicense { licenseFileName := path.Join(outputFolder, "license.txt") log.Printf("Creating \"%s\"", licenseFileName) licenseFile, err := CreateLanguageFile(licenseFileName, "") @@ -87,8 +87,8 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin } else { log.Printf("Suppressing license...") } - - if (!suppressBindings) { + + if !suppressBindings { if len(component.BindingList.Bindings) > 0 { err = os.MkdirAll(outputFolderBindings, os.ModePerm) if err != nil { @@ -123,9 +123,9 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin if err != nil { return err } - - outputFolderExampleCDynamic := ""; - if (!suppressExamples) { + + outputFolderExampleCDynamic := "" + if !suppressExamples { outputFolderExampleCDynamic = outputFolderExamples + "/CDynamic" err = os.MkdirAll(outputFolderExampleCDynamic, os.ModePerm) if err != nil { @@ -146,27 +146,27 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin } case "CppDynamic": - { - - outputFolderDocumentationCppExplicit := ""; - - if (binding.Documentation != "") { - + { + + outputFolderDocumentationCppExplicit := "" + + if binding.Documentation != "" { + outputFolderDocumentationCppExplicit = outputFolderDocumentation + "/Cpp" err = os.MkdirAll(outputFolderDocumentationCppExplicit, os.ModePerm) if err != nil { log.Fatal(err) } } - + outputFolderBindingCppDynamic := outputFolderBindings + "/CppDynamic" err = os.MkdirAll(outputFolderBindingCppDynamic, os.ModePerm) if err != nil { return err } - - outputFolderExampleCppDynamic := ""; - if (!suppressExamples) { + + outputFolderExampleCppDynamic := "" + if !suppressExamples { outputFolderExampleCppDynamic = outputFolderExamples + "/CppDynamic" err = os.MkdirAll(outputFolderExampleCppDynamic, os.ModePerm) if err != nil { @@ -189,10 +189,10 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin case "Cpp": { - outputFolderDocumentationCppImplicit := ""; - - if (binding.Documentation != "") { - outputFolderDocumentationCppImplicit = outputFolderDocumentation + "/Cpp"; + outputFolderDocumentationCppImplicit := "" + + if binding.Documentation != "" { + outputFolderDocumentationCppImplicit = outputFolderDocumentation + "/Cpp" err = os.MkdirAll(outputFolderDocumentationCppImplicit, os.ModePerm) if err != nil { log.Fatal(err) @@ -204,9 +204,9 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin if err != nil { return err } - - outputFolderExampleCppImplicit := ""; - if (!suppressExamples) { + + outputFolderExampleCppImplicit := "" + if !suppressExamples { outputFolderExampleCppImplicit = outputFolderExamples + "/Cpp" err = os.MkdirAll(outputFolderExampleCppImplicit, os.ModePerm) if err != nil { @@ -241,8 +241,8 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin return err } - outputFolderExampleGo := ""; - if (!suppressExamples) { + outputFolderExampleGo := "" + if !suppressExamples { outputFolderExampleGo = outputFolderExamples + "/Go" err = os.MkdirAll(outputFolderExampleGo, os.ModePerm) if err != nil { @@ -290,9 +290,8 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin return err } - - outputFolderExamplePascal := ""; - if (!suppressExamples) { + outputFolderExamplePascal := "" + if !suppressExamples { outputFolderExamplePascal = outputFolderExamples + "/Pascal" err = os.MkdirAll(outputFolderExamplePascal, os.ModePerm) if err != nil { @@ -308,25 +307,24 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin case "CSharp": { - outputFolderBindingCSharp := outputFolderBindings + "/CSharp"; - err = os.MkdirAll(outputFolderBindingCSharp, os.ModePerm); - if (err != nil) { - log.Fatal (err); - } - - - outputFolderExampleCSharp := ""; - if (!suppressExamples) { - outputFolderExampleCSharp = outputFolderExamples + "/CSharp"; - err = os.MkdirAll(outputFolderExampleCSharp, os.ModePerm); - if (err != nil) { - log.Fatal (err); + outputFolderBindingCSharp := outputFolderBindings + "/CSharp" + err = os.MkdirAll(outputFolderBindingCSharp, os.ModePerm) + if err != nil { + log.Fatal(err) + } + + outputFolderExampleCSharp := "" + if !suppressExamples { + outputFolderExampleCSharp = outputFolderExamples + "/CSharp" + err = os.MkdirAll(outputFolderExampleCSharp, os.ModePerm) + if err != nil { + log.Fatal(err) } } - - err = BuildBindingCSharp(component, outputFolderBindingCSharp, outputFolderExampleCSharp, indentString); - if (err != nil) { - log.Fatal (err); + + err = BuildBindingCSharp(component, outputFolderBindingCSharp, outputFolderExampleCSharp, indentString) + if err != nil { + log.Fatal(err) } } @@ -338,8 +336,8 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin return err } - outputFolderExamplePython := ""; - if (!suppressExamples) { + outputFolderExamplePython := "" + if !suppressExamples { outputFolderExamplePython = outputFolderExamples + "/Python" err = os.MkdirAll(outputFolderExamplePython, os.ModePerm) if err != nil { @@ -387,8 +385,8 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin case "Cppwasmtime": { - outputFolderExampleCppwasmtime := ""; - if (!suppressExamples) { + outputFolderExampleCppwasmtime := "" + if !suppressExamples { outputFolderExampleCppwasmtime = outputFolderExamples + "/Cppwasmtime" err = os.MkdirAll(outputFolderExampleCppwasmtime, os.ModePerm) if err != nil { @@ -414,7 +412,7 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin return err } - outputFolderDocumentationCppwasmtime := ""; + outputFolderDocumentationCppwasmtime := "" err = BuildBindingCppwasmtimeHost(component, outputFolderBindingCppwasmtimeHost, outputFolderExampleCppwasmtime, outputFolderDocumentationCppwasmtime, indentString, binding.ClassIdentifier) if err != nil { @@ -435,7 +433,7 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin } err = BuildBindingCppwasmtimeGuest(component, outputFolderBindingCppwasmtimeGuest, outputFolderExampleCppwasmtime, - outputFolderDocumentationCppwasmtime, indentString, binding.ClassIdentifier) + outputFolderDocumentationCppwasmtime, indentString, binding.ClassIdentifier) // TODO: example + documentation } @@ -469,22 +467,22 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin outputFolderImplementationCpp := outputFolderImplementations + "/Cpp/Interfaces" outputFolderImplementationCppStub := outputFolderImplementations + "/Cpp/Stub" - if (!suppressStub) { - - if (stubDirectoryOverride != "") { - outputFolderImplementationCppStub = stubDirectoryOverride; + if !suppressStub { + + if stubDirectoryOverride != "" { + outputFolderImplementationCppStub = stubDirectoryOverride } - + err = os.MkdirAll(outputFolderImplementationCppStub, os.ModePerm) if err != nil { return err } } - if (!suppressInterfaces) { + if !suppressInterfaces { - if (interfacesDirectoryOverride != "") { - outputFolderImplementationCpp = interfacesDirectoryOverride; + if interfacesDirectoryOverride != "" { + outputFolderImplementationCpp = interfacesDirectoryOverride } err = os.MkdirAll(outputFolderImplementationCpp, os.ModePerm) @@ -518,21 +516,20 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin outputFolderImplementationPascal := outputFolderImplementations + "/Pascal/Interfaces" outputFolderImplementationPascalStub := outputFolderImplementations + "/Pascal/Stub" - if (!suppressStub) { - if (stubDirectoryOverride != "") { - outputFolderImplementationPascalStub = stubDirectoryOverride; + if !suppressStub { + if stubDirectoryOverride != "" { + outputFolderImplementationPascalStub = stubDirectoryOverride } - + err = os.MkdirAll(outputFolderImplementationPascalStub, os.ModePerm) if err != nil { return err } } - - if (!suppressInterfaces) { - if (interfacesDirectoryOverride != "") { - outputFolderImplementationPascal = interfacesDirectoryOverride; + if !suppressInterfaces { + if interfacesDirectoryOverride != "" { + outputFolderImplementationPascal = interfacesDirectoryOverride } err = os.MkdirAll(outputFolderImplementationPascal, os.ModePerm) if err != nil { @@ -543,7 +540,7 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin if err != nil { return err } - + } } @@ -551,6 +548,69 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin { log.Printf("Implementation in language \"%s\" is not yet supported.", implementation.Language) } + + case "JS": + { + + outputFolderImplementationProject := outputFolderImplementations + "/JS" + outputFolderImplementationJS := outputFolderImplementations + "/JS/Interfaces" + outputFolderImplementationJSStub := outputFolderImplementations + "/JS/Stub" + outputFolderImplementationJSDocumentation := outputFolderImplementations + "/JS/Documentation" + + if !suppressStub { + if stubDirectoryOverride != "" { + outputFolderImplementationJSStub = stubDirectoryOverride + } + + err = os.MkdirAll(outputFolderImplementationJSStub, os.ModePerm) + if err != nil { + return err + } + } + + if !suppressInterfaces { + if interfacesDirectoryOverride != "" { + outputFolderImplementationJS = interfacesDirectoryOverride + } + err = os.MkdirAll(outputFolderImplementationJS, os.ModePerm) + if err != nil { + return err + } + + err = os.MkdirAll(outputFolderImplementationJSDocumentation, os.ModePerm) + if err != nil { + return err + } + + err = BuildImplementationJS(component, outputFolderImplementationJS, outputFolderImplementationJSStub, + outputFolderImplementationProject, implementation, suppressStub, suppressInterfaces, outputFolderImplementationJSDocumentation) + if err != nil { + return err + } + + } + } + + case "TS": + { + + output := path.Join(outfolderBase, "TS") + + err = os.MkdirAll(output, os.ModePerm) + if err != nil { + return err + } + + err = BuildImplementationTS( + component, + output, + implementation, + ) + if err != nil { + return err + } + } + default: log.Fatal("Unknown export") } @@ -559,7 +619,6 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin return nil } - func printUsageInfo() { fmt.Fprintln(os.Stdout, "Run ACT with the Interface Description XML as command line parameter:") fmt.Fprintln(os.Stdout, " $>act INTERFACEDESCRIPTION.xml [FLAGS]") @@ -609,64 +668,64 @@ func main() { bindingsDirectoryOverride := "" interfacesDirectoryOverride := "" stubDirectoryOverride := "" - - suppressLicense := false; - suppressBindings := false; - suppressStub := false; - suppressInterfaces := false; - suppressSubcomponents := false; - suppressExamples := false; - + + suppressLicense := false + suppressBindings := false + suppressStub := false + suppressInterfaces := false + suppressSubcomponents := false + suppressExamples := false + if len(os.Args) >= 4 { - for idx := 2; idx < len(os.Args); idx ++ { + for idx := 2; idx < len(os.Args); idx++ { if os.Args[idx] == "-o" { - outfolderBase = os.Args[idx + 1] + outfolderBase = os.Args[idx+1] } - + if os.Args[idx] == "-d" { - diffFile = os.Args[idx + 1] + diffFile = os.Args[idx+1] mode = eACTModeDiff } - + if os.Args[idx] == "-bindings" { - bindingsDirectoryOverride = os.Args[idx + 1] + bindingsDirectoryOverride = os.Args[idx+1] log.Printf("Bindings override directory: %s", bindingsDirectoryOverride) } if os.Args[idx] == "-interfaces" { - interfacesDirectoryOverride = os.Args[idx + 1] + interfacesDirectoryOverride = os.Args[idx+1] log.Printf("Interfaces override directory: %s", interfacesDirectoryOverride) } if os.Args[idx] == "-stubs" { - stubDirectoryOverride = os.Args[idx + 1] + stubDirectoryOverride = os.Args[idx+1] log.Printf("Stub override directory: %s", stubDirectoryOverride) } - + if os.Args[idx] == "-suppresslicense" { - suppressLicense = true; + suppressLicense = true } if os.Args[idx] == "-suppressbindings" { - suppressBindings = true; + suppressBindings = true } if os.Args[idx] == "-suppressstub" { - suppressStub = true; + suppressStub = true } if os.Args[idx] == "-suppressinterfaces" { - suppressInterfaces = true; + suppressInterfaces = true } if os.Args[idx] == "-suppresssubcomponents" { - suppressSubcomponents = true; + suppressSubcomponents = true } if os.Args[idx] == "-suppressexamples" { - suppressExamples = true; + suppressExamples = true } - + } } if mode == eACTModeGenerate { @@ -729,9 +788,9 @@ func main() { // } // } // } - + err = createComponent(component, outfolderBase, bindingsDirectoryOverride, interfacesDirectoryOverride, stubDirectoryOverride, suppressBindings, suppressStub, suppressInterfaces, suppressSubcomponents, suppressLicense, suppressExamples) - if (err != nil) { + if err != nil { log.Println("Fatal error") log.Fatal(err) } else { diff --git a/Source/buildbindingccpp.go b/Source/buildbindingccpp.go index cb714a1f..7a8d6ab1 100644 --- a/Source/buildbindingccpp.go +++ b/Source/buildbindingccpp.go @@ -115,7 +115,7 @@ func BuildBindingCExplicit(component ComponentDefinition, outputFolder string, o } // BuildBindingCppImplicit builds dynamic C++-bindings of a library's API in form of implicitly linked functions handles. -func BuildBindingCppImplicit(component ComponentDefinition, outputFolder string, outputFolderExample string, +func BuildBindingCppImplicit(component ComponentDefinition, outputFolder string, outputFolderExample string, outputFolderDocumentation string, indentString string, ClassIdentifier string) error { forceRecreation := false ExplicitLinking := false @@ -170,20 +170,18 @@ func BuildBindingCppImplicit(component ComponentDefinition, outputFolder string, } } - if (outputFolderDocumentation != "") { + if outputFolderDocumentation != "" { err = BuildCCPPDocumentation(component, outputFolderDocumentation, ClassIdentifier) if err != nil { return err } - - } + } return nil } - func buildDynamicCCPPHeader(component ComponentDefinition, w LanguageWriter, NameSpace string, BaseName string, headerOnly bool, useCPPTypes bool) error { @@ -201,7 +199,7 @@ func buildDynamicCCPPHeader(component ComponentDefinition, w LanguageWriter, Nam w.Writeln("#include \"%s_types.h\"", BaseName) } w.Writeln("") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { if useCPPTypes { w.Writeln("#include \"%s_types.hpp\"", subComponent.BaseName) } else { @@ -284,14 +282,14 @@ func buildDynamicCInitTableCode(component ComponentDefinition, w LanguageWriter, global := component.Global nullPtrStr := "nullptr" - if (useStrictC) { + if useStrictC { nullPtrStr = "NULL" } w.Writeln("if (pWrapperTable == %s)", nullPtrStr) w.Writeln(" return %s_ERROR_INVALIDPARAM;", strings.ToUpper(NameSpace)) w.Writeln("") - + w.Writeln("pWrapperTable->m_LibraryHandle = %s;", nullPtrStr) for i := 0; i < len(component.Classes); i++ { @@ -316,7 +314,7 @@ func buildDynamicCInitTableCode(component ComponentDefinition, w LanguageWriter, func buildDynamicCReleaseTableCode(component ComponentDefinition, w LanguageWriter, NameSpace string, BaseName string, initWrapperFunctionName string, useStrictC bool) error { nullPtrStr := "nullptr" - if (useStrictC) { + if useStrictC { nullPtrStr = "NULL" } @@ -340,12 +338,12 @@ func buildDynamicCReleaseTableCode(component ComponentDefinition, w LanguageWrit func writeLoadingOfMethodFromSymbolLookupMethod(w LanguageWriter, methodName string, NameSpace string, useStrictC bool) { nullPtrStr := "nullptr" - if (useStrictC) { + if useStrictC { nullPtrStr = "NULL" } w.Writeln("eLookupError = (*pLookup)(\"%s_%s\", (void**)&(pWrapperTable->m_%s));", strings.ToLower(NameSpace), strings.ToLower(methodName), methodName) - + w.Writeln("if ( (eLookupError != 0) || (pWrapperTable->m_%s == %s) )", methodName, nullPtrStr) w.Writeln(" return %s_ERROR_COULDNOTFINDLIBRARYEXPORT;", strings.ToUpper(NameSpace)) w.Writeln("") @@ -354,7 +352,7 @@ func writeLoadingOfMethodFromSymbolLookupMethod(w LanguageWriter, methodName str // WriteLoadingOfMethod the loading of a method from a library into a LanguagWriter func WriteLoadingOfMethod(class ComponentDefinitionClass, method ComponentDefinitionMethod, w LanguageWriter, NameSpace string, useStrictC bool) { nullPtrStr := "nullptr" - if (useStrictC) { + if useStrictC { nullPtrStr = "NULL" } @@ -369,12 +367,11 @@ func WriteLoadingOfMethod(class ComponentDefinitionClass, method ComponentDefini w.Writeln("") } - func buildDynamicCLoadTableFromSymbolLookupMethodCode(component ComponentDefinition, w LanguageWriter, NameSpace string, BaseName string, useStrictC bool) error { global := component.Global nullPtrStr := "nullptr" - if (useStrictC) { + if useStrictC { nullPtrStr = "NULL" } @@ -388,8 +385,7 @@ func buildDynamicCLoadTableFromSymbolLookupMethodCode(component ComponentDefinit w.Writeln("SymbolLookupType pLookup = (SymbolLookupType)pSymbolLookupMethod;") w.Writeln("") w.Writeln("%sResult eLookupError = %s_SUCCESS;", NameSpace, strings.ToUpper(NameSpace)) - - + for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] for j := 0; j < len(class.Methods); j++ { @@ -415,7 +411,7 @@ func buildDynamicCLoadTableCode(component ComponentDefinition, w LanguageWriter, global := component.Global nullPtrStr := "nullptr" - if (useStrictC) { + if useStrictC { nullPtrStr = "NULL" } @@ -432,7 +428,7 @@ func buildDynamicCLoadTableCode(component ComponentDefinition, w LanguageWriter, w.Writeln("while ((pLibraryFileName[nLength] != 0) && (nLength < MAX_PATH))") w.Writeln(" nLength++;") w.Writeln("int nBufferSize = nLength * 2 + 2;") - if (!useStrictC) { + if !useStrictC { w.Writeln("std::vector wsLibraryFileName(nBufferSize);") w.Writeln("int nResult = MultiByteToWideChar(CP_UTF8, 0, pLibraryFileName, nLength, &wsLibraryFileName[0], nBufferSize);") w.Writeln("if (nResult == 0)") @@ -451,7 +447,7 @@ func buildDynamicCLoadTableCode(component ComponentDefinition, w LanguageWriter, w.Writeln("HMODULE hLibrary = LoadLibraryW(wsLibraryFileName);") w.Writeln("free(wsLibraryFileName);") } - + w.Writeln("if (hLibrary == 0) ") w.Writeln(" return %s_ERROR_COULDNOTLOADLIBRARY;", strings.ToUpper(NameSpace)) w.Writeln("#else // _WIN32") @@ -496,7 +492,7 @@ func buildDynamicCImplementation(component ComponentDefinition, w LanguageWriter w.Writeln("#include \"%s_dynamic.h\"", BaseName) w.Writeln("#ifdef _WIN32") - if (!useStrictC) { + if !useStrictC { w.Writeln("#include ") } w.Writeln("#include ") @@ -504,7 +500,7 @@ func buildDynamicCImplementation(component ComponentDefinition, w LanguageWriter w.Writeln("#else // _WIN32") w.Writeln("#include ") w.Writeln("#include ") - w.Writeln("#endif // _WIN32") + w.Writeln("#endif // _WIN32") w.Writeln("") w.Writeln("%sResult Init%sWrapperTable(s%sDynamicWrapperTable * pWrapperTable)", NameSpace, NameSpace, NameSpace) @@ -586,7 +582,7 @@ func getDynamicCPPMethodParameters(method ComponentDefinitionMethod, NameSpace s func writeDynamicCPPMethodDeclaration(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string, ClassIdentifier string, ClassName string) error { parameters, returntype, err := getDynamicCPPMethodParameters(method, NameSpace, ClassIdentifier, ClassName) - if (err!= nil) { + if err != nil { return err } w.Writeln(" inline %s %s(%s);", returntype, method.MethodName, parameters) @@ -599,7 +595,7 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N WASMPrefix := "" WASMCast := "" WASMCastp := "" - if (forWASM) { + if forWASM { WASMPrefix = "_" WASMCast = "(uint64_t)" WASMCastp = "(uint64_t)&" @@ -610,9 +606,9 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N parameters := "" returntype := "void" - callParameters := "" // parameters for call of the C-function + callParameters := "" // parameters for call of the C-function - requiresInitCall := false + requiresInitCall := false initCallParameters := "" // usually used to check sizes of buffers checkErrorCodeBegin := "" @@ -631,7 +627,7 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N if ExplicitLinking { CMethodName = fmt.Sprintf("m_pWrapper->m_WrapperTable.m_%s_%s", ClassName, method.MethodName) } else { - CMethodName = fmt.Sprintf("%s%s_%s_%s", WASMPrefix, strings.ToLower(NameSpace), strings.ToLower(ClassName), strings.ToLower(method.MethodName)) + CMethodName = fmt.Sprintf("%s%s_%s_%s", WASMPrefix, strings.ToLower(NameSpace), strings.ToLower(ClassName), strings.ToLower(method.MethodName)) } callParameters = WASMCastp + "m_pHandle" initCallParameters = callParameters @@ -658,7 +654,7 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N for _, param := range method.Params { variableName := getBindingCppVariableName(param) - callParameter := "" // parameter of the actual call of the C-function + callParameter := "" // parameter of the actual call of the C-function initCallParameter := "" // parameter of an switch param.ParamPass { @@ -716,7 +712,7 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N requiresInitCall = true definitionCodeLines = append(definitionCodeLines, fmt.Sprintf("%s_uint32 bytesNeeded%s = 0;", NameSpace, param.ParamName)) definitionCodeLines = append(definitionCodeLines, fmt.Sprintf("%s_uint32 bytesWritten%s = 0;", NameSpace, param.ParamName)) - if (forWASM) { + if forWASM { initCallParameter = fmt.Sprintf("%sbytesWritten%s, %s&bytesNeeded%s, 0", WASMCastp, param.ParamName, WASMCast, param.ParamName) } else { initCallParameter = fmt.Sprintf("0, &bytesNeeded%s, nullptr", param.ParamName) @@ -738,7 +734,7 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N initCallParameter = callParameter CPPClass := fmt.Sprintf("%s%s%s", cppClassPrefix, ClassIdentifier, param.ParamClass) - if (param.ParamType == "optionalclass") { + if param.ParamType == "optionalclass" { postCallCodeLines = append(postCallCodeLines, fmt.Sprintf("if (h%s) {", param.ParamName)) postCallCodeLines = append(postCallCodeLines, fmt.Sprintf(" p%s = std::shared_ptr<%s>(dynamic_cast<%s*>(%s->polymorphicFactory(h%s)));", param.ParamName, CPPClass, CPPClass, makeSharedParameter, param.ParamName)) postCallCodeLines = append(postCallCodeLines, fmt.Sprintf("} else {")) @@ -757,7 +753,7 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N definitionCodeLines = append(definitionCodeLines, fmt.Sprintf("%s_uint64 elementsNeeded%s = 0;", NameSpace, param.ParamName)) definitionCodeLines = append(definitionCodeLines, fmt.Sprintf("%s_uint64 elementsWritten%s = 0;", NameSpace, param.ParamName)) - if (forWASM) { + if forWASM { initCallParameter = fmt.Sprintf("%s&elementsWritten%s, %s&elementsNeeded%s, 0", WASMCast, param.ParamName, WASMCast, param.ParamName) } else { initCallParameter = fmt.Sprintf("0, &elementsNeeded%s, nullptr", param.ParamName) @@ -786,7 +782,7 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N definitionCodeLines = append(definitionCodeLines, fmt.Sprintf("%s_uint32 bytesNeeded%s = 0;", NameSpace, param.ParamName)) definitionCodeLines = append(definitionCodeLines, fmt.Sprintf("%s_uint32 bytesWritten%s = 0;", NameSpace, param.ParamName)) - if (forWASM) { + if forWASM { initCallParameter = fmt.Sprintf("%s&bytesWritten%s, %s&bytesNeeded%s, 0", WASMCast, param.ParamName, WASMCast, param.ParamName) } else { initCallParameter = fmt.Sprintf("0, &bytesNeeded%s, nullptr", param.ParamName) @@ -819,12 +815,12 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N CPPClass = paramNameSpaceCPP + CPPClass makeSharedParameter = makeSharedParameter + "->m_p" + paramNameSpace + "Wrapper.get()" } - + definitionCodeLines = append(definitionCodeLines, fmt.Sprintf("%sHandle h%s = (%sHandle)nullptr;", paramNameSpace, param.ParamName, NameSpace)) callParameter = fmt.Sprintf("%s&h%s", WASMCast, param.ParamName) initCallParameter = callParameter - - if (param.ParamType == "optionalclass") { + + if param.ParamType == "optionalclass" { returnCodeLines = append(returnCodeLines, fmt.Sprintf("if (h%s) {", param.ParamName)) returnCodeLines = append(returnCodeLines, fmt.Sprintf(" return std::shared_ptr<%s>(dynamic_cast<%s*>(%s->polymorphicFactory(h%s)));", CPPClass, CPPClass, makeSharedParameter, param.ParamName)) returnCodeLines = append(returnCodeLines, fmt.Sprintf("} else {")) @@ -834,11 +830,24 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N returnCodeLines = append(returnCodeLines, fmt.Sprintf("if (!h%s) {", param.ParamName)) returnCodeLines = append(returnCodeLines, fmt.Sprintf(" %s%s_ERROR_INVALIDPARAM%s;", checkErrorCodeBegin, strings.ToUpper(NameSpace), checkErrorCodeEnd)) returnCodeLines = append(returnCodeLines, fmt.Sprintf("}")) - returnCodeLines = append(returnCodeLines, fmt.Sprintf("return std::shared_ptr<%s>(dynamic_cast<%s*>(%s->polymorphicFactory(h%s)));", CPPClass, CPPClass, makeSharedParameter, param.ParamName)) } + returnCodeLines = append(returnCodeLines, fmt.Sprintf("return std::shared_ptr<%s>(dynamic_cast<%s*>(%s->polymorphicFactory(h%s)));", CPPClass, CPPClass, makeSharedParameter, param.ParamName)) case "basicarray": - return fmt.Errorf("can not return basicarray \"%s\" for %s.%s(%s)", param.ParamPass, ClassName, method.MethodName, param.ParamName) + requiresInitCall = true + definitionCodeLines = append(definitionCodeLines, fmt.Sprintf("%s %s;", returntype, variableName)) + definitionCodeLines = append(definitionCodeLines, fmt.Sprintf("%s_uint64 elementsNeeded%s = 0;", NameSpace, param.ParamName)) + definitionCodeLines = append(definitionCodeLines, fmt.Sprintf("%s_uint64 elementsWritten%s = 0;", NameSpace, param.ParamName)) + + if forWASM { + initCallParameter = fmt.Sprintf("%s&elementsWritten%s, %s&elementsNeeded%s, 0", WASMCast, param.ParamName, WASMCast, param.ParamName) + } else { + initCallParameter = fmt.Sprintf("0, &elementsNeeded%s, nullptr", param.ParamName) + } + functionCodeLines = append(functionCodeLines, fmt.Sprintf("%s.resize((size_t) elementsNeeded%s);", variableName, param.ParamName)) + callParameter = fmt.Sprintf("%selementsNeeded%s, %s&elementsWritten%s, %s%s.data()", WASMCastp, param.ParamName, WASMCast, param.ParamName, WASMCast, variableName) + + returnCodeLines = append(returnCodeLines, fmt.Sprintf("return %s;", variableName)) case "structarray": return fmt.Errorf("can not return structarray \"%s\" for %s.%s(%s)", param.ParamPass, ClassName, method.MethodName, param.ParamName) @@ -886,12 +895,12 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N w.Writeln(" %s%s(%s)%s;", checkErrorCodeBegin, CMethodName, callParameters, checkErrorCodeEnd) w.Writelns(" ", postCallCodeLines) - if (len(implementationLines) >0) { + if len(implementationLines) > 0 { w.Writeln(" ") w.Writelns(" ", implementationLines) } - if (len(returnCodeLines) >0) { + if len(returnCodeLines) > 0 { w.Writeln(" ") w.Writelns(" ", returnCodeLines) } @@ -954,7 +963,6 @@ func writeDynamicCppBaseClassMethods(component ComponentDefinition, baseClass Co return nil } - func buildBindingCPPAllForwardDeclarations(component ComponentDefinition, w LanguageWriter, NameSpace string, cppClassPrefix string, ClassIdentifier string) { w.Writeln("/*************************************************************************************************************************") w.Writeln(" Forward Declaration of all classes") @@ -965,7 +973,7 @@ func buildBindingCPPAllForwardDeclarations(component ComponentDefinition, w Lang className := cppClassPrefix + ClassIdentifier + class.ClassName w.Writeln("class %s;", className) } - if (strings.Compare(ClassIdentifier, NameSpace) != 0) { + if strings.Compare(ClassIdentifier, NameSpace) != 0 { w.Writeln("") w.Writeln("/*************************************************************************************************************************") w.Writeln(" Declaration of deprecated class types") @@ -988,8 +996,8 @@ func buildBindingCPPAllForwardDeclarations(component ComponentDefinition, w Lang className := cppClassPrefix + ClassIdentifier + class.ClassName w.Writeln("typedef std::shared_ptr<%s> P%s%s;", className, ClassIdentifier, class.ClassName) } - - if (strings.Compare(ClassIdentifier, NameSpace) != 0) { + + if strings.Compare(ClassIdentifier, NameSpace) != 0 { w.Writeln("") w.Writeln("/*************************************************************************************************************************") w.Writeln(" Declaration of deprecated shared pointer types") @@ -1037,7 +1045,7 @@ func writeCPPInputVector(w LanguageWriter, NameSpace string, ClassIdentifier str w.Writeln(" }") w.Writeln(" ") w.Writeln("};") - if (strings.Compare(ClassIdentifier, NameSpace) != 0) { + if strings.Compare(ClassIdentifier, NameSpace) != 0 { w.Writeln("") w.Writeln("// declare deprecated class name") w.Writeln("template") @@ -1098,13 +1106,12 @@ func writeWrapperLifeTimeHandling(w LanguageWriter, cppClassPrefix string, Class } } - func decomposeParamClassNameCPP(paramClassName string) (string, string, error) { paramNameSpace, paramClassName, err := decomposeParamClassName(paramClassName) - if (err != nil) { + if err != nil { return "", "", err } - if (len(paramNameSpace) >0 ) { + if len(paramNameSpace) > 0 { paramNameSpace = paramNameSpace + "::" } return paramNameSpace, paramClassName, err @@ -1138,15 +1145,15 @@ func getBindingCppParamType(paramType string, paramClass string, NameSpace strin } return fmt.Sprintf("std::vector<%s>", cppBasicType) case "structarray": - typeName := paramNameSpace + "s"+paramClassName + typeName := paramNameSpace + "s" + paramClassName if isInput { return fmt.Sprintf("C%sInputVector<%s>", ClassIdentifier, typeName) } return fmt.Sprintf("std::vector<%s>", typeName) case "enum": - return fmt.Sprintf(paramNameSpace + "e"+paramClassName) + return fmt.Sprintf(paramNameSpace + "e" + paramClassName) case "struct": - return fmt.Sprintf(paramNameSpace + "s"+paramClassName) + return fmt.Sprintf(paramNameSpace + "s" + paramClassName) case "class", "optionalclass": if isInput { return fmt.Sprintf("%sclassParam<%s%s%s%s>", paramNameSpace, paramNameSpace, cppClassPrefix, ClassIdentifier, paramClassName) @@ -1197,7 +1204,7 @@ func getCPPInheritanceSpecifier(component ComponentDefinition, class ComponentDe if class.ParentClass == "" { cppParentClassName = cppClassPrefix + ClassIdentifier + component.Global.BaseClassName } else { - cppParentClassName = cppClassPrefix + ClassIdentifier+ class.ParentClass + cppParentClassName = cppClassPrefix + ClassIdentifier + class.ParentClass } inheritanceSpecifier = fmt.Sprintf(": public %s ", cppParentClassName) } @@ -1276,7 +1283,7 @@ func writeExceptionClass(w LanguageWriter, NameSpace string, errors ComponentDef w.Writeln(" {") w.Writeln(" return m_errorMessage.c_str();") w.Writeln(" }") - w.Writeln(""); + w.Writeln("") w.Writeln(" const char* getErrorMessage() const noexcept") w.Writeln(" {") w.Writeln(" return m_originalErrorMessage.c_str();") @@ -1286,22 +1293,22 @@ func writeExceptionClass(w LanguageWriter, NameSpace string, errors ComponentDef w.Writeln(" {") w.Writeln(" switch(getErrorCode()) {") w.Writeln(" case %s_SUCCESS: return \"SUCCESS\";", strings.ToUpper(NameSpace)) - for _, errorDef := range(errors.Errors) { + for _, errorDef := range errors.Errors { w.Writeln(" case %s_ERROR_%s: return \"%s\";", strings.ToUpper(NameSpace), errorDef.Name, errorDef.Name) } w.Writeln(" }") - w.Writeln(" return \"UNKNOWN\";"); + w.Writeln(" return \"UNKNOWN\";") w.Writeln(" }") w.Writeln("") w.Writeln(" const char* getErrorDescription() const noexcept") w.Writeln(" {") w.Writeln(" switch(getErrorCode()) {") w.Writeln(" case %s_SUCCESS: return \"success\";", strings.ToUpper(NameSpace)) - for _, errorDef := range(errors.Errors) { + for _, errorDef := range errors.Errors { w.Writeln(" case %s_ERROR_%s: return \"%s\";", strings.ToUpper(NameSpace), errorDef.Name, errorDef.Description) } w.Writeln(" }") - w.Writeln(" return \"unknown error\";"); + w.Writeln(" return \"unknown error\";") w.Writeln(" }") w.Writeln("") @@ -1314,7 +1321,7 @@ func writeExceptionClass(w LanguageWriter, NameSpace string, errors ComponentDef w.Writeln(" if (msg.empty()) {") w.Writeln(" msg = getErrorDescription();") w.Writeln(" }") - w.Writeln(" return std::string(\"Error: \") + getErrorName() + \": \" + msg;") + w.Writeln(" return std::string(getErrorName()) + \": \" + msg;") w.Writeln(" }") w.Writeln("};") @@ -1401,7 +1408,7 @@ func writeClassDeclarations(w LanguageWriter, component ComponentDefinition, cpp } } - for _, method := range class.Methods { + for _, method := range class.Methods { err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, cppClassName) if err != nil { return err @@ -1412,12 +1419,11 @@ func writeClassDeclarations(w LanguageWriter, component ComponentDefinition, cpp return nil } - func writePolymorphicFactoryImplementation(w LanguageWriter, component ComponentDefinition, NameSpace string, cppClassPrefix string, ClassIdentifier string, ExplicitLinking bool, forWASM bool) { WASMPrefix := "" WASMCast := "" WASMCastp := "" - if (forWASM) { + if forWASM { WASMPrefix = "_" WASMCast = "(uint64_t)" WASMCastp = "(uint64_t)&" @@ -1455,7 +1461,6 @@ func writePolymorphicFactoryImplementation(w LanguageWriter, component Component w.Writeln("}") } - func writeCheckErrorImplementation(w LanguageWriter, ErrorMethodName string, ClassIdentifier string, cppBaseClassName string, NameSpace string) { w.Writeln(" inline void C%sWrapper::CheckError(%s * pBaseClass, %sResult nResult)", ClassIdentifier, cppBaseClassName, NameSpace) w.Writeln(" {") @@ -1479,14 +1484,14 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s baseClass := component.baseClass() cppBaseClassName := cppClassPrefix + ClassIdentifier + baseClass.ClassName - sIncludeGuard := ""; - + sIncludeGuard := "" + if ExplicitLinking { sIncludeGuard = "__" + strings.ToUpper(NameSpace) + "_CPPHEADER_DYNAMIC" } else { sIncludeGuard = "__" + strings.ToUpper(NameSpace) + "_CPPHEADER_IMPLICIT" } - + if useCPPTypes { sIncludeGuard += "_CPP" } @@ -1495,15 +1500,15 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s w.Writeln("") w.Writeln("#include \"%s_types.hpp\"", BaseName) - + if ExplicitLinking { w.Writeln("#include \"%s_dynamic.h\"", BaseName) } else { w.Writeln("#include \"%s_abi.hpp\"", BaseName) } - + w.Writeln("") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { w.Writeln("#include \"%s_dynamic.hpp\"", subComponent.BaseName) } w.Writeln("") @@ -1541,9 +1546,9 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s w.Writeln("class %s%sWrapper {", cppClassPrefix, ClassIdentifier) w.Writeln("public:") w.Writeln(" ") - + writeWrapperLifeTimeHandling(w, cppClassPrefix, ClassIdentifier, ExplicitLinking) - + w.Writeln(" ") w.Writeln(" inline void CheckError(%s * pBaseClass, %sResult nResult);", cppBaseClassName, NameSpace) w.Writeln("") @@ -1567,14 +1572,13 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s if len(component.ImportedComponentDefinitions) > 0 { w.Writeln(" // Injected Components") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { subNameSpace := subComponent.NameSpace w.Writeln(" %s::PWrapper m_p%sWrapper;", subNameSpace, subNameSpace) } w.Writeln("") } - - + w.Writeln(" ") writeCheckBinaryVersion(w, NameSpace, component) @@ -1598,7 +1602,7 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s w.Writeln("") err := writeClassDeclarations(w, component, cppClassPrefix, ClassIdentifier, NameSpace, BaseName) - if (err != nil) { + if err != nil { return err } @@ -1609,16 +1613,16 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s if err != nil { return err } - + implementationLines := make([]string, 0) - if (isSpecialFunction == eSpecialMethodInjection) { + if isSpecialFunction == eSpecialMethodInjection { implementationLines = append(implementationLines, "bool bNameSpaceFound = false;") sParamName := "s" + method.Params[0].ParamName - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { theNameSpace := subComponent.NameSpace implementationLines = append(implementationLines, fmt.Sprintf("if (%s == \"%s\") {", sParamName, theNameSpace)) implementationLines = append(implementationLines, fmt.Sprintf(" if (m_p%sWrapper != nullptr) {", theNameSpace)) - implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Library with namespace \" + %s + \" is already registered.\");", NameSpace, strings.ToUpper(NameSpace), sParamName) ) + implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Library with namespace \" + %s + \" is already registered.\");", NameSpace, strings.ToUpper(NameSpace), sParamName)) implementationLines = append(implementationLines, fmt.Sprintf(" }")) implementationLines = append(implementationLines, fmt.Sprintf(" m_p%sWrapper = %s::CWrapper::loadLibraryFromSymbolLookupMethod(p%s);", theNameSpace, theNameSpace, method.Params[1].ParamName)) @@ -1626,7 +1630,7 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s implementationLines = append(implementationLines, fmt.Sprintf("}")) } implementationLines = append(implementationLines, "if (!bNameSpaceFound)") - implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Unknown namespace \" + %s);", NameSpace, strings.ToUpper(NameSpace), sParamName )) + implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Unknown namespace \" + %s);", NameSpace, strings.ToUpper(NameSpace), sParamName)) } err = writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, "Wrapper", implementationLines, true, true, false, useCPPTypes, ExplicitLinking, false) @@ -1639,7 +1643,7 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s w.Writeln("") writeCheckErrorImplementation(w, component.Global.ErrorMethod, ClassIdentifier, cppBaseClassName, NameSpace) w.Writeln("") - + if ExplicitLinking { w.AddIndentationLevel(1) writeWrapperTableHandling(w, component, NameSpace, cppClassPrefix, ClassIdentifier, BaseName) @@ -1655,7 +1659,7 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s w.Writeln(" */") for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] - err := writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, class.ClassName, make([]string,0), false, true, false, useCPPTypes, ExplicitLinking, false) + err := writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, class.ClassName, make([]string, 0), false, true, false, useCPPTypes, ExplicitLinking, false) if err != nil { return err } @@ -1735,25 +1739,24 @@ func BuildBindingCppExplicit(component ComponentDefinition, outputFolder string, dyncppcmake.WriteCMakeLicenseHeader(component, fmt.Sprintf("This is an autogenerated CMake Project that demonstrates the\n usage of the Dynamic C++ bindings of %s", libraryname), true) - buildCppDynamicExampleCMake(component, dyncppcmake, outputFolder, outputFolderExample, ExplicitLinking) + buildCppDynamicExampleCMake(component, dyncppcmake, outputFolder, outputFolderExample, ExplicitLinking) } else { log.Printf("Omitting recreation of C++Dynamic example file \"%s\"", DynamicCPPCMake) } } - - if (outputFolderDocumentation != "") { + + if outputFolderDocumentation != "" { err = BuildCCPPDocumentation(component, outputFolderDocumentation, ClassIdentifier) if err != nil { return err } - + } return nil } - // BuildBindingCppwasmtimeHost builds headeronly C++-bindings of a library's API in form of explicitly loaded function handles. // it maps all C-functions to functions objects that can be linked into a wasmtime module func BuildBindingCppwasmtimeHost(component ComponentDefinition, outputFolder string, outputFolderExample string, @@ -1769,8 +1772,8 @@ func BuildBindingCppwasmtimeHost(component ComponentDefinition, outputFolder str return err } wasmhosthppfile.WriteCLicenseHeader(component, - fmt.Sprintf("This is an autogenerated C++-Header file in order to allow an easy\n use of %s.", libraryname) + - fmt.Sprintf("It loads the functions exported by the component and wraps them with C++ function objects\nthat can be linked into a wasmtime module."), + fmt.Sprintf("This is an autogenerated C++-Header file in order to allow an easy\n use of %s.", libraryname)+ + fmt.Sprintf("It loads the functions exported by the component and wraps them with C++ function objects\nthat can be linked into a wasmtime module."), true) err = buildCppwasmHostHeader(component, wasmhosthppfile, namespace, baseName, ClassIdentifier) if err != nil { @@ -1785,7 +1788,7 @@ func BuildBindingCppwasmtimeHost(component ComponentDefinition, outputFolder str // It imports the component's functions exported by the host and creates a C++ wrapper\n that can be used within a wasmtime module like the regular C++ bindings of that component. func BuildBindingCppwasmtimeGuest(component ComponentDefinition, outputFolder string, outputFolderExample string, outputFolderDocumentation string, indentString string, ClassIdentifier string) error { - + namespace := component.NameSpace libraryname := component.LibraryName baseName := component.BaseName @@ -1797,8 +1800,8 @@ func BuildBindingCppwasmtimeGuest(component ComponentDefinition, outputFolder st return err } wasmguesthppfile.WriteCLicenseHeader(component, - fmt.Sprintf("This is an autogenerated C++-Header file in order to allow an easy\n use of %s.", libraryname) + - fmt.Sprintf("It imports the component's functions exported by the host and creates a C++ wrapper\n that can be used within a wasmtime module like the regular C++ bindings of that component."), + fmt.Sprintf("This is an autogenerated C++-Header file in order to allow an easy\n use of %s.", libraryname)+ + fmt.Sprintf("It imports the component's functions exported by the host and creates a C++ wrapper\n that can be used within a wasmtime module like the regular C++ bindings of that component."), true) err = buildCppwasmGuestHeader(component, wasmguesthppfile, namespace, baseName, ClassIdentifier) if err != nil { @@ -1809,21 +1812,20 @@ func BuildBindingCppwasmtimeGuest(component ComponentDefinition, outputFolder st return nil } -func cParamIsPointer(cParam CParameter) (bool) { +func cParamIsPointer(cParam CParameter) bool { if len(cParam.ParamType) == 0 { return false } return cParam.ParamType[len(cParam.ParamType)-1:] == "*" } - -func writeWasmtimeImport(w LanguageWriter, NameSpace string, method ComponentDefinitionMethod, methodName string, className string ) (error) { +func writeWasmtimeImport(w LanguageWriter, NameSpace string, method ComponentDefinitionMethod, methodName string, className string) error { wasmtimeParams := "" first := true - + var allCParams []CParameter - if (className != "") { - allCParams = make([]CParameter,1) + if className != "" { + allCParams = make([]CParameter, 1) allCParams[0].ParamName = "hHandle" allCParams[0].ParamType = NameSpace + "Handle" } @@ -1835,7 +1837,7 @@ func writeWasmtimeImport(w LanguageWriter, NameSpace string, method ComponentDef } allCParams = append(allCParams, cParams...) } - for i:=0; i < len(allCParams); i++ { + for i := 0; i < len(allCParams); i++ { if !first { wasmtimeParams += ", " } @@ -1843,22 +1845,22 @@ func writeWasmtimeImport(w LanguageWriter, NameSpace string, method ComponentDef wasmtimeParams += "uint64_t" } - if (className != "") { + if className != "" { className = className + "_" } w.Writeln(" __attribute__((import_module(\"\"), import_name(\"%s\"))) int32_t %s(%s);", methodName, methodName, wasmtimeParams) return nil } -func writeWasmtimeLambda(w LanguageWriter, NameSpace string, method ComponentDefinitionMethod, methodName string, className string ) (error) { +func writeWasmtimeLambda(w LanguageWriter, NameSpace string, method ComponentDefinitionMethod, methodName string, className string) error { wasmtimeParams := "" cParameters := "" var lines []string first := true - + var allCParams []CParameter - if (className != "") { - allCParams = make([]CParameter,1) + if className != "" { + allCParams = make([]CParameter, 1) allCParams[0].ParamName = "hHandle" allCParams[0].ParamType = NameSpace + "Handle" } @@ -1878,7 +1880,7 @@ func writeWasmtimeLambda(w LanguageWriter, NameSpace string, method ComponentDef first = false wasmtimeParams += "uint64_t w" + cParam.ParamName cParameters += cParam.ParamName - + pointerString := "" if !cParamIsPointer(cParam) { pointerString = "*" @@ -1886,10 +1888,10 @@ func writeWasmtimeLambda(w LanguageWriter, NameSpace string, method ComponentDef // ensure memory access does not go outside of WASM linear memory lines = append(lines, fmt.Sprintf("if (w%s + sizeof(%s) >= nMemorySize)", cParam.ParamName, cParam.ParamType)) lines = append(lines, fmt.Sprintf(" return %s_ERROR_INVALIDPARAM;", strings.ToUpper(NameSpace))) - lines = append(lines, fmt.Sprintf("%s %s = %s( (%s %s)(_pData + w%s) );" , cParam.ParamType, cParam.ParamName, pointerString, cParam.ParamType, pointerString, cParam.ParamName)) + lines = append(lines, fmt.Sprintf("%s %s = %s( (%s %s)(_pData + w%s) );", cParam.ParamType, cParam.ParamName, pointerString, cParam.ParamType, pointerString, cParam.ParamName)) if cParamIsPointer(cParam) { // a nullptr in the WASM module is conveyed to the host as a 0 offset in WASM linear memory - lines = append(lines, fmt.Sprintf("if (w%s == 0)" , cParam.ParamName)) + lines = append(lines, fmt.Sprintf("if (w%s == 0)", cParam.ParamName)) lines = append(lines, fmt.Sprintf("{")) lines = append(lines, fmt.Sprintf(" %s = nullptr;", cParam.ParamName)) lines = append(lines, fmt.Sprintf("}")) @@ -1902,14 +1904,14 @@ func writeWasmtimeLambda(w LanguageWriter, NameSpace string, method ComponentDef w.Writeln(" uint8_t* _pData = data.data();") w.Writeln(" const uint64_t nMemorySize = data.size();") w.Writeln(" ") - + w.Writelns(" ", lines) - - if (className != "") { + + if className != "" { className = className + "_" } w.Writeln(" %sResult result = this->m_WrapperTable.m_%s%s(%s);", NameSpace, className, method.MethodName, cParameters) - + w.Writeln(" return result;") w.Writeln(" };") w.Writeln(" ") @@ -1938,10 +1940,9 @@ func buildCppwasmHostHeader(component ComponentDefinition, w LanguageWriter, Nam w.Writeln("#endif // _WIN32") w.Writeln("") - w.Writeln("#include \"%s_dynamic.h\"", BaseName) - - if len(component.ImportedComponentDefinitions)>0 { + + if len(component.ImportedComponentDefinitions) > 0 { return fmt.Errorf("C++ wasmtime bindings to not support imported components yet") } w.Writeln("") @@ -1964,7 +1965,7 @@ func buildCppwasmHostHeader(component ComponentDefinition, w LanguageWriter, Nam w.Writeln("class %s%sWrapper {", cppClassPrefix, ClassIdentifier) w.Writeln("public:") w.Writeln(" ") - + w.Writeln(" explicit %s%sWrapper(void* pSymbolLookupMethod)", cppClassPrefix, ClassIdentifier) w.Writeln(" {") w.Writeln(" CheckError(initWrapperTable(&m_WrapperTable));") @@ -2023,9 +2024,9 @@ func buildCppwasmHostHeader(component ComponentDefinition, w LanguageWriter, Nam w.Writeln(" s%sDynamicWrapperTable m_WrapperTable;", NameSpace) w.Writeln(" wasmtime::Memory* m_pMemory;") w.Writeln(" ") - + // writeCheckBinaryVersion(w, NameSpace, component) - + w.Writeln(" ") w.Writeln(" %sResult initWrapperTable(s%sDynamicWrapperTable * pWrapperTable);", NameSpace, NameSpace) w.Writeln(" %sResult releaseWrapperTable(s%sDynamicWrapperTable * pWrapperTable);", NameSpace, NameSpace) @@ -2034,16 +2035,15 @@ func buildCppwasmHostHeader(component ComponentDefinition, w LanguageWriter, Nam w.Writeln("};") w.Writeln("") - + writeWrapperTableHandling(w, component, NameSpace, cppClassPrefix, ClassIdentifier, BaseName) w.Writeln("") - w.Writeln("inline void %s%sWrapper::linkComponentToWASM(wasmtime::Linker& linker, wasmtime::Store& store)", cppClassPrefix, ClassIdentifier) w.Writeln("{") var functionNames []string - + for j := 0; j < len(component.Global.Methods); j++ { method := component.Global.Methods[j] methodName := "_" + strings.ToLower(NameSpace) + "_" + strings.ToLower(method.MethodName) @@ -2061,7 +2061,7 @@ func buildCppwasmHostHeader(component ComponentDefinition, w LanguageWriter, Nam for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] methodName := "_" + strings.ToLower(NameSpace) + "_" + strings.ToLower(class.ClassName) + "_" + strings.ToLower(method.MethodName) - + err := writeWasmtimeLambda(w, NameSpace, method, methodName, class.ClassName) if err != nil { return err @@ -2088,12 +2088,12 @@ func buildCppwasmHostHeader(component ComponentDefinition, w LanguageWriter, Nam func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, NameSpace string, BaseName string, ClassIdentifier string) error { cppClassPrefix := "C" - + baseClass := component.baseClass() cppBaseClassName := cppClassPrefix + ClassIdentifier + baseClass.ClassName sIncludeGuard := "__" + strings.ToUpper(NameSpace) + "_CPPHEADER_IMPLICIT_CPP" - + w.Writeln("#ifndef %s", sIncludeGuard) w.Writeln("#define %s", sIncludeGuard) w.Writeln("") @@ -2101,10 +2101,10 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na w.Writeln("#include \"%s_types.hpp\"", BaseName) w.Writeln("") w.Writeln("#include ") - + w.Writeln("") - - if len(component.ImportedComponentDefinitions)>0 { + + if len(component.ImportedComponentDefinitions) > 0 { return fmt.Errorf("C++ wasmtime bindings to not support imported components yet") } @@ -2120,7 +2120,7 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na for j := 0; j < len(component.Global.Methods); j++ { method := component.Global.Methods[j] methodName := "_" + strings.ToLower(NameSpace) + "_" + strings.ToLower(method.MethodName) - + err := writeWasmtimeImport(w, NameSpace, method, methodName, "") if err != nil { return err @@ -2132,7 +2132,7 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] methodName := "_" + strings.ToLower(NameSpace) + "_" + strings.ToLower(class.ClassName) + "_" + strings.ToLower(method.MethodName) - + err := writeWasmtimeImport(w, NameSpace, method, methodName, class.ClassName) if err != nil { return err @@ -2163,14 +2163,14 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na w.Writeln("class %s%sWrapper {", cppClassPrefix, ClassIdentifier) w.Writeln("public:") w.Writeln(" ") - + writeWrapperLifeTimeHandling(w, cppClassPrefix, ClassIdentifier, false) - + w.Writeln(" ") w.Writeln(" inline void CheckError(%s * pBaseClass, %sResult nResult);", cppBaseClassName, NameSpace) w.Writeln("") - for _ , method := range component.Global.Methods { + for _, method := range component.Global.Methods { err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, "Wrapper") if err != nil { return err @@ -2194,7 +2194,7 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na w.Writeln("") err := writeClassDeclarations(w, component, cppClassPrefix, ClassIdentifier, NameSpace, BaseName) - if (err != nil) { + if err != nil { return err } @@ -2208,16 +2208,16 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na if err != nil { return err } - + implementationLines := make([]string, 0) - if (isSpecialFunction == eSpecialMethodInjection) { + if isSpecialFunction == eSpecialMethodInjection { implementationLines = append(implementationLines, "bool bNameSpaceFound = false;") sParamName := "s" + method.Params[0].ParamName - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { theNameSpace := subComponent.NameSpace implementationLines = append(implementationLines, fmt.Sprintf("if (%s == \"%s\") {", sParamName, theNameSpace)) implementationLines = append(implementationLines, fmt.Sprintf(" if (m_p%sWrapper != nullptr) {", theNameSpace)) - implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Library with namespace \" + %s + \" is already registered.\");", NameSpace, strings.ToUpper(NameSpace), sParamName) ) + implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Library with namespace \" + %s + \" is already registered.\");", NameSpace, strings.ToUpper(NameSpace), sParamName)) implementationLines = append(implementationLines, fmt.Sprintf(" }")) implementationLines = append(implementationLines, fmt.Sprintf(" m_p%sWrapper = %s::CWrapper::loadLibraryFromSymbolLookupMethod(p%s);", theNameSpace, theNameSpace, method.Params[1].ParamName)) @@ -2225,7 +2225,7 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na implementationLines = append(implementationLines, fmt.Sprintf("}")) } implementationLines = append(implementationLines, "if (!bNameSpaceFound)") - implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Unknown namespace \" + %s);", NameSpace, strings.ToUpper(NameSpace), sParamName )) + implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Unknown namespace \" + %s);", NameSpace, strings.ToUpper(NameSpace), sParamName)) } err = writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, "Wrapper", implementationLines, true, true, false, useCPPTypes, ExplicitLinking, true) @@ -2247,7 +2247,7 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na w.Writeln(" */") for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] - err := writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, class.ClassName, make([]string,0), false, true, false, useCPPTypes, ExplicitLinking, true) + err := writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, class.ClassName, make([]string, 0), false, true, false, useCPPTypes, ExplicitLinking, true) if err != nil { return err } @@ -2264,18 +2264,17 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na return nil } - func buildDynamicCppExample(componentdefinition ComponentDefinition, w LanguageWriter, outputFolder string, ClassIdentifier string, ExplicitLinking bool) { NameSpace := componentdefinition.NameSpace BaseName := componentdefinition.BaseName w.Writeln("#include ") - if (ExplicitLinking) { + if ExplicitLinking { w.Writeln("#include \"%s_dynamic.hpp\"", strings.ToLower(BaseName)) } else { w.Writeln("#include \"%s_implicit.hpp\"", strings.ToLower(BaseName)) } - + w.Writeln("") w.Writeln("") @@ -2283,22 +2282,22 @@ func buildDynamicCppExample(componentdefinition ComponentDefinition, w LanguageW w.Writeln("{") w.Writeln(" try") w.Writeln(" {") - if (ExplicitLinking) { + if ExplicitLinking { w.Writeln(" std::string libpath = (\"\"); // TODO: put the location of the %s-library file here.", NameSpace) - w.Writeln(" auto wrapper = %s::C%sWrapper::loadLibrary(libpath + \"/%s.\"); // TODO: add correct suffix of the library", NameSpace, ClassIdentifier, BaseName,) + w.Writeln(" auto wrapper = %s::C%sWrapper::loadLibrary(libpath + \"/%s.\"); // TODO: add correct suffix of the library", NameSpace, ClassIdentifier, BaseName) } else { w.Writeln(" auto wrapper = %s::C%sWrapper::loadLibrary();", NameSpace, ClassIdentifier) } w.Writeln(" %s_uint32 nMajor, nMinor, nMicro;", NameSpace) w.Writeln(" wrapper->%s(nMajor, nMinor, nMicro);", componentdefinition.Global.VersionMethod) w.Writeln(" std::cout << \"%s.Version = \" << nMajor << \".\" << nMinor << \".\" << nMicro;", NameSpace) - if len(componentdefinition.Global.PrereleaseMethod)>0 { + if len(componentdefinition.Global.PrereleaseMethod) > 0 { w.Writeln(" std::string sPreReleaseInfo;") w.Writeln(" if (wrapper->%s(sPreReleaseInfo)) {", componentdefinition.Global.PrereleaseMethod) w.Writeln(" std::cout << \"-\" << sPreReleaseInfo;") w.Writeln(" }") } - if len(componentdefinition.Global.BuildinfoMethod)>0 { + if len(componentdefinition.Global.BuildinfoMethod) > 0 { w.Writeln(" std::string sBuildInfo;") w.Writeln(" if (wrapper->%s(sBuildInfo)) {", componentdefinition.Global.BuildinfoMethod) w.Writeln(" std::cout << \"+\" << sBuildInfo;") @@ -2331,7 +2330,7 @@ func buildCppDynamicExampleCMake(componentdefinition ComponentDefinition, w Lang } bindingFolder, err := filepath.Rel(outputFolderExample, outputFolder) - if (err != nil) { + if err != nil { return err } bindingFolder = strings.Replace(bindingFolder, "\\", "/", -1) @@ -2341,7 +2340,7 @@ func buildCppDynamicExampleCMake(componentdefinition ComponentDefinition, w Lang w.Writeln("project(%s)", projectName) w.Writeln("set(CMAKE_CXX_STANDARD 11)") w.Writeln("add_executable(%s \"${CMAKE_CURRENT_SOURCE_DIR}/%s_example.cpp\")", projectName, NameSpace) - if (ExplicitLinking || (len(componentdefinition.ImportedComponentDefinitions)>0)) { + if ExplicitLinking || (len(componentdefinition.ImportedComponentDefinitions) > 0) { w.Writeln("if (UNIX)") w.Writeln(" target_link_libraries(%s ${CMAKE_DL_LIBS})", projectName) w.Writeln("endif (UNIX)") @@ -2351,13 +2350,12 @@ func buildCppDynamicExampleCMake(componentdefinition ComponentDefinition, w Lang w.Writeln("target_link_libraries(%s ${%sLOCATION})", projectName, strings.ToUpper(BaseName)) } w.Writeln("target_include_directories(%s PRIVATE \"${%s}\")", projectName, cmakeBindingFolder) - for _, subComponent := range(componentdefinition.ImportedComponentDefinitions) { + for _, subComponent := range componentdefinition.ImportedComponentDefinitions { w.Writeln("target_include_directories(%s PRIVATE \"${%s}/../../../%s_component/Bindings/CppDynamic\")", projectName, cmakeBindingFolder, subComponent.NameSpace) } return nil } - func buildDynamicCExample(componentdefinition ComponentDefinition, w LanguageWriter, outputFolder string, ClassIdentifier string) error { NameSpace := componentdefinition.NameSpace BaseName := componentdefinition.BaseName @@ -2365,7 +2363,7 @@ func buildDynamicCExample(componentdefinition ComponentDefinition, w LanguageWri w.Writeln("#include ") w.Writeln("#include ") w.Writeln("#include \"%s_dynamic.h\"", strings.ToLower(BaseName)) - + w.Writeln("") w.Writeln("") w.Writeln("void releaseWrapper(s%sDynamicWrapperTable* pWrapperTable) {", NameSpace) @@ -2404,12 +2402,12 @@ func buildDynamicCExample(componentdefinition ComponentDefinition, w LanguageWri w.Writeln(" }") w.Writeln(" printf_s(\"%s.Version = %%d.%%d.%%d\", nMajor, nMinor, nMicro);", NameSpace) w.Writeln(" ") - if len(componentdefinition.Global.PrereleaseMethod)>0 || len(componentdefinition.Global.BuildinfoMethod)>0 { + if len(componentdefinition.Global.PrereleaseMethod) > 0 || len(componentdefinition.Global.BuildinfoMethod) > 0 { w.Writeln(" %s_uint32 nBufferRequired = 0;", NameSpace) w.Writeln(" %s_uint8* theString = NULL;", NameSpace) w.Writeln(" bool bHasInfo = false;", NameSpace) } - if len(componentdefinition.Global.PrereleaseMethod)>0 { + if len(componentdefinition.Global.PrereleaseMethod) > 0 { w.Writeln(" eResult = sWrapperTable.m_%s(&bHasInfo, 0, &nBufferRequired, theString);", componentdefinition.Global.PrereleaseMethod) w.Writeln(" if (%s_SUCCESS != eResult) {", strings.ToUpper(NameSpace)) w.Writeln(" releaseWrapper(&sWrapperTable);") @@ -2420,7 +2418,7 @@ func buildDynamicCExample(componentdefinition ComponentDefinition, w LanguageWri w.Writeln(" theString[nBufferRequired] = 0;") w.Writeln(" eResult = sWrapperTable.m_%s(&bHasInfo, nBufferRequired + 1, &nBufferRequired, theString);", componentdefinition.Global.PrereleaseMethod) w.Writeln(" if (%s_SUCCESS != eResult) {", strings.ToUpper(NameSpace)) - w.Writeln(" printf_s(\"Failed to get prerelease information\\n\""); + w.Writeln(" printf_s(\"Failed to get prerelease information\\n\"") w.Writeln(" releaseWrapper(&sWrapperTable);") w.Writeln(" free(theString);") w.Writeln(" return eResult;") @@ -2431,7 +2429,7 @@ func buildDynamicCExample(componentdefinition ComponentDefinition, w LanguageWri w.Writeln(" }") w.Writeln(" ") } - if len(componentdefinition.Global.BuildinfoMethod)>0 { + if len(componentdefinition.Global.BuildinfoMethod) > 0 { w.Writeln(" eResult = sWrapperTable.m_%s(&bHasInfo, 0, &nBufferRequired, theString);", componentdefinition.Global.BuildinfoMethod) w.Writeln(" if (%s_SUCCESS != eResult) {", strings.ToUpper(NameSpace)) w.Writeln(" releaseWrapper(&sWrapperTable);") @@ -2442,7 +2440,7 @@ func buildDynamicCExample(componentdefinition ComponentDefinition, w LanguageWri w.Writeln(" theString[nBufferRequired] = 0;") w.Writeln(" eResult = sWrapperTable.m_%s(&bHasInfo, nBufferRequired + 1, &nBufferRequired, theString);", componentdefinition.Global.BuildinfoMethod) w.Writeln(" if (%s_SUCCESS != eResult) {", strings.ToUpper(NameSpace)) - w.Writeln(" printf_s(\"Failed to get build information\\n\""); + w.Writeln(" printf_s(\"Failed to get build information\\n\"") w.Writeln(" releaseWrapper(&sWrapperTable);") w.Writeln(" free(theString);") w.Writeln(" return eResult;") @@ -2482,7 +2480,7 @@ func buildCDynamicExampleCMake(componentdefinition ComponentDefinition, w Langua } bindingFolder, err := filepath.Rel(outputFolderExample, outputFolder) - if (err != nil) { + if err != nil { return err } bindingFolder = strings.Replace(bindingFolder, "\\", "/", -1) @@ -2493,15 +2491,15 @@ func buildCDynamicExampleCMake(componentdefinition ComponentDefinition, w Langua w.Writeln("project(%s C)", projectName) w.Writeln("") bindingSource := "" - if (ExplicitLinking) { - bindingSource = "\"${"+cmakeBindingFolder+"}/"+strings.ToLower(NameSpace)+"_dynamic.cc\"" + if ExplicitLinking { + bindingSource = "\"${" + cmakeBindingFolder + "}/" + strings.ToLower(NameSpace) + "_dynamic.cc\"" w.Writeln("SET_SOURCE_FILES_PROPERTIES(%s PROPERTIES LANGUAGE C)", bindingSource) bindingSource += "\n" } w.Writeln("add_executable(%s\n \"${CMAKE_CURRENT_SOURCE_DIR}/%s_example.c\"\n %s\n)", projectName, NameSpace, bindingSource) w.Writeln("set_property(TARGET %s PROPERTY C_STANDARD 99)", projectName) - if (ExplicitLinking) { + if ExplicitLinking { w.Writeln("if (UNIX)") w.Writeln(" target_link_libraries(%s ${CMAKE_DL_LIBS})", projectName) w.Writeln("endif (UNIX)") diff --git a/Source/buildbindingccppdocumentation.go b/Source/buildbindingccppdocumentation.go index 2e6e4dad..9834b829 100644 --- a/Source/buildbindingccppdocumentation.go +++ b/Source/buildbindingccppdocumentation.go @@ -39,12 +39,11 @@ import ( "path" ) - // BuildCCPPDocumentation builds the Sphinx documentation of a library's C++-bindings -func BuildCCPPDocumentation(component ComponentDefinition, outputFolder string, ClassIdentifier string) (error) { +func BuildCCPPDocumentation(component ComponentDefinition, outputFolder string, ClassIdentifier string) error { BaseName := component.BaseName - globalFileName := path.Join(outputFolder, BaseName + ".rst") + globalFileName := path.Join(outputFolder, BaseName+".rst") log.Printf("Creating \"%s\"", globalFileName) globalDocFile, err := CreateLanguageFile(globalFileName, "\t") if err != nil { @@ -55,7 +54,7 @@ func BuildCCPPDocumentation(component ComponentDefinition, outputFolder string, return err } - typesFileName := path.Join(outputFolder, BaseName + "-types.rst") + typesFileName := path.Join(outputFolder, BaseName+"-types.rst") log.Printf("Creating \"%s\"", typesFileName) typesDocFile, err := CreateLanguageFile(typesFileName, "\t") if err != nil { @@ -65,10 +64,10 @@ func BuildCCPPDocumentation(component ComponentDefinition, outputFolder string, if err != nil { return err } - + for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] - classFileName := path.Join(outputFolder, BaseName + "_" + class.ClassName + ".rst") + classFileName := path.Join(outputFolder, BaseName+"_"+class.ClassName+".rst") log.Printf("Creating \"%s\"", classFileName) classDocFile, err := CreateLanguageFile(classFileName, "\t") if err != nil { @@ -81,7 +80,6 @@ func BuildCCPPDocumentation(component ComponentDefinition, outputFolder string, } - err = buildCCPPDocumentationExample(component, outputFolder, ClassIdentifier, true, "_dynamic") if err != nil { return err @@ -90,14 +88,14 @@ func BuildCCPPDocumentation(component ComponentDefinition, outputFolder string, if err != nil { return err } - + return nil } func buildCCPPDocumentationExample(component ComponentDefinition, outputFolder string, ClassIdentifier string, ExplicitLinking bool, suffix string) error { NameSpace := component.NameSpace - DynamicCPPExample := path.Join(outputFolder, NameSpace +"_example"+suffix+".cpp") + DynamicCPPExample := path.Join(outputFolder, NameSpace+"_example"+suffix+".cpp") log.Printf("Creating \"%s\"", DynamicCPPExample) dyncppexamplefile, err := CreateLanguageFile(DynamicCPPExample, " ") if err != nil { @@ -116,8 +114,8 @@ func buildCCPPDocumentationExample(component ComponentDefinition, outputFolder s } func writeCPPDocumentationFunctionPointer(component ComponentDefinition, w LanguageWriter, - functiontype ComponentDefinitionFunctionType) (error) { - + functiontype ComponentDefinitionFunctionType) error { + NameSpace := component.NameSpace returnType := "void" parameters := "" @@ -125,14 +123,14 @@ func writeCPPDocumentationFunctionPointer(component ComponentDefinition, w Langu for j := 0; j < len(functiontype.Params); j++ { param := functiontype.Params[j] - cParamTypeName, err := getCPPParameterTypeName(param.ParamType, NameSpace, param.ParamClass); - if (err != nil) { - return err; + cParamTypeName, err := getCPPParameterTypeName(param.ParamType, NameSpace, param.ParamClass) + if err != nil { + return err } - if (parameters != "") { + if parameters != "" { parameters = parameters + ", " } - if (param.ParamPass == "in") { + if param.ParamPass == "in" { parameters = parameters + cParamTypeName } else { parameters = parameters + cParamTypeName + "*" @@ -147,11 +145,11 @@ func writeCPPDocumentationFunctionPointer(component ComponentDefinition, w Langu param := functiontype.Params[j] cParams, err := generateCCPPParameter(param, "", functiontype.FunctionName, NameSpace, true) - if (err != nil) { - return err; + if err != nil { + return err } for _, cParam := range cParams { - w.Writeln(" %s", cParam.ParamDocumentationLine); + w.Writeln(" %s", cParam.ParamDocumentationLine) } } w.Writeln(" ") @@ -159,14 +157,13 @@ func writeCPPDocumentationFunctionPointer(component ComponentDefinition, w Langu return nil } - -func buildCCPPDocumentationGlobal(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) (error) { +func buildCCPPDocumentationGlobal(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) error { NameSpace := component.NameSpace LibraryName := component.LibraryName global := component.Global - wrapperName := "C"+ClassIdentifier+"Wrapper" + wrapperName := "C" + ClassIdentifier + "Wrapper" w.Writeln("") w.Writeln("The wrapper class %s", wrapperName) @@ -182,12 +179,11 @@ func buildCCPPDocumentationGlobal(component ComponentDefinition, w LanguageWrite w.Writeln(" A suitable way to use %s::%s is as a singleton.", NameSpace, wrapperName) w.Writeln("") - for j := 0; j < len(global.Methods); j++ { method := global.Methods[j] parameters, returntype, err := getDynamicCPPMethodParameters(method, NameSpace, ClassIdentifier, "Wrapper") - if (err != nil) { + if err != nil { return err } w.Writeln(" .. cpp:function:: %s %s(%s)", returntype, method.MethodName, parameters) @@ -200,20 +196,19 @@ func buildCCPPDocumentationGlobal(component ComponentDefinition, w LanguageWrite w.Writeln(".. cpp:type:: std::shared_ptr<%s> %s::P%s%s", wrapperName, NameSpace, ClassIdentifier, "Wrapper") w.Writeln(" ") - + // Load library functions // Check error functions of the base class return nil } - func writeCPPDocumentationParameters(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string) { for k := 0; k < len(method.Params); k++ { param := method.Params[k] variableName := getBindingCppVariableName(param) - if (param.ParamPass == "return") { - w.Writeln(" :returns: %s", param.ParamDescription ) + if param.ParamPass == "return" { + w.Writeln(" :returns: %s", param.ParamDescription) } else { w.Writeln(" :param %s: %s ", variableName, param.ParamDescription) } @@ -221,17 +216,17 @@ func writeCPPDocumentationParameters(method ComponentDefinitionMethod, w Languag w.Writeln("") } -func buildCCPPDocumentationClass(component ComponentDefinition, w LanguageWriter, class ComponentDefinitionClass, ClassIdentifier string) (error) { - +func buildCCPPDocumentationClass(component ComponentDefinition, w LanguageWriter, class ComponentDefinitionClass, ClassIdentifier string) error { + NameSpace := component.NameSpace - className := "C"+ClassIdentifier+class.ClassName + className := "C" + ClassIdentifier + class.ClassName w.Writeln("") w.Writeln("%s", className) w.Writeln("====================================================================================================") w.Writeln("") w.Writeln("") - + _, inheritanceSpecifier := getCPPInheritanceSpecifier(component, class, "C", ClassIdentifier) w.Writeln(".. cpp:class:: %s::%s %s", NameSpace, className, inheritanceSpecifier) @@ -246,7 +241,7 @@ func buildCCPPDocumentationClass(component ComponentDefinition, w LanguageWriter method := class.Methods[j] parameters, returntype, err := getDynamicCPPMethodParameters(method, NameSpace, ClassIdentifier, class.ClassName) - if (err != nil) { + if err != nil { return err } w.Writeln(" .. cpp:function:: %s %s(%s)", returntype, method.MethodName, parameters) @@ -267,7 +262,7 @@ func buildCCPPDocumentationClass(component ComponentDefinition, w LanguageWriter func buildCCPPDocumentationException(component ComponentDefinition, w LanguageWriter) { LibraryName := component.LibraryName - NameSpace := component.NameSpace + NameSpace := component.NameSpace ExceptionName := "E" + NameSpace + "Exception" w.Writeln(" ") @@ -286,7 +281,6 @@ func buildCCPPDocumentationException(component ComponentDefinition, w LanguageWr w.Writeln(" :return: the error message of this exception") w.Writeln(" ") - w.Writeln(" ") w.Writeln(" .. cpp:function:: %sResult %s::getErrorCode() const noexcept", NameSpace, ExceptionName) w.Writeln(" ") @@ -296,10 +290,9 @@ func buildCCPPDocumentationException(component ComponentDefinition, w LanguageWr w.Writeln(" ") } - func buildCCPPDocumentationInputVector(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) { LibraryName := component.LibraryName - NameSpace := component.NameSpace + NameSpace := component.NameSpace InputVector := "C" + ClassIdentifier + "InputVector" w.Writeln(" ") @@ -314,8 +307,7 @@ func buildCCPPDocumentationInputVector(component ComponentDefinition, w Language w.Writeln(" Usually, instances of %s are generated anonymously (or even implicitly) in the call to a function that expects an input array.", InputVector) w.Writeln(" ") w.Writeln(" ") - - + w.Writeln(" .. cpp:class:: template %s::%s", NameSpace, InputVector) w.Writeln(" ") w.Writeln(" .. cpp:function:: %s(const std::vector& vec)", InputVector) @@ -339,8 +331,7 @@ func buildCCPPDocumentationInputVector(component ComponentDefinition, w Language w.Writeln(" ") } - -func buildCCPPDocumentationStructs(component ComponentDefinition, w LanguageWriter) (error) { +func buildCCPPDocumentationStructs(component ComponentDefinition, w LanguageWriter) error { if len(component.Structs) == 0 { return nil } @@ -354,34 +345,34 @@ func buildCCPPDocumentationStructs(component ComponentDefinition, w LanguageWrit w.Writeln(" All structs are defined as `packed`, i.e. with the") w.Writeln(" ") w.Writeln(" .. code-block:: c") - w.Writeln(" "); - w.Writeln(" #pragma pack (1)"); - w.Writeln(""); + w.Writeln(" ") + w.Writeln(" #pragma pack (1)") + w.Writeln("") for i := 0; i < len(component.Structs); i++ { - structinfo := component.Structs[i]; - w.Writeln(" .. cpp:struct:: s%s", structinfo.Name); - w.Writeln(" "); + structinfo := component.Structs[i] + w.Writeln(" .. cpp:struct:: s%s", structinfo.Name) + w.Writeln(" ") // w.Writeln(" %s", structinfo.Description); // w.Writeln(" "); for j := 0; j < len(structinfo.Members); j++ { - member := structinfo.Members[j]; - arraysuffix := ""; - if (member.Rows > 0) { - if (member.Columns > 0) { - arraysuffix = fmt.Sprintf ("[%d][%d]", member.Columns, member.Rows) + member := structinfo.Members[j] + arraysuffix := "" + if member.Rows > 0 { + if member.Columns > 0 { + arraysuffix = fmt.Sprintf("[%d][%d]", member.Columns, member.Rows) } else { - arraysuffix = fmt.Sprintf ("[%d]",member.Rows) + arraysuffix = fmt.Sprintf("[%d]", member.Rows) } } - memberLine, err:= getCPPMemberLine(member, NameSpace, arraysuffix, structinfo.Name, "") - if (err!=nil) { + memberLine, err := getCPPMemberLine(member, NameSpace, arraysuffix, structinfo.Name, "") + if err != nil { return err } w.Writeln(" .. cpp:member:: %s", memberLine) - w.Writeln(" "); + w.Writeln(" ") } - w.Writeln(""); + w.Writeln("") } return nil @@ -393,7 +384,7 @@ func buildCCPPDocumentationSimpleTypes(component ComponentDefinition, w Language w.Writeln("Simple types") w.Writeln("--------------") w.Writeln("") - types := []string{"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64"} + types := []string{"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64"} for _, _type := range types { w.Writeln(" .. cpp:type:: %s_t %s_%s", _type, NameSpace, _type) w.Writeln(" ") @@ -422,19 +413,19 @@ func buildCCPPDocumentationEnums(component ComponentDefinition, w LanguageWriter w.Writeln("") for i := 0; i < len(component.Enums); i++ { enum := component.Enums[i] - w.Writeln(" .. cpp:enum-class:: e%s : %s_int32", enum.Name, NameSpace); + w.Writeln(" .. cpp:enum-class:: e%s : %s_int32", enum.Name, NameSpace) w.Writeln(" ") // w.Writeln(" %s", enum.Description) // w.Writeln(" ") for j := 0; j < len(enum.Options); j++ { - option := enum.Options[j]; - w.Writeln(" .. cpp:enumerator:: %s = %d", option.Name, option.Value); + option := enum.Options[j] + w.Writeln(" .. cpp:enumerator:: %s = %d", option.Name, option.Value) } - w.Writeln(" "); + w.Writeln(" ") } } -func buildCCPPDocumentationFunctionTypes(component ComponentDefinition, w LanguageWriter) (error) { +func buildCCPPDocumentationFunctionTypes(component ComponentDefinition, w LanguageWriter) error { if len(component.Functions) == 0 { return nil } @@ -446,7 +437,7 @@ func buildCCPPDocumentationFunctionTypes(component ComponentDefinition, w Langua for i := 0; i < len(component.Functions); i++ { functiontype := component.Functions[i] err := writeCPPDocumentationFunctionPointer(component, w, functiontype) - if (err!=nil) { + if err != nil { return err } } @@ -455,7 +446,7 @@ func buildCCPPDocumentationFunctionTypes(component ComponentDefinition, w Langua return nil } -func buildCCPPDocumentationTypes(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) (error) { +func buildCCPPDocumentationTypes(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) error { LibraryName := component.LibraryName w.Writeln("") @@ -466,13 +457,13 @@ func buildCCPPDocumentationTypes(component ComponentDefinition, w LanguageWriter buildCCPPDocumentationSimpleTypes(component, w) buildCCPPDocumentationEnums(component, w) - + err := buildCCPPDocumentationStructs(component, w) - if (err!=nil) { + if err != nil { return err } err = buildCCPPDocumentationFunctionTypes(component, w) - if (err!=nil) { + if err != nil { return err } buildCCPPDocumentationException(component, w) diff --git a/Source/buildbindingcsharp.go b/Source/buildbindingcsharp.go index 6900291f..10b0788f 100644 --- a/Source/buildbindingcsharp.go +++ b/Source/buildbindingcsharp.go @@ -59,9 +59,9 @@ func BuildBindingCSharp(component ComponentDefinition, outputFolder string, outp return err } - CSharpImplFile.WriteCLicenseHeader(component, - fmt.Sprintf("This is an autogenerated CSharp file in order to allow an easy\n use of %s", libraryName), - true) + CSharpImplFile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated CSharp file in order to allow an easy\n use of %s", libraryName), + true) err = buildBindingCSharpImplementation(component, CSharpImplFile, namespace, baseName) if len(outputFolderExample) > 0 { @@ -407,7 +407,7 @@ func writeCSharpClassMethodImplementation(method ComponentDefinitionMethod, w La initCallParameter = callFunctionParameter case "class", "optionalclass": - if (ParamTypeName == "IntPtr") { + if ParamTypeName == "IntPtr" { callFunctionParameter = "A" + param.ParamName } else { defineCommands = append(defineCommands, fmt.Sprintf(" IntPtr A%sHandle = IntPtr.Zero;", param.ParamName)) @@ -415,7 +415,7 @@ func writeCSharpClassMethodImplementation(method ComponentDefinitionMethod, w La defineCommands = append(defineCommands, fmt.Sprintf(" A%sHandle = A%s.GetHandle();", param.ParamName, param.ParamName)) callFunctionParameter = "A" + param.ParamName + "Handle" } - + initCallParameter = callFunctionParameter default: @@ -585,7 +585,7 @@ func writeCSharpClassMethodImplementation(method ComponentDefinitionMethod, w La defineCommands = append(defineCommands, fmt.Sprintf(" IntPtr new%s = IntPtr.Zero;", param.ParamName)) callFunctionParameter = "out new" + param.ParamName initCallParameter = callFunctionParameter - if (ParamTypeName == "IntPtr") { + if ParamTypeName == "IntPtr" { returnCodeLines = append(returnCodeLines, fmt.Sprintf(" return new%s;", param.ParamName)) } else { // TODO: Using plain NameSpace here for calling PolymorphicFactory is most likely incorrect. @@ -1128,7 +1128,7 @@ func buildBindingCSharpImplementation(component ComponentDefinition, w LanguageW } else { writeCSharpClassMethodImplementation(method, w, NameSpace, "Wrapper", true, " ") } - + w.Writeln(" }") w.Writeln("") } diff --git a/Source/buildbindinggo.go b/Source/buildbindinggo.go index 8eb41843..281e2c63 100644 --- a/Source/buildbindinggo.go +++ b/Source/buildbindinggo.go @@ -471,7 +471,7 @@ func WriteCGoAbiMethod(method ComponentDefinitionMethod, w LanguageWriter, NameS return err } for _, cParam := range cParams { - parameters = append(parameters, cParam.ParamType + " " + cParam.ParamName) + parameters = append(parameters, cParam.ParamType+" "+cParam.ParamName) callParameters = append(callParameters, cParam.ParamName) } diff --git a/Source/buildbindingjava.go b/Source/buildbindingjava.go index 0d018cc9..3c2b9069 100644 --- a/Source/buildbindingjava.go +++ b/Source/buildbindingjava.go @@ -34,14 +34,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package main import ( + "bytes" "fmt" "log" - "path" - "strings" - "bytes" "os" - "strconv" + "path" "sort" + "strconv" + "strings" ) type JavaParameter struct { @@ -53,10 +53,10 @@ type JavaParameter struct { } type JavaReturn struct { - ParamName string - ParamType string - ParamValue string - ParamDescription string + ParamName string + ParamType string + ParamValue string + ParamDescription string } // BuildBindingJavaDynamic builds dynamic Java-bindings of a library's API using Java Native Access (JNA). @@ -64,125 +64,125 @@ func BuildBindingJavaDynamic(component ComponentDefinition, outputFolder string, forceRecreation := false namespace := component.NameSpace libraryname := component.LibraryName - JavaFolder := path.Join(outputFolder, strings.ToLower(namespace)); + JavaFolder := path.Join(outputFolder, strings.ToLower(namespace)) err := os.MkdirAll(JavaFolder, os.ModePerm) if err != nil { - return err; + return err } - JavaWrapperName := namespace + "Wrapper"; - JavaWrapperPath := path.Join(JavaFolder, JavaWrapperName + ".java"); + JavaWrapperName := namespace + "Wrapper" + JavaWrapperPath := path.Join(JavaFolder, JavaWrapperName+".java") log.Printf("Creating \"%s\"", JavaWrapperPath) - JavaWrapperFile, err := CreateLanguageFile (JavaWrapperPath, indent) + JavaWrapperFile, err := CreateLanguageFile(JavaWrapperPath, indent) if err != nil { - return err; + return err } JavaWrapperFile.WriteJavaLicenseHeader(component, fmt.Sprintf("This is an autogenerated Java file in order to allow an easy\n use of %s", libraryname), true) - + err = buildJavaWrapper(component, JavaWrapperFile, indent) if err != nil { - return err; + return err } - JavaExceptionName := namespace + "Exception"; - JavaExceptionPath := path.Join(JavaFolder, JavaExceptionName + ".java"); + JavaExceptionName := namespace + "Exception" + JavaExceptionPath := path.Join(JavaFolder, JavaExceptionName+".java") log.Printf("Creating \"%s\"", JavaExceptionPath) - JavaExceptionFile, err1 := CreateLanguageFile (JavaExceptionPath, indent) + JavaExceptionFile, err1 := CreateLanguageFile(JavaExceptionPath, indent) if err1 != nil { - return err1; + return err1 } JavaExceptionFile.WriteJavaLicenseHeader(component, fmt.Sprintf("This is an autogenerated Java file in order to allow an easy\n use of %s", libraryname), true) - + err = buildJavaException(component, JavaExceptionFile, indent) if err != nil { - return err; + return err } for i := 0; i < len(component.Structs); i++ { structinfo := component.Structs[i] - JavaStructPath := path.Join(JavaFolder, structinfo.Name + ".java"); + JavaStructPath := path.Join(JavaFolder, structinfo.Name+".java") log.Printf("Creating \"%s\"", JavaStructPath) - JavaStructFile, err := CreateLanguageFile (JavaStructPath, indent) + JavaStructFile, err := CreateLanguageFile(JavaStructPath, indent) if err != nil { - return err; + return err } JavaStructFile.WriteJavaLicenseHeader(component, fmt.Sprintf("This is an autogenerated Java file in order to allow an easy\n use of %s", libraryname), true) - + err = buildJavaStruct(component, JavaStructFile, indent, structinfo) if err != nil { - return err; + return err } } for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] - JavaClassPath := path.Join(JavaFolder, class.ClassName + ".java"); + JavaClassPath := path.Join(JavaFolder, class.ClassName+".java") log.Printf("Creating \"%s\"", JavaClassPath) - JavaClassFile, err := CreateLanguageFile (JavaClassPath, indent) + JavaClassFile, err := CreateLanguageFile(JavaClassPath, indent) if err != nil { - return err; + return err } JavaClassFile.WriteJavaLicenseHeader(component, fmt.Sprintf("This is an autogenerated Java file in order to allow an easy\n use of %s", libraryname), true) - + err = buildJavaClass(component, JavaClassFile, indent, class, version) if err != nil { - return err; + return err } } - JavaBuildName := "build_jar.sh"; - JavaBuildPath := path.Join(outputFolder, JavaBuildName); + JavaBuildName := "build_jar.sh" + JavaBuildPath := path.Join(outputFolder, JavaBuildName) log.Printf("Creating \"%s\"", JavaBuildPath) - JavaWrapperFile, err2 := CreateLanguageFile (JavaBuildPath, indent) + JavaWrapperFile, err2 := CreateLanguageFile(JavaBuildPath, indent) if err2 != nil { - return err2; + return err2 } err = buildJavaBuildScript(component, JavaWrapperFile) if err != nil { - return err; + return err } - if (len(outputFolderExample) > 0) { - DynamicJavaExample := path.Join(outputFolderExample, namespace+"_Example"+".java"); - if (forceRecreation || !FileExists(DynamicJavaExample)) { + if len(outputFolderExample) > 0 { + DynamicJavaExample := path.Join(outputFolderExample, namespace+"_Example"+".java") + if forceRecreation || !FileExists(DynamicJavaExample) { log.Printf("Creating \"%s\"", DynamicJavaExample) - DynJavaExampleFile, err := CreateLanguageFile (DynamicJavaExample, indent) + DynJavaExampleFile, err := CreateLanguageFile(DynamicJavaExample, indent) DynJavaExampleFile.WriteJavaLicenseHeader(component, fmt.Sprintf("This is an autogenerated Java application that demonstrates the\n usage of the Java bindings of %s", libraryname), true) err = buildDynamicJavaExample(component, DynJavaExampleFile, outputFolder) if err != nil { - return err; + return err } } else { log.Printf("Omitting recreation of Java example \"%s\"", DynamicJavaExample) } - JavaBuildName := "build.sh"; - JavaBuildPath := path.Join(outputFolderExample, JavaBuildName); - if (forceRecreation || !FileExists(JavaBuildPath)) { + JavaBuildName := "build.sh" + JavaBuildPath := path.Join(outputFolderExample, JavaBuildName) + if forceRecreation || !FileExists(JavaBuildPath) { log.Printf("Creating \"%s\"", JavaBuildPath) - JavaWrapperFile, err2 := CreateLanguageFile (JavaBuildPath, indent) + JavaWrapperFile, err2 := CreateLanguageFile(JavaBuildPath, indent) if err2 != nil { - return err2; + return err2 } err = buildJavaBuildExampleScript(component, JavaWrapperFile, version) if err != nil { - return err; + return err } } else { log.Printf("Omitting recreation of Java example build file\"%s\"", JavaBuildPath) @@ -190,15 +190,15 @@ func BuildBindingJavaDynamic(component ComponentDefinition, outputFolder string, } - return nil; + return nil } func decorateSpecialFunction(name string) string { name = MakeFirstLowerCase(name) - if (name == "clone" || name == "toString" || name == "equals" || + if name == "clone" || name == "toString" || name == "equals" || name == "hashCode" || name == "finalize" || name == "wait" || - name == "notify" || name == "notifyAll" || name == "getClass"){ - return name + "_" + name == "notify" || name == "notifyAll" || name == "getClass" { + return name + "_" } return name } @@ -209,7 +209,7 @@ func buildDynamicJavaExample(component ComponentDefinition, w LanguageWriter, ou var VersionMethod *ComponentDefinitionMethod var PrereleaseMethod *ComponentDefinitionMethod var BuildInfoMethod *ComponentDefinitionMethod - for j:=0; j= 9 { w.Writeln("import java.lang.ref.Cleaner;") - } + } w.Writeln("") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { w.Writeln("import %s.*;", strings.ToLower(subComponent.NameSpace)) } w.Writeln("") - w.Writeln("import java.nio.charset.StandardCharsets;"); + w.Writeln("import java.nio.charset.StandardCharsets;") w.Writeln("import java.util.Arrays;") w.Writeln("import java.util.List;") w.Writeln("") @@ -408,7 +407,7 @@ func buildJavaClass(component ComponentDefinition, w LanguageWriter, indent stri ParentClass = component.Global.BaseClassName } w.Writeln("public class %s extends %s {", class.ClassName, ParentClass) - w.Writeln("") + w.Writeln("") } if component.isBaseClass(class) { if version >= 9 { @@ -418,7 +417,7 @@ func buildJavaClass(component ComponentDefinition, w LanguageWriter, indent stri w.Writeln(" protected Pointer mHandle;") w.Writeln("") w.Writeln(" protected %sWrapper mWrapper;", component.NameSpace) - w.Writeln("") + w.Writeln("") } w.Writeln(" public %s(%sWrapper wrapper, Pointer handle) {", class.ClassName, component.NameSpace) @@ -431,7 +430,7 @@ func buildJavaClass(component ComponentDefinition, w LanguageWriter, indent stri } else { w.Writeln(" super(wrapper, handle);") } - w.Writeln(" }"); + w.Writeln(" }") w.Writeln("") if component.isBaseClass(class) { @@ -482,10 +481,10 @@ func buildJavaClass(component ComponentDefinition, w LanguageWriter, indent stri w.Writeln("") w.Writeln("}") w.Writeln("") - return nil; + return nil } -func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string, ClassName string, +func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string, ClassName string, indent string, isGlobal bool, additionalCode []string, additionalExceptions string) error { parameters := "" @@ -542,7 +541,7 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang OutFieldCount := 0 for k := 0; k < len(method.Params); k++ { param := method.Params[k] - if (param.ParamPass == "out" || param.ParamPass == "return") { + if param.ParamPass == "out" || param.ParamPass == "return" { OutFieldCount = OutFieldCount + 1 } } @@ -561,10 +560,10 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang if initCallParameters != "" { initCallParameters = initCallParameters + ", " } - if (param.ParamPass == "out" || param.ParamPass == "return") { + if param.ParamPass == "out" || param.ParamPass == "return" { if OutFieldCount == 1 { w.Writeln(" * @return %s", param.ParamDescription) - } + } } else { w.Writeln(" * @param %s %s", MakeFirstLowerCase(param.ParamName), param.ParamDescription) } @@ -578,10 +577,10 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang initCallParameters = initCallParameters + MakeFirstLowerCase(param.ParamName) case "string": - initCommands = append(initCommands, "byte[] bytes" + param.ParamName + " = " + MakeFirstLowerCase(param.ParamName) + ".getBytes(StandardCharsets.UTF_8);") - initCommands = append(initCommands, "Memory buffer" + param.ParamName + " = new Memory(bytes" + param.ParamName + ".length + 1);") - initCommands = append(initCommands, "buffer" + param.ParamName + ".write(0, bytes" + param.ParamName + ", 0, bytes" + param.ParamName + ".length);") - initCommands = append(initCommands, "buffer" + param.ParamName + ".setByte(bytes" + param.ParamName + ".length, (byte)0);") + initCommands = append(initCommands, "byte[] bytes"+param.ParamName+" = "+MakeFirstLowerCase(param.ParamName)+".getBytes(StandardCharsets.UTF_8);") + initCommands = append(initCommands, "Memory buffer"+param.ParamName+" = new Memory(bytes"+param.ParamName+".length + 1);") + initCommands = append(initCommands, "buffer"+param.ParamName+".write(0, bytes"+param.ParamName+", 0, bytes"+param.ParamName+".length);") + initCommands = append(initCommands, "buffer"+param.ParamName+".setByte(bytes"+param.ParamName+".length, (byte)0);") callFunctionParameters = callFunctionParameters + "buffer" + param.ParamName initCallParameters = initCallParameters + "buffer" + param.ParamName @@ -628,14 +627,14 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang initCallParameters = initCallParameters + MakeFirstLowerCase(param.ParamName) case "class", "optionalclass": - initCommands = append(initCommands, "Pointer " + MakeFirstLowerCase(param.ParamName) + "Handle = null;") + initCommands = append(initCommands, "Pointer "+MakeFirstLowerCase(param.ParamName)+"Handle = null;") initCommands = append(initCommands, fmt.Sprintf("if (%s != null) {", MakeFirstLowerCase(param.ParamName))) - initCommands = append(initCommands, indent + MakeFirstLowerCase(param.ParamName) + "Handle = " + MakeFirstLowerCase(param.ParamName) + ".getHandle();") - if (param.ParamType == "optionalclass") { + initCommands = append(initCommands, indent+MakeFirstLowerCase(param.ParamName)+"Handle = "+MakeFirstLowerCase(param.ParamName)+".getHandle();") + if param.ParamType == "optionalclass" { } else { initCommands = append(initCommands, fmt.Sprintf("} else {")) - initCommands = append(initCommands, indent + fmt.Sprintf("throw new %sException(%sException.%s_ERROR_INVALIDPARAM, \"%s is a null value.\");", NameSpace, NameSpace, strings.ToUpper(NameSpace), param.ParamName)) + initCommands = append(initCommands, indent+fmt.Sprintf("throw new %sException(%sException.%s_ERROR_INVALIDPARAM, \"%s is a null value.\");", NameSpace, NameSpace, strings.ToUpper(NameSpace), param.ParamName)) } initCommands = append(initCommands, fmt.Sprintf("}")) callFunctionParameters = callFunctionParameters + MakeFirstLowerCase(param.ParamName) + "Handle" @@ -673,7 +672,7 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang doInitCall = true case "enum": - initCommands = append(initCommands, "Pointer buffer" + param.ParamName + " = new Memory(4);") + initCommands = append(initCommands, "Pointer buffer"+param.ParamName+" = new Memory(4);") callFunctionParameters = callFunctionParameters + "buffer" + param.ParamName initCallParameters = initCallParameters + "buffer" + param.ParamName @@ -682,7 +681,7 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang ReturnTuple = append(ReturnTuple, ReturnItem) case "bool": - initCommands = append(initCommands, "Pointer buffer" + param.ParamName + " = new Memory(1);") + initCommands = append(initCommands, "Pointer buffer"+param.ParamName+" = new Memory(1);") callFunctionParameters = callFunctionParameters + "buffer" + param.ParamName initCallParameters = initCallParameters + "buffer" + param.ParamName @@ -710,7 +709,7 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang initCallParameters = initCallParameters + fmt.Sprintf("0L, countNeeded%s, Pointer.NULL", param.ParamName) - postInitCommands = append(postInitCommands, fmt.Sprintf("long count%s = countNeeded%s.getLong(0);", param.ParamName, param.ParamName)) + postInitCommands = append(postInitCommands, fmt.Sprintf("long count%s = countNeeded%s.getLong(0);", param.ParamName, param.ParamName)) postInitCommands = append(postInitCommands, fmt.Sprintf("Pointer buffer%s = new Memory(Math.max(1, %d * count%s));", param.ParamName, ElementBytes, param.ParamName)) callFunctionParameters = callFunctionParameters + fmt.Sprintf("count%s, countNeeded%s, buffer%s", param.ParamName, param.ParamName, param.ParamName) @@ -735,7 +734,7 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang initCallParameters = initCallParameters + fmt.Sprintf("0L, countNeeded%s, null", param.ParamName) - postInitCommands = append(postInitCommands, fmt.Sprintf("long count%s = countNeeded%s.getLong(0);", param.ParamName, param.ParamName)) + postInitCommands = append(postInitCommands, fmt.Sprintf("long count%s = countNeeded%s.getLong(0);", param.ParamName, param.ParamName)) postInitCommands = append(postInitCommands, fmt.Sprintf("Pointer buffer%s = new Memory(Math.max(1, count%s * %s.SIZE));", param.ParamName, param.ParamName, param.ParamClass)) callFunctionParameters = callFunctionParameters + fmt.Sprintf("count%s, countNeeded%s, buffer%s", param.ParamName, param.ParamName, param.ParamName) @@ -759,14 +758,14 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang } else { theNameSpace = NameSpace } - initCommands = append(initCommands, "Pointer buffer" + param.ParamName + " = new Memory(8);") + initCommands = append(initCommands, "Pointer buffer"+param.ParamName+" = new Memory(8);") callFunctionParameters = callFunctionParameters + "buffer" + param.ParamName resultCommands = append(resultCommands, fmt.Sprintf("Pointer value%s = buffer%s.getPointer(0);", param.ParamName, param.ParamName)) resultCommands = append(resultCommands, fmt.Sprintf("%s %s = null;", theParamClass, MakeFirstLowerCase(param.ParamName))) if param.ParamType == "class" { resultCommands = append(resultCommands, fmt.Sprintf("if (value%s == Pointer.NULL) {", param.ParamName)) - resultCommands = append(resultCommands, fmt.Sprintf(" throw new %sException(%sException.%s_ERROR_INVALIDPARAM, \"%s was a null pointer\");", - NameSpace, NameSpace, strings.ToUpper(NameSpace), param.ParamName)) + resultCommands = append(resultCommands, fmt.Sprintf(" throw new %sException(%sException.%s_ERROR_INVALIDPARAM, \"%s was a null pointer\");", + NameSpace, NameSpace, strings.ToUpper(NameSpace), param.ParamName)) resultCommands = append(resultCommands, "}") resultCommands = append(resultCommands, fmt.Sprintf("%s = %s.PolymorphicFactory(value%s, %s.class);", MakeFirstLowerCase(param.ParamName), theWrapperInstance, param.ParamName, theParamClass)) } else { @@ -797,20 +796,20 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang w.Writeln(" public %s %s(%s) throws %sException%s {", ReturnType, decorateSpecialFunction(method.MethodName), parameters, NameSpace, additionalExceptions) if len(defineCommands) > 0 { - w.Writelns(indent + indent, defineCommands) + w.Writelns(indent+indent, defineCommands) } - w.Writelns(indent + indent, initCommands) + w.Writelns(indent+indent, initCommands) if doInitCall { w.Writeln(" %scheckError(%s, %s%s.invokeInt(new java.lang.Object[]{%s}));", wrapperCallPrefix, errorInstanceHandle, wrapperCallPrefix, callFunctionName, initCallParameters) } - w.Writelns(indent + indent, postInitCommands) + w.Writelns(indent+indent, postInitCommands) w.Writeln(" %scheckError(%s, %s%s.invokeInt(new java.lang.Object[]{%s}));", wrapperCallPrefix, errorInstanceHandle, wrapperCallPrefix, callFunctionName, callFunctionParameters) - w.Writelns(indent + indent, resultCommands) + w.Writelns(indent+indent, resultCommands) if len(additionalCode) > 0 { w.Writeln("") @@ -822,7 +821,7 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang } if len(ReturnTuple) > 1 { w.Writeln(" %sResult returnTuple = new %sResult();", method.MethodName, method.MethodName) - for _,ReturnParam := range(ReturnTuple) { + for _, ReturnParam := range ReturnTuple { w.Writeln(" returnTuple.%s = %s", ReturnParam.ParamName, ReturnParam.ParamValue) } w.Writeln(" return returnTuple;") @@ -833,7 +832,7 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang if len(ReturnTuple) > 1 { w.Writeln(" public static class %sResult {", method.MethodName) - for _,ReturnParam := range(ReturnTuple) { + for _, ReturnParam := range ReturnTuple { w.Writeln(" /**") w.Writeln(" * " + ReturnParam.ParamDescription) w.Writeln(" */") @@ -843,7 +842,6 @@ func writeJavaClassMethodImplementation(method ComponentDefinitionMethod, w Lang w.Writeln(" }") } - return nil } @@ -874,25 +872,25 @@ func buildJavaStruct(component ComponentDefinition, w LanguageWriter, indent str if element.Columns > 0 { arrayprefix = fmt.Sprintf("[][]") arraysuffix = fmt.Sprintf("[%d][%d]", element.Rows, element.Columns) - byteSum = byteSum + bytes * element.Columns * element.Rows; + byteSum = byteSum + bytes*element.Columns*element.Rows } else { arrayprefix = fmt.Sprintf("[]") arraysuffix = fmt.Sprintf("[%d]", element.Rows) - byteSum = byteSum + bytes * element.Rows; + byteSum = byteSum + bytes*element.Rows } w.Writeln(" public %s%s %s = new %s%s;", fieldType, arrayprefix, element.Name, fieldType, arraysuffix) } else { - byteSum = byteSum + bytes; + byteSum = byteSum + bytes w.Writeln(" public %s %s;", fieldType, element.Name) } w.Writeln("") } - w.Writeln(" public static final int SIZE = %d;", byteSum); + w.Writeln(" public static final int SIZE = %d;", byteSum) w.Writeln("") // Write memory reader byteSum = 0 - w.Writeln(" public void readFromPointer(Pointer p, long offset) {"); + w.Writeln(" public void readFromPointer(Pointer p, long offset) {") for j := 0; j < len(structinfo.Members); j++ { element := structinfo.Members[j] boolSuffix := "" @@ -911,24 +909,24 @@ func buildJavaStruct(component ComponentDefinition, w LanguageWriter, indent str if element.Columns > 0 { for l := 0; l < element.Columns; l++ { w.Writeln(" %s[%d][%d] = p.get%s(offset + %d)%s;", element.Name, k, l, MakeFirstUpperCase(fieldType), byteSum, boolSuffix) - byteSum = byteSum + bytes; + byteSum = byteSum + bytes } } else { w.Writeln(" %s[%d] = p.get%s(offset + %d)%s;", element.Name, k, MakeFirstUpperCase(fieldType), byteSum, boolSuffix) - byteSum = byteSum + bytes; + byteSum = byteSum + bytes } } } else { w.Writeln(" %s = p.get%s(offset + %d)%s;", element.Name, MakeFirstUpperCase(fieldType), byteSum, boolSuffix) - byteSum = byteSum + bytes; + byteSum = byteSum + bytes } } - w.Writeln(" }"); + w.Writeln(" }") w.Writeln("") // Write memory writer byteSum = 0 - w.Writeln(" public void writeToPointer(Pointer p, long offset) {"); + w.Writeln(" public void writeToPointer(Pointer p, long offset) {") for j := 0; j < len(structinfo.Members); j++ { element := structinfo.Members[j] value := element.Name @@ -945,20 +943,20 @@ func buildJavaStruct(component ComponentDefinition, w LanguageWriter, indent str for k := 0; k < element.Rows; k++ { if element.Columns > 0 { for l := 0; l < element.Columns; l++ { - w.Writeln(" p.set%s(offset + %d, %s[%d][%d]);", MakeFirstUpperCase(fieldType), byteSum, value, k, l, ) - byteSum = byteSum + bytes; + w.Writeln(" p.set%s(offset + %d, %s[%d][%d]);", MakeFirstUpperCase(fieldType), byteSum, value, k, l) + byteSum = byteSum + bytes } } else { - w.Writeln(" p.set%s(offset + %d, %s[%d]);", MakeFirstUpperCase(fieldType), byteSum, value, k, ) - byteSum = byteSum + bytes; + w.Writeln(" p.set%s(offset + %d, %s[%d]);", MakeFirstUpperCase(fieldType), byteSum, value, k) + byteSum = byteSum + bytes } } } else { w.Writeln(" p.set%s(offset + %d, %s);", MakeFirstUpperCase(fieldType), byteSum, value) - byteSum = byteSum + bytes; + byteSum = byteSum + bytes } } - w.Writeln(" }"); + w.Writeln(" }") w.Writeln("") w.Writeln("}") @@ -969,7 +967,7 @@ func buildJavaStruct(component ComponentDefinition, w LanguageWriter, indent str func buildJavaWrapper(component ComponentDefinition, w LanguageWriter, indent string) error { NameSpace := component.NameSpace - JavaWrapperName := NameSpace + "Wrapper"; + JavaWrapperName := NameSpace + "Wrapper" w.Writeln("package %s;", strings.ToLower(component.NameSpace)) w.Writeln("") @@ -978,7 +976,7 @@ func buildJavaWrapper(component ComponentDefinition, w LanguageWriter, indent st w.Writeln("import java.nio.charset.StandardCharsets;") w.Writeln("") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { w.Writeln("import %s.*;", strings.ToLower(subComponent.NameSpace)) } w.Writeln("") @@ -990,12 +988,12 @@ func buildJavaWrapper(component ComponentDefinition, w LanguageWriter, indent st for i := 0; i < len(component.Enums); i++ { enum := component.Enums[i] for j := 0; j < len(enum.Options); j++ { - w.Writeln(" public static final int %s_%s = %d;", strings.ToUpper(enum.Name), strings.ToUpper(enum.Options[j].Name), enum.Options[j].Value) + w.Writeln(" public static final int %s_%s = %d;", strings.ToUpper(enum.Name), strings.ToUpper(enum.Options[j].Name), enum.Options[j].Value) } w.Writeln("") w.Writeln(" public enum %s {", enum.Name) for j := 0; j < len(enum.Options); j++ { - if j < len(enum.Options) - 1 { + if j < len(enum.Options)-1 { w.Writeln(" e" + enum.Options[j].Name + ",") } else { w.Writeln(" e" + enum.Options[j].Name) @@ -1004,7 +1002,7 @@ func buildJavaWrapper(component ComponentDefinition, w LanguageWriter, indent st w.Writeln(" }") w.Writeln("") } - if (len(component.Errors.Errors) > 0) { + if len(component.Errors.Errors) > 0 { w.Writeln(" public static class EnumConversion {") for i := 0; i < len(component.Enums); i++ { enum := component.Enums[i] @@ -1013,7 +1011,7 @@ func buildJavaWrapper(component ComponentDefinition, w LanguageWriter, indent st for j := 0; j < len(enum.Options); j++ { w.Writeln(" case e%s: return %s_%s;", enum.Options[j].Name, strings.ToUpper(enum.Name), strings.ToUpper(enum.Options[j].Name)) } - w.Writeln(" default: throw new %sException(%sException.%s_ERROR_INVALIDPARAM, \"Unknown enum value : \" + value);", NameSpace, NameSpace, strings.ToUpper(NameSpace)) + w.Writeln(" default: throw new %sException(%sException.%s_ERROR_INVALIDPARAM, \"Unknown enum value : \" + value);", NameSpace, NameSpace, strings.ToUpper(NameSpace)) w.Writeln(" }") w.Writeln(" }") w.Writeln("") @@ -1022,7 +1020,7 @@ func buildJavaWrapper(component ComponentDefinition, w LanguageWriter, indent st for j := 0; j < len(enum.Options); j++ { w.Writeln(" case %s_%s: return %s.e%s;", strings.ToUpper(enum.Name), strings.ToUpper(enum.Options[j].Name), enum.Name, enum.Options[j].Name) } - w.Writeln(" default: throw new %sException(%sException.%s_ERROR_INVALIDPARAM, \"Unknown enum const : \" + value);", NameSpace, NameSpace, strings.ToUpper(NameSpace)) + w.Writeln(" default: throw new %sException(%sException.%s_ERROR_INVALIDPARAM, \"Unknown enum const : \" + value);", NameSpace, NameSpace, strings.ToUpper(NameSpace)) w.Writeln(" }") w.Writeln(" }") w.Writeln("") @@ -1032,7 +1030,7 @@ func buildJavaWrapper(component ComponentDefinition, w LanguageWriter, indent st } // Write callback functions - for j:=0; j.Make(Wrapper: T%sWrapper; Handle: T%sHandle): _T;", NameSpace, NameSpace, NameSpace) w.Writeln(" var") w.Writeln(" ClassTypeId: QWord;") - w.Writeln(" Obj: T%sBase;", strings.ToUpper(NameSpace)) + w.Writeln(" Obj: T%sBase;", strings.ToUpper(NameSpace)) w.Writeln(" begin") w.Writeln(" Result := nil;") w.Writeln(" Wrapper.CheckError(nil, Wrapper.%sBase_ClassTypeIdFunc(handle, ClassTypeId));", NameSpace) @@ -461,7 +461,7 @@ func buildDynamicPascalImplementation(component ComponentDefinition, w LanguageW w.Writeln(" function T%sPolymorphicFactoryMake%s(Wrapper: T%sWrapper; Handle: T%sHandle): %s;", NameSpace, class.ClassName, NameSpace, NameSpace, fullClassName) w.Writeln(" begin") w.Writeln(" Result := T%sPolymorphicFactory<%s, %s>.Make(Wrapper, Handle);", NameSpace, fullClassName, fullClassName) - w.Writeln(" end;") + w.Writeln(" end;") } w.Writeln("") w.Writeln("(*************************************************************************************************************************") @@ -916,9 +916,9 @@ func writePascalClassMethodImplementation(method ComponentDefinitionMethod, w La } defineCommands = append(defineCommands, "A"+param.ParamName+"Handle: T"+paramNameSpace+"Handle;") initCommands = append(initCommands, fmt.Sprintf("if Assigned(A%s) then", param.ParamName)) - initCommands = append(initCommands, "A"+param.ParamName+"Handle := A" + param.ParamName + ".TheHandle") + initCommands = append(initCommands, "A"+param.ParamName+"Handle := A"+param.ParamName+".TheHandle") initCommands = append(initCommands, fmt.Sprintf("else")) - if (param.ParamType == "optionalclass") { + if param.ParamType == "optionalclass" { initCommands = append(initCommands, "A"+param.ParamName+"Handle := nil;") } else { initCommands = append(initCommands, fmt.Sprintf(" raise E%sException.CreateCustomMessage(%s_ERROR_INVALIDPARAM, 'A%s is a nil value.');", NameSpace, strings.ToUpper(NameSpace), param.ParamName)) diff --git a/Source/buildbindingpython.go b/Source/buildbindingpython.go index 1837f9db..9cd098ed 100644 --- a/Source/buildbindingpython.go +++ b/Source/buildbindingpython.go @@ -48,42 +48,41 @@ func BuildBindingPythonDynamic(componentdefinition ComponentDefinition, outputFo namespace := componentdefinition.NameSpace libraryname := componentdefinition.LibraryName - - DynamicPythonImpl := path.Join(outputFolder, namespace+".py"); + + DynamicPythonImpl := path.Join(outputFolder, namespace+".py") log.Printf("Creating \"%s\"", DynamicPythonImpl) - dynpythonfile, err := CreateLanguageFile (DynamicPythonImpl, indentString) + dynpythonfile, err := CreateLanguageFile(DynamicPythonImpl, indentString) if err != nil { - return err; + return err } dynpythonfile.WritePythonLicenseHeader(componentdefinition, fmt.Sprintf("This is an autogenerated Python file in order to allow an easy\n use of %s", libraryname), true) - + err = buildDynamicPythonImplementation(componentdefinition, dynpythonfile) if err != nil { - return err; + return err } - - if (len(outputFolderExample) > 0) { - DynamicPythonExample := path.Join(outputFolderExample, namespace+"_Example"+".py"); - if (forceRecreation || !FileExists(DynamicPythonExample)) { + + if len(outputFolderExample) > 0 { + DynamicPythonExample := path.Join(outputFolderExample, namespace+"_Example"+".py") + if forceRecreation || !FileExists(DynamicPythonExample) { log.Printf("Creating \"%s\"", DynamicPythonExample) - dynpythonexamplefile, err := CreateLanguageFile (DynamicPythonExample, indentString) + dynpythonexamplefile, err := CreateLanguageFile(DynamicPythonExample, indentString) dynpythonexamplefile.WritePythonLicenseHeader(componentdefinition, fmt.Sprintf("This is an autogenerated Python application that demonstrates the\n usage of the Python bindings of %s", libraryname), true) err = buildDynamicPythonExample(componentdefinition, dynpythonexamplefile, outputFolder) if err != nil { - return err; + return err } } else { log.Printf("Omitting recreation of Python example \"%s\"", DynamicPythonExample) } } - - return nil; + return nil } func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w LanguageWriter) error { @@ -98,11 +97,10 @@ func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w w.Writeln("import os") w.Writeln("") - if len(componentdefinition.ImportedComponentDefinitions) > 0 { w.Writeln("import sys") w.Writeln("# Injected Components") - for _, subComponent := range(componentdefinition.ImportedComponentDefinitions) { + for _, subComponent := range componentdefinition.ImportedComponentDefinitions { subNameSpace := subComponent.NameSpace w.Writeln("sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"..\", \"%s_component\", \"Bindings\", \"Python\"))", subNameSpace) w.Writeln("import %s", subNameSpace) @@ -126,7 +124,6 @@ func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w w.Writeln(" return '%sException ' + str(self._code)", NameSpace) w.Writeln("") - w.Writeln("'''Definition of binding API version") w.Writeln("'''") w.Writeln("class BindingVersion(enum.IntEnum):") @@ -139,7 +136,7 @@ func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w w.Writeln("'''") w.Writeln("class ErrorCodes(enum.IntEnum):") w.Writeln(" SUCCESS = 0") - for i := 0; i 0) { + if len(componentdefinition.Enums) > 0 { w.Writeln("'''Definition of Enumerations") w.Writeln("'''") w.Writeln("") @@ -172,50 +169,50 @@ func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w w.Writeln(" return int(obj)") w.Writeln("") - for i := 0; i 0) { + + if len(componentdefinition.Structs) > 0 { w.Writeln("'''Definition of Structs") w.Writeln("'''") - for i := 0; i 0) { + if len(_struct.Members) > 0 { w.Writeln(" _pack_ = 1") w.Writeln(" _fields_ = [") - for j:= 0; j 0) { - memberType = fmt.Sprintf(typeFormatter + " * %d", memberType, member.Rows) + if member.Rows > 0 { + memberType = fmt.Sprintf(typeFormatter+" * %d", memberType, member.Rows) typeFormatter = "(%s)" } - if (member.Columns > 0) { - memberType = fmt.Sprintf(typeFormatter + " * %d", memberType, member.Columns) + if member.Columns > 0 { + memberType = fmt.Sprintf(typeFormatter+" * %d", memberType, member.Columns) typeFormatter = "(%s)" } w.Writeln(" (\"%s\", %s)%s", member.Name, memberType, comma) @@ -226,22 +223,22 @@ func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w w.Writeln("") } - if (len(componentdefinition.Functions) > 0) { + if len(componentdefinition.Functions) > 0 { w.Writeln("'''Definition of Function Types") w.Writeln("'''") - for i := 0; i 0 { w.Writeln("# Injected Components") - for _, subComponent := range(componentdefinition.ImportedComponentDefinitions) { + for _, subComponent := range componentdefinition.ImportedComponentDefinitions { subNameSpace := subComponent.NameSpace w.Writeln(" _%sWrapper = None", subNameSpace) } @@ -285,14 +282,14 @@ func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w w.Writeln(" try:") w.Writeln(" self.lib = ctypes.CDLL(path)") w.Writeln(" except Exception as e:") - w.Writeln(" raise E%sException(ErrorCodes.COULDNOTLOADLIBRARY, str(e) + '| \"'+path + '\"' )", NameSpace ) + w.Writeln(" raise E%sException(ErrorCodes.COULDNOTLOADLIBRARY, str(e) + '| \"'+path + '\"' )", NameSpace) w.Writeln(" ") w.Writeln(" self._loadFunctionTable()") w.Writeln(" elif symbolLookupMethodAddress is not None:") w.Writeln(" self.lib = FunctionTable()") w.Writeln(" self._loadFunctionTableFromMethod(symbolLookupMethodAddress)") w.Writeln(" else:") - w.Writeln(" raise E%sException(ErrorCodes.COULDNOTLOADLIBRARY, str(e))", NameSpace ) + w.Writeln(" raise E%sException(ErrorCodes.COULDNOTLOADLIBRARY, str(e))", NameSpace) w.Writeln(" ") w.Writeln(" self._checkBinaryVersion()") w.Writeln(" ") @@ -301,7 +298,7 @@ func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w w.Writeln(" try:") w.AddIndentationLevel(3) err := loadFunctionTableFromMethod(componentdefinition, w) - if (err!=nil) { + if err != nil { return err } w.AddIndentationLevel(-3) @@ -312,7 +309,7 @@ func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w w.Writeln(" def _loadFunctionTable(self):") w.Writeln(" try:") err = loadFunctionTable(componentdefinition, w) - if (err!=nil) { + if err != nil { return err } w.Writeln(" except AttributeError as ae:") @@ -325,7 +322,6 @@ func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w w.Writeln(" raise E%sException(ErrorCodes.INCOMPATIBLEBINARYVERSION)", NameSpace) w.Writeln(" ") - w.Writeln(" def checkError(self, instance, errorCode):") w.Writeln(" if errorCode != ErrorCodes.SUCCESS.value:") w.Writeln(" if instance:") @@ -334,33 +330,33 @@ func buildDynamicPythonImplementation(componentdefinition ComponentDefinition, w w.Writeln(" message,_ = self.%s(instance)", componentdefinition.Global.ErrorMethod) w.Writeln(" raise E%sException(errorCode, message)", NameSpace) w.Writeln(" ") - - for j:=0; j 0 { - theWrapperReference = theWrapperReference + "._" + subNameSpace + "Wrapper" - subNameSpace = subNameSpace + "." - } - postCallLines = append(postCallLines, fmt.Sprintf("if %sHandle:", param.ParamName)) - postCallLines = append(postCallLines, - fmt.Sprintf(" %sObject = %s._polymorphicFactory(%sHandle)", - param.ParamName, theWrapperReference, param.ParamName)) - postCallLines = append(postCallLines, fmt.Sprintf("else:")) - if (param.ParamType == "optionalclass") { - postCallLines = append(postCallLines, fmt.Sprintf(" %sObject = None", param.ParamName)) - } else { - postCallLines = append(postCallLines, fmt.Sprintf(" raise E%sException(ErrorCodes.INVALIDCAST, 'Invalid return/output value')", NameSpace)) - } + case "class", "optionalclass": + { + if retVals != "" { + retVals = retVals + ", " + } + preCallLines = append(preCallLines, fmt.Sprintf("%sHandle = %s()", param.ParamName, cParams[0].ParamCallType)) + newArgument := fmt.Sprintf("%sHandle", param.ParamName) + cArguments = cArguments + newArgument + cCheckArguments = cCheckArguments + newArgument + + theWrapperReference := wrapperReference + subNameSpace, _, _ := decomposeParamClassName(param.ParamClass) + if len(subNameSpace) > 0 { + theWrapperReference = theWrapperReference + "._" + subNameSpace + "Wrapper" + subNameSpace = subNameSpace + "." + } + postCallLines = append(postCallLines, fmt.Sprintf("if %sHandle:", param.ParamName)) + postCallLines = append(postCallLines, + fmt.Sprintf(" %sObject = %s._polymorphicFactory(%sHandle)", + param.ParamName, theWrapperReference, param.ParamName)) + postCallLines = append(postCallLines, fmt.Sprintf("else:")) + if param.ParamType == "optionalclass" { + postCallLines = append(postCallLines, fmt.Sprintf(" %sObject = None", param.ParamName)) + } else { + postCallLines = append(postCallLines, fmt.Sprintf(" raise E%sException(ErrorCodes.INVALIDCAST, 'Invalid return/output value')", NameSpace)) + } - - retVals = retVals + fmt.Sprintf("%sObject", param.ParamName) - } - case "string": { - if (retVals != "") { - retVals = retVals + ", "; + retVals = retVals + fmt.Sprintf("%sObject", param.ParamName) } - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[0].ParamName, cParams[0].ParamCallType)) - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[1].ParamName, cParams[1].ParamCallType)) - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(None)", cParams[2].ParamName, cParams[2].ParamCallType)) - - cCheckArguments = cCheckArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName - checkCallLines = append(checkCallLines, fmt.Sprintf("%s = %s(%s.value)", cParams[0].ParamName, cParams[0].ParamCallType, cParams[1].ParamName)) - checkCallLines = append(checkCallLines, fmt.Sprintf("%s = (ctypes.c_char * (%s.value))()", cParams[2].ParamName, cParams[1].ParamName)) - doCheckCall = true - cArguments = cArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName - retVals = retVals + cParams[2].ParamName + ".value.decode()" - } - case "basicarray": { - if (retVals != "") { - retVals = retVals + ", "; + case "string": + { + if retVals != "" { + retVals = retVals + ", " + } + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[0].ParamName, cParams[0].ParamCallType)) + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[1].ParamName, cParams[1].ParamCallType)) + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(None)", cParams[2].ParamName, cParams[2].ParamCallType)) + + cCheckArguments = cCheckArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName + checkCallLines = append(checkCallLines, fmt.Sprintf("%s = %s(%s.value)", cParams[0].ParamName, cParams[0].ParamCallType, cParams[1].ParamName)) + checkCallLines = append(checkCallLines, fmt.Sprintf("%s = (ctypes.c_char * (%s.value))()", cParams[2].ParamName, cParams[1].ParamName)) + doCheckCall = true + cArguments = cArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName + retVals = retVals + cParams[2].ParamName + ".value.decode()" } - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[0].ParamName, cParams[0].ParamCallType)) - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[1].ParamName, cParams[1].ParamCallType)) - preCallLines = append(preCallLines, fmt.Sprintf("%s = (%s*0)()", cParams[2].ParamName, cParams[2].ParamCallType)) + case "basicarray": + { + if retVals != "" { + retVals = retVals + ", " + } + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[0].ParamName, cParams[0].ParamCallType)) + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[1].ParamName, cParams[1].ParamCallType)) + preCallLines = append(preCallLines, fmt.Sprintf("%s = (%s*0)()", cParams[2].ParamName, cParams[2].ParamCallType)) - cCheckArguments = cCheckArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName - checkCallLines = append(checkCallLines, fmt.Sprintf("%s = %s(%s.value)", cParams[0].ParamName, cParams[0].ParamCallType, cParams[1].ParamName)) - checkCallLines = append(checkCallLines, fmt.Sprintf("%s = (%s * %s.value)()", cParams[2].ParamName, cParams[2].ParamCallType, cParams[1].ParamName)) - doCheckCall = true + cCheckArguments = cCheckArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName + checkCallLines = append(checkCallLines, fmt.Sprintf("%s = %s(%s.value)", cParams[0].ParamName, cParams[0].ParamCallType, cParams[1].ParamName)) + checkCallLines = append(checkCallLines, fmt.Sprintf("%s = (%s * %s.value)()", cParams[2].ParamName, cParams[2].ParamCallType, cParams[1].ParamName)) + doCheckCall = true - cArguments = cArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName - retVals = retVals + fmt.Sprintf("[%s[i] for i in range(%s.value)]", cParams[2].ParamName, cParams[1].ParamName) - } - case "structarray": { - if (retVals != "") { - retVals = retVals + ", "; + cArguments = cArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName + retVals = retVals + fmt.Sprintf("[%s[i] for i in range(%s.value)]", cParams[2].ParamName, cParams[1].ParamName) } - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[0].ParamName, cParams[0].ParamCallType)) - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[1].ParamName, cParams[1].ParamCallType)) - preCallLines = append(preCallLines, fmt.Sprintf("%s = (%s*0)()", cParams[2].ParamName, cParams[2].ParamCallType)) + case "structarray": + { + if retVals != "" { + retVals = retVals + ", " + } + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[0].ParamName, cParams[0].ParamCallType)) + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(0)", cParams[1].ParamName, cParams[1].ParamCallType)) + preCallLines = append(preCallLines, fmt.Sprintf("%s = (%s*0)()", cParams[2].ParamName, cParams[2].ParamCallType)) - cCheckArguments = cCheckArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName - checkCallLines = append(checkCallLines, fmt.Sprintf("%s = %s(%s.value)", cParams[0].ParamName, cParams[0].ParamCallType, cParams[1].ParamName)) - checkCallLines = append(checkCallLines, fmt.Sprintf("%s = (%s * %s.value)()", cParams[2].ParamName, cParams[2].ParamCallType, cParams[1].ParamName)) - doCheckCall = true + cCheckArguments = cCheckArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName + checkCallLines = append(checkCallLines, fmt.Sprintf("%s = %s(%s.value)", cParams[0].ParamName, cParams[0].ParamCallType, cParams[1].ParamName)) + checkCallLines = append(checkCallLines, fmt.Sprintf("%s = (%s * %s.value)()", cParams[2].ParamName, cParams[2].ParamCallType, cParams[1].ParamName)) + doCheckCall = true - cArguments = cArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName - retVals = retVals + fmt.Sprintf("[%s[i] for i in range(%s.value)]", cParams[2].ParamName, cParams[1].ParamName) - } - case "enum": { - if (retVals != "") { - retVals = retVals + ", "; + cArguments = cArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + ", " + cParams[2].ParamName + retVals = retVals + fmt.Sprintf("[%s[i] for i in range(%s.value)]", cParams[2].ParamName, cParams[1].ParamName) + } + case "enum": + { + if retVals != "" { + retVals = retVals + ", " + } + preCallLines = append(preCallLines, fmt.Sprintf("%s = ctypes.c_int32()", cParams[0].ParamName)) + cArguments = cArguments + cParams[0].ParamName + cCheckArguments = cCheckArguments + cParams[0].ParamName + retVals = retVals + fmt.Sprintf("%s(%s.value)", cParams[0].ParamCallType, cParams[0].ParamName) } - preCallLines = append(preCallLines, fmt.Sprintf("%s = ctypes.c_int32()", cParams[0].ParamName)) - cArguments = cArguments + cParams[0].ParamName - cCheckArguments = cCheckArguments + cParams[0].ParamName - retVals = retVals + fmt.Sprintf("%s(%s.value)", cParams[0].ParamCallType, cParams[0].ParamName) - } case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double", "bool", "pointer": - if (retVals != "") { - retVals = retVals + ", "; + if retVals != "" { + retVals = retVals + ", " } preCallLines = append(preCallLines, fmt.Sprintf("%s = %s()", cParams[0].ParamName, cParams[0].ParamCallType)) cArguments = cArguments + cParams[0].ParamName - cCheckArguments = cCheckArguments + cParams[0].ParamName + cCheckArguments = cCheckArguments + cParams[0].ParamName retVals = retVals + cParams[0].ParamName + ".value" - case "struct": { - if (retVals != "") { - retVals = retVals + ", "; + case "struct": + { + if retVals != "" { + retVals = retVals + ", " + } + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s()", cParams[0].ParamName, cParams[0].ParamCallType)) + cArguments = cArguments + cParams[0].ParamName + cCheckArguments = cCheckArguments + cParams[0].ParamName + retVals = retVals + fmt.Sprintf("%s", cParams[0].ParamName) } - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s()", cParams[0].ParamName, cParams[0].ParamCallType)) - cArguments = cArguments + cParams[0].ParamName - cCheckArguments = cCheckArguments + cParams[0].ParamName - retVals = retVals + fmt.Sprintf("%s", cParams[0].ParamName) - } default: return fmt.Errorf("Invalid parameter of type \"%s\" used as pass=\"%s\"", param.ParamType, param.ParamPass) } case "in": - if (cArguments != "") { - cArguments = cArguments + ", "; + if cArguments != "" { + cArguments = cArguments + ", " } - if (cCheckArguments != "") { + if cCheckArguments != "" { cCheckArguments = cCheckArguments + ", " } - pythonInParams = pythonInParams + ", "; - + pythonInParams = pythonInParams + ", " + switch param.ParamType { case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double", "bool", "pointer": preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(%s)", cParams[0].ParamName, cParams[0].ParamCallType, param.ParamName)) pythonInParams = pythonInParams + param.ParamName cArguments = cArguments + cParams[0].ParamName - cCheckArguments = cCheckArguments + cParams[0].ParamName - case "enum": { - pythonInParams = pythonInParams + param.ParamName - cArguments = cArguments + param.ParamName - cCheckArguments = cCheckArguments + param.ParamName - } - case "string": { - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(str.encode(%s))", cParams[0].ParamName, cParams[0].ParamCallType, param.ParamName)) - pythonInParams = pythonInParams + param.ParamName - cArguments = cArguments + cParams[0].ParamName - cCheckArguments = cCheckArguments + cParams[0].ParamName - } - case "basicarray": { - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(len(%s))", cParams[0].ParamName, cParams[0].ParamCallType, param.ParamName)) - preCallLines = append(preCallLines, fmt.Sprintf("%s = (%s*len(%s))(*%s)", cParams[1].ParamName, cParams[1].ParamCallType, param.ParamName, param.ParamName)) - pythonInParams = pythonInParams + param.ParamName - cArguments = cArguments + cParams[0].ParamName + ", " + cParams[1].ParamName - cCheckArguments = cCheckArguments + cParams[0].ParamName + ", " + cParams[1].ParamName - } - case "structarray": { - preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(len(%s))", cParams[0].ParamName, cParams[0].ParamCallType, param.ParamName)) - preCallLines = append(preCallLines, fmt.Sprintf("%s = (%s*len(%s))(*%s)", cParams[1].ParamName, cParams[1].ParamCallType, param.ParamName, param.ParamName)) - pythonInParams = pythonInParams + param.ParamName - cArguments = cArguments + cParams[0].ParamName + ", " + cParams[1].ParamName - cCheckArguments = cCheckArguments + cParams[0].ParamName + ", " + cParams[1].ParamName - } - case "struct": { - pythonInParams = pythonInParams + param.ParamName - cArguments = cArguments + param.ParamName - cCheckArguments = cCheckArguments + param.ParamName - } - case "class", "optionalclass": { - pythonInParams = pythonInParams + param.ParamName + "Object" - preCallLines = append(preCallLines, fmt.Sprintf("%sHandle = None", param.ParamName)) - preCallLines = append(preCallLines, fmt.Sprintf("if %sObject:", param.ParamName)) - preCallLines = append(preCallLines, fmt.Sprintf(" %sHandle = %sObject._handle", param.ParamName, param.ParamName)) - if (param.ParamType == "class") { - preCallLines = append(preCallLines, fmt.Sprintf("else:")) - preCallLines = append(preCallLines, fmt.Sprintf(" raise E%sException(ErrorCodes.INVALIDPARAM, 'Invalid return/output value')", NameSpace)) + cCheckArguments = cCheckArguments + cParams[0].ParamName + case "enum": + { + pythonInParams = pythonInParams + param.ParamName + cArguments = cArguments + param.ParamName + cCheckArguments = cCheckArguments + param.ParamName + } + case "string": + { + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(str.encode(%s))", cParams[0].ParamName, cParams[0].ParamCallType, param.ParamName)) + pythonInParams = pythonInParams + param.ParamName + cArguments = cArguments + cParams[0].ParamName + cCheckArguments = cCheckArguments + cParams[0].ParamName + } + case "basicarray": + { + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(len(%s))", cParams[0].ParamName, cParams[0].ParamCallType, param.ParamName)) + preCallLines = append(preCallLines, fmt.Sprintf("%s = (%s*len(%s))(*%s)", cParams[1].ParamName, cParams[1].ParamCallType, param.ParamName, param.ParamName)) + pythonInParams = pythonInParams + param.ParamName + cArguments = cArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + cCheckArguments = cCheckArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + } + case "structarray": + { + preCallLines = append(preCallLines, fmt.Sprintf("%s = %s(len(%s))", cParams[0].ParamName, cParams[0].ParamCallType, param.ParamName)) + preCallLines = append(preCallLines, fmt.Sprintf("%s = (%s*len(%s))(*%s)", cParams[1].ParamName, cParams[1].ParamCallType, param.ParamName, param.ParamName)) + pythonInParams = pythonInParams + param.ParamName + cArguments = cArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + cCheckArguments = cCheckArguments + cParams[0].ParamName + ", " + cParams[1].ParamName + } + case "struct": + { + pythonInParams = pythonInParams + param.ParamName + cArguments = cArguments + param.ParamName + cCheckArguments = cCheckArguments + param.ParamName + } + case "class", "optionalclass": + { + pythonInParams = pythonInParams + param.ParamName + "Object" + preCallLines = append(preCallLines, fmt.Sprintf("%sHandle = None", param.ParamName)) + preCallLines = append(preCallLines, fmt.Sprintf("if %sObject:", param.ParamName)) + preCallLines = append(preCallLines, fmt.Sprintf(" %sHandle = %sObject._handle", param.ParamName, param.ParamName)) + if param.ParamType == "class" { + preCallLines = append(preCallLines, fmt.Sprintf("else:")) + preCallLines = append(preCallLines, fmt.Sprintf(" raise E%sException(ErrorCodes.INVALIDPARAM, 'Invalid return/output value')", NameSpace)) + } + cArguments = cArguments + param.ParamName + "Handle" + cCheckArguments = cCheckArguments + param.ParamName + "Handle" + } + case "functiontype": + { + pythonInParams = pythonInParams + param.ParamName + "Func" + cArguments = cArguments + param.ParamName + "Func" + cCheckArguments = cCheckArguments + param.ParamName + "Func" } - cArguments = cArguments + param.ParamName + "Handle" - cCheckArguments = cCheckArguments + param.ParamName + "Handle" - } - case "functiontype": { - pythonInParams = pythonInParams + param.ParamName + "Func" - cArguments = cArguments + param.ParamName + "Func" - cCheckArguments = cCheckArguments + param.ParamName + "Func" - } default: return fmt.Errorf("Invalid parameter of type \"%s\" used as pass=\"%s\"", param.ParamType, param.ParamPass) } } } - + exportName := GetCExportName(NameSpace, ClassName, method, isGlobal) - + w.Writeln(" def %s(self%s):", method.MethodName, pythonInParams) w.Writelns(" ", preCallLines) - if (doCheckCall) { + if doCheckCall { w.Writeln(" %s.checkError(%s, %s.lib.%s(%s))", wrapperReference, selfReference, wrapperReference, exportName, cCheckArguments) w.Writelns(" ", checkCallLines) } @@ -1034,7 +1040,7 @@ func buildDynamicPythonExample(componentdefinition ComponentDefinition, w Langua w.Writeln("import os") w.Writeln("import sys") w.Writeln("sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"..\", \"..\", \"Bindings\", \"Python\"))") - w.Writeln("import %s",NameSpace ) + w.Writeln("import %s", NameSpace) w.Writeln("") w.Writeln("") @@ -1044,12 +1050,12 @@ func buildDynamicPythonExample(componentdefinition ComponentDefinition, w Langua w.Writeln(" ") w.Writeln(" major, minor, micro = wrapper.%s()", componentdefinition.Global.VersionMethod) w.Writeln(" print(\"%s version: {:d}.{:d}.{:d}\".format(major, minor, micro), end=\"\")", NameSpace) - if len(componentdefinition.Global.PrereleaseMethod)>0 { + if len(componentdefinition.Global.PrereleaseMethod) > 0 { w.Writeln(" hasInfo, prereleaseinfo = wrapper.%s()", componentdefinition.Global.PrereleaseMethod) w.Writeln(" if hasInfo:") w.Writeln(" print(\"-\"+prereleaseinfo, end=\"\")") } - if len(componentdefinition.Global.BuildinfoMethod)>0 { + if len(componentdefinition.Global.BuildinfoMethod) > 0 { w.Writeln(" hasInfo, buildinfo = wrapper.%s()", componentdefinition.Global.BuildinfoMethod) w.Writeln(" if hasInfo:") w.Writeln(" print(\"+\"+buildinfo, end=\"\")") diff --git a/Source/buildimplementationcpp.go b/Source/buildimplementationcpp.go index 16acaee5..b443f7c9 100644 --- a/Source/buildimplementationcpp.go +++ b/Source/buildimplementationcpp.go @@ -46,12 +46,12 @@ import ( func BuildImplementationCPP(component ComponentDefinition, outputFolder string, stubOutputFolder string, projectOutputFolder string, implementation ComponentDefinitionImplementation, suppressStub bool, suppressInterfaces bool) error { forceRecreation := false - doJournal := len (component.Global.JournalMethod) > 0; - - NameSpace := component.NameSpace; + doJournal := len(component.Global.JournalMethod) > 0 + + NameSpace := component.NameSpace ImplementationSubNameSpace := "Impl" - LibraryName := component.LibraryName; - BaseName := component.BaseName; + LibraryName := component.LibraryName + BaseName := component.BaseName indentString := getIndentationString(implementation.Indentation) stubIdentifier := "" @@ -59,11 +59,11 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, stubIdentifier = "_" + strings.ToLower(implementation.StubIdentifier) } - if (!suppressInterfaces) { + if !suppressInterfaces { - IntfExceptionHeaderName := path.Join(outputFolder, BaseName+"_interfaceexception.hpp"); + IntfExceptionHeaderName := path.Join(outputFolder, BaseName+"_interfaceexception.hpp") log.Printf("Creating \"%s\"", IntfExceptionHeaderName) - hInternalExceptionHeaderFile, err := CreateLanguageFile (IntfExceptionHeaderName, indentString) + hInternalExceptionHeaderFile, err := CreateLanguageFile(IntfExceptionHeaderName, indentString) if err != nil { return err } @@ -71,9 +71,9 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, fmt.Sprintf("This is an autogenerated C++ Header file with the basic internal\n exception type in order to allow an easy use of %s", LibraryName), true) - IntfExceptionImplName := path.Join(outputFolder, BaseName+"_interfaceexception.cpp"); + IntfExceptionImplName := path.Join(outputFolder, BaseName+"_interfaceexception.cpp") log.Printf("Creating \"%s\"", IntfExceptionImplName) - hInternalExceptionImplFile, err := CreateLanguageFile (IntfExceptionImplName, indentString) + hInternalExceptionImplFile, err := CreateLanguageFile(IntfExceptionImplName, indentString) if err != nil { return err } @@ -81,14 +81,14 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, fmt.Sprintf("This is an autogenerated C++ Implementation file with the basic internal\n exception type in order to allow an easy use of %s", LibraryName), true) - err = buildCPPInternalException(hInternalExceptionHeaderFile, hInternalExceptionImplFile, NameSpace, BaseName ) + err = buildCPPInternalException(hInternalExceptionHeaderFile, hInternalExceptionImplFile, NameSpace, BaseName) if err != nil { return err } - IntfHeaderName := path.Join(outputFolder, BaseName+"_interfaces.hpp"); + IntfHeaderName := path.Join(outputFolder, BaseName+"_interfaces.hpp") log.Printf("Creating \"%s\"", IntfHeaderName) - interfaceshppfile, err := CreateLanguageFile (IntfHeaderName, indentString) + interfaceshppfile, err := CreateLanguageFile(IntfHeaderName, indentString) if err != nil { return err } @@ -100,7 +100,7 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, return err } - IntfWrapperImplName := path.Join(outputFolder, BaseName+"_interfacewrapper.cpp"); + IntfWrapperImplName := path.Join(outputFolder, BaseName+"_interfacewrapper.cpp") log.Printf("Creating \"%s\"", IntfWrapperImplName) cppWrapperfile, err := CreateLanguageFile(IntfWrapperImplName, indentString) if err != nil { @@ -114,18 +114,18 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, return err } - if (doJournal) { - IntfJournalHeaderName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.hpp"); + if doJournal { + IntfJournalHeaderName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.hpp") log.Printf("Creating \"%s\"", IntfJournalHeaderName) - interfacejournalhppfile, err := CreateLanguageFile (IntfJournalHeaderName, indentString) + interfacejournalhppfile, err := CreateLanguageFile(IntfJournalHeaderName, indentString) if err != nil { return err } interfacejournalhppfile.WriteCLicenseHeader(component, fmt.Sprintf("This is an autogenerated C++ header file in order to allow easy\ndevelopment of %s. It provides an automatic Journaling mechanism for the library implementation.", LibraryName), true) - - IntfJournalImplName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.cpp"); + + IntfJournalImplName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.cpp") log.Printf("Creating \"%s\"", IntfJournalImplName) interfacejournalcppfile, err := CreateLanguageFile(IntfJournalImplName, indentString) if err != nil { @@ -134,33 +134,33 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, interfacejournalcppfile.WriteCLicenseHeader(component, fmt.Sprintf("This is an autogenerated C++ implementation file in order to allow easy\ndevelopment of %s. It provides an automatic Journaling mechanism for the library implementation.", LibraryName), true) - + err = buildJournalingCPP(component, interfacejournalhppfile, interfacejournalcppfile) if err != nil { return err } } - + } - if (!suppressStub) { + if !suppressStub { err := buildCPPStub(component, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier, forceRecreation) if err != nil { return err } - IntfWrapperStubName := path.Join(stubOutputFolder, BaseName + stubIdentifier + ".cpp") - if forceRecreation || (!FileExists(IntfWrapperStubName) ) { + IntfWrapperStubName := path.Join(stubOutputFolder, BaseName+stubIdentifier+".cpp") + if forceRecreation || (!FileExists(IntfWrapperStubName)) { log.Printf("Creating \"%s\"", IntfWrapperStubName) - stubfile, err := CreateLanguageFile (IntfWrapperStubName, indentString) + stubfile, err := CreateLanguageFile(IntfWrapperStubName, indentString) if err != nil { return err } stubfile.WriteCLicenseHeader(component, fmt.Sprintf("This is an autogenerated C++ implementation file in order to allow easy\ndevelopment of %s. It needs to be generated only once.", LibraryName), true) - + err = buildCPPGlobalStubFile(component, stubfile, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName) if err != nil { return err @@ -169,8 +169,8 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, log.Printf("Omitting recreation of implementation stub \"%s\"", IntfWrapperStubName) } - if ( len(projectOutputFolder) > 0 ) { - CMakeListsFileName := path.Join(projectOutputFolder, "CMakeLists.txt"); + if len(projectOutputFolder) > 0 { + CMakeListsFileName := path.Join(projectOutputFolder, "CMakeLists.txt") if forceRecreation || !FileExists(CMakeListsFileName) { log.Printf("Creating CMake-Project \"%s\" for CPP Implementation", CMakeListsFileName) CMakeListsFile, err := CreateLanguageFile(CMakeListsFileName, indentString) @@ -185,97 +185,97 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, log.Printf("Omitting recreation of CMake-Project \"%s\" for CPP Implementation", CMakeListsFileName) } } - + } return nil } -func buildCPPInternalException(wHeader LanguageWriter, wImpl LanguageWriter, NameSpace string, BaseName string) (error) { - wHeader.Writeln("#ifndef __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)); - wHeader.Writeln("#define __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)); - wHeader.Writeln(""); - - wHeader.Writeln("#include "); - wHeader.Writeln("#include "); - - wHeader.Writeln("#include \"%s_types.hpp\"", BaseName); - wHeader.Writeln(""); - - wHeader.Writeln("/*************************************************************************************************************************"); - wHeader.Writeln(" Class E%sInterfaceException", NameSpace); - wHeader.Writeln("**************************************************************************************************************************/"); - wHeader.Writeln(""); - wHeader.Writeln(""); - wHeader.Writeln("class E%sInterfaceException : public std::exception {", NameSpace); - wHeader.Writeln("protected:"); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Error code for the Exception."); - wHeader.Writeln(" */"); - wHeader.Writeln(" %sResult m_errorCode;", NameSpace); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Error message for the Exception."); - wHeader.Writeln(" */"); - wHeader.Writeln(" std::string m_errorMessage;"); +func buildCPPInternalException(wHeader LanguageWriter, wImpl LanguageWriter, NameSpace string, BaseName string) error { + wHeader.Writeln("#ifndef __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)) + wHeader.Writeln("#define __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)) + wHeader.Writeln("") + + wHeader.Writeln("#include ") + wHeader.Writeln("#include ") + wHeader.Writeln("#include ") + + wHeader.Writeln("#include \"%s_types.hpp\"", BaseName) + wHeader.Writeln("") + + wHeader.Writeln("/*************************************************************************************************************************") + wHeader.Writeln(" Class E%sInterfaceException", NameSpace) + wHeader.Writeln("**************************************************************************************************************************/") + wHeader.Writeln("") + wHeader.Writeln("") + wHeader.Writeln("class E%sInterfaceException : public std::exception {", NameSpace) + wHeader.Writeln("protected:") + wHeader.Writeln(" /**") + wHeader.Writeln(" * Error code for the Exception.") + wHeader.Writeln(" */") + wHeader.Writeln(" %sResult m_errorCode;", NameSpace) + wHeader.Writeln(" /**") + wHeader.Writeln(" * Error message for the Exception.") + wHeader.Writeln(" */") + wHeader.Writeln(" std::string m_errorMessage;") + wHeader.Writeln("") + wHeader.Writeln("public:") + wHeader.Writeln(" /**") + wHeader.Writeln(" * Exception Constructor.") + wHeader.Writeln(" */") + wHeader.Writeln(" E%sInterfaceException(%sResult errorCode);", NameSpace, NameSpace) + wHeader.Writeln("") + wHeader.Writeln(" /**") + wHeader.Writeln(" * Custom Exception Constructor.") + wHeader.Writeln(" */") + wHeader.Writeln(" E%sInterfaceException(%sResult errorCode, std::string errorMessage);", NameSpace, NameSpace) + wHeader.Writeln("") + wHeader.Writeln(" /**") + wHeader.Writeln(" * Returns error code") + wHeader.Writeln(" */") + wHeader.Writeln(" %sResult getErrorCode();", NameSpace) + wHeader.Writeln(" /**") + wHeader.Writeln(" * Returns error message") + wHeader.Writeln(" */") + wHeader.Writeln(" const char* what() const noexcept override;") + wHeader.Writeln("};") wHeader.Writeln("") - wHeader.Writeln("public:"); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Exception Constructor."); - wHeader.Writeln(" */"); - wHeader.Writeln(" E%sInterfaceException(%sResult errorCode);", NameSpace, NameSpace); - wHeader.Writeln(""); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Custom Exception Constructor."); - wHeader.Writeln(" */"); - wHeader.Writeln(" E%sInterfaceException(%sResult errorCode, std::string errorMessage);", NameSpace, NameSpace); - wHeader.Writeln(""); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Returns error code"); - wHeader.Writeln(" */"); - wHeader.Writeln(" %sResult getErrorCode();", NameSpace); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Returns error message"); - wHeader.Writeln(" */"); - wHeader.Writeln(" const char* what() const noexcept override;"); - wHeader.Writeln("};"); - wHeader.Writeln(""); - - wHeader.Writeln("#endif // __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)); - - - wImpl.Writeln(""); - wImpl.Writeln("#include "); - wImpl.Writeln(""); - wImpl.Writeln("#include \"%s_interfaceexception.hpp\"", BaseName); - wImpl.Writeln(""); - - wImpl.Writeln("/*************************************************************************************************************************"); - wImpl.Writeln(" Class E%sInterfaceException", NameSpace); - wImpl.Writeln("**************************************************************************************************************************/"); - wImpl.Writeln("E%sInterfaceException::E%sInterfaceException(%sResult errorCode)", NameSpace, NameSpace, NameSpace); - wImpl.Writeln(" : m_errorMessage(%s_GETERRORSTRING (errorCode))", strings.ToUpper (NameSpace)); - wImpl.Writeln("{"); - wImpl.Writeln(" m_errorCode = errorCode;"); - wImpl.Writeln("}"); - wImpl.Writeln(""); - wImpl.Writeln("E%sInterfaceException::E%sInterfaceException(%sResult errorCode, std::string errorMessage)", NameSpace, NameSpace, NameSpace); - wImpl.Writeln(" : m_errorMessage(errorMessage + \" (\" + std::to_string (errorCode) + \")\")"); - wImpl.Writeln("{"); - wImpl.Writeln(" m_errorCode = errorCode;"); - wImpl.Writeln("}"); - wImpl.Writeln(""); - wImpl.Writeln("%sResult E%sInterfaceException::getErrorCode ()", NameSpace, NameSpace); - wImpl.Writeln("{"); - wImpl.Writeln(" return m_errorCode;"); - wImpl.Writeln("}"); - wImpl.Writeln(""); - wImpl.Writeln("const char * E%sInterfaceException::what () const noexcept", NameSpace); - wImpl.Writeln("{"); - wImpl.Writeln(" return m_errorMessage.c_str();"); - wImpl.Writeln("}"); - wImpl.Writeln(""); - - return nil; + + wHeader.Writeln("#endif // __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)) + + wImpl.Writeln("") + wImpl.Writeln("#include ") + wImpl.Writeln("") + wImpl.Writeln("#include \"%s_interfaceexception.hpp\"", BaseName) + wImpl.Writeln("") + + wImpl.Writeln("/*************************************************************************************************************************") + wImpl.Writeln(" Class E%sInterfaceException", NameSpace) + wImpl.Writeln("**************************************************************************************************************************/") + wImpl.Writeln("E%sInterfaceException::E%sInterfaceException(%sResult errorCode)", NameSpace, NameSpace, NameSpace) + wImpl.Writeln(" : m_errorMessage(%s_GETERRORSTRING (errorCode))", strings.ToUpper(NameSpace)) + wImpl.Writeln("{") + wImpl.Writeln(" m_errorCode = errorCode;") + wImpl.Writeln("}") + wImpl.Writeln("") + wImpl.Writeln("E%sInterfaceException::E%sInterfaceException(%sResult errorCode, std::string errorMessage)", NameSpace, NameSpace, NameSpace) + wImpl.Writeln(" : m_errorMessage(errorMessage + \" (\" + std::to_string (errorCode) + \")\")") + wImpl.Writeln("{") + wImpl.Writeln(" m_errorCode = errorCode;") + wImpl.Writeln("}") + wImpl.Writeln("") + wImpl.Writeln("%sResult E%sInterfaceException::getErrorCode ()", NameSpace, NameSpace) + wImpl.Writeln("{") + wImpl.Writeln(" return m_errorCode;") + wImpl.Writeln("}") + wImpl.Writeln("") + wImpl.Writeln("const char * E%sInterfaceException::what () const noexcept", NameSpace) + wImpl.Writeln("{") + wImpl.Writeln(" return m_errorMessage.c_str();") + wImpl.Writeln("}") + wImpl.Writeln("") + + return nil } func writeSharedPtrTemplate(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) { @@ -314,34 +314,34 @@ func writeSharedPtrTemplate(component ComponentDefinition, w LanguageWriter, Cla w.Writeln("") } -func writeCPPClassInterface(component ComponentDefinition, class ComponentDefinitionClass, w LanguageWriter, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string) (error) { +func writeCPPClassInterface(component ComponentDefinition, class ComponentDefinitionClass, w LanguageWriter, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string) error { w.Writeln("") w.Writeln("/*************************************************************************************************************************") w.Writeln(" Class interface for %s ", class.ClassName) w.Writeln("**************************************************************************************************************************/") w.Writeln("") parentClassString := " " - if (!component.isBaseClass(class)) { + if !component.isBaseClass(class) { parentClassString = " : public virtual " - if (class.ParentClass == "") { + if class.ParentClass == "" { parentClassString += fmt.Sprintf("I%s%s ", ClassIdentifier, component.Global.BaseClassName) } else { parentClassString += fmt.Sprintf("I%s%s ", ClassIdentifier, class.ParentClass) } } - + classInterfaceName := fmt.Sprintf("I%s%s", ClassIdentifier, class.ClassName) w.Writeln("class %s%s{", classInterfaceName, parentClassString) - if (component.isStringOutBaseClass(class)) { + if component.isStringOutBaseClass(class) { w.Writeln("private:") w.Writeln(" std::unique_ptr m_ParameterCache;") - + } w.Writeln("public:") - if (component.isBaseClass(class)) { + if component.isBaseClass(class) { w.Writeln(" /**") w.Writeln(" * %s::~%s - virtual destructor of %s", classInterfaceName, classInterfaceName, classInterfaceName) w.Writeln(" */") @@ -354,7 +354,7 @@ func writeCPPClassInterface(component ComponentDefinition, class ComponentDefini return err } w.Writeln("%s", methodstring) - argument := "p"+releaseBaseClassInterfaceMethod.Params[0].ParamName + argument := "p" + releaseBaseClassInterfaceMethod.Params[0].ParamName w.Writeln(" {") w.Writeln(" if (%s) {", argument) w.Writeln(" %s->%s();", argument, DecRefCountMethod().MethodName) @@ -368,7 +368,7 @@ func writeCPPClassInterface(component ComponentDefinition, class ComponentDefini return err } w.Writeln("%s", methodstring) - argument = "p"+acquireBaseClassInterfaceMethod.Params[0].ParamName + argument = "p" + acquireBaseClassInterfaceMethod.Params[0].ParamName w.Writeln(" {") w.Writeln(" if (%s) {", argument) w.Writeln(" %s->%s();", argument, IncRefCountMethod().MethodName) @@ -392,36 +392,36 @@ func writeCPPClassInterface(component ComponentDefinition, class ComponentDefini } } - if (component.isStringOutBaseClass(class)) { - - w.Writeln("") + if component.isStringOutBaseClass(class) { + + w.Writeln("") w.Writeln(" /**") w.Writeln(" * %s::_setCache - set parameter cache of object", classInterfaceName) w.Writeln(" */") - w.Writeln(" void _setCache(ParameterCache * pCache)") - w.Writeln(" {") - w.Writeln(" m_ParameterCache.reset(pCache);") - w.Writeln(" }") - w.Writeln("") - + w.Writeln(" void _setCache(ParameterCache * pCache)") + w.Writeln(" {") + w.Writeln(" m_ParameterCache.reset(pCache);") + w.Writeln(" }") + w.Writeln("") + w.Writeln(" /**") w.Writeln(" * %s::_getCache - returns parameter cache of object", classInterfaceName) w.Writeln(" */") - w.Writeln(" ParameterCache* _getCache()") - w.Writeln(" {") - w.Writeln(" return m_ParameterCache.get();") - w.Writeln(" }") - w.Writeln("") + w.Writeln(" ParameterCache* _getCache()") + w.Writeln(" {") + w.Writeln(" return m_ParameterCache.get();") + w.Writeln(" }") + w.Writeln("") } - if (component.isBaseClass(class)) { + if component.isBaseClass(class) { methodstring, _, err := buildCPPInterfaceMethodDeclaration(component.classTypeIdMethod(), class.ClassName, NameSpace, ClassIdentifier, BaseName, w.IndentString, false, true, true) if err != nil { return err } // Only IBase class has pure virtual ClassTypeId method. It's needed for proper interpretation of "override" in deriver interface classes. w.Writeln("%s;", methodstring) - + } else { methodstring, _, err := buildCPPInterfaceMethodDeclaration(component.classTypeIdMethod(), class.ClassName, NameSpace, ClassIdentifier, BaseName, w.IndentString, false, false, true) if err != nil { @@ -431,8 +431,8 @@ func writeCPPClassInterface(component ComponentDefinition, class ComponentDefini w.Writeln("%s", methodstring) w.Writeln(" {") w.Writeln(" return 0x%XUL; // First 64 bits of SHA1 of a string: \"%s\"", classTypeId, chashHashString) - w.Writeln(" }") - w.Writeln("") + w.Writeln(" }") + w.Writeln("") } for j := 0; j < len(class.Methods); j++ { @@ -470,7 +470,6 @@ func writeClassDefinitions(component ComponentDefinition, w LanguageWriter, Name } } - func writeParameterCacheDefinitions(component ComponentDefinition, w LanguageWriter, NameSpaceImplementation string, ClassIdentifier string) { w.Writeln("") @@ -483,23 +482,23 @@ func writeParameterCacheDefinitions(component ComponentDefinition, w LanguageWri w.Writeln(" virtual ~ParameterCache() {}") w.Writeln("};") w.Writeln("") - - maxParamCount := component.countMaxOutParameters (); - + + maxParamCount := component.countMaxOutParameters() + for paramCount := uint32(1); paramCount <= maxParamCount; paramCount++ { - - classString := "class T1"; - constructorString := "const T1 & param1"; - assignmentString := "m_param1 (param1)"; - retrieveString := "T1 & param1"; + + classString := "class T1" + constructorString := "const T1 & param1" + assignmentString := "m_param1 (param1)" + retrieveString := "T1 & param1" for paramIdx := uint32(2); paramIdx <= paramCount; paramIdx++ { - classString += fmt.Sprintf (", class T%d", paramIdx); - constructorString += fmt.Sprintf (", const T%d & param%d", paramIdx, paramIdx); - assignmentString += fmt.Sprintf (", m_param%d (param%d)", paramIdx, paramIdx); - retrieveString += fmt.Sprintf (", T%d & param%d", paramIdx, paramIdx); + classString += fmt.Sprintf(", class T%d", paramIdx) + constructorString += fmt.Sprintf(", const T%d & param%d", paramIdx, paramIdx) + assignmentString += fmt.Sprintf(", m_param%d (param%d)", paramIdx, paramIdx) + retrieveString += fmt.Sprintf(", T%d & param%d", paramIdx, paramIdx) } - w.Writeln("template <%s> class ParameterCache_%d : public ParameterCache {", classString, paramCount); + w.Writeln("template <%s> class ParameterCache_%d : public ParameterCache {", classString, paramCount) w.Writeln(" private:") for paramIdx := uint32(1); paramIdx <= paramCount; paramIdx++ { w.Writeln(" T%d m_param%d;", paramIdx, paramIdx) @@ -520,9 +519,8 @@ func writeParameterCacheDefinitions(component ComponentDefinition, w LanguageWri w.Writeln("") } - -} +} func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpaceImplementation string, ClassIdentifier string) error { NameSpace := component.NameSpace @@ -539,7 +537,7 @@ func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpa w.Writeln("#include \"%s_types.hpp\"", BaseName) w.Writeln("") w.Writeln("") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { w.Writeln("#include \"%s_dynamic.hpp\"", subComponent.BaseName) } w.Writeln("") @@ -554,7 +552,7 @@ func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpa w.Writeln("*/") for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] - w.Writeln("class I%s%s;", ClassIdentifier, class.ClassName); + w.Writeln("class I%s%s;", ClassIdentifier, class.ClassName) } w.Writeln("") w.Writeln("") @@ -573,19 +571,19 @@ func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpa if len(component.ImportedComponentDefinitions) > 0 { w.Writeln(" // Injected Components") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { subNameSpace := subComponent.NameSpace w.Writeln(" static %s::PWrapper sP%sWrapper;", subNameSpace, subNameSpace) } w.Writeln("") } - global := component.Global; + global := component.Global for j := 0; j < len(global.Methods); j++ { method := global.Methods[j] // Omit special functions that are automatically implemented - isSpecialFunction, err := CheckHeaderSpecialFunction(method, global); + isSpecialFunction, err := CheckHeaderSpecialFunction(method, global) if err != nil { return err } @@ -603,10 +601,10 @@ func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpa } w.Writeln("};") w.Writeln("") - + w.Writeln("%sResult %s_GetProcAddress (const char * pProcName, void ** ppProcAddress);", NameSpace, NameSpace) w.Writeln("") - + w.Writeln("} // namespace %s", NameSpaceImplementation) w.Writeln("} // namespace %s", NameSpace) w.Writeln("") @@ -630,7 +628,7 @@ func buildCPPGlobalStubFile(component ComponentDefinition, stubfile LanguageWrit if len(component.ImportedComponentDefinitions) > 0 { stubfile.Writeln("// Injected Components") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { subNameSpace := subComponent.NameSpace stubfile.Writeln("%s::PWrapper C%sWrapper::sP%sWrapper;", subNameSpace, ClassIdentifier, subNameSpace) } @@ -641,9 +639,9 @@ func buildCPPGlobalStubFile(component ComponentDefinition, stubfile LanguageWrit method := component.Global.Methods[j] thisMethodDefaultImpl := defaultImplementation - + // Omit special functions that are automatically implemented - isSpecialFunction, err := CheckHeaderSpecialFunction(method, component.Global); + isSpecialFunction, err := CheckHeaderSpecialFunction(method, component.Global) if err != nil { return err } @@ -651,31 +649,31 @@ func buildCPPGlobalStubFile(component ComponentDefinition, stubfile LanguageWrit (isSpecialFunction == eSpecialMethodSymbolLookup) { continue } - if (isSpecialFunction == eSpecialMethodVersion) { + if isSpecialFunction == eSpecialMethodVersion { var versionImplementation []string versionImplementation = append(versionImplementation, fmt.Sprintf("n%s = %s_VERSION_MAJOR;", method.Params[0].ParamName, strings.ToUpper(NameSpace)), fmt.Sprintf("n%s = %s_VERSION_MINOR;", method.Params[1].ParamName, strings.ToUpper(NameSpace)), - fmt.Sprintf("n%s = %s_VERSION_MICRO;", method.Params[2].ParamName, strings.ToUpper(NameSpace)) ) + fmt.Sprintf("n%s = %s_VERSION_MICRO;", method.Params[2].ParamName, strings.ToUpper(NameSpace))) thisMethodDefaultImpl = versionImplementation } - if (isSpecialFunction == eSpecialMethodError) { + if isSpecialFunction == eSpecialMethodError { var errorImplementation []string errorImplementation = append(errorImplementation, fmt.Sprintf("if (p%s) {", method.Params[0].ParamName), fmt.Sprintf(" return p%s->%s (s%s);", method.Params[0].ParamName, GetLastErrorMessageMethod().MethodName, method.Params[1].ParamName), "} else {", " return false;", - "}"); + "}") thisMethodDefaultImpl = errorImplementation } - if (isSpecialFunction == eSpecialMethodRelease) { + if isSpecialFunction == eSpecialMethodRelease { var releaseImplementation []string releaseImplementation = append(releaseImplementation, fmt.Sprintf("I%s%s::%s(p%s);", ClassIdentifier, component.Global.BaseClassName, ReleaseBaseClassInterfaceMethod(component.Global.BaseClassName).MethodName, method.Params[0].ParamName)) thisMethodDefaultImpl = releaseImplementation } - if (isSpecialFunction == eSpecialMethodAcquire) { + if isSpecialFunction == eSpecialMethodAcquire { var acquireImplementation []string acquireImplementation = append(acquireImplementation, fmt.Sprintf("I%s%s::%s(p%s);", ClassIdentifier, component.Global.BaseClassName, AcquireBaseClassInterfaceMethod(component.Global.BaseClassName).MethodName, method.Params[0].ParamName)) @@ -707,7 +705,7 @@ func buildCPPInterfaceWrapperMethods(component ComponentDefinition, class Compon for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] - err := writeCImplementationMethod(component, method, w, BaseName, NameSpace, NameSpaceImplementation, ClassIdentifier, class.ClassName, component.Global.BaseClassName, false, doJournal, eSpecialMethodNone, component.isStringOutClass (class)) + err := writeCImplementationMethod(component, method, w, BaseName, NameSpace, NameSpaceImplementation, ClassIdentifier, class.ClassName, component.Global.BaseClassName, false, doJournal, eSpecialMethodNone, component.isStringOutClass(class)) if err != nil { return err } @@ -722,40 +720,39 @@ func buildCPPGetSymbolAddressMethod(component ComponentDefinition, w LanguageWri w.Writeln(" Function table lookup implementation") w.Writeln("**************************************************************************************************************************/") w.Writeln("") - + w.Writeln("%sResult %s::%s::%s_GetProcAddress (const char * pProcName, void ** ppProcAddress)", NameSpace, NameSpace, NameSpaceImplementation, NameSpace) w.Writeln("{") w.AddIndentationLevel(1) - - var processfuncMap []string; - - global := component.Global; + + var processfuncMap []string + + global := component.Global for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] procName := strings.ToLower(class.ClassName + "_" + method.MethodName) - processfuncMap = append (processfuncMap, fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), procName)); + processfuncMap = append(processfuncMap, fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), procName)) } } for j := 0; j < len(global.Methods); j++ { method := global.Methods[j] procName := strings.ToLower(method.MethodName) - processfuncMap = append (processfuncMap, fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), procName)); + processfuncMap = append(processfuncMap, fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), procName)) } - - w.Writeln("if (pProcName == nullptr)") + w.Writeln("if (pProcName == nullptr)") w.Writeln(" return %s_ERROR_INVALIDPARAM;", strings.ToUpper(NameSpace)) - w.Writeln("if (ppProcAddress == nullptr)") + w.Writeln("if (ppProcAddress == nullptr)") w.Writeln(" return %s_ERROR_INVALIDPARAM;", strings.ToUpper(NameSpace)) w.Writeln("*ppProcAddress = nullptr;") w.Writeln("std::string sProcName (pProcName);") w.Writeln("") - for j := 0; j < len (processfuncMap); j++ { + for j := 0; j < len(processfuncMap); j++ { w.Writeln("if (sProcName == \"%s\") ", processfuncMap[j]) w.Writeln(" *ppProcAddress = (void*) &%s;", processfuncMap[j]) } @@ -763,17 +760,17 @@ func buildCPPGetSymbolAddressMethod(component ComponentDefinition, w LanguageWri w.Writeln("") w.Writeln("if (*ppProcAddress == nullptr) ") w.Writeln(" return %s_ERROR_COULDNOTFINDLIBRARYEXPORT;", strings.ToUpper(NameSpace)) - w.Writeln("return %s_SUCCESS;", strings.ToUpper (NameSpace)) + w.Writeln("return %s_SUCCESS;", strings.ToUpper(NameSpace)) w.AddIndentationLevel(-1) w.Writeln("}") - return nil; + return nil } func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, doJournal bool) error { w.Writeln("#include \"%s_abi.hpp\"", strings.ToLower(BaseName)) w.Writeln("#include \"%s_interfaces.hpp\"", strings.ToLower(BaseName)) w.Writeln("#include \"%s_interfaceexception.hpp\"", strings.ToLower(BaseName)) - if (doJournal) { + if doJournal { w.Writeln("#include \"%s_interfacejournal.hpp\"", strings.ToLower(BaseName)) } w.Writeln("") @@ -782,15 +779,14 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N w.Writeln("using namespace %s::%s;", NameSpace, NameSpaceImplementation) w.Writeln("") - if (doJournal) { + if doJournal { w.Writeln("P%sInterfaceJournal m_GlobalJournal;", NameSpace) w.Writeln("") } - - journalParameter := ""; - if (doJournal) { - journalParameter = fmt.Sprintf (", C%sInterfaceJournalEntry * pJournalEntry = nullptr", NameSpace); + journalParameter := "" + if doJournal { + journalParameter = fmt.Sprintf(", C%sInterfaceJournalEntry * pJournalEntry = nullptr", NameSpace) } IBaseClassName := "I" + ClassIdentifier + component.Global.BaseClassName @@ -799,14 +795,14 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N w.Writeln("{") w.Writeln(" %sResult errorCode = Exception.getErrorCode();", NameSpace) w.Writeln("") - if (doJournal) { + if doJournal { w.Writeln(" if (pJournalEntry != nullptr)") w.Writeln(" pJournalEntry->writeError(errorCode);") w.Writeln("") } w.Writeln(" if (pIBaseClass != nullptr)") - + w.Writeln(" pIBaseClass->%s(Exception.what());", registerErrorMethod.MethodName) w.Writeln("") @@ -818,7 +814,7 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N w.Writeln("{") w.Writeln(" %sResult errorCode = %s_ERROR_GENERICEXCEPTION;", NameSpace, strings.ToUpper(NameSpace)) w.Writeln("") - if (doJournal) { + if doJournal { w.Writeln(" if (pJournalEntry != nullptr)") w.Writeln(" pJournalEntry->writeError(errorCode);") w.Writeln("") @@ -836,32 +832,31 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N w.Writeln("{") w.Writeln(" %sResult errorCode = %s_ERROR_GENERICEXCEPTION;", NameSpace, strings.ToUpper(NameSpace)) w.Writeln("") - if (doJournal) { + if doJournal { w.Writeln(" if (pJournalEntry != nullptr)") w.Writeln(" pJournalEntry->writeError(errorCode);") w.Writeln("") } - + w.Writeln(" if (pIBaseClass != nullptr)") w.Writeln(" pIBaseClass->%s(\"Unhandled Exception\");", registerErrorMethod.MethodName) - + w.Writeln("") w.Writeln(" return errorCode;") w.Writeln("}") w.Writeln("") - - + w.Writeln("") for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] err := buildCPPInterfaceWrapperMethods(component, class, w, NameSpace, NameSpaceImplementation, ClassIdentifier, BaseName, doJournal) - if (err != nil) { + if err != nil { return err } } w.Writeln("") - err := buildCPPGetSymbolAddressMethod(component, w, NameSpace, NameSpaceImplementation); + err := buildCPPGetSymbolAddressMethod(component, w, NameSpace, NameSpaceImplementation) if err != nil { return err } @@ -870,20 +865,20 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N w.Writeln("/*************************************************************************************************************************") w.Writeln(" Global functions implementation") w.Writeln("**************************************************************************************************************************/") - global := component.Global; + global := component.Global for j := 0; j < len(global.Methods); j++ { method := global.Methods[j] - + // Check for special functions - isSpecialFunction, err := CheckHeaderSpecialFunction(method, global); + isSpecialFunction, err := CheckHeaderSpecialFunction(method, global) if err != nil { return err } - + // Do not self-journal Journal special method - doMethodJournal := doJournal; - if (isSpecialFunction == eSpecialMethodJournal) { - doMethodJournal = false; + doMethodJournal := doJournal + if isSpecialFunction == eSpecialMethodJournal { + doMethodJournal = false } // Write Static function implementation @@ -898,31 +893,28 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N return nil } +func buildOutCacheTemplateParameters(method ComponentDefinitionMethod, NameSpace string, BaseClassName string, ClassIdentifier string) (string, error) { + result := "" + + for i := 0; i < len(method.Params); i++ { + param := method.Params[i] -func buildOutCacheTemplateParameters (method ComponentDefinitionMethod, NameSpace string, BaseClassName string, ClassIdentifier string) (string, error) { - result := ""; - - for i := 0; i < len (method.Params); i++ { - param := method.Params[i]; - - if ((param.ParamPass == "out") || (param.ParamPass == "return")) { - if (result != "") { - result += ", "; + if (param.ParamPass == "out") || (param.ParamPass == "return") { + if result != "" { + result += ", " } - - cppParamType := getCppParamType(param, NameSpace, true); + + cppParamType := getCppParamType(param, NameSpace, true) if param.ParamType == "class" || param.ParamType == "optionalclass" { - cppParamType = fmt.Sprintf("I%s%s*", ClassIdentifier, BaseClassName) + cppParamType = fmt.Sprintf("I%s%s*", ClassIdentifier, param.ParamClass) } - result += cppParamType; + result += cppParamType } - - + } - - return result, nil; -} + return result, nil +} func writeCImplementationMethod(component ComponentDefinition, method ComponentDefinitionMethod, w LanguageWriter, BaseName string, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, ClassName string, BaseClassName string, isGlobal bool, doJournal bool, isSpecialFunction int, isStringOutClass bool) error { CMethodName := "" @@ -950,27 +942,27 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD } callCPPFunctionCode := make([]string, 0) - + checkInputCPPFunctionCode, preCallCPPFunctionCode, postCallCPPFunctionCode, returnVariable, callParameters, outCallParameters, err := generatePrePostCallCPPFunctionCode(component, method, NameSpace, ClassIdentifier, ClassName, BaseClassName) if err != nil { return err } - - if (isSpecialFunction == eSpecialMethodJournal) { + + if isSpecialFunction == eSpecialMethodJournal { callCPPFunctionCode = append(callCPPFunctionCode, "m_GlobalJournal = nullptr;") callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("if (s%s != \"\") {", method.Params[0].ParamName)) callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" m_GlobalJournal = std::make_shared (s%s);", NameSpace, method.Params[0].ParamName)) callCPPFunctionCode = append(callCPPFunctionCode, "}") - } else if (isSpecialFunction == eSpecialMethodInjection) { + } else if isSpecialFunction == eSpecialMethodInjection { callCPPFunctionCode = append(callCPPFunctionCode, "") callCPPFunctionCode = append(callCPPFunctionCode, "bool bNameSpaceFound = false;") callCPPFunctionCode = append(callCPPFunctionCode, "") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { theNameSpace := subComponent.NameSpace callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("if (s%s == \"%s\") {", method.Params[0].ParamName, theNameSpace)) wrapperName := "C" + ClassIdentifier + "Wrapper" callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" if (%s::sP%sWrapper.get() != nullptr) {", wrapperName, theNameSpace)) - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_COULDNOTLOADLIBRARY);", NameSpace, strings.ToUpper(NameSpace)) ) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_COULDNOTLOADLIBRARY);", NameSpace, strings.ToUpper(NameSpace))) callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" }")) callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" %s::sP%sWrapper = %s::CWrapper::loadLibraryFromSymbolLookupMethod(p%s);", wrapperName, theNameSpace, theNameSpace, method.Params[1].ParamName)) callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" bNameSpaceFound = true;")) @@ -978,89 +970,87 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD } callCPPFunctionCode = append(callCPPFunctionCode, "") callCPPFunctionCode = append(callCPPFunctionCode, "if (!bNameSpaceFound)") - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_COULDNOTLOADLIBRARY);", NameSpace, strings.ToUpper(NameSpace)) ) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_COULDNOTLOADLIBRARY);", NameSpace, strings.ToUpper(NameSpace))) callCPPFunctionCode = append(callCPPFunctionCode, "") - } else if (isSpecialFunction == eSpecialMethodSymbolLookup) { + } else if isSpecialFunction == eSpecialMethodSymbolLookup { callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("*p%s = (void*)&%s::%s::%s_GetProcAddress;", method.Params[0].ParamName, NameSpace, NameSpaceImplementation, NameSpace)) } else { callCode, err := generateCallCPPFunctionCode(method, NameSpace, ClassIdentifier, ClassName, returnVariable, callParameters, isGlobal) if err != nil { return err } - - stringOutParameters := method.getStringOutParameters (); - outParameterCount := method.countOutParameters (); - - + + stringOutParameters := method.getStringOutParameters() + outParameterCount := method.countOutParameters() + // Special functions are an exception for string outs in global functions! - bHasCacheCall := (len (stringOutParameters) > 0) && (isSpecialFunction != eSpecialMethodError) && (isSpecialFunction != eSpecialMethodBuildinfo) && (isSpecialFunction != eSpecialMethodPrerelease); - if (method.DisableStringOutCache) { - bHasCacheCall = false; + bHasCacheCall := (len(stringOutParameters) > 0) && (isSpecialFunction != eSpecialMethodError) && (isSpecialFunction != eSpecialMethodBuildinfo) && (isSpecialFunction != eSpecialMethodPrerelease) + if method.DisableStringOutCache { + bHasCacheCall = false } - - if (bHasCacheCall) { - - if (isGlobal) { - return errors.New ("String out parameter not allowed in global functions: " + method.MethodName); + + if bHasCacheCall { + + if isGlobal { + return errors.New("String out parameter not allowed in global functions: " + method.MethodName) } - - if (!isStringOutClass) { - return errors.New ("String out parameter without being the string out base class: " + method.MethodName) + + if !isStringOutClass { + return errors.New("String out parameter without being the string out base class: " + method.MethodName) } - - templateParameters, err := buildOutCacheTemplateParameters (method, NameSpace, BaseClassName, ClassIdentifier); + + templateParameters, err := buildOutCacheTemplateParameters(method, NameSpace, BaseClassName, ClassIdentifier) if err != nil { return err } - - cacheClassName := fmt.Sprintf ("ParameterCache_%d<%s>", outParameterCount, templateParameters); - cacheClassParameters := outCallParameters; - cacheCallCondition := ""; - - for i := 0; i < len (stringOutParameters); i++ { - if (i > 0) { - cacheCallCondition = cacheCallCondition + " || "; + + cacheClassName := fmt.Sprintf("ParameterCache_%d<%s>", outParameterCount, templateParameters) + cacheClassParameters := outCallParameters + cacheCallCondition := "" + + for i := 0; i < len(stringOutParameters); i++ { + if i > 0 { + cacheCallCondition = cacheCallCondition + " || " } - - cacheCallCondition += fmt.Sprintf ("(p%sBuffer == nullptr)", stringOutParameters[i]); + + cacheCallCondition += fmt.Sprintf("(p%sBuffer == nullptr)", stringOutParameters[i]) } - - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("bool isCacheCall = %s;", cacheCallCondition)); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("if (isCacheCall) {")); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" " + callCode)) - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" pI%s->_setCache (new %s (%s));", ClassName, cacheClassName, cacheClassParameters)); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("}")); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("else {")); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" auto cache = dynamic_cast<%s*> (pI%s->_getCache ());", cacheClassName, ClassName)); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" if (cache == nullptr)")); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" throw E%sInterfaceException(%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace)) ); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" cache->retrieveData (%s);", cacheClassParameters)); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" pI%s->_setCache (nullptr);", ClassName)); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("}")); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("")); - + + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("bool isCacheCall = %s;", cacheCallCondition)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("if (isCacheCall) {")) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" "+callCode)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" pI%s->_setCache (new %s (%s));", ClassName, cacheClassName, cacheClassParameters)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("}")) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("else {")) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" auto cache = dynamic_cast<%s*> (pI%s->_getCache ());", cacheClassName, ClassName)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" if (cache == nullptr)")) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace))) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" cache->retrieveData (%s);", cacheClassParameters)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" pI%s->_setCache (nullptr);", ClassName)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("}")) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("")) + } else { - - callCPPFunctionCode = append(callCPPFunctionCode, callCode); - + + callCPPFunctionCode = append(callCPPFunctionCode, callCode) + } - + } - + journalInitFunctionCode := make([]string, 0) journalSuccessFunctionCode := make([]string, 0) - if (doJournal) { + if doJournal { journalInitFunctionCode, journalSuccessFunctionCode, err = generateJournalFunctionCode(method, NameSpace, ClassName, isGlobal) if err != nil { return err } } - if !isGlobal { preCallCPPFunctionCode = append(preCallCPPFunctionCode, fmt.Sprintf("I%s%s* pI%s = dynamic_cast(pIBaseClass);", ClassIdentifier, ClassName, ClassName, ClassIdentifier, ClassName)) preCallCPPFunctionCode = append(preCallCPPFunctionCode, fmt.Sprintf("if (!pI%s)", ClassName)) - preCallCPPFunctionCode = append(preCallCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace)) ) + preCallCPPFunctionCode = append(preCallCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace))) preCallCPPFunctionCode = append(preCallCPPFunctionCode, "") } @@ -1069,19 +1059,18 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD IBaseClassName := fmt.Sprintf("I%s%s", ClassIdentifier, BaseClassName) if !isGlobal { - w.Writeln (" %s* pIBaseClass = (%s *)p%s;\n", IBaseClassName, IBaseClassName, ClassName); + w.Writeln(" %s* pIBaseClass = (%s *)p%s;\n", IBaseClassName, IBaseClassName, ClassName) } else { - w.Writeln (" %s* pIBaseClass = nullptr;\n", IBaseClassName); + w.Writeln(" %s* pIBaseClass = nullptr;\n", IBaseClassName) } - - - if (doJournal) { - w.Writeln(" P%sInterfaceJournalEntry pJournalEntry;", NameSpace); + + if doJournal { + w.Writeln(" P%sInterfaceJournalEntry pJournalEntry;", NameSpace) } - + w.Writeln(" try {") - if (doJournal) { + if doJournal { w.Writelns(" ", journalInitFunctionCode) } @@ -1090,13 +1079,13 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD w.Writelns(" ", callCPPFunctionCode) w.Writelns(" ", postCallCPPFunctionCode) - journalHandleParam := ""; - - if (doJournal) { + journalHandleParam := "" + + if doJournal { w.Writelns(" ", journalSuccessFunctionCode) - journalHandleParam = ", pJournalEntry.get()"; + journalHandleParam = ", pJournalEntry.get()" } - + w.Writeln(" return %s_SUCCESS;", strings.ToUpper(NameSpace)) w.Writeln(" }") w.Writeln(" catch (E%sInterfaceException & Exception) {", NameSpace) @@ -1114,181 +1103,155 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD return nil } - func buildCPPStubClass(component ComponentDefinition, class ComponentDefinitionClass, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string, forceRecreation bool) error { - outClassName := "C" + ClassIdentifier + class.ClassName + outClassName := "C" + ClassIdentifier + class.ClassName - StubHeaderFileName := path.Join(outputFolder, BaseName + stubIdentifier + "_" +strings.ToLower(class.ClassName)+".hpp"); - StubImplFileName := path.Join(outputFolder, BaseName + stubIdentifier + "_" + strings.ToLower(class.ClassName)+".cpp"); - if !forceRecreation && ( FileExists(StubHeaderFileName) || FileExists(StubImplFileName) ) { - log.Printf("Omitting recreation of Stub implementation for \"%s\"", outClassName) - return nil - } + StubHeaderFileName := path.Join(outputFolder, BaseName+stubIdentifier+"_"+strings.ToLower(class.ClassName)+".hpp") + StubImplFileName := path.Join(outputFolder, BaseName+stubIdentifier+"_"+strings.ToLower(class.ClassName)+".cpp") + if !forceRecreation && (FileExists(StubHeaderFileName) || FileExists(StubImplFileName)) { + log.Printf("Omitting recreation of Stub implementation for \"%s\"", outClassName) + return nil + } - log.Printf("Creating \"%s\"", StubHeaderFileName) - stubheaderw, err := CreateLanguageFile(StubHeaderFileName, indentString) - if err != nil { - return err - } - stubheaderw.WriteCLicenseHeader(component, - fmt.Sprintf("This is the class declaration of %s", outClassName), - false) - - log.Printf("Creating \"%s\"", StubImplFileName) - stubimplw, err := CreateLanguageFile(StubImplFileName, indentString) - if err != nil { - return err - } - stubimplw.WriteCLicenseHeader(component, - fmt.Sprintf("This is a stub class definition of %s", outClassName), - false) + log.Printf("Creating \"%s\"", StubHeaderFileName) + stubheaderw, err := CreateLanguageFile(StubHeaderFileName, indentString) + if err != nil { + return err + } + stubheaderw.WriteCLicenseHeader(component, + fmt.Sprintf("This is the class declaration of %s", outClassName), + false) - stubheaderw.Writeln("") - stubheaderw.Writeln("#ifndef __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) - stubheaderw.Writeln("#define __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) - stubheaderw.Writeln("") + log.Printf("Creating \"%s\"", StubImplFileName) + stubimplw, err := CreateLanguageFile(StubImplFileName, indentString) + if err != nil { + return err + } + stubimplw.WriteCLicenseHeader(component, + fmt.Sprintf("This is a stub class definition of %s", outClassName), + false) - stubheaderw.Writeln("#include \"%s_interfaces.hpp\"", BaseName) - if (component.isBaseClass(class)) { - stubheaderw.Writeln("#include ") - stubheaderw.Writeln("#include ") - stubheaderw.Writeln("#include ") - } - stubheaderw.Writeln("") + stubheaderw.Writeln("") + stubheaderw.Writeln("#ifndef __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) + stubheaderw.Writeln("#define __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) + stubheaderw.Writeln("") - if (!component.isBaseClass(class)) { - if (class.ParentClass == "") { - class.ParentClass = component.Global.BaseClassName - } - } + stubheaderw.Writeln("#include \"%s_interfaces.hpp\"", BaseName) + if component.isBaseClass(class) { + stubheaderw.Writeln("#include ") + stubheaderw.Writeln("#include ") + stubheaderw.Writeln("#include ") + } + stubheaderw.Writeln("") - if class.ParentClass != "" { - stubheaderw.Writeln("// Parent classes") - stubheaderw.Writeln("#include \"%s%s_%s.hpp\"", BaseName, stubIdentifier, strings.ToLower(class.ParentClass)) - stubheaderw.Writeln("#ifdef _MSC_VER") - stubheaderw.Writeln("#pragma warning(push)") - stubheaderw.Writeln("#pragma warning(disable : 4250)") - stubheaderw.Writeln("#endif") + if !component.isBaseClass(class) { + if class.ParentClass == "" { + class.ParentClass = component.Global.BaseClassName } - stubheaderw.Writeln("") - - stubheaderw.Writeln("// Include custom headers here.") - stubheaderw.Writeln("") - - stubheaderw.Writeln("") - stubheaderw.Writeln("namespace %s {", NameSpace) - stubheaderw.Writeln("namespace %s {", NameSpaceImplementation) - stubheaderw.Writeln("") + } - stubheaderw.Writeln("") - stubheaderw.Writeln("/*************************************************************************************************************************") - stubheaderw.Writeln(" Class declaration of %s ", outClassName) - stubheaderw.Writeln("**************************************************************************************************************************/") - stubheaderw.Writeln("") - parentClassName := fmt.Sprintf("I%s%s", ClassIdentifier, class.ClassName) - if "" != class.ParentClass { - parentClassName = parentClassName + ", " + fmt.Sprintf("public virtual C%s%s", ClassIdentifier, class.ParentClass) - } - stubheaderw.Writeln("class %s : public virtual %s {", outClassName, parentClassName) - stubheaderw.Writeln("private:") - stubheaderw.Writeln("") - - if (component.isBaseClass(class)) { - stubheaderw.Writeln(" std::unique_ptr m_pLastError;") - stubheaderw.Writeln(" uint32_t m_nReferenceCount = 1;") - stubheaderw.Writeln("") - } - stubheaderw.Writeln(" /**") - stubheaderw.Writeln(" * Put private members here.") - stubheaderw.Writeln(" */") - stubheaderw.Writeln("") + if class.ParentClass != "" { + stubheaderw.Writeln("// Parent classes") + stubheaderw.Writeln("#include \"%s%s_%s.hpp\"", BaseName, stubIdentifier, strings.ToLower(class.ParentClass)) + stubheaderw.Writeln("#ifdef _MSC_VER") + stubheaderw.Writeln("#pragma warning(push)") + stubheaderw.Writeln("#pragma warning(disable : 4250)") + stubheaderw.Writeln("#endif") + } + stubheaderw.Writeln("") + + stubheaderw.Writeln("// Include custom headers here.") + stubheaderw.Writeln("") + + stubheaderw.Writeln("") + stubheaderw.Writeln("namespace %s {", NameSpace) + stubheaderw.Writeln("namespace %s {", NameSpaceImplementation) + stubheaderw.Writeln("") + + stubheaderw.Writeln("") + stubheaderw.Writeln("/*************************************************************************************************************************") + stubheaderw.Writeln(" Class declaration of %s ", outClassName) + stubheaderw.Writeln("**************************************************************************************************************************/") + stubheaderw.Writeln("") + parentClassName := fmt.Sprintf("I%s%s", ClassIdentifier, class.ClassName) + if "" != class.ParentClass { + parentClassName = parentClassName + ", " + fmt.Sprintf("public virtual C%s%s", ClassIdentifier, class.ParentClass) + } + stubheaderw.Writeln("class %s : public virtual %s {", outClassName, parentClassName) + stubheaderw.Writeln("private:") + stubheaderw.Writeln("") - stubheaderw.Writeln("protected:") - stubheaderw.Writeln("") - stubheaderw.Writeln(" /**") - stubheaderw.Writeln(" * Put protected members here.") - stubheaderw.Writeln(" */") - stubheaderw.Writeln("") - stubheaderw.Writeln("public:") - stubheaderw.Writeln("") - stubheaderw.Writeln(" /**") - stubheaderw.Writeln(" * Put additional public members here. They will not be visible in the external API.") - stubheaderw.Writeln(" */") + if component.isBaseClass(class) { + stubheaderw.Writeln(" std::unique_ptr m_pLastError;") + stubheaderw.Writeln(" uint32_t m_nReferenceCount = 1;") stubheaderw.Writeln("") + } + stubheaderw.Writeln(" /**") + stubheaderw.Writeln(" * Put private members here.") + stubheaderw.Writeln(" */") + stubheaderw.Writeln("") + + stubheaderw.Writeln("protected:") + stubheaderw.Writeln("") + stubheaderw.Writeln(" /**") + stubheaderw.Writeln(" * Put protected members here.") + stubheaderw.Writeln(" */") + stubheaderw.Writeln("") + stubheaderw.Writeln("public:") + stubheaderw.Writeln("") + stubheaderw.Writeln(" /**") + stubheaderw.Writeln(" * Put additional public members here. They will not be visible in the external API.") + stubheaderw.Writeln(" */") + stubheaderw.Writeln("") + + stubimplw.Writeln("#include \"%s%s_%s.hpp\"", BaseName, stubIdentifier, strings.ToLower(class.ClassName)) + stubimplw.Writeln("#include \"%s_interfaceexception.hpp\"", BaseName) + stubimplw.Writeln("") + stubimplw.Writeln("// Include custom headers here.") + stubimplw.Writeln("") + + stubimplw.Writeln("") + stubimplw.Writeln("using namespace %s::%s;", NameSpace, NameSpaceImplementation) + stubimplw.Writeln("") + + stubimplw.Writeln("/*************************************************************************************************************************") + stubimplw.Writeln(" Class definition of %s ", outClassName) + stubimplw.Writeln("**************************************************************************************************************************/") + stubimplw.Writeln("") + if component.isBaseClass(class) { + var methods [5]ComponentDefinitionMethod + methods[0] = GetLastErrorMessageMethod() + methods[1] = ClearErrorMessageMethod() + methods[2] = RegisterErrorMessageMethod() + methods[3] = IncRefCountMethod() + methods[4] = DecRefCountMethod() - stubimplw.Writeln("#include \"%s%s_%s.hpp\"", BaseName, stubIdentifier, strings.ToLower(class.ClassName)) - stubimplw.Writeln("#include \"%s_interfaceexception.hpp\"", BaseName) - stubimplw.Writeln("") - stubimplw.Writeln("// Include custom headers here.") - stubimplw.Writeln("") - - - stubimplw.Writeln("") - stubimplw.Writeln("using namespace %s::%s;", NameSpace, NameSpaceImplementation) - stubimplw.Writeln("") - - stubimplw.Writeln("/*************************************************************************************************************************") - stubimplw.Writeln(" Class definition of %s ", outClassName) - stubimplw.Writeln("**************************************************************************************************************************/") - stubimplw.Writeln("") - - if (component.isBaseClass(class)) { - var methods [5]ComponentDefinitionMethod - methods[0] = GetLastErrorMessageMethod() - methods[1] = ClearErrorMessageMethod() - methods[2] = RegisterErrorMessageMethod() - methods[3] = IncRefCountMethod() - methods[4] = DecRefCountMethod() - - var implementations [5][]string - implementations[0] = append(implementations[0], "if (m_pLastError.get() != nullptr) {") - implementations[0] = append(implementations[0], " sErrorMessage = *m_pLastError;") - implementations[0] = append(implementations[0], " return true;") - implementations[0] = append(implementations[0], "} else {") - implementations[0] = append(implementations[0], " sErrorMessage = \"\";") - implementations[0] = append(implementations[0], " return false;") - implementations[0] = append(implementations[0], "}") - implementations[1] = append(implementations[1], "m_pLastError.reset();") - - implementations[2] = append(implementations[2], "if (m_pLastError.get() == nullptr) {") - implementations[2] = append(implementations[2], " m_pLastError.reset(new std::string());") - implementations[2] = append(implementations[2], "}") - implementations[2] = append(implementations[2], "*m_pLastError = sErrorMessage;") - - implementations[3] = append(implementations[3], "++m_nReferenceCount;") - - implementations[4] = append(implementations[4], "m_nReferenceCount--;") - implementations[4] = append(implementations[4], "if (!m_nReferenceCount) {") - implementations[4] = append(implementations[4], " delete this;") - implementations[4] = append(implementations[4], " return true;") - implementations[4] = append(implementations[4], "}") - implementations[4] = append(implementations[4], "return false;") - for i := 0; i < len(methods); i++ { - methodstring, implementationdeclaration, err := buildCPPInterfaceMethodDeclaration(methods[i], class.ClassName, NameSpace, ClassIdentifier, BaseName, stubimplw.IndentString, false, false, false) - if (err!=nil) { - return err - } - stubheaderw.Writeln("%s;", methodstring) - stubheaderw.Writeln("") - - stubimplw.Writeln("%s", implementationdeclaration) - stubimplw.Writeln("{") - stubimplw.Writelns(" ", implementations[i]) - stubimplw.Writeln("}") - stubimplw.Writeln("") - } - } - - stubheaderw.Writeln("") - stubheaderw.Writeln(" /**") - stubheaderw.Writeln(" * Public member functions to implement.") - stubheaderw.Writeln(" */") - stubheaderw.Writeln("") - - for j := 0; j < len(class.Methods); j++ { - method := class.Methods[j] - methodstring, implementationdeclaration, err := buildCPPInterfaceMethodDeclaration(method, class.ClassName, NameSpace, ClassIdentifier, BaseName, stubimplw.IndentString, false, false, false) + var implementations [5][]string + implementations[0] = append(implementations[0], "if (m_pLastError.get() != nullptr) {") + implementations[0] = append(implementations[0], " sErrorMessage = *m_pLastError;") + implementations[0] = append(implementations[0], " return true;") + implementations[0] = append(implementations[0], "} else {") + implementations[0] = append(implementations[0], " sErrorMessage = \"\";") + implementations[0] = append(implementations[0], " return false;") + implementations[0] = append(implementations[0], "}") + implementations[1] = append(implementations[1], "m_pLastError.reset();") + + implementations[2] = append(implementations[2], "if (m_pLastError.get() == nullptr) {") + implementations[2] = append(implementations[2], " m_pLastError.reset(new std::string());") + implementations[2] = append(implementations[2], "}") + implementations[2] = append(implementations[2], "*m_pLastError = sErrorMessage;") + + implementations[3] = append(implementations[3], "++m_nReferenceCount;") + + implementations[4] = append(implementations[4], "m_nReferenceCount--;") + implementations[4] = append(implementations[4], "if (!m_nReferenceCount) {") + implementations[4] = append(implementations[4], " delete this;") + implementations[4] = append(implementations[4], " return true;") + implementations[4] = append(implementations[4], "}") + implementations[4] = append(implementations[4], "return false;") + for i := 0; i < len(methods); i++ { + methodstring, implementationdeclaration, err := buildCPPInterfaceMethodDeclaration(methods[i], class.ClassName, NameSpace, ClassIdentifier, BaseName, stubimplw.IndentString, false, false, false) if err != nil { return err } @@ -1297,24 +1260,47 @@ func buildCPPStubClass(component ComponentDefinition, class ComponentDefinitionC stubimplw.Writeln("%s", implementationdeclaration) stubimplw.Writeln("{") - stubimplw.Writeln(" throw E%sInterfaceException(%s_ERROR_NOTIMPLEMENTED);", NameSpace, strings.ToUpper(NameSpace)) + stubimplw.Writelns(" ", implementations[i]) stubimplw.Writeln("}") stubimplw.Writeln("") } + } - stubheaderw.Writeln("};") - stubheaderw.Writeln("") + stubheaderw.Writeln("") + stubheaderw.Writeln(" /**") + stubheaderw.Writeln(" * Public member functions to implement.") + stubheaderw.Writeln(" */") + stubheaderw.Writeln("") - stubheaderw.Writeln("} // namespace %s", NameSpaceImplementation) - stubheaderw.Writeln("} // namespace %s", NameSpace) + for j := 0; j < len(class.Methods); j++ { + method := class.Methods[j] + methodstring, implementationdeclaration, err := buildCPPInterfaceMethodDeclaration(method, class.ClassName, NameSpace, ClassIdentifier, BaseName, stubimplw.IndentString, false, false, false) + if err != nil { + return err + } + stubheaderw.Writeln("%s;", methodstring) stubheaderw.Writeln("") - if class.ParentClass != "" { - stubheaderw.Writeln("#ifdef _MSC_VER") - stubheaderw.Writeln("#pragma warning(pop)") - stubheaderw.Writeln("#endif") - } - stubheaderw.Writeln("#endif // __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) + stubimplw.Writeln("%s", implementationdeclaration) + stubimplw.Writeln("{") + stubimplw.Writeln(" throw E%sInterfaceException(%s_ERROR_NOTIMPLEMENTED);", NameSpace, strings.ToUpper(NameSpace)) + stubimplw.Writeln("}") + stubimplw.Writeln("") + } + + stubheaderw.Writeln("};") + stubheaderw.Writeln("") + + stubheaderw.Writeln("} // namespace %s", NameSpaceImplementation) + stubheaderw.Writeln("} // namespace %s", NameSpace) + stubheaderw.Writeln("") + + if class.ParentClass != "" { + stubheaderw.Writeln("#ifdef _MSC_VER") + stubheaderw.Writeln("#pragma warning(pop)") + stubheaderw.Writeln("#endif") + } + stubheaderw.Writeln("#endif // __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) return nil } @@ -1322,7 +1308,7 @@ func buildCPPStub(component ComponentDefinition, NameSpace string, NameSpaceImpl for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] - err := buildCPPStubClass(component, class, NameSpace, NameSpaceImplementation, ClassIdentifier, BaseName, outputFolder, indentString, stubIdentifier, forceRecreation) + err := buildCPPStubClass(component, class, NameSpace, NameSpaceImplementation, ClassIdentifier, BaseName, outputFolder, indentString, stubIdentifier, forceRecreation) if err != nil { return err } @@ -1331,42 +1317,42 @@ func buildCPPStub(component ComponentDefinition, NameSpace string, NameSpaceImpl return nil } -func getCppVariableName (param ComponentDefinitionParam) (string) { - switch (param.ParamType) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": - return "n" + param.ParamName; - case "string": - return "s" + param.ParamName; - case "bool": - return "b" + param.ParamName; - case "single": - return "f" + param.ParamName; - case "basicarray", "structarray": - return "p" + param.ParamName + "Buffer"; - case "double": - return "d" + param.ParamName; - case "pointer": - return "p" + param.ParamName; - case "enum": - return "e" + param.ParamName; - case "struct": - return param.ParamName; - case "class", "optionalclass": - return "p" + param.ParamName; - case "functiontype": - return "p" + param.ParamName; - } - - log.Fatal ("Invalid parameter type: ", param.ParamType); - - return ""; +func getCppVariableName(param ComponentDefinitionParam) string { + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": + return "n" + param.ParamName + case "string": + return "s" + param.ParamName + case "bool": + return "b" + param.ParamName + case "single": + return "f" + param.ParamName + case "basicarray", "structarray": + return "p" + param.ParamName + "Buffer" + case "double": + return "d" + param.ParamName + case "pointer": + return "p" + param.ParamName + case "enum": + return "e" + param.ParamName + case "struct": + return param.ParamName + case "class", "optionalclass": + return "p" + param.ParamName + case "functiontype": + return "p" + param.ParamName + } + + log.Fatal("Invalid parameter type: ", param.ParamType) + + return "" } func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, className string, NameSpace string, ClassIdentifier string, BaseName string, indentString string, isGlobal bool, isVirtual bool, writeComment bool) (string, string, error) { parameters := "" returntype := "void" commentcode := "" - + templateimplementation := "" for k := 0; k < len(method.Params); k++ { @@ -1385,39 +1371,39 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN switch param.ParamType { case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s n%s", cppParamType, param.ParamName) case "string": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] s%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] s%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const std::string & s%s", param.ParamName) case "bool": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] b%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] b%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s b%s", cppParamType, param.ParamName) case "single": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] f%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] f%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s f%s", cppParamType, param.ParamName) case "double": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] d%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] d%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s d%s", cppParamType, param.ParamName) case "pointer": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s p%s", cppParamType, param.ParamName) case "enum": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] e%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] e%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s e%s", cppParamType, param.ParamName) case "struct": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] %s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] %s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s %s", cppParamType, param.ParamName) case "class", "optionalclass": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] p%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] p%s - %s\n", param.ParamName, param.ParamDescription) if len(paramNameSpaceCPP) > 0 { // TODO: ClassIdentifier is incorrect! get via // component.ImportedComponentDefinitions[paramNameSpace].Bindings parameters = parameters + fmt.Sprintf("%sP%s%s p%s", paramNameSpaceCPP, ClassIdentifier, paramClassNameCPP, param.ParamName) @@ -1426,17 +1412,17 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN } case "basicarray": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] p%sBuffer - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] p%sBuffer - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s_uint64 n%sBufferSize, const %s p%sBuffer", NameSpace, param.ParamName, cppParamType, param.ParamName) case "structarray": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] p%sBuffer - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] p%sBuffer - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s_uint64 n%sBufferSize, const %s p%sBuffer", NameSpace, param.ParamName, cppParamType, param.ParamName) case "functiontype": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] p%s - callback function\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] p%s - callback function\n", param.ParamName) parameters = parameters + fmt.Sprintf("const %s p%s", cppParamType, param.ParamName) default: @@ -1453,58 +1439,57 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN switch param.ParamType { case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] n%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] n%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & n%s", cppParamType, param.ParamName) case "bool": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] b%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] b%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & b%s", cppParamType, param.ParamName) case "single": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] f%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] f%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & f%s", cppParamType, param.ParamName) case "double": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] d%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] d%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & d%s", cppParamType, param.ParamName) case "pointer": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] d%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] d%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & p%s", cppParamType, param.ParamName) case "string": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] s%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] s%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("std::string & s%s", param.ParamName) case "enum": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] e%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] e%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & e%s", cppParamType, param.ParamName) case "struct": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] s%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] s%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & s%s", cppParamType, param.ParamName) case "basicarray": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s_uint64 n%sBufferSize, %s_uint64* p%sNeededCount, %s p%sBuffer", NameSpace, param.ParamName, NameSpace, param.ParamName, cppParamType, param.ParamName) case "structarray": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s_uint64 n%sBufferSize, %s_uint64* p%sNeededCount, %s p%sBuffer", NameSpace, param.ParamName, NameSpace, param.ParamName, cppParamType, param.ParamName) case "class", "optionalclass": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%s - %s\n", param.ParamName, param.ParamDescription) if len(paramNameSpaceCPP) > 0 { // TODO: ClassIdentifier is incorrect! get via // component.ImportedComponentDefinitions[paramNameSpace].Bindings parameters = parameters + fmt.Sprintf("%sP%s%s p%s", paramNameSpaceCPP, ClassIdentifier, paramClassNameCPP, param.ParamName) } else { parameters = parameters + fmt.Sprintf("I%s%s*& p%s", ClassIdentifier, param.ParamClass, param.ParamName) } - default: return "", "", fmt.Errorf("invalid method parameter type \"%s\" for %s.%s(%s)", param.ParamType, className, method.MethodName, param.ParamName) @@ -1515,10 +1500,10 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN switch param.ParamType { case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double", "pointer", "string", "enum", "struct": returntype = currentReturnType - commentcode = commentcode + fmt.Sprintf(indentString + "* @return %s\n", param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @return %s\n", param.ParamDescription) case "class", "optionalclass": - commentcode = commentcode + fmt.Sprintf(indentString + "* @return %s\n", param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @return %s\n", param.ParamDescription) if len(paramNameSpaceCPP) > 0 { // TODO: ClassIdentifier is incorrect! get via // component.ImportedComponentDefinitions[paramNameSpace].Bindings returntype = fmt.Sprintf("%sP%s%s", paramNameSpaceCPP, ClassIdentifier, paramClassNameCPP) @@ -1526,6 +1511,14 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN returntype = fmt.Sprintf("I%s%s *", ClassIdentifier, param.ParamClass) } + case "basicarray": + cppParamType := getCppParamType(param, NameSpace, false) + + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) + parameters = parameters + fmt.Sprintf("%s_uint64 n%sBufferSize, %s_uint64* p%sNeededCount, %s p%sBuffer", NameSpace, param.ParamName, NameSpace, param.ParamName, cppParamType, param.ParamName) + default: return "", "", fmt.Errorf("invalid method parameter type \"%s\" for %s.%s(%s)", param.ParamType, className, method.MethodName, param.ParamName) } @@ -1534,24 +1527,24 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN return "", "", fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s(%s)", param.ParamPass, className, method.MethodName, param.ParamName) } } - outstring := ""; - if (writeComment) { + outstring := "" + if writeComment { outstring = indentString + "/**\n" - outstring = outstring + fmt.Sprintf(indentString + "* I%s%s::%s - %s\n", ClassIdentifier, className, method.MethodName, method.MethodDescription) + outstring = outstring + fmt.Sprintf(indentString+"* I%s%s::%s - %s\n", ClassIdentifier, className, method.MethodName, method.MethodDescription) outstring = outstring + commentcode outstring = outstring + indentString + "*/\n" } - + if isGlobal { if isVirtual { return "", "", fmt.Errorf("Method \"%s\"can not be virtual static", method.MethodName) } - outstring = outstring + fmt.Sprintf(indentString + "static %s %s(%s)", returntype, method.MethodName, parameters) + outstring = outstring + fmt.Sprintf(indentString+"static %s %s(%s)", returntype, method.MethodName, parameters) } else { if isVirtual { - outstring = outstring + fmt.Sprintf(indentString + "virtual %s %s(%s) = 0", returntype, method.MethodName, parameters) + outstring = outstring + fmt.Sprintf(indentString+"virtual %s %s(%s) = 0", returntype, method.MethodName, parameters) } else { - outstring = outstring + fmt.Sprintf(indentString + "%s %s(%s) override", returntype, method.MethodName, parameters) + outstring = outstring + fmt.Sprintf(indentString+"%s %s(%s) override", returntype, method.MethodName, parameters) } } @@ -1564,55 +1557,55 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN return outstring, templateimplementation, nil } -func getCppParamType (param ComponentDefinitionParam, NameSpace string, isInput bool) (string) { - cppClassPrefix := "C" + NameSpace; - switch (param.ParamType) { +func getCppParamType(param ComponentDefinitionParam, NameSpace string, isInput bool) string { + cppClassPrefix := "C" + NameSpace + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": + return fmt.Sprintf("%s_%s", NameSpace, param.ParamType) + case "string": + return fmt.Sprintf("std::string") + case "bool": + return fmt.Sprintf("bool") + case "pointer": + return fmt.Sprintf("%s_pvoid", NameSpace) + + case "basicarray": + cppBasicType := "" + switch param.ParamClass { case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": - return fmt.Sprintf ("%s_%s", NameSpace, param.ParamType); - case "string": - return fmt.Sprintf ("std::string"); + cppBasicType = fmt.Sprintf("%s_%s", NameSpace, param.ParamClass) case "bool": - return fmt.Sprintf ("bool"); + cppBasicType = "bool" case "pointer": - return fmt.Sprintf ("%s_pvoid", NameSpace); - - case "basicarray": - cppBasicType := ""; - switch (param.ParamClass) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": - cppBasicType = fmt.Sprintf ("%s_%s", NameSpace, param.ParamClass); - case "bool": - cppBasicType = "bool"; - case "pointer": - cppBasicType = fmt.Sprintf ("%s_pvoid", NameSpace); - default: - log.Fatal ("Invalid parameter type: ", param.ParamClass); - } - return fmt.Sprintf ("%s *", cppBasicType); - case "structarray": - return fmt.Sprintf ("%s::s%s *", NameSpace, param.ParamClass); - case "enum": - return fmt.Sprintf ("%s::e%s", NameSpace, param.ParamClass); - case "struct": - return fmt.Sprintf ("%s::s%s", NameSpace, param.ParamClass); - case "class", "optionalclass": - if (isInput) { - return fmt.Sprintf ("%s%s *", cppClassPrefix, param.ParamClass); - } - return fmt.Sprintf ("P%s", param.ParamClass); - case "functiontype": - return fmt.Sprintf ("%s::%s", NameSpace, param.ParamClass); + cppBasicType = fmt.Sprintf("%s_pvoid", NameSpace) + default: + log.Fatal("Invalid parameter type: ", param.ParamClass) + } + return fmt.Sprintf("%s *", cppBasicType) + case "structarray": + return fmt.Sprintf("%s::s%s *", NameSpace, param.ParamClass) + case "enum": + return fmt.Sprintf("%s::e%s", NameSpace, param.ParamClass) + case "struct": + return fmt.Sprintf("%s::s%s", NameSpace, param.ParamClass) + case "class", "optionalclass": + if isInput { + return fmt.Sprintf("%s%s *", cppClassPrefix, param.ParamClass) + } + return fmt.Sprintf("P%s", param.ParamClass) + case "functiontype": + return fmt.Sprintf("%s::%s", NameSpace, param.ParamClass) } - - log.Fatal ("Invalid parameter type: ", param.ParamType); - return ""; + + log.Fatal("Invalid parameter type: ", param.ParamType) + return "" } func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method ComponentDefinitionMethod, NameSpace string, ClassIdentifier string, ClassName string, BaseClassName string) ([]string, []string, []string, string, string, string, error) { preCallCode := make([]string, 0) postCallCode := make([]string, 0) callParameters := "" - outCallParameters := ""; + outCallParameters := "" returnVariable := "" checkInputCode := make([]string, 0) IBaseClassName := fmt.Sprintf("I%s%s", ClassIdentifier, BaseClassName) @@ -1654,13 +1647,13 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co preCallCode = append(preCallCode, fmt.Sprintf("%s* pIBaseClass%s = (%s *)p%s;", IBaseClassName, param.ParamName, IBaseClassName, param.ParamName)) preCallCode = append(preCallCode, fmt.Sprintf("I%s%s* pI%s = dynamic_cast(pIBaseClass%s);", ClassIdentifier, param.ParamClass, param.ParamName, ClassIdentifier, param.ParamClass, param.ParamName)) } - - if (param.ParamType == "class") { + + if param.ParamType == "class" && param.ParamOptional != "true" { preCallCode = append(preCallCode, fmt.Sprintf("if (!pI%s)", param.ParamName)) preCallCode = append(preCallCode, fmt.Sprintf(" throw E%sInterfaceException (%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace))) preCallCode = append(preCallCode, "") } - + callParameters = callParameters + fmt.Sprintf("pI%s", param.ParamName) case "string": checkInputCode = append(checkInputCode, fmt.Sprintf("if (p%s == nullptr)", param.ParamName)) @@ -1683,7 +1676,6 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co outCallParameters = outCallParameters + ", " } - switch param.ParamType { case "bool", "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double", "enum", "struct", "pointer": @@ -1726,23 +1718,22 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co theWrapper := "C" + ClassIdentifier + "Wrapper::sP" + paramNameSpace + "Wrapper" acqurireMethod := component.ImportedComponentDefinitions[paramNameSpace].Global.AcquireMethod postCallCode = append(postCallCode, fmt.Sprintf("%s->%s(%s.get());", theWrapper, acqurireMethod, outVarName)) - postCallCode = append(postCallCode, fmt.Sprintf("*%s = %s->handle();", variableName, outVarName)); + postCallCode = append(postCallCode, fmt.Sprintf("*%s = %s->handle();", variableName, outVarName)) callParameters = callParameters + outVarName outCallParameters = outCallParameters + outVarName } else { - preCallCode = append(preCallCode, fmt.Sprintf("I%s* pBase%s(nullptr);", paramClassName, param.ParamName)) - postCallCode = append(postCallCode, fmt.Sprintf("*%s = (%s*)(pBase%s);", variableName, IBaseClassName, param.ParamName)); - callParameters = callParameters + "pBase" + param.ParamName - outCallParameters = outCallParameters + "pBase" + param.ParamName + preCallCode = append(preCallCode, fmt.Sprintf("I%s* pClass%s(nullptr);", paramClassName, param.ParamName)) + postCallCode = append(postCallCode, fmt.Sprintf("*%s = (%s*)(pClass%s);", variableName, IBaseClassName, param.ParamName)) + callParameters = callParameters + "pClass" + param.ParamName + outCallParameters = fmt.Sprintf("%s pClass%s", outCallParameters, param.ParamName) } - default: return checkInputCode, preCallCode, postCallCode, "", "", "", fmt.Errorf("method parameter type \"%s\" of param pass \"%s\" is not implemented for %s::%s(%s) )", param.ParamType, param.ParamPass, ClassName, method.MethodName, param.ParamName) } case "return": - + if outCallParameters != "" { outCallParameters = outCallParameters + ", " } @@ -1754,14 +1745,19 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co checkInputCode = append(checkInputCode, fmt.Sprintf(" throw E%sInterfaceException (%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper(NameSpace))) returnVariable = fmt.Sprintf("*p%s", param.ParamName) - outCallParameters = outCallParameters + returnVariable; + outCallParameters = outCallParameters + returnVariable case "struct": checkInputCode = append(checkInputCode, fmt.Sprintf("if (p%s == nullptr)", param.ParamName)) checkInputCode = append(checkInputCode, fmt.Sprintf("throw E%sInterfaceException (%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper(NameSpace))) returnVariable = fmt.Sprintf("*p%s", param.ParamName) - outCallParameters = outCallParameters + returnVariable; + outCallParameters = outCallParameters + returnVariable + + case "basicarray": + checkInputCode = append(checkInputCode, fmt.Sprintf("if ((!p%sBuffer) && !(p%sNeededCount))", param.ParamName, param.ParamName)) + checkInputCode = append(checkInputCode, fmt.Sprintf(" throw E%sInterfaceException (%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper(NameSpace))) + callParameters = callParameters + fmt.Sprintf("n%sBufferSize, p%sNeededCount, ", param.ParamName, param.ParamName) + variableName case "string": checkInputCode = append(checkInputCode, fmt.Sprintf("if ( (!p%sBuffer) && !(p%sNeededChars) )", param.ParamName, param.ParamName)) @@ -1769,7 +1765,7 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co preCallCode = append(preCallCode, fmt.Sprintf("std::string %s(\"\");", variableName)) returnVariable = variableName - outCallParameters = outCallParameters + returnVariable; + outCallParameters = outCallParameters + returnVariable postCallCode = append(postCallCode, fmt.Sprintf("if (p%sNeededChars)", param.ParamName)) postCallCode = append(postCallCode, fmt.Sprintf(" *p%sNeededChars = (%s_uint32) (%s.size()+1);", param.ParamName, NameSpace, variableName)) @@ -1792,14 +1788,13 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co acqurireMethod := component.ImportedComponentDefinitions[paramNameSpace].Global.AcquireMethod returnVariable = fmt.Sprintf("p%s%s", paramNameSpace, param.ParamName) postCallCode = append(postCallCode, fmt.Sprintf("%s->%s(p%s%s.get());", theWrapper, acqurireMethod, paramNameSpace, param.ParamName)) - postCallCode = append(postCallCode, fmt.Sprintf("*%s = p%s%s->handle();", variableName, paramNameSpace, param.ParamName)); + postCallCode = append(postCallCode, fmt.Sprintf("*%s = p%s%s->handle();", variableName, paramNameSpace, param.ParamName)) } else { preCallCode = append(preCallCode, fmt.Sprintf("%s* pBase%s(nullptr);", IBaseClassName, param.ParamName)) returnVariable = fmt.Sprintf("pBase%s", param.ParamName) - postCallCode = append(postCallCode, fmt.Sprintf("*%s = (%s*)(pBase%s);", variableName, IBaseClassName, param.ParamName)); + postCallCode = append(postCallCode, fmt.Sprintf("*%s = (%s*)(pBase%s);", variableName, IBaseClassName, param.ParamName)) } - outCallParameters = outCallParameters + returnVariable; - + outCallParameters = outCallParameters + returnVariable default: return checkInputCode, preCallCode, postCallCode, "", "", "", fmt.Errorf("invalid method parameter type \"%s\" for %s.%s(%s)", param.ParamType, ClassName, method.MethodName, param.ParamName) @@ -1827,150 +1822,148 @@ func generateCallCPPFunctionCode(method ComponentDefinitionMethod, NameSpace str return callFunctionCode, nil } - func generateJournalFunctionCode(method ComponentDefinitionMethod, NameSpace string, ClassName string, isGlobal bool) ([]string, []string, error) { - journalInitFunctionCode := make([]string,0) - journalSuccessFunctionCode := make([]string,0) - - + journalInitFunctionCode := make([]string, 0) + journalSuccessFunctionCode := make([]string, 0) + journalInitFunctionCode = append(journalInitFunctionCode, fmt.Sprintf("if (m_GlobalJournal.get() != nullptr) {")) - if (isGlobal) { + if isGlobal { journalInitFunctionCode = append(journalInitFunctionCode, fmt.Sprintf(" pJournalEntry = m_GlobalJournal->beginStaticFunction(\"%s\");", method.MethodName)) } else { journalInitFunctionCode = append(journalInitFunctionCode, fmt.Sprintf(" pJournalEntry = m_GlobalJournal->beginClassMethod(p%s, \"%s\", \"%s\");", ClassName, ClassName, method.MethodName)) } - + for k := 0; k < len(method.Params); k++ { param := method.Params[k] variableName := getCppVariableName(param) - - if (param.ParamPass == "in") { - journalCall := ""; - - switch (param.ParamType) { - case "bool": - journalCall = "addBooleanParameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "uint8": - journalCall = "addUInt8Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "uint16": - journalCall = "addUInt16Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "uint32": - journalCall = "addUInt32Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "uint64": - journalCall = "addUInt64Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "int8": - journalCall = "addInt8Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "int16": - journalCall = "addInt16Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "int32": - journalCall = "addInt32Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "int64": - journalCall = "addInt64Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "single": - journalCall = "addSingleParameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "double": - journalCall = "addDoubleParameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "pointer": - journalCall = "addPointerParameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "string": - journalCall = "addStringParameter(\"" + param.ParamName+ "\", p" + param.ParamName + ")"; - - case "enum": - journalCall = "addEnumParameter(\"" + param.ParamName+ "\", \"" + param.ParamClass + "\", (" + NameSpace + "_int32)(" + variableName + "))"; - - case "class", "optionalclass": - journalCall = "addHandleParameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "struct": - case "basicarray": - case "structarray": - case "functiontype": - - default: - return journalInitFunctionCode, journalSuccessFunctionCode, fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s(%s)", param.ParamPass, ClassName, method.MethodName, param.ParamName) - + + if param.ParamPass == "in" { + journalCall := "" + + switch param.ParamType { + case "bool": + journalCall = "addBooleanParameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "uint8": + journalCall = "addUInt8Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "uint16": + journalCall = "addUInt16Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "uint32": + journalCall = "addUInt32Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "uint64": + journalCall = "addUInt64Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "int8": + journalCall = "addInt8Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "int16": + journalCall = "addInt16Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "int32": + journalCall = "addInt32Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "int64": + journalCall = "addInt64Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "single": + journalCall = "addSingleParameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "double": + journalCall = "addDoubleParameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "pointer": + journalCall = "addPointerParameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "string": + journalCall = "addStringParameter(\"" + param.ParamName + "\", p" + param.ParamName + ")" + + case "enum": + journalCall = "addEnumParameter(\"" + param.ParamName + "\", \"" + param.ParamClass + "\", (" + NameSpace + "_int32)(" + variableName + "))" + + case "class", "optionalclass": + journalCall = "addHandleParameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "struct": + case "basicarray": + case "structarray": + case "functiontype": + + default: + return journalInitFunctionCode, journalSuccessFunctionCode, fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s(%s)", param.ParamPass, ClassName, method.MethodName, param.ParamName) + } if journalCall != "" { journalInitFunctionCode = append(journalInitFunctionCode, fmt.Sprintf(" pJournalEntry->%s;", journalCall)) } - } + } } - + journalInitFunctionCode = append(journalInitFunctionCode, fmt.Sprintf("}")) journalSuccessFunctionCode = append(journalSuccessFunctionCode, fmt.Sprintf("if (pJournalEntry.get() != nullptr) {")) for k := 0; k < len(method.Params); k++ { param := method.Params[k] - + if (param.ParamPass == "out") || (param.ParamPass == "return") { - journalCall := ""; - - switch (param.ParamType) { - case "bool": - journalCall = "addBooleanResult(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "uint8": - journalCall = "addUInt8Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "uint16": - journalCall = "addUInt16Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "uint32": - journalCall = "addUInt32Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "uint64": - journalCall = "addUInt64Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "int8": - journalCall = "addInt8Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "int16": - journalCall = "addInt16Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "int32": - journalCall = "addInt32Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "int64": - journalCall = "addInt64Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "single": - journalCall = "addSingleResult(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "double": - journalCall = "addDoubleResult(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "pointer": - journalCall = "addPointerResult(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "string": - journalCall = "addStringResult(\"" + param.ParamName+ "\", s" + param.ParamName + ".c_str())"; - - case "enum": - journalCall = "addEnumResult(\"" + param.ParamName+ "\", \"" + param.ParamClass + "\", (" + NameSpace + "_int32)(*p" + param.ParamName + "))"; - - case "class", "optionalclass": - journalCall = "addHandleResult(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "struct": - case "basicarray": - case "structarray": - - default: - return journalInitFunctionCode, journalSuccessFunctionCode, fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s(%s)", param.ParamPass, ClassName, method.MethodName, param.ParamName) - + journalCall := "" + + switch param.ParamType { + case "bool": + journalCall = "addBooleanResult(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "uint8": + journalCall = "addUInt8Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "uint16": + journalCall = "addUInt16Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "uint32": + journalCall = "addUInt32Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "uint64": + journalCall = "addUInt64Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "int8": + journalCall = "addInt8Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "int16": + journalCall = "addInt16Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "int32": + journalCall = "addInt32Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "int64": + journalCall = "addInt64Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "single": + journalCall = "addSingleResult(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "double": + journalCall = "addDoubleResult(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "pointer": + journalCall = "addPointerResult(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "string": + journalCall = "addStringResult(\"" + param.ParamName + "\", s" + param.ParamName + ".c_str())" + + case "enum": + journalCall = "addEnumResult(\"" + param.ParamName + "\", \"" + param.ParamClass + "\", (" + NameSpace + "_int32)(*p" + param.ParamName + "))" + + case "class", "optionalclass": + journalCall = "addHandleResult(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "struct": + case "basicarray": + case "structarray": + + default: + return journalInitFunctionCode, journalSuccessFunctionCode, fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s(%s)", param.ParamPass, ClassName, method.MethodName, param.ParamName) + } if journalCall != "" { journalSuccessFunctionCode = append(journalSuccessFunctionCode, fmt.Sprintf(" pJournalEntry->%s;", journalCall)) @@ -1980,15 +1973,15 @@ func generateJournalFunctionCode(method ComponentDefinitionMethod, NameSpace str journalSuccessFunctionCode = append(journalSuccessFunctionCode, fmt.Sprintf(" pJournalEntry->writeSuccess();")) journalSuccessFunctionCode = append(journalSuccessFunctionCode, fmt.Sprintf("}")) - - return journalInitFunctionCode, journalSuccessFunctionCode, nil; + + return journalInitFunctionCode, journalSuccessFunctionCode, nil } func buildCMakeForCPPImplementation(component ComponentDefinition, w LanguageWriter, doJournal bool) { NameSpace := component.NameSpace BaseName := component.BaseName - + w.Writeln("cmake_minimum_required(VERSION 3.5)") w.Writeln("") @@ -1997,9 +1990,9 @@ func buildCMakeForCPPImplementation(component ComponentDefinition, w LanguageWri w.Writeln("") w.Writeln("set (CMAKE_CXX_STANDARD 11)") w.Writeln("") - + w.Writeln("# The location of autogenerated interfaces") - w.Writeln("set(CMAKE_CURRENT_AUTOGENERATED_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Interfaces)",) + w.Writeln("set(CMAKE_CURRENT_AUTOGENERATED_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Interfaces)") w.Writeln("") w.Writeln("file(GLOB %s_SRC", strings.ToUpper(NameSpace)) @@ -2012,7 +2005,7 @@ func buildCMakeForCPPImplementation(component ComponentDefinition, w LanguageWri w.Writeln("set(%s_SRC ${%s_SRC} ${%s_SRC}", strings.ToUpper(NameSpace), strings.ToUpper(NameSpace), strings.ToUpper(NameSpace)) w.Writeln(" ${CMAKE_CURRENT_AUTOGENERATED_DIR}/%s_interfaceexception.cpp", strings.ToLower(BaseName)) w.Writeln(" ${CMAKE_CURRENT_AUTOGENERATED_DIR}/%s_interfacewrapper.cpp", strings.ToLower(BaseName)) - if (doJournal) { + if doJournal { w.Writeln(" ${CMAKE_CURRENT_AUTOGENERATED_DIR}/%s_interfacejournal.cpp", strings.ToLower(BaseName)) } w.Writeln(")") @@ -2029,7 +2022,7 @@ func buildCMakeForCPPImplementation(component ComponentDefinition, w LanguageWri w.Writeln("target_compile_options(%s PRIVATE \"-D__%s_EXPORTS\")", targetName, strings.ToUpper(NameSpace)) w.Writeln("target_include_directories(%s PRIVATE ${CMAKE_CURRENT_AUTOGENERATED_DIR})", targetName) w.Writeln("target_include_directories(%s PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Stub)", targetName) - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { w.Writeln("target_include_directories(%s PRIVATE \"${CMAKE_CURRENT_SOURCE_DIR}/../../../%s_component/Bindings/CppDynamic\")", targetName, subComponent.NameSpace) } } @@ -2039,430 +2032,426 @@ func buildJournalingCPP(component ComponentDefinition, headerw LanguageWriter, i NameSpace := component.NameSpace BaseName := component.BaseName - headerw.Writeln("#ifndef __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper (NameSpace)); - headerw.Writeln("#define __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper (NameSpace)); - headerw.Writeln(""); - headerw.Writeln("#include "); - headerw.Writeln("#include "); - headerw.Writeln("#include "); - headerw.Writeln("#include "); - headerw.Writeln("#include "); - headerw.Writeln("#include "); - headerw.Writeln("#include "); - headerw.Writeln("#include \"%s_types.hpp\"", BaseName); - headerw.Writeln(""); - headerw.Writeln("/*************************************************************************************************************************"); - headerw.Writeln(" Class C%sInterfaceJournal ", NameSpace); - headerw.Writeln("**************************************************************************************************************************/"); - headerw.Writeln(""); - headerw.Writeln("class C%sInterfaceJournal;", NameSpace); - headerw.Writeln(""); - headerw.Writeln("class C%sInterfaceJournalEntry {", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" protected:"); - headerw.Writeln(""); - headerw.Writeln(" C%sInterfaceJournal * m_pJournal;", NameSpace); - headerw.Writeln(" %sResult m_ErrorCode;", NameSpace); - headerw.Writeln(" std::string m_sClassName;"); - headerw.Writeln(" std::string m_sMethodName;"); - headerw.Writeln(" std::string m_sInstanceHandle;"); - headerw.Writeln(" %s_uint64 m_nInitTimeStamp;", NameSpace); - headerw.Writeln(" %s_uint64 m_nFinishTimeStamp;", NameSpace); - headerw.Writeln(" std::list, std::string>> m_sParameters;"); - headerw.Writeln(" std::list, std::string>> m_sResultValues;"); - headerw.Writeln(""); - headerw.Writeln(" std::string getXMLString();"); - headerw.Writeln(" void addParameter (const std::string & sName, const std::string & sParameterType, const std::string & sParameterValue);"); - headerw.Writeln(" void addResult (const std::string & sName, const std::string & sResultType, const std::string & sResultValue);"); - - headerw.Writeln(""); - headerw.Writeln(" public:"); - headerw.Writeln(" C%sInterfaceJournalEntry(C%sInterfaceJournal * pJournal, std::string sClassName, std::string sMethodName, %sHandle pInstanceHandle);", NameSpace, NameSpace, NameSpace); - headerw.Writeln(" ~C%sInterfaceJournalEntry();", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" void writeSuccess ();"); - headerw.Writeln(" void writeError (%sResult nErrorCode);", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" void addBooleanParameter(const std::string & sName, const bool bValue);"); - headerw.Writeln(" void addUInt8Parameter(const std::string & sName, const %s_uint8 nValue);", NameSpace); - headerw.Writeln(" void addUInt16Parameter(const std::string & sName, const %s_uint16 nValue);", NameSpace); - headerw.Writeln(" void addUInt32Parameter(const std::string & sName, const %s_uint32 nValue);", NameSpace); - headerw.Writeln(" void addUInt64Parameter(const std::string & sName, const %s_uint64 nValue);", NameSpace); - headerw.Writeln(" void addInt8Parameter(const std::string & sName, const %s_int8 nValue);", NameSpace); - headerw.Writeln(" void addInt16Parameter(const std::string & sName, const %s_int16 nValue);", NameSpace); - headerw.Writeln(" void addInt32Parameter(const std::string & sName, const %s_int32 nValue);", NameSpace); - headerw.Writeln(" void addInt64Parameter(const std::string & sName, const %s_int64 nValue);", NameSpace); - headerw.Writeln(" void addSingleParameter(const std::string & sName, const %s_single fValue);", NameSpace); - headerw.Writeln(" void addDoubleParameter(const std::string & sName, const %s_double dValue);", NameSpace); - headerw.Writeln(" void addPointerParameter(const std::string & sName, const %s_pvoid pValue);", NameSpace); - headerw.Writeln(" void addStringParameter(const std::string & sName, const char * pValue);"); - headerw.Writeln(" void addHandleParameter(const std::string & sName, const %sHandle pHandle);", NameSpace); - headerw.Writeln(" void addEnumParameter(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue);", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" void addBooleanResult(const std::string & sName, const bool bValue);"); - headerw.Writeln(" void addUInt8Result(const std::string & sName, const %s_uint8 nValue);", NameSpace); - headerw.Writeln(" void addUInt16Result(const std::string & sName, const %s_uint16 nValue);", NameSpace); - headerw.Writeln(" void addUInt32Result(const std::string & sName, const %s_uint32 nValue);", NameSpace); - headerw.Writeln(" void addUInt64Result(const std::string & sName, const %s_uint64 nValue);", NameSpace); - headerw.Writeln(" void addInt8Result(const std::string & sName, const %s_int8 nValue);", NameSpace); - headerw.Writeln(" void addInt16Result(const std::string & sName, const %s_int16 nValue);", NameSpace); - headerw.Writeln(" void addInt32Result(const std::string & sName, const %s_int32 nValue);", NameSpace); - headerw.Writeln(" void addInt64Result(const std::string & sName, const %s_int64 nValue);", NameSpace); - headerw.Writeln(" void addSingleResult(const std::string & sName, const %s_single fValue);", NameSpace); - headerw.Writeln(" void addDoubleResult(const std::string & sName, const %s_double dValue);", NameSpace); - headerw.Writeln(" void addPointerResult(const std::string & sName, const %s_pvoid pValue);", NameSpace); - headerw.Writeln(" void addStringResult(const std::string & sName, const char * pValue);"); - headerw.Writeln(" void addHandleResult(const std::string & sName, const %sHandle pHandle);", NameSpace); - headerw.Writeln(" void addEnumResult(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue);", NameSpace); - headerw.Writeln(""); - headerw.Writeln("friend class C%sInterfaceJournal;", NameSpace); - headerw.Writeln(""); - headerw.Writeln("};"); - headerw.Writeln(""); - headerw.Writeln("typedef std::shared_ptr P%sInterfaceJournalEntry;", NameSpace, NameSpace); - headerw.Writeln(""); - headerw.Writeln(""); - headerw.Writeln(""); - - - headerw.Writeln("class C%sInterfaceJournal {", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" protected:"); - headerw.Writeln(""); - headerw.Writeln(" std::string m_sFileName;"); - headerw.Writeln(" std::mutex m_Mutex;"); - headerw.Writeln(" std::ofstream m_Stream;"); - headerw.Writeln(" std::chrono::time_point m_StartTime;"); - headerw.Writeln(" void writeEntry (C%sInterfaceJournalEntry * pEntry);", NameSpace); - headerw.Writeln(" %s_uint64 getTimeStamp ();", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" public:"); - headerw.Writeln(""); - headerw.Writeln(" C%sInterfaceJournal (const std::string & sFileName);", NameSpace); - headerw.Writeln(" ~C%sInterfaceJournal ();", NameSpace); - headerw.Writeln(" P%sInterfaceJournalEntry beginClassMethod (const %sHandle pHandle, const std::string & sClassName, const std::string & sMethodName);", NameSpace, NameSpace); - headerw.Writeln(" P%sInterfaceJournalEntry beginStaticFunction (const std::string & sMethodName);", NameSpace); - headerw.Writeln(" friend class C%sInterfaceJournalEntry;", NameSpace); - headerw.Writeln("};"); - headerw.Writeln(""); - headerw.Writeln("typedef std::shared_ptr P%sInterfaceJournal;", NameSpace, NameSpace); - headerw.Writeln(""); - headerw.Writeln("#endif // __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper (NameSpace)); - headerw.Writeln(""); - - - implw.Writeln(""); - implw.Writeln("#include "); - implw.Writeln("#include "); - implw.Writeln("#include "); - implw.Writeln(""); - implw.Writeln("#include \"%s_interfacejournal.hpp\"", strings.ToLower(BaseName)); - implw.Writeln("#include \"%s_interfaceexception.hpp\"", strings.ToLower(BaseName)); - implw.Writeln(""); - implw.Writeln(""); - - implw.Writeln("std::string %sHandleToHex (%sHandle pHandle)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" std::stringstream stream;"); - implw.Writeln(" stream << std::setfill('0') << std::setw(sizeof(%s_uint64) * 2)", NameSpace); - implw.Writeln(" << std::hex << (%s_uint64) pHandle;", NameSpace); - implw.Writeln(" return stream.str();"); - implw.Writeln("}"); - implw.Writeln(""); - - implw.Writeln("C%sInterfaceJournalEntry::C%sInterfaceJournalEntry(C%sInterfaceJournal * pJournal, std::string sClassName, std::string sMethodName, %sHandle pInstanceHandle)", NameSpace, NameSpace, NameSpace, NameSpace); + headerw.Writeln("#ifndef __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper(NameSpace)) + headerw.Writeln("#define __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper(NameSpace)) + headerw.Writeln("") + headerw.Writeln("#include ") + headerw.Writeln("#include ") + headerw.Writeln("#include ") + headerw.Writeln("#include ") + headerw.Writeln("#include ") + headerw.Writeln("#include ") + headerw.Writeln("#include ") + headerw.Writeln("#include \"%s_types.hpp\"", BaseName) + headerw.Writeln("") + headerw.Writeln("/*************************************************************************************************************************") + headerw.Writeln(" Class C%sInterfaceJournal ", NameSpace) + headerw.Writeln("**************************************************************************************************************************/") + headerw.Writeln("") + headerw.Writeln("class C%sInterfaceJournal;", NameSpace) + headerw.Writeln("") + headerw.Writeln("class C%sInterfaceJournalEntry {", NameSpace) + headerw.Writeln("") + headerw.Writeln(" protected:") + headerw.Writeln("") + headerw.Writeln(" C%sInterfaceJournal * m_pJournal;", NameSpace) + headerw.Writeln(" %sResult m_ErrorCode;", NameSpace) + headerw.Writeln(" std::string m_sClassName;") + headerw.Writeln(" std::string m_sMethodName;") + headerw.Writeln(" std::string m_sInstanceHandle;") + headerw.Writeln(" %s_uint64 m_nInitTimeStamp;", NameSpace) + headerw.Writeln(" %s_uint64 m_nFinishTimeStamp;", NameSpace) + headerw.Writeln(" std::list, std::string>> m_sParameters;") + headerw.Writeln(" std::list, std::string>> m_sResultValues;") + headerw.Writeln("") + headerw.Writeln(" std::string getXMLString();") + headerw.Writeln(" void addParameter (const std::string & sName, const std::string & sParameterType, const std::string & sParameterValue);") + headerw.Writeln(" void addResult (const std::string & sName, const std::string & sResultType, const std::string & sResultValue);") + + headerw.Writeln("") + headerw.Writeln(" public:") + headerw.Writeln(" C%sInterfaceJournalEntry(C%sInterfaceJournal * pJournal, std::string sClassName, std::string sMethodName, %sHandle pInstanceHandle);", NameSpace, NameSpace, NameSpace) + headerw.Writeln(" ~C%sInterfaceJournalEntry();", NameSpace) + headerw.Writeln("") + headerw.Writeln(" void writeSuccess ();") + headerw.Writeln(" void writeError (%sResult nErrorCode);", NameSpace) + headerw.Writeln("") + headerw.Writeln(" void addBooleanParameter(const std::string & sName, const bool bValue);") + headerw.Writeln(" void addUInt8Parameter(const std::string & sName, const %s_uint8 nValue);", NameSpace) + headerw.Writeln(" void addUInt16Parameter(const std::string & sName, const %s_uint16 nValue);", NameSpace) + headerw.Writeln(" void addUInt32Parameter(const std::string & sName, const %s_uint32 nValue);", NameSpace) + headerw.Writeln(" void addUInt64Parameter(const std::string & sName, const %s_uint64 nValue);", NameSpace) + headerw.Writeln(" void addInt8Parameter(const std::string & sName, const %s_int8 nValue);", NameSpace) + headerw.Writeln(" void addInt16Parameter(const std::string & sName, const %s_int16 nValue);", NameSpace) + headerw.Writeln(" void addInt32Parameter(const std::string & sName, const %s_int32 nValue);", NameSpace) + headerw.Writeln(" void addInt64Parameter(const std::string & sName, const %s_int64 nValue);", NameSpace) + headerw.Writeln(" void addSingleParameter(const std::string & sName, const %s_single fValue);", NameSpace) + headerw.Writeln(" void addDoubleParameter(const std::string & sName, const %s_double dValue);", NameSpace) + headerw.Writeln(" void addPointerParameter(const std::string & sName, const %s_pvoid pValue);", NameSpace) + headerw.Writeln(" void addStringParameter(const std::string & sName, const char * pValue);") + headerw.Writeln(" void addHandleParameter(const std::string & sName, const %sHandle pHandle);", NameSpace) + headerw.Writeln(" void addEnumParameter(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue);", NameSpace) + headerw.Writeln("") + headerw.Writeln(" void addBooleanResult(const std::string & sName, const bool bValue);") + headerw.Writeln(" void addUInt8Result(const std::string & sName, const %s_uint8 nValue);", NameSpace) + headerw.Writeln(" void addUInt16Result(const std::string & sName, const %s_uint16 nValue);", NameSpace) + headerw.Writeln(" void addUInt32Result(const std::string & sName, const %s_uint32 nValue);", NameSpace) + headerw.Writeln(" void addUInt64Result(const std::string & sName, const %s_uint64 nValue);", NameSpace) + headerw.Writeln(" void addInt8Result(const std::string & sName, const %s_int8 nValue);", NameSpace) + headerw.Writeln(" void addInt16Result(const std::string & sName, const %s_int16 nValue);", NameSpace) + headerw.Writeln(" void addInt32Result(const std::string & sName, const %s_int32 nValue);", NameSpace) + headerw.Writeln(" void addInt64Result(const std::string & sName, const %s_int64 nValue);", NameSpace) + headerw.Writeln(" void addSingleResult(const std::string & sName, const %s_single fValue);", NameSpace) + headerw.Writeln(" void addDoubleResult(const std::string & sName, const %s_double dValue);", NameSpace) + headerw.Writeln(" void addPointerResult(const std::string & sName, const %s_pvoid pValue);", NameSpace) + headerw.Writeln(" void addStringResult(const std::string & sName, const char * pValue);") + headerw.Writeln(" void addHandleResult(const std::string & sName, const %sHandle pHandle);", NameSpace) + headerw.Writeln(" void addEnumResult(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue);", NameSpace) + headerw.Writeln("") + headerw.Writeln("friend class C%sInterfaceJournal;", NameSpace) + headerw.Writeln("") + headerw.Writeln("};") + headerw.Writeln("") + headerw.Writeln("typedef std::shared_ptr P%sInterfaceJournalEntry;", NameSpace, NameSpace) + headerw.Writeln("") + headerw.Writeln("") + headerw.Writeln("") + + headerw.Writeln("class C%sInterfaceJournal {", NameSpace) + headerw.Writeln("") + headerw.Writeln(" protected:") + headerw.Writeln("") + headerw.Writeln(" std::string m_sFileName;") + headerw.Writeln(" std::mutex m_Mutex;") + headerw.Writeln(" std::ofstream m_Stream;") + headerw.Writeln(" std::chrono::time_point m_StartTime;") + headerw.Writeln(" void writeEntry (C%sInterfaceJournalEntry * pEntry);", NameSpace) + headerw.Writeln(" %s_uint64 getTimeStamp ();", NameSpace) + headerw.Writeln("") + headerw.Writeln(" public:") + headerw.Writeln("") + headerw.Writeln(" C%sInterfaceJournal (const std::string & sFileName);", NameSpace) + headerw.Writeln(" ~C%sInterfaceJournal ();", NameSpace) + headerw.Writeln(" P%sInterfaceJournalEntry beginClassMethod (const %sHandle pHandle, const std::string & sClassName, const std::string & sMethodName);", NameSpace, NameSpace) + headerw.Writeln(" P%sInterfaceJournalEntry beginStaticFunction (const std::string & sMethodName);", NameSpace) + headerw.Writeln(" friend class C%sInterfaceJournalEntry;", NameSpace) + headerw.Writeln("};") + headerw.Writeln("") + headerw.Writeln("typedef std::shared_ptr P%sInterfaceJournal;", NameSpace, NameSpace) + headerw.Writeln("") + headerw.Writeln("#endif // __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper(NameSpace)) + headerw.Writeln("") + + implw.Writeln("") + implw.Writeln("#include ") + implw.Writeln("#include ") + implw.Writeln("#include ") + implw.Writeln("") + implw.Writeln("#include \"%s_interfacejournal.hpp\"", strings.ToLower(BaseName)) + implw.Writeln("#include \"%s_interfaceexception.hpp\"", strings.ToLower(BaseName)) + implw.Writeln("") + implw.Writeln("") + + implw.Writeln("std::string %sHandleToHex (%sHandle pHandle)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" std::stringstream stream;") + implw.Writeln(" stream << std::setfill('0') << std::setw(sizeof(%s_uint64) * 2)", NameSpace) + implw.Writeln(" << std::hex << (%s_uint64) pHandle;", NameSpace) + implw.Writeln(" return stream.str();") + implw.Writeln("}") + implw.Writeln("") + + implw.Writeln("C%sInterfaceJournalEntry::C%sInterfaceJournalEntry(C%sInterfaceJournal * pJournal, std::string sClassName, std::string sMethodName, %sHandle pInstanceHandle)", NameSpace, NameSpace, NameSpace, NameSpace) implw.Writeln(" : m_pJournal(pJournal), m_ErrorCode(%s_SUCCESS), m_sClassName(sClassName), m_sMethodName(sMethodName), m_nInitTimeStamp(0), m_nFinishTimeStamp(0)", strings.ToUpper(NameSpace)) - implw.Writeln("{"); - implw.Writeln(" if (pJournal == nullptr)"); - implw.Writeln(" throw E%sInterfaceException(%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper (NameSpace)); - implw.Writeln(" m_nInitTimeStamp = m_pJournal->getTimeStamp ();"); - implw.Writeln(" m_sInstanceHandle = %sHandleToHex (pInstanceHandle);", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("C%sInterfaceJournalEntry::~C%sInterfaceJournalEntry()", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addParameter(const std::string & sName, const std::string & sParameterType, const std::string & sParameterValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" m_sParameters.push_back(std::make_pair(std::make_pair(sName, sParameterType), sParameterValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addResult(const std::string & sName, const std::string & sResultType, const std::string & sResultValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" m_sResultValues.push_back(std::make_pair(std::make_pair(sName, sResultType), sResultValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("std::string C%sInterfaceJournalEntry::getXMLString()", NameSpace); - implw.Writeln("{"); - implw.Writeln(" std::stringstream sStream;"); - implw.Writeln(" %s_uint64 nDuration = 0;", NameSpace); - implw.Writeln(""); - implw.Writeln(" if (m_nFinishTimeStamp > m_nInitTimeStamp)"); - implw.Writeln(" nDuration = m_nFinishTimeStamp - m_nInitTimeStamp;"); - implw.Writeln(""); - implw.Writeln(" sStream << \" \\n\";"); - implw.Writeln(""); - implw.Writeln(" if (m_sClassName != \"\")"); - implw.Writeln(" sStream << \" \\n\";"); - implw.Writeln(""); - implw.Writeln(" auto iParamIter = m_sParameters.begin();"); - implw.Writeln(" while (iParamIter != m_sParameters.end()) {"); - implw.Writeln(" sStream << \" first.first << \"\\\" type=\\\"\" << iParamIter->first.second << \"\\\" value=\\\"\" << iParamIter->second <<\"\\\" />\\n\";"); - implw.Writeln(" iParamIter++;"); - implw.Writeln(" }"); - implw.Writeln(""); - implw.Writeln(" auto iResultIter = m_sResultValues.begin();",); - implw.Writeln(" while (iResultIter != m_sResultValues.end()) {"); - implw.Writeln(" sStream << \" first.first << \"\\\" type=\\\"\" << iResultIter->first.second << \"\\\" value=\\\"\" << iResultIter->second << \"\\\" />\\n\";"); - implw.Writeln(" iResultIter++;"); - implw.Writeln(" }"); - implw.Writeln(""); - implw.Writeln(" sStream << \" \\n\";"); - implw.Writeln(" return sStream.str ();"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::writeSuccess()", NameSpace); - implw.Writeln("{"); - implw.Writeln(" writeError(%s_SUCCESS);", strings.ToUpper (NameSpace)); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::writeError(%sResult nErrorCode)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" m_ErrorCode = nErrorCode;"); - implw.Writeln(" m_nFinishTimeStamp = m_pJournal->getTimeStamp();"); - implw.Writeln(" m_pJournal->writeEntry(this);"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addBooleanParameter(const std::string & sName, const bool bValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter (sName, \"bool\", std::to_string((int)bValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt8Parameter(const std::string & sName, const %s_uint8 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"uint8\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt16Parameter(const std::string & sName, const %s_uint16 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"uint16\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt32Parameter(const std::string & sName, const %s_uint32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"uint32\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt64Parameter(const std::string & sName, const %s_uint64 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"uint64\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt8Parameter(const std::string & sName, const %s_int8 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"int8\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt16Parameter(const std::string & sName, const %s_int16 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"int16\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt32Parameter(const std::string & sName, const %s_int32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"uint32\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt64Parameter(const std::string & sName, const %s_int64 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"int64\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addSingleParameter(const std::string & sName, const %s_single fValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"single\", std::to_string(fValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addDoubleParameter(const std::string & sName, const %s_double dValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"double\", std::to_string(dValue));"); - implw.Writeln("}"); - implw.Writeln("void C%sInterfaceJournalEntry::addPointerParameter(const std::string & sName, const %s_pvoid pValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"pointer\", std::to_string(reinterpret_cast(pValue)));", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addStringParameter(const std::string & sName, const char * pValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" if (pValue != nullptr) {"); - implw.Writeln(" addParameter(sName, \"string\", pValue);"); - implw.Writeln(" }"); - implw.Writeln(" else {"); - implw.Writeln(" addParameter(sName, \"nullstring\", \"\");"); - implw.Writeln(" }"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addHandleParameter(const std::string & sName, const %sHandle pHandle)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"handle\", %sHandleToHex(pHandle));", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addEnumParameter(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"enum\" + sEnumType, std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addBooleanResult(const std::string & sName, const bool bValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"bool\", std::to_string((int)bValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt8Result(const std::string & sName, const %s_uint8 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"uint8\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt16Result(const std::string & sName, const %s_uint16 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"uint16\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt32Result(const std::string & sName, const %s_uint32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"uint32\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt64Result(const std::string & sName, const %s_uint64 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"uint64\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt8Result(const std::string & sName, const %s_int8 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"int8\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt16Result(const std::string & sName, const %s_int16 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"int16\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt32Result(const std::string & sName, const %s_int32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"uint32\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt64Result(const std::string & sName, const %s_int64 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"int64\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addSingleResult(const std::string & sName, const %s_single fValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"single\", std::to_string(fValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addDoubleResult(const std::string & sName, const %s_double dValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"double\", std::to_string(dValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addPointerResult(const std::string & sName, const %s_pvoid pValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"pointer\", std::to_string(reinterpret_cast(pValue)));", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addStringResult(const std::string & sName, const char * pValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" if (pValue != nullptr) {"); - implw.Writeln(" addResult(sName, \"string\", pValue);"); - implw.Writeln(" }"); - implw.Writeln(" else {"); - implw.Writeln(" addResult(sName, \"nullstring\", \"\");"); - implw.Writeln(" }"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addHandleResult(const std::string & sName, const %sHandle pHandle)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"handle\", %sHandleToHex(pHandle));", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addEnumResult(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"enum\" + sEnumType, std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln(""); - implw.Writeln("C%sInterfaceJournal::C%sInterfaceJournal (const std::string & sFileName)", NameSpace, NameSpace); - implw.Writeln(" : m_sFileName (sFileName)"); - implw.Writeln("{"); - implw.Writeln(" m_StartTime = std::chrono::high_resolution_clock::now();"); - implw.Writeln(" m_Stream.open (sFileName, std::ios::out);"); - implw.Writeln(" m_Stream << \"\\n\";"); + implw.Writeln("{") + implw.Writeln(" if (pJournal == nullptr)") + implw.Writeln(" throw E%sInterfaceException(%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper(NameSpace)) + implw.Writeln(" m_nInitTimeStamp = m_pJournal->getTimeStamp ();") + implw.Writeln(" m_sInstanceHandle = %sHandleToHex (pInstanceHandle);", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("C%sInterfaceJournalEntry::~C%sInterfaceJournalEntry()", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addParameter(const std::string & sName, const std::string & sParameterType, const std::string & sParameterValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" m_sParameters.push_back(std::make_pair(std::make_pair(sName, sParameterType), sParameterValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addResult(const std::string & sName, const std::string & sResultType, const std::string & sResultValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" m_sResultValues.push_back(std::make_pair(std::make_pair(sName, sResultType), sResultValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("std::string C%sInterfaceJournalEntry::getXMLString()", NameSpace) + implw.Writeln("{") + implw.Writeln(" std::stringstream sStream;") + implw.Writeln(" %s_uint64 nDuration = 0;", NameSpace) + implw.Writeln("") + implw.Writeln(" if (m_nFinishTimeStamp > m_nInitTimeStamp)") + implw.Writeln(" nDuration = m_nFinishTimeStamp - m_nInitTimeStamp;") + implw.Writeln("") + implw.Writeln(" sStream << \" \\n\";") + implw.Writeln("") + implw.Writeln(" if (m_sClassName != \"\")") + implw.Writeln(" sStream << \" \\n\";") + implw.Writeln("") + implw.Writeln(" auto iParamIter = m_sParameters.begin();") + implw.Writeln(" while (iParamIter != m_sParameters.end()) {") + implw.Writeln(" sStream << \" first.first << \"\\\" type=\\\"\" << iParamIter->first.second << \"\\\" value=\\\"\" << iParamIter->second <<\"\\\" />\\n\";") + implw.Writeln(" iParamIter++;") + implw.Writeln(" }") + implw.Writeln("") + implw.Writeln(" auto iResultIter = m_sResultValues.begin();") + implw.Writeln(" while (iResultIter != m_sResultValues.end()) {") + implw.Writeln(" sStream << \" first.first << \"\\\" type=\\\"\" << iResultIter->first.second << \"\\\" value=\\\"\" << iResultIter->second << \"\\\" />\\n\";") + implw.Writeln(" iResultIter++;") + implw.Writeln(" }") + implw.Writeln("") + implw.Writeln(" sStream << \" \\n\";") + implw.Writeln(" return sStream.str ();") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::writeSuccess()", NameSpace) + implw.Writeln("{") + implw.Writeln(" writeError(%s_SUCCESS);", strings.ToUpper(NameSpace)) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::writeError(%sResult nErrorCode)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" m_ErrorCode = nErrorCode;") + implw.Writeln(" m_nFinishTimeStamp = m_pJournal->getTimeStamp();") + implw.Writeln(" m_pJournal->writeEntry(this);") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addBooleanParameter(const std::string & sName, const bool bValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter (sName, \"bool\", std::to_string((int)bValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt8Parameter(const std::string & sName, const %s_uint8 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"uint8\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt16Parameter(const std::string & sName, const %s_uint16 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"uint16\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt32Parameter(const std::string & sName, const %s_uint32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"uint32\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt64Parameter(const std::string & sName, const %s_uint64 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"uint64\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt8Parameter(const std::string & sName, const %s_int8 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"int8\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt16Parameter(const std::string & sName, const %s_int16 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"int16\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt32Parameter(const std::string & sName, const %s_int32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"uint32\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt64Parameter(const std::string & sName, const %s_int64 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"int64\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addSingleParameter(const std::string & sName, const %s_single fValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"single\", std::to_string(fValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addDoubleParameter(const std::string & sName, const %s_double dValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"double\", std::to_string(dValue));") + implw.Writeln("}") + implw.Writeln("void C%sInterfaceJournalEntry::addPointerParameter(const std::string & sName, const %s_pvoid pValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"pointer\", std::to_string(reinterpret_cast(pValue)));", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addStringParameter(const std::string & sName, const char * pValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" if (pValue != nullptr) {") + implw.Writeln(" addParameter(sName, \"string\", pValue);") + implw.Writeln(" }") + implw.Writeln(" else {") + implw.Writeln(" addParameter(sName, \"nullstring\", \"\");") + implw.Writeln(" }") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addHandleParameter(const std::string & sName, const %sHandle pHandle)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"handle\", %sHandleToHex(pHandle));", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addEnumParameter(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"enum\" + sEnumType, std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addBooleanResult(const std::string & sName, const bool bValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"bool\", std::to_string((int)bValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt8Result(const std::string & sName, const %s_uint8 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"uint8\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt16Result(const std::string & sName, const %s_uint16 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"uint16\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt32Result(const std::string & sName, const %s_uint32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"uint32\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt64Result(const std::string & sName, const %s_uint64 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"uint64\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt8Result(const std::string & sName, const %s_int8 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"int8\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt16Result(const std::string & sName, const %s_int16 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"int16\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt32Result(const std::string & sName, const %s_int32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"uint32\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt64Result(const std::string & sName, const %s_int64 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"int64\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addSingleResult(const std::string & sName, const %s_single fValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"single\", std::to_string(fValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addDoubleResult(const std::string & sName, const %s_double dValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"double\", std::to_string(dValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addPointerResult(const std::string & sName, const %s_pvoid pValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"pointer\", std::to_string(reinterpret_cast(pValue)));", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addStringResult(const std::string & sName, const char * pValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" if (pValue != nullptr) {") + implw.Writeln(" addResult(sName, \"string\", pValue);") + implw.Writeln(" }") + implw.Writeln(" else {") + implw.Writeln(" addResult(sName, \"nullstring\", \"\");") + implw.Writeln(" }") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addHandleResult(const std::string & sName, const %sHandle pHandle)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"handle\", %sHandleToHex(pHandle));", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addEnumResult(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"enum\" + sEnumType, std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("") + implw.Writeln("C%sInterfaceJournal::C%sInterfaceJournal (const std::string & sFileName)", NameSpace, NameSpace) + implw.Writeln(" : m_sFileName (sFileName)") + implw.Writeln("{") + implw.Writeln(" m_StartTime = std::chrono::high_resolution_clock::now();") + implw.Writeln(" m_Stream.open (sFileName, std::ios::out);") + implw.Writeln(" m_Stream << \"\\n\";") implw.Writeln(" m_Stream << \"\\n\";", - NameSpace, component.Version, NameSpace, component.Version); - implw.Writeln(" m_Stream << \"\\n\";"); - implw.Writeln(""); - - - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("C%sInterfaceJournal::~C%sInterfaceJournal ()", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" m_Stream << \"\\n\";"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("P%sInterfaceJournalEntry C%sInterfaceJournal::beginClassMethod(const %sHandle pHandle, const std::string & sClassName, const std::string & sMethodName)", NameSpace, NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" return std::make_shared(this, sClassName, sMethodName, pHandle);", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("P%sInterfaceJournalEntry C%sInterfaceJournal::beginStaticFunction(const std::string & sMethodName)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" return std::make_shared(this, \"\", sMethodName, nullptr);", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournal::writeEntry (C%sInterfaceJournalEntry * pEntry)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" if (pEntry == nullptr)"); - implw.Writeln(" throw E%sInterfaceException (%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper (NameSpace)); - implw.Writeln(""); - implw.Writeln(" std::string sXMLString = pEntry->getXMLString();"); - implw.Writeln(" m_Mutex.lock();"); - implw.Writeln(" try {"); - implw.Writeln(" m_Stream << sXMLString;"); - implw.Writeln(" m_Stream << \"\\n\";"); - implw.Writeln(""); - implw.Writeln(" m_Mutex.unlock();"); - implw.Writeln(" }"); - implw.Writeln(" catch (...) {"); - implw.Writeln(" m_Mutex.unlock();"); - implw.Writeln(" }"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("%s_uint64 C%sInterfaceJournal::getTimeStamp ()", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" auto currentTime = std::chrono::high_resolution_clock::now();"); - implw.Writeln(" if (m_StartTime < currentTime) {"); - implw.Writeln(" auto duration = currentTime - m_StartTime;"); - implw.Writeln(" auto milliSeconds = std::chrono::duration_cast (duration);"); - implw.Writeln(""); - implw.Writeln(" return (%s_uint64) milliSeconds.count();", NameSpace); - implw.Writeln(" }"); - implw.Writeln(" else {"); - implw.Writeln(" return 0;"); - implw.Writeln(" }"); - implw.Writeln(""); - implw.Writeln("}"); - implw.Writeln(""); - - return nil; -} + NameSpace, component.Version, NameSpace, component.Version) + implw.Writeln(" m_Stream << \"\\n\";") + implw.Writeln("") + + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("C%sInterfaceJournal::~C%sInterfaceJournal ()", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" m_Stream << \"\\n\";") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("P%sInterfaceJournalEntry C%sInterfaceJournal::beginClassMethod(const %sHandle pHandle, const std::string & sClassName, const std::string & sMethodName)", NameSpace, NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" return std::make_shared(this, sClassName, sMethodName, pHandle);", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("P%sInterfaceJournalEntry C%sInterfaceJournal::beginStaticFunction(const std::string & sMethodName)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" return std::make_shared(this, \"\", sMethodName, nullptr);", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournal::writeEntry (C%sInterfaceJournalEntry * pEntry)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" if (pEntry == nullptr)") + implw.Writeln(" throw E%sInterfaceException (%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper(NameSpace)) + implw.Writeln("") + implw.Writeln(" std::string sXMLString = pEntry->getXMLString();") + implw.Writeln(" m_Mutex.lock();") + implw.Writeln(" try {") + implw.Writeln(" m_Stream << sXMLString;") + implw.Writeln(" m_Stream << \"\\n\";") + implw.Writeln("") + implw.Writeln(" m_Mutex.unlock();") + implw.Writeln(" }") + implw.Writeln(" catch (...) {") + implw.Writeln(" m_Mutex.unlock();") + implw.Writeln(" }") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("%s_uint64 C%sInterfaceJournal::getTimeStamp ()", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" auto currentTime = std::chrono::high_resolution_clock::now();") + implw.Writeln(" if (m_StartTime < currentTime) {") + implw.Writeln(" auto duration = currentTime - m_StartTime;") + implw.Writeln(" auto milliSeconds = std::chrono::duration_cast (duration);") + implw.Writeln("") + implw.Writeln(" return (%s_uint64) milliSeconds.count();", NameSpace) + implw.Writeln(" }") + implw.Writeln(" else {") + implw.Writeln(" return 0;") + implw.Writeln(" }") + implw.Writeln("") + implw.Writeln("}") + implw.Writeln("") + return nil +} diff --git a/Source/buildimplementationjs.go b/Source/buildimplementationjs.go new file mode 100644 index 00000000..8b4a8e6c --- /dev/null +++ b/Source/buildimplementationjs.go @@ -0,0 +1,1327 @@ +/*++ + +Copyright (C) 2018 Autodesk Inc. (Original Author) + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--*/ + +////////////////////////////////////////////////////////////////////////////////////////////////////// +// buildimplementationjs.go +// functions to generate C++ interface classes, implementation stubs and wrapper code that maps to +// the C-header. +////////////////////////////////////////////////////////////////////////////////////////////////////// + +package main + +import ( + "fmt" + "log" + "path" + "strings" +) + +// BuildImplementationJS builds C++ interface classes, implementation stubs and wrapper code that maps to the C-header +func BuildImplementationJS(component ComponentDefinition, outputFolder string, stubOutputFolder string, projectOutputFolder string, implementation ComponentDefinitionImplementation, suppressStub bool, suppressInterfaces bool, outputFolderDocumentation string) error { + + doJournal := len(component.Global.JournalMethod) > 0 + + NameSpace := component.NameSpace + LibraryName := component.LibraryName + BaseName := component.BaseName + ImplementationSubNameSpace := "Impl" + + log.Printf("Creating JavaScript Implementation") + + indentString := getIndentationString(implementation.Indentation) + stubIdentifier := "" + if len(implementation.StubIdentifier) > 0 { + stubIdentifier = "_" + strings.ToLower(implementation.StubIdentifier) + } + + if !suppressInterfaces { + + IntfExceptionHeaderName := path.Join(outputFolder, BaseName+"_interfaceexception.hpp") + log.Printf("Creating \"%s\"", IntfExceptionHeaderName) + hInternalExceptionHeaderFile, err := CreateLanguageFile(IntfExceptionHeaderName, indentString) + if err != nil { + return err + } + hInternalExceptionHeaderFile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated C++ Header file with the basic internal\n exception type in order to allow an easy use of %s", LibraryName), + true) + + IntfExceptionImplName := path.Join(outputFolder, BaseName+"_interfaceexception.cpp") + log.Printf("Creating \"%s\"", IntfExceptionImplName) + hInternalExceptionImplFile, err := CreateLanguageFile(IntfExceptionImplName, indentString) + if err != nil { + return err + } + hInternalExceptionImplFile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated C++ Implementation file with the basic internal\n exception type in order to allow an easy use of %s", LibraryName), + true) + + err = buildCPPInternalException(hInternalExceptionHeaderFile, hInternalExceptionImplFile, NameSpace, BaseName) + if err != nil { + return err + } + + IntfHeaderName := path.Join(outputFolder, BaseName+"_interfaces.hpp") + log.Printf("Creating \"%s\"", IntfHeaderName) + interfaceshppfile, err := CreateLanguageFile(IntfHeaderName, indentString) + if err != nil { + return err + } + interfaceshppfile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated C++ header file in order to allow easy\ndevelopment of %s. The implementer of %s needs to\nderive concrete classes from the abstract classes in this header.", LibraryName, LibraryName), + true) + err = buildCPPInterfaces(component, interfaceshppfile, ImplementationSubNameSpace, implementation.ClassIdentifier) + if err != nil { + return err + } + + IntfWrapperImplName := path.Join(outputFolder, BaseName+"_interfacewrapper.cpp") + log.Printf("Creating \"%s\"", IntfWrapperImplName) + cppWrapperfile, err := CreateLanguageFile(IntfWrapperImplName, indentString) + if err != nil { + return err + } + cppWrapperfile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated C++ implementation file in order to allow easy\ndevelopment of %s. The functions in this file need to be implemented. It needs to be generated only once.", LibraryName), + true) + err = buildCPPInterfaceWrapper(component, cppWrapperfile, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, doJournal) + if err != nil { + return err + } + + if doJournal { + IntfJournalHeaderName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.hpp") + log.Printf("Creating \"%s\"", IntfJournalHeaderName) + interfacejournalhppfile, err := CreateLanguageFile(IntfJournalHeaderName, indentString) + if err != nil { + return err + } + interfacejournalhppfile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated C++ header file in order to allow easy\ndevelopment of %s. It provides an automatic Journaling mechanism for the library implementation.", LibraryName), + true) + + IntfJournalImplName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.cpp") + log.Printf("Creating \"%s\"", IntfJournalImplName) + interfacejournalcppfile, err := CreateLanguageFile(IntfJournalImplName, indentString) + if err != nil { + return err + } + interfacejournalcppfile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated C++ implementation file in order to allow easy\ndevelopment of %s. It provides an automatic Journaling mechanism for the library implementation.", LibraryName), + true) + + err = buildJournalingCPP(component, interfacejournalhppfile, interfacejournalcppfile) + if err != nil { + return err + } + } + + } + + err := buildJSTypesFiles(component, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier) + if err != nil { + return err + } + + for _, subComponent := range component.ImportedComponentDefinitions { + + for i := 0; i < len(subComponent.Classes); i++ { + class := subComponent.Classes[i] + err := buildJSInjectionClass(component, subComponent, class, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier) + if err != nil { + return err + } + } + + } + + if outputFolderDocumentation != "" { + + err = BuildJSDocumentation(component, outputFolderDocumentation, implementation.ClassIdentifier) + if err != nil { + return err + } + + } + + return nil +} + +func buildJSTypesFiles(component ComponentDefinition, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string) error { + + TypesDefinitionFileName := path.Join(outputFolder, BaseName+stubIdentifier+"_v8types.hpp") + ClassDefinitionFileName := path.Join(outputFolder, BaseName+stubIdentifier+"_v8classes.hpp") + + log.Printf("Creating \"%s\"", TypesDefinitionFileName) + typesdefinitionw, err := CreateLanguageFile(TypesDefinitionFileName, indentString) + if err != nil { + return err + } + typesdefinitionw.WriteCLicenseHeader(component, + "JavaScript injection type definitions", false) + + log.Printf("Creating \"%s\"", ClassDefinitionFileName) + classdefinitionw, err := CreateLanguageFile(ClassDefinitionFileName, indentString) + if err != nil { + return err + } + classdefinitionw.WriteCLicenseHeader(component, + "JavaScript injection class definitions", false) + + typesdefinitionw.Writeln("") + typesdefinitionw.Writeln("#ifndef __%s_V8TYPES", strings.ToUpper(NameSpace)) + typesdefinitionw.Writeln("#define __%s_V8TYPES", strings.ToUpper(NameSpace)) + typesdefinitionw.Writeln("") + typesdefinitionw.Writeln("#include ") + typesdefinitionw.Writeln("") + + typeEnumID := 1 + + typesdefinitionw.Writeln("namespace v8%s {", NameSpace) + typesdefinitionw.Writeln(" namespace %s {", NameSpaceImplementation) + typesdefinitionw.Writeln("") + typesdefinitionw.Writeln(" enum class eInjectionClassType {") + typesdefinitionw.Writeln(" e_Injection_Invalid = 0,") + for _, subComponent := range component.ImportedComponentDefinitions { + + for i := 0; i < len(subComponent.Classes); i++ { + class := subComponent.Classes[i] + typesdefinitionw.Writeln(" e_v8%s_%s = %d,", subComponent.NameSpace, class.ClassName, typeEnumID) + typeEnumID = typeEnumID + 1 + } + + } + typesdefinitionw.Writeln(" e_Injection_enumMax") + typesdefinitionw.Writeln(" };") + typesdefinitionw.Writeln("") + typesdefinitionw.Writeln(" }") + typesdefinitionw.Writeln("}") + typesdefinitionw.Writeln("") + typesdefinitionw.Writeln("#endif // __%s_V8TYPES", strings.ToUpper(NameSpace)) + typesdefinitionw.Writeln("") + + classdefinitionw.Writeln("") + classdefinitionw.Writeln("#ifndef __%s_V8CLASSES", strings.ToUpper(NameSpace)) + classdefinitionw.Writeln("#define __%s_V8CLASSES", strings.ToUpper(NameSpace)) + classdefinitionw.Writeln("") + for _, subComponent := range component.ImportedComponentDefinitions { + + for i := 0; i < len(subComponent.Classes); i++ { + class := subComponent.Classes[i] + classdefinitionw.Writeln("#include \"%s_v8_%s_%s.hpp\"", component.BaseName+stubIdentifier, subComponent.BaseName, strings.ToLower(class.ClassName)) + } + + } + classdefinitionw.Writeln("") + + classdefinitionw.Writeln("namespace v8%s {", NameSpace) + classdefinitionw.Writeln(" namespace %s {", NameSpaceImplementation) + classdefinitionw.Writeln("") + classdefinitionw.Writeln(" inline void registerInjectionClasses (std::shared_ptr pObjectCreator, v8::Local pTarget)") + classdefinitionw.Writeln(" {") + for _, subComponent := range component.ImportedComponentDefinitions { + + for i := 0; i < len(subComponent.Classes); i++ { + class := subComponent.Classes[i] + classdefinitionw.Writeln(" v8%s::Cv8%s%s::internalV8Register(pObjectCreator, pTarget);", subComponent.NameSpace, ClassIdentifier, class.ClassName) + } + + } + classdefinitionw.Writeln(" }") + classdefinitionw.Writeln("") + + classdefinitionw.AddIndentationLevel(2) + for _, subComponent := range component.ImportedComponentDefinitions { + writeMapClassIdtoInjectionClassTypeFunction(classdefinitionw, subComponent, subComponent.NameSpace) + classdefinitionw.Writeln("") + } + classdefinitionw.AddIndentationLevel(-2) + + classdefinitionw.Writeln(" }") + classdefinitionw.Writeln("}") + classdefinitionw.Writeln("") + classdefinitionw.Writeln("#endif // __%s_V8CLASSES", strings.ToUpper(NameSpace)) + classdefinitionw.Writeln("") + + return nil +} + +func buildJSInjectionClass(component ComponentDefinition, subComponent ComponentDefinition, class ComponentDefinitionClass, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string) error { + baseFileName := fmt.Sprintf("%s_v8_%s_%s", component.BaseName+stubIdentifier, subComponent.BaseName, strings.ToLower(class.ClassName)) + HeaderFileName := path.Join(outputFolder, baseFileName+".hpp") + CppFileName := path.Join(outputFolder, baseFileName+".cpp") + + log.Printf("Creating \"%s\"", HeaderFileName) + headerw, err := CreateLanguageFile(HeaderFileName, indentString) + if err != nil { + return err + } + + headerw.WriteCLicenseHeader(component, + "JavaScript definition for injection class "+subComponent.NameSpace+"::"+class.ClassName, false) + + log.Printf("Creating \"%s\"", CppFileName) + cppw, err := CreateLanguageFile(CppFileName, indentString) + if err != nil { + return err + } + cppw.WriteCLicenseHeader(component, + "JavaScript implementation for injection class "+subComponent.NameSpace+"::"+class.ClassName, false) + + headerw.Writeln("") + headerw.Writeln("") + headerw.Writeln("#ifndef __%s_V8_%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(subComponent.NameSpace), strings.ToUpper(class.ClassName)) + headerw.Writeln("#define __%s_V8_%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(subComponent.NameSpace), strings.ToUpper(class.ClassName)) + headerw.Writeln("") + headerw.Writeln("#include \"%s_v8objectcreator.hpp\"", component.BaseName) + headerw.Writeln("#include \"%s_v8objectwrapper.hpp\"", component.BaseName) + headerw.Writeln("") + + headerw.Writeln("namespace v8%s {", NameSpace) + headerw.Writeln(" namespace %s {", NameSpaceImplementation) + headerw.Writeln(" namespace v8%s {", subComponent.NameSpace) + headerw.Writeln("") + + headerw.Writeln(" class Cv8%s : public Cv8objectWrapper", class.ClassName) + headerw.Writeln(" {") + headerw.Writeln(" public:") + headerw.Writeln("") + headerw.Writeln(" /* constructors, destructor and operators */") + headerw.Writeln(" Cv8%s();", class.ClassName) + headerw.Writeln(" Cv8%s(v8::Local localObject);", class.ClassName) + headerw.Writeln(" Cv8%s(const Cv8%s& valueReference);", class.ClassName, class.ClassName) + headerw.Writeln(" virtual ~Cv8%s();", class.ClassName) + headerw.Writeln("") + headerw.Writeln(" Cv8%s& operator=(const Cv8%s& valueReference);", class.ClassName, class.ClassName) + headerw.Writeln(" static Cv8%s* Cast(Cv8objectWrapper* objectWrapper);", class.ClassName) + headerw.Writeln("") + headerw.Writeln(" /* class helper methods */") + headerw.Writeln(" static eInjectionClassType getClassType();") + headerw.Writeln("") + headerw.Writeln(" static %s::P%s getInstance(const v8::Local& holder);", subComponent.NameSpace, class.ClassName) + headerw.Writeln("") + headerw.Writeln(" /* V8 Registration commands */") + headerw.Writeln(" static void internalV8RegisterMethods(v8::Local localClassTemplate, std::shared_ptr pObjectCreator, v8::Local target);") + headerw.Writeln(" static void internalV8Register(std::shared_ptr pObjectCreator, v8::Local target);") + headerw.Writeln(" static void internalV8New(const v8::FunctionCallbackInfo& args);") + headerw.Writeln("") + headerw.Writeln(" /* V8 Method implementations */") + + for j := 0; j < len(class.Methods); j++ { + method := class.Methods[j] + if method.PropertyGet != "" { + headerw.Writeln(" static void v8%s(v8::Local property, const v8::PropertyCallbackInfo& args);", method.MethodName) + } else if method.PropertySet != "" { + headerw.Writeln(" static void v8%s(v8::Local property, v8::Local value, const v8::PropertyCallbackInfo& args);", method.MethodName) + } else { + headerw.Writeln(" static void v8%s(const v8::FunctionCallbackInfo& args);", method.MethodName) + } + } + + //static void V8Data(const v8::FunctionCallbackInfo& args); + headerw.Writeln("") + headerw.Writeln(" };") + + headerw.Writeln("") + headerw.Writeln(" }") + headerw.Writeln(" }") + headerw.Writeln("}") + headerw.Writeln("") + headerw.Writeln("#endif // __%s_V8_%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(subComponent.NameSpace), strings.ToUpper(class.ClassName)) + headerw.Writeln("") + + cppw.Writeln("") + cppw.Writeln("#include \"%s.hpp\"", baseFileName) + cppw.Writeln("") + cppw.Writeln("#include \"%s_v8utils.hpp\"", component.BaseName) + cppw.Writeln("#include \"%s_v8objectcreator.hpp\"", component.BaseName) + cppw.Writeln("#include \"%s%s_v8classes.hpp\"", component.BaseName, stubIdentifier) + cppw.Writeln("") + cppw.Writeln("") + + cppw.Writeln("using namespace v8%s::%s;", NameSpace, NameSpaceImplementation) + cppw.Writeln("using namespace v8%s::%s::v8%s;", NameSpace, NameSpaceImplementation, subComponent.NameSpace) + cppw.Writeln("") + + cppw.Writeln("Cv8%s::Cv8%s()", class.ClassName, class.ClassName) + cppw.Writeln(" : Cv8objectWrapper(getClassType())") + cppw.Writeln("{") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("Cv8%s::Cv8%s(v8::Local localObject)", class.ClassName, class.ClassName) + cppw.Writeln(" : Cv8objectWrapper(getClassType())") + cppw.Writeln("{") + cppw.Writeln(" Wrap(localObject);") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("Cv8%s::Cv8%s(const Cv8%s& valueReference)", class.ClassName, class.ClassName, class.ClassName) + cppw.Writeln(" : Cv8objectWrapper(getClassType())") + cppw.Writeln("{") + cppw.Writeln(" setObjectInstances(valueReference.m_pObjectCreator, valueReference.m_pObjectInstance);") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("Cv8%s::~Cv8%s()", class.ClassName, class.ClassName) + cppw.Writeln("{") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("eInjectionClassType Cv8%s::getClassType()", class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" return eInjectionClassType::e_v8%s_%s;", subComponent.NameSpace, class.ClassName) + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("Cv8%s* Cv8%s::Cast(Cv8objectWrapper* objectWrapper)", class.ClassName, class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" if (objectWrapper != nullptr) {") + cppw.Writeln(" if (objectWrapper->get_type() == getClassType())") + cppw.Writeln(" return static_cast(objectWrapper);", class.ClassName) + cppw.Writeln(" }") + cppw.Writeln(" return nullptr;") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("%s::P%s Cv8%s::getInstance(const v8::Local& holder)", subComponent.NameSpace, class.ClassName, class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" auto objectWrapper = UnwrapBase(holder);") + cppw.Writeln(" if (objectWrapper == nullptr)") + cppw.Writeln(" throw std::runtime_error (\"could not get %s instance wrapper.\");", class.ClassName) + cppw.Writeln("") + cppw.Writeln(" auto pInstance = objectWrapper->getObjectInstance ();") + cppw.Writeln(" if (pInstance.get () == nullptr)") + cppw.Writeln(" throw std::runtime_error (\"could not get %s instance.\");", class.ClassName) + cppw.Writeln("") + cppw.Writeln(" auto pCastInstance = std::dynamic_pointer_cast<%s::C%s> (pInstance);", subComponent.NameSpace, class.ClassName) + cppw.Writeln(" if (pCastInstance.get () == nullptr)") + cppw.Writeln(" throw std::runtime_error (\"invalid %s instance type.\");", class.ClassName) + cppw.Writeln("") + cppw.Writeln(" return pCastInstance;") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("Cv8%s& Cv8%s::operator=(const Cv8%s& valueReference)", class.ClassName, class.ClassName, class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" if (this != &valueReference)") + cppw.Writeln(" {") + cppw.Writeln(" setObjectInstances(valueReference.m_pObjectCreator, valueReference.m_pObjectInstance);") + cppw.Writeln(" }") + cppw.Writeln(" return *this;") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("void Cv8%s::internalV8Register(std::shared_ptr pObjectCreator, v8::Local target)", class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" v8::Isolate* isolate = v8::Isolate::GetCurrent();") + cppw.Writeln(" if (isolate == nullptr)") + cppw.Writeln(" return;") + cppw.Writeln("") + cppw.Writeln(" // Create class template") + cppw.Writeln(" v8::HandleScope handle_scope(isolate);") + cppw.Writeln("") + cppw.Writeln(" v8::Local localClassTemplate = createClassTemplate (isolate, \"%s\", Cv8%s::internalV8New);", class.ClassName, class.ClassName) + cppw.Writeln("") + cppw.Writeln(" Cv8%s::internalV8RegisterMethods(localClassTemplate, pObjectCreator, target);", class.ClassName) + cppw.Writeln("") + cppw.Writeln(" pObjectCreator->setTemplate(getClassType(), localClassTemplate);") + cppw.Writeln("}") + cppw.Writeln("") + cppw.Writeln("void Cv8%s::internalV8RegisterMethods(v8::Local localClassTemplate,", class.ClassName) + cppw.Writeln(" std::shared_ptr pObjectCreator, v8::Local target)") + cppw.Writeln("{") + if (class.ParentClass != "") && (class.ClassName != "Base") { + cppw.Writeln(" Cv8%s::internalV8RegisterMethods(localClassTemplate, pObjectCreator, target);", class.ParentClass) + } + cppw.Writeln(" // Add functions to prototype object") + for i := 0; i < len(class.Methods); i++ { + method := class.Methods[i] + if method.PropertySet != "" { + // Ignore setters + } else if method.PropertyGet != "" { + readOnly := true + var getter = &method + var setter *ComponentDefinitionMethod + for _, method := range class.Methods { + if method.PropertySet == getter.PropertyGet { + setter = &method + readOnly = false + break + } + } + if readOnly { + cppw.Writeln(" Cv8toolsUtils::Set_proto_accessor(localClassTemplate, \"%s\", Cv8%s::v8%s);", getter.PropertyGet, class.ClassName, getter.MethodName) + cppw.Writeln(" Cv8toolsUtils::Set_proto_accessor(localClassTemplate, \"%s\", Cv8%s::v8%s);", camelize(getter.PropertyGet), class.ClassName, getter.MethodName) + } else { + cppw.Writeln(" Cv8toolsUtils::Set_proto_accessor(localClassTemplate, \"%s\", Cv8%s::v8%s, Cv8%s::v8%s);", setter.PropertySet, class.ClassName, getter.MethodName, class.ClassName, setter.MethodName) + cppw.Writeln(" Cv8toolsUtils::Set_proto_accessor(localClassTemplate, \"%s\", Cv8%s::v8%s, Cv8%s::v8%s);", camelize(setter.PropertySet), class.ClassName, getter.MethodName, class.ClassName, setter.MethodName) + } + } else { + cppw.Writeln(" Cv8toolsUtils::Set_proto_method(localClassTemplate, \"%s\", Cv8%s::v8%s);", method.MethodName, class.ClassName, method.MethodName) + cppw.Writeln(" Cv8toolsUtils::Set_proto_method(localClassTemplate, \"%s\", Cv8%s::v8%s);", camelize(method.MethodName), class.ClassName, method.MethodName) + } + } + cppw.Writeln("") + cppw.Writeln("}") + + cppw.Writeln("void Cv8%s::internalV8New(const v8::FunctionCallbackInfo& args)", class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" if (!args.IsConstructCall())") + cppw.Writeln(" {") + cppw.Writeln(" Cv8toolsUtils::Throw_error(\"Expected constructor call type\");") + cppw.Writeln(" return;") + cppw.Writeln(" }") + cppw.Writeln(" new Cv8%s(args.This());", class.ClassName) + cppw.Writeln("}") + cppw.Writeln("") + cppw.Writeln("") + + for j := 0; j < len(class.Methods); j++ { + method := class.Methods[j] + + if method.PropertyGet != "" { + cppw.Writeln("void Cv8%s::v8%s(v8::Local property, const v8::PropertyCallbackInfo& args)", class.ClassName, method.MethodName) + } else if method.PropertySet != "" { + cppw.Writeln("void Cv8%s::v8%s(v8::Local property, v8::Local value, const v8::PropertyCallbackInfo& args)", class.ClassName, method.MethodName) + } else { + cppw.Writeln("void Cv8%s::v8%s(const v8::FunctionCallbackInfo& args)", class.ClassName, method.MethodName) + } + cppw.Writeln("{") + cppw.Writeln(" v8::Isolate* isolate = v8::Isolate::GetCurrent();") + cppw.Writeln("") + cppw.Writeln(" try {") + cppw.Indentation += 2 + + if method.PropertySet == "" && method.PropertyGet == "" { + inArgs := filterPass(method.Params, "in") + optionalArgs := filterOptional(inArgs) + argString := "" + for k, param := range inArgs { + if k != 0 { + argString = argString + ", " + } + if param.ParamOptional == "true" { + argString = argString + "[" + param.ParamName + "]" + } else { + argString = argString + param.ParamName + } + } + cppw.Writeln( + "checkArgumentParameters(args, %d, %d, \"%s.%s (%s)\");", + len(inArgs)-len(optionalArgs), + len(inArgs), + class.ClassName, + method.MethodName, + argString, + ) + cppw.Writeln("") + } + + // This is probably because I should be adding to the prototype + if method.PropertySet != "" || method.PropertyGet != "" { + cppw.Writeln("auto instancePtr = getInstance(args.This());") + cppw.Writeln("") + cppw.Writeln("auto v8instance = UnwrapBase(args.This());") + } else { + cppw.Writeln("auto instancePtr = getInstance(args.Holder());") + cppw.Writeln("") + cppw.Writeln("auto v8instance = UnwrapBase(args.Holder());") + } + cppw.Writeln("if (v8instance == nullptr)") + cppw.Writeln(" throw std::runtime_error(\"could not get %s instance.\");", class.ClassName) + cppw.Writeln("") + cppw.Writeln("auto objectCreator = v8instance->getObjectCreator();") + cppw.Writeln("if (objectCreator == nullptr)") + cppw.Writeln(" throw std::runtime_error(\"invalid object creator.\");") + cppw.Writeln("") + + baseClassName := "P" + component.Global.BaseClassName + argumentString := "" + + for k, param := range method.Params { + if param.ParamPass == "in" { + argName := "value" + if method.PropertySet == "" { + argName = fmt.Sprintf("args[%d]", k) + } + writeExtractV8InArg(param, k, subComponent, baseClassName, argName, cppw) + } + } + + for _, param := range method.Params { + if param.ParamPass == "out" || param.ParamPass == "return" { + if param.ParamType == "basicarray" { + cppw.Writeln("std::vector<%s> param%s;", cppArrayClass(param), param.ParamName) + } else { + cppw.Writeln("%s param%s = %s;", cppParamType(param, subComponent), param.ParamName, argumentDefault(param, subComponent)) + } + } + } + + resultString := "" + for _, param := range method.Params { + if param.ParamPass != "return" { + if argumentString != "" { + argumentString = argumentString + ", " + } + argumentString = argumentString + "param" + param.ParamName + } + } + + returnArgs := filterPass(method.Params, "return") + if len(returnArgs) > 0 { + // Just take the first + param := returnArgs[0] + resultString = "param" + param.ParamName + " = " + } + + cppw.Writeln("%sinstancePtr->%s (%s);", resultString, method.MethodName, argumentString) + + outArgs := filterPass(method.Params, "out") + if len(outArgs) > 0 { + cppw.Writeln("auto context = isolate->GetCurrentContext();") + cppw.Writeln("auto outArgs = v8::Array::New(isolate);") + + for n, param := range outArgs { + argName := "v8" + param.ParamName + writeInsertV8OutArg(param, subComponent, argName, cppw) + cppw.Writeln("outArgs->Set(context, %d, %s);", n, argName) + } + + cppw.Writeln("args.GetReturnValue().Set(outArgs);") + } else { + for k := 0; k < len(method.Params); k++ { + param := method.Params[k] + if param.ParamPass == "return" { + if method.PropertySet == "" { + writeReturnValue(cppw, param, subComponent) + cppw.Writeln("setReturnValue(isolate, args, retVal);") + } + } + } + } + cppw.Writeln("") + cppw.Indentation -= 2 + cppw.Writeln("") + + cppw.Writeln(" }") + cppw.Writeln(" catch (std::exception& E) {") + cppw.Writeln(" throwV8Exception(isolate, E);") + cppw.Writeln(" }") + cppw.Writeln("}") + cppw.Writeln("") + } + cppw.Writeln("") + + return nil +} + +func writeMapClassIdtoInjectionClassTypeFunction(w LanguageWriter, component ComponentDefinition, NameSpace string) { + w.Writeln("") + w.Writeln("inline eInjectionClassType %s_MapClassIdToInjectionClassType(uint64_t nClassTypeId)", NameSpace) + w.Writeln("{") + w.Writeln(" switch(nClassTypeId) {") + for i := 0; i < len(component.Classes); i++ { + class := component.Classes[i] + classTypeId, chashHashString := class.classTypeId(NameSpace) + w.Writeln(" case 0x%016XUL: return eInjectionClassType::e_v8%s_%s; break; // First 64 bits of SHA1 of a string: \"%s\"", classTypeId, NameSpace, class.ClassName, chashHashString) + } + w.Writeln(" }") + + w.Writeln(" return eInjectionClassType::e_Injection_Invalid;") + w.Writeln("}") +} + +func writeExtractV8InArg( + param ComponentDefinitionParam, + index int, + subComponent ComponentDefinition, + baseClassName string, + argName string, + writer LanguageWriter, +) { + switch param.ParamType { + case "class", "optionalclass": + writer.Writeln("%s::%s object%s;", subComponent.NameSpace, baseClassName, param.ParamName) + case "basicarray": + writer.Writeln("std::vector<%s> param%s;", cppArrayClass(param), param.ParamName) + case "string": + if param.ParamOptional == "true" { + writer.Writeln("%s param%s = \"%s\";", cppParamType(param, subComponent), param.ParamName, param.ParamDefaultValue) + } else { + writer.Writeln("%s param%s;", cppParamType(param, subComponent), param.ParamName) + } + case "enum": + if param.ParamOptional == "true" { + writer.Writeln("%s param%s = %s::%s;", cppParamType(param, subComponent), param.ParamName, cppParamType(param, subComponent), param.ParamDefaultValue) + } else { + writer.Writeln("%s param%s;", cppParamType(param, subComponent), param.ParamName) + } + default: + if param.ParamOptional == "true" { + writer.Writeln("%s param%s = %s;", cppParamType(param, subComponent), param.ParamName, param.ParamDefaultValue) + } else { + writer.Writeln("%s param%s;", cppParamType(param, subComponent), param.ParamName) + } + } + if param.ParamOptional == "true" { + writer.Writeln("if (args.Length() > %d) {", index) + writer.Indentation++ + } + switch param.ParamType { + case "class", "optionalclass": + writer.Writeln("object%s = v8instance->get%sArgument (isolate, %s);", param.ParamName, argumentMethodCallType(param), argName) + case "basicarray": + writer.Writeln("v8instance->get%sArgument (isolate, %s, param%s);", argumentMethodCallType(param), argName, param.ParamName) + default: + writer.Writeln("param%s = %sv8instance->get%sArgument (isolate, %s);", param.ParamName, cppReturnValueCast(param, subComponent), argumentMethodCallType(param), argName) + } + if param.ParamOptional == "true" { + writer.Indentation-- + writer.Writeln("}") + } + switch param.ParamType { + case "class", "optionalclass": + writer.Writeln("%s param%s = std::dynamic_pointer_cast<%s::C%s> (object%s);", cppParamType(param, subComponent), param.ParamName, subComponent.NameSpace, param.ParamClass, param.ParamName) + } +} + +func writeInsertV8OutArg( + param ComponentDefinitionParam, + subComponent ComponentDefinition, + argName string, + writer LanguageWriter, +) { + switch param.ParamType { + case "class": + writer.Writeln("auto %s = createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s()));", argName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + case "optionalclass": + writer.Writeln("auto %s = param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local();", argName, param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + case "enum": + writer.Writeln("auto %s = v8::Number::New(isolate, (uint32_t)param%s);", argName, param.ParamName) + case "string": + writer.Writeln("auto %s = v8::String::NewFromUtf8(isolate, param%s.c_str()).ToLocalChecked();", argName, param.ParamName) + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": + writer.Writeln("auto %s = v8::Number::New(isolate, param%s);", argName, param.ParamName) + case "bool": + writer.Writeln("auto %s = v8::Boolean::New(isolate, param%s);", argName, param.ParamName) + case "basicarray": + writer.Writeln("auto %s = v8::Array::New(isolate);", argName) + writer.Writeln("for (size_t i = 0; i < param%s.size(); ++i) {", param.ParamName) + writer.Writeln(" const auto& %s = param%s.at(i);", strings.ToLower(param.ParamName), param.ParamName) + writer.Writeln(" %s->Set(context, i, v8::%s::New(isolate, %s));", argName, v8Type(param), strings.ToLower(param.ParamName)) + writer.Writeln("}") + default: + writer.Writeln("<" + param.ParamType + ">") + } +} + +func v8Type(param ComponentDefinitionParam) string { + if param.ParamType == "basicarray" { + return v8TypeString(param.ParamClass) + } + return v8TypeString(param.ParamType) +} + +func v8TypeString(paramType string) string { + v8type := "" + switch paramType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": + v8type = "Number" + case "bool": + v8type = "Boolean" + case "string": + v8type = "String" + default: + v8type = "<" + paramType + ">" + } + return v8type +} + +func writeReturnValue(writer LanguageWriter, param ComponentDefinitionParam, subComponent ComponentDefinition) { + if param.ParamType == "class" { + writer.Writeln( + "auto retVal = param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local();", + param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + } else if param.ParamType == "optionalclass" { + writer.Writeln("v8::Local retVal = v8::Null(isolate);") + writer.Writeln("if (param%s) {", param.ParamName) + writer.Writeln( + " retVal = createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s()));", + param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + writer.Writeln("}") + } else if param.ParamType == "enum" { + writer.Writeln("auto retVal = (uint32_t) param%s;", param.ParamName) + } else { + writer.Writeln("auto retVal = param%s;", param.ParamName) + } +} + +func cppParamType( + param ComponentDefinitionParam, + subComponent ComponentDefinition, +) string { + result := "" + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": + result = param.ParamType + "_t" + case "single": + result = "float" + case "double": + result = "double" + case "string": + result = "std::string" + case "bool": + result = "bool" + case "pointer": + result = "void *" + case "class", "optionalclass": + result = subComponent.NameSpace + "::P" + param.ParamClass + case "enum": + result = subComponent.NameSpace + "::e" + param.ParamClass + default: + result = "<" + param.ParamType + ">" + } + return result +} + +func argumentMethodCallType(param ComponentDefinitionParam) string { + result := "" + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", + "single", "double", "string", "bool": + result = strings.Title(param.ParamType) + case "pointer": + result = "Pointer" + case "class", "optionalclass": + result = "Object" + case "enum": + result = "Int32" + case "basicarray": + switch param.ParamClass { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", + "single", "double", "string", "bool": + result = strings.Title(param.ParamClass) + "Array" + default: + result = "<" + param.ParamType + "|" + param.ParamClass + ">" + } + default: + result = "<" + param.ParamType + ">" + } + return result +} + +func argumentDefault( + param ComponentDefinitionParam, + subComponent ComponentDefinition, +) string { + result := "" + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": + result = "0" + case "single": + result = "0.0f" + case "double": + result = "0.0" + case "string": + result = "\"\"" + case "bool": + result = "false" + case "pointer", "class", "optionalclass": + result = "nullptr" + case "enum": + result = "(" + subComponent.NameSpace + "::e" + param.ParamClass + ") 0" + default: + result = "<" + param.ParamType + ">" + } + + return result +} + +func cppArrayClass(param ComponentDefinitionParam) string { + result := "" + if param.ParamType == "basicarray" { + switch param.ParamClass { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": + result = param.ParamClass + "_t" + case "single", "double": + result = "double" + case "bool": + result = "uint8_t" + default: + result = "<" + param.ParamClass + ">" + } + + } + return result +} + +func cppReturnValueCast( + param ComponentDefinitionParam, + subComponent ComponentDefinition, +) string { + result := "" + if param.ParamType == "enum" { + result = "(" + subComponent.NameSpace + "::e" + param.ParamClass + ")" + } + return result +} + +// BuildJSDocumentation builds the Sphinx documentation of a library's C++-bindings +func BuildJSDocumentation(component ComponentDefinition, outputFolder string, ClassIdentifier string) error { + BaseName := component.BaseName + + globalFileName := path.Join(outputFolder, BaseName+".rst") + log.Printf("Creating \"%s\"", globalFileName) + globalDocFile, err := CreateLanguageFile(globalFileName, "\t") + if err != nil { + return err + } + err = buildJSDocumentationGlobal(component, globalDocFile, ClassIdentifier) + if err != nil { + return err + } + + typesFileName := path.Join(outputFolder, BaseName+"-types.rst") + log.Printf("Creating \"%s\"", typesFileName) + typesDocFile, err := CreateLanguageFile(typesFileName, "\t") + if err != nil { + return err + } + err = buildJSDocumentationTypes(component, typesDocFile, ClassIdentifier) + if err != nil { + return err + } + + for i := 0; i < len(component.Classes); i++ { + class := component.Classes[i] + classFileName := path.Join(outputFolder, BaseName+"_"+class.ClassName+".rst") + log.Printf("Creating \"%s\"", classFileName) + classDocFile, err := CreateLanguageFile(classFileName, "\t") + if err != nil { + return err + } + err = buildJSDocumentationClass(component, classDocFile, class, ClassIdentifier) + if err != nil { + return err + } + + } + + err = buildJSDocumentationExample(component, outputFolder, ClassIdentifier, true, "_dynamic") + if err != nil { + return err + } + err = buildJSDocumentationExample(component, outputFolder, ClassIdentifier, false, "_implicit") + if err != nil { + return err + } + + return nil +} + +func buildJSDocumentationExample(component ComponentDefinition, outputFolder string, ClassIdentifier string, ExplicitLinking bool, suffix string) error { + NameSpace := component.NameSpace + + DynamicCPPExample := path.Join(outputFolder, NameSpace+"_example"+suffix+".cpp") + log.Printf("Creating \"%s\"", DynamicCPPExample) + dyncppexamplefile, err := CreateLanguageFile(DynamicCPPExample, " ") + if err != nil { + return err + } + buildDynamicCppExample(component, dyncppexamplefile, outputFolder, ClassIdentifier, ExplicitLinking) + + DynamicCPPCMake := path.Join(outputFolder, "CMakeLists"+suffix+".txt") + log.Printf("Creating \"%s\"", DynamicCPPCMake) + dyncppcmake, err := CreateLanguageFile(DynamicCPPCMake, " ") + if err != nil { + return err + } + buildCppDynamicExampleCMake(component, dyncppcmake, outputFolder, outputFolder, ExplicitLinking) + return nil +} + +func writeJSDocumentationFunctionPointer(component ComponentDefinition, w LanguageWriter, + functiontype ComponentDefinitionFunctionType) error { + + NameSpace := component.NameSpace + returnType := "void" + parameters := "" + + for j := 0; j < len(functiontype.Params); j++ { + param := functiontype.Params[j] + + cParamTypeName, err := getCPPParameterTypeName(param.ParamType, NameSpace, param.ParamClass) + if err != nil { + return err + } + if parameters != "" { + parameters = parameters + ", " + } + if param.ParamPass == "in" { + parameters = parameters + cParamTypeName + } else { + parameters = parameters + cParamTypeName + "*" + } + } + w.Writeln(" .. cpp:type:: %s = %s(*)(%s)", functiontype.FunctionName, returnType, parameters) + w.Writeln(" ") + w.Writeln(" %s", functiontype.FunctionDescription) + w.Writeln(" ") + + for j := 0; j < len(functiontype.Params); j++ { + param := functiontype.Params[j] + + cParams, err := generateCCPPParameter(param, "", functiontype.FunctionName, NameSpace, true) + if err != nil { + return err + } + for _, cParam := range cParams { + w.Writeln(" %s", cParam.ParamDocumentationLine) + } + } + w.Writeln(" ") + + return nil +} + +func buildJSDocumentationGlobal(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) error { + + NameSpace := component.NameSpace + LibraryName := component.LibraryName + global := component.Global + + wrapperName := "C" + ClassIdentifier + "Wrapper" + + w.Writeln("") + w.Writeln("The wrapper class %s", wrapperName) + w.Writeln("===================================================================================") + w.Writeln("") + w.Writeln("") + w.Writeln(".. cpp:class:: %s::%s", NameSpace, wrapperName) + + w.Writeln("") + w.Writeln(" All types of %s reside in the namespace %s and all", LibraryName, NameSpace) + w.Writeln(" functionality of %s resides in %s::%s.", LibraryName, NameSpace, wrapperName) + w.Writeln("") + w.Writeln(" A suitable way to use %s::%s is as a singleton.", NameSpace, wrapperName) + w.Writeln("") + + for j := 0; j < len(global.Methods); j++ { + method := global.Methods[j] + + parameters, returntype, err := getDynamicCPPMethodParameters(method, NameSpace, ClassIdentifier, "Wrapper") + if err != nil { + return err + } + w.Writeln(" .. cpp:function:: %s %s(%s)", returntype, method.MethodName, parameters) + w.Writeln(" ") + w.Writeln(" %s", method.MethodDescription) + w.Writeln(" ") + writeJSDocumentationParameters(method, w, NameSpace) + w.Writeln(" ") + } + + w.Writeln(".. cpp:type:: std::shared_ptr<%s> %s::P%s%s", wrapperName, NameSpace, ClassIdentifier, "Wrapper") + w.Writeln(" ") + + // Load library functions + // Check error functions of the base class + + return nil +} + +func writeJSDocumentationParameters(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string) { + for k := 0; k < len(method.Params); k++ { + param := method.Params[k] + variableName := getBindingCppVariableName(param) + if param.ParamPass == "return" { + w.Writeln(" :returns: %s", param.ParamDescription) + } else { + w.Writeln(" :param %s: %s ", variableName, param.ParamDescription) + } + } + w.Writeln("") +} + +func buildJSDocumentationClass(component ComponentDefinition, w LanguageWriter, class ComponentDefinitionClass, ClassIdentifier string) error { + + NameSpace := component.NameSpace + className := "C" + ClassIdentifier + class.ClassName + + w.Writeln("") + w.Writeln("%s", className) + w.Writeln("====================================================================================================") + w.Writeln("") + w.Writeln("") + + _, inheritanceSpecifier := getCPPInheritanceSpecifier(component, class, "C", ClassIdentifier) + + w.Writeln(".. cpp:class:: %s::%s %s", NameSpace, className, inheritanceSpecifier) + w.Writeln("") + w.Writeln(" %s", class.ClassDescription) + w.Writeln("") + w.Writeln("") + + w.Writeln("") + w.Writeln("") + for j := 0; j < len(class.Methods); j++ { + method := class.Methods[j] + + parameters, returntype, err := getDynamicCPPMethodParameters(method, NameSpace, ClassIdentifier, class.ClassName) + if err != nil { + return err + } + w.Writeln(" .. cpp:function:: %s %s(%s)", returntype, method.MethodName, parameters) + w.Writeln("") + w.Writeln(" %s", method.MethodDescription) + w.Writeln("") + writeJSDocumentationParameters(method, w, NameSpace) + w.Writeln("") + } + + w.Writeln(".. cpp:type:: std::shared_ptr<%s> %s::P%s%s", className, NameSpace, ClassIdentifier, class.ClassName) + w.Writeln("") + w.Writeln(" Shared pointer to %s to easily allow reference counting.", className) + w.Writeln("") + + return nil +} + +func buildJSDocumentationException(component ComponentDefinition, w LanguageWriter) { + LibraryName := component.LibraryName + NameSpace := component.NameSpace + + ExceptionName := "E" + NameSpace + "Exception" + w.Writeln(" ") + w.Writeln("%s: The standard exception class of %s", ExceptionName, LibraryName) + w.Writeln("============================================================================================================================================================================================================") + w.Writeln(" ") + w.Writeln(" Errors in %s are reported as Exceptions. It is recommended to not throw these exceptions in your client code.", LibraryName) + w.Writeln(" ") + w.Writeln(" ") + w.Writeln(" .. cpp:class:: %s::%s", NameSpace, ExceptionName) + w.Writeln(" ") + w.Writeln(" .. cpp:function:: void %s::what() const noexcept", ExceptionName) + w.Writeln(" ") + w.Writeln(" Returns error message") + w.Writeln(" ") + w.Writeln(" :return: the error message of this exception") + w.Writeln(" ") + + w.Writeln(" ") + w.Writeln(" .. cpp:function:: %sResult %s::getErrorCode() const noexcept", NameSpace, ExceptionName) + w.Writeln(" ") + w.Writeln(" Returns error code") + w.Writeln(" ") + w.Writeln(" :return: the error code of this exception") + w.Writeln(" ") +} + +func buildJSDocumentationInputVector(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) { + LibraryName := component.LibraryName + NameSpace := component.NameSpace + + InputVector := "C" + ClassIdentifier + "InputVector" + w.Writeln(" ") + w.Writeln("%s: Adapter for passing arrays as input for functions", InputVector) + w.Writeln("===============================================================================================================================================================") + w.Writeln(" ") + w.Writeln(" Several functions of %s expect arrays of integral types or structs as input parameters.", LibraryName) + w.Writeln(" To not restrict the interface to, say, std::vector,") + w.Writeln(" and to have a more abstract interface than a location in memory and the number of elements to input to a function") + w.Writeln(" %s provides a templated adapter class to pass arrays as input for functions.", LibraryName) + w.Writeln(" ") + w.Writeln(" Usually, instances of %s are generated anonymously (or even implicitly) in the call to a function that expects an input array.", InputVector) + w.Writeln(" ") + w.Writeln(" ") + + w.Writeln(" .. cpp:class:: template %s::%s", NameSpace, InputVector) + w.Writeln(" ") + w.Writeln(" .. cpp:function:: %s(const std::vector& vec)", InputVector) + w.Writeln(" ") + w.Writeln(" Constructs of a %s from a std::vector", InputVector) + w.Writeln(" ") + w.Writeln(" .. cpp:function:: %s(const T* in_data, size_t in_size)", InputVector) + w.Writeln(" ") + w.Writeln(" Constructs of a %s from a memory address and a given number of elements", InputVector) + w.Writeln(" ") + + w.Writeln(" .. cpp:function:: const T* %s::data() const", InputVector) + w.Writeln(" ") + w.Writeln(" returns the start address of the data captured by this %s", InputVector) + w.Writeln(" ") + + w.Writeln(" .. cpp:function:: size_t %s::size() const", InputVector) + w.Writeln(" ") + w.Writeln(" returns the number of elements captured by this %s", InputVector) + w.Writeln(" ") + w.Writeln(" ") +} + +func buildJSDocumentationStructs(component ComponentDefinition, w LanguageWriter) error { + if len(component.Structs) == 0 { + return nil + } + + NameSpace := component.NameSpace + + w.Writeln("") + w.Writeln("Structs") + w.Writeln("--------------") + w.Writeln("") + w.Writeln(" All structs are defined as `packed`, i.e. with the") + w.Writeln(" ") + w.Writeln(" .. code-block:: c") + w.Writeln(" ") + w.Writeln(" #pragma pack (1)") + w.Writeln("") + + for i := 0; i < len(component.Structs); i++ { + structinfo := component.Structs[i] + w.Writeln(" .. cpp:struct:: s%s", structinfo.Name) + w.Writeln(" ") + // w.Writeln(" %s", structinfo.Description); + // w.Writeln(" "); + for j := 0; j < len(structinfo.Members); j++ { + member := structinfo.Members[j] + arraysuffix := "" + if member.Rows > 0 { + if member.Columns > 0 { + arraysuffix = fmt.Sprintf("[%d][%d]", member.Columns, member.Rows) + } else { + arraysuffix = fmt.Sprintf("[%d]", member.Rows) + } + } + memberLine, err := getCPPMemberLine(member, NameSpace, arraysuffix, structinfo.Name, "") + if err != nil { + return err + } + w.Writeln(" .. cpp:member:: %s", memberLine) + w.Writeln(" ") + } + w.Writeln("") + } + + return nil +} + +func buildJSDocumentationSimpleTypes(component ComponentDefinition, w LanguageWriter) { + NameSpace := component.NameSpace + + w.Writeln("Simple types") + w.Writeln("--------------") + w.Writeln("") + types := []string{"uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64"} + for _, _type := range types { + w.Writeln(" .. cpp:type:: %s_t %s_%s", _type, NameSpace, _type) + w.Writeln(" ") + } + w.Writeln(" .. cpp:type:: float %s_single", NameSpace) + w.Writeln(" ") + w.Writeln(" .. cpp:type:: double %s_double", NameSpace) + w.Writeln(" ") + w.Writeln(" .. cpp:type:: %s_pvoid = void*", NameSpace) + w.Writeln(" ") + w.Writeln(" .. cpp:type:: %sResult = %s_int32", NameSpace, NameSpace) + w.Writeln(" ") + w.Writeln(" ") +} + +func buildJSDocumentationEnums(component ComponentDefinition, w LanguageWriter) { + if len(component.Enums) == 0 { + return + } + + NameSpace := component.NameSpace + + w.Writeln("") + w.Writeln("Enumerations") + w.Writeln("--------------") + w.Writeln("") + for i := 0; i < len(component.Enums); i++ { + enum := component.Enums[i] + w.Writeln(" .. cpp:enum-class:: e%s : %s_int32", enum.Name, NameSpace) + w.Writeln(" ") + // w.Writeln(" %s", enum.Description) + // w.Writeln(" ") + for j := 0; j < len(enum.Options); j++ { + option := enum.Options[j] + w.Writeln(" .. cpp:enumerator:: %s = %d", option.Name, option.Value) + } + w.Writeln(" ") + } +} + +func buildJSDocumentationFunctionTypes(component ComponentDefinition, w LanguageWriter) error { + if len(component.Functions) == 0 { + return nil + } + w.Writeln("") + w.Writeln("Function types") + w.Writeln("---------------") + w.Writeln("") + w.Writeln("") + for i := 0; i < len(component.Functions); i++ { + functiontype := component.Functions[i] + err := writeJSDocumentationFunctionPointer(component, w, functiontype) + if err != nil { + return err + } + } + w.Writeln("") + + return nil +} + +func buildJSDocumentationTypes(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) error { + LibraryName := component.LibraryName + + w.Writeln("") + w.Writeln("Types used in %s", LibraryName) + w.Writeln("==========================================================================================================") + w.Writeln("") + w.Writeln("") + + buildJSDocumentationSimpleTypes(component, w) + buildJSDocumentationEnums(component, w) + + err := buildJSDocumentationStructs(component, w) + if err != nil { + return err + } + err = buildJSDocumentationFunctionTypes(component, w) + if err != nil { + return err + } + buildJSDocumentationException(component, w) + buildJSDocumentationInputVector(component, w, ClassIdentifier) + + return nil +} diff --git a/Source/buildimplementationpascal.go b/Source/buildimplementationpascal.go index 71c91620..7eaa3363 100644 --- a/Source/buildimplementationpascal.go +++ b/Source/buildimplementationpascal.go @@ -62,7 +62,7 @@ func BuildImplementationPascal(component ComponentDefinition, outputFolder strin return errors.New("pascal Stub Identifier must not be empty") } - if (!suppressInterfaces) { + if !suppressInterfaces { IntfWrapperTypesName := path.Join(outputFolder, baseName+"_types.pas") log.Printf("Creating \"%s\"", IntfWrapperTypesName) @@ -114,7 +114,7 @@ func BuildImplementationPascal(component ComponentDefinition, outputFolder strin var defaultImplementation []string defaultImplementation = append(defaultImplementation, fmt.Sprintf("raise E%sException.Create(%s_ERROR_NOTIMPLEMENTED);", NameSpace, strings.ToUpper(NameSpace))) - if (!suppressStub) { + if !suppressStub { IntfWrapperStubName := path.Join(stubOutputFolder, baseName+stubIdentifier+".pas") if forceRecreation || (!FileExists(IntfWrapperStubName)) { @@ -551,7 +551,7 @@ func generatePrePostCallPascalFunctionCode(component ComponentDefinition, method variableDefinitions = append(variableDefinitions, fmt.Sprintf("Object%s: TObject;", param.ParamName)) checkInputCode = append(checkInputCode, fmt.Sprintf("Object%s := TObject(%s);", param.ParamName, pascalParams[0].ParamName)) - if (param.ParamType == "class") { + if param.ParamType == "class" { checkInputCode = append(checkInputCode, fmt.Sprintf("if (not Supports(Object%s, I%s%s)) then", param.ParamName, NameSpace, param.ParamClass)) checkInputCode = append(checkInputCode, fmt.Sprintf(" raise E%sException.Create(%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace))) } @@ -1467,7 +1467,7 @@ func buildPascalStub(component ComponentDefinition, NameSpace string, ClassIdent var methodImplementation []string methodImplementation = append(methodImplementation, fmt.Sprintf("Result := QWord($%016X); // First 64 bits of SHA1 of a string: \"%s\"", classTypeId, chashHashString)) - + err := writePascalClassMethodDummyStub(component.classTypeIdMethod(), w, NameSpace, class.ClassName, outClassName, false, methodImplementation) if err != nil { return err @@ -1503,24 +1503,24 @@ func writePascalImplClassMethodDefinition(method ComponentDefinitionMethod, w La if isGlobal { classPrefix = "class " } - str := ""; + str := "" if returnType == "" { str = fmt.Sprintf("%sprocedure %s(%s);", classPrefix, method.MethodName, parameters) } else { str = fmt.Sprintf("%sfunction %s(%s): %s;", classPrefix, method.MethodName, parameters, returnType) } if isOverride { - str = str + " Override;"; + str = str + " Override;" } else { if isVirtual { - str = str + " Virtual;"; + str = str + " Virtual;" } if isAbstract { - str = str + " Abstract;"; - } + str = str + " Abstract;" + } } - w.Writeln(str); + w.Writeln(str) return nil } diff --git a/Source/buildimplementationts.go b/Source/buildimplementationts.go new file mode 100644 index 00000000..f5ce2786 --- /dev/null +++ b/Source/buildimplementationts.go @@ -0,0 +1,506 @@ +/*++ + +Copyright (C) 2023 Autodesk Inc. (Original Author) + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--*/ + +////////////////////////////////////////////////////////////////////////////////////////////////////// +// buildimplementationts.go +// Builds typescript interface definitions. +////////////////////////////////////////////////////////////////////////////////////////////////////// + +package main + +import ( + "errors" + "log" + "path" + "regexp" + "strings" + "unicode/utf8" +) + +type TypeScriptOptions struct { + Camelize bool + JsArrays bool + LineLength int +} + +// BuildImplementationTS builds typescript interface definitions +func BuildImplementationTS( + component ComponentDefinition, + outputFolder string, + implementation ComponentDefinitionImplementation, +) error { + + log.Printf("Creating TypeScript Implementation") + + options := TypeScriptOptions{ + Camelize: true, + JsArrays: false, + LineLength: 80, + } + + filename := path.Join(outputFolder, "fusion-environment-act.d.ts") + log.Printf("Creating \"%s\"", filename) + file, err := CreateLanguageFile(filename, " ") + if err != nil { + return err + } + + file.WriteCLicenseHeader(component, "", true) + file.Writeln("") + file.Writeln("export namespace %s {", component.NameSpace) + + err = writeTypescriptInterfaces(component, file, options) + if err != nil { + return err + } + err = writeTypescriptEnums(component, file, options) + if err != nil { + return err + } + file.Writeln("} // %s ", component.NameSpace) + + return nil +} + +func writeTypescriptEnums( + component ComponentDefinition, + writer LanguageWriter, + options TypeScriptOptions, +) error { + + for _, enum := range component.Enums { + err := writeTypescriptEnum(enum, writer, options) + if err != nil { + return err + } + } + return nil +} + +func writeTypescriptEnum( + enum ComponentDefinitionEnum, + writer LanguageWriter, + options TypeScriptOptions, +) error { + writer.Writeln("const enum %s {", getTypeId(enum.Name, options)) + writer.Indentation++ + for _, option := range enum.Options { + writeCommentEnumOption(option, writer, options) + identifier := getTypeId(option.Name, options) + value := option.Value + writer.Writeln("%s = %d,", identifier, value) + } + writer.Indentation-- + writer.Writeln("}") + writer.Writeln("") + return nil +} + +func writeTypescriptInterfaces( + component ComponentDefinition, + writer LanguageWriter, + options TypeScriptOptions, +) error { + for _, class := range component.Classes { + err := writeTypescriptInterface(class, writer, options) + if err != nil { + return err + } + } + return nil +} + +func writeTypescriptInterface( + class ComponentDefinitionClass, + writer LanguageWriter, + options TypeScriptOptions, +) error { + writeCommentClass(class, writer, options) + identifier := getTypeId(class.ClassName, options) + extends := "" + if class.ParentClass != "" { + extends = "extends " + class.ParentClass + " " + } + writer.Writeln("interface %s %s{", identifier, extends) + + for _, method := range class.Methods { + writer.Indentation++ + var err error + if method.PropertyGet != "" || method.PropertySet != "" { + err = writeTypescriptProperty(class, method, writer, options) + } else { + err = writeTypescriptMethod(class, method, writer, options) + } + if err != nil { + return err + } + writer.Indentation-- + } + writer.Writeln("}") + writer.Writeln("") + return nil +} + +func writeTypescriptMethod( + class ComponentDefinitionClass, + method ComponentDefinitionMethod, + writer LanguageWriter, + options TypeScriptOptions, +) error { + inParams := filterPass(method.Params, "in") + outParams := filterPass(method.Params, "out") + returnParams := filterPass(method.Params, "return") + + writer.Writeln("") + writeCommentMethod(class, method, writer, options) + writer.BeginLine() + writer.Printf("%s(", getName(method.MethodName, options)) + for i, param := range inParams { + if param.ParamOptional == "true" { + writer.Printf( + "%s?: %s", + getName(param.ParamName, options), + getType(param, options), + ) + } else { + writer.Printf( + "%s: %s", + getName(param.ParamName, options), + getType(param, options), + ) + } + if i+1 < len(inParams) { + writer.Printf(", ") + } + } + writer.Printf("): ") + + if len(outParams) > 0 { + writer.Printf("[") + for i, param := range outParams { + writer.Printf( + "%s: %s", + getName(param.ParamName, options), + getType(param, options), + ) + if i+1 < len(outParams) { + writer.Printf(", ") + } + } + writer.Printf("]") + } else { + if len(returnParams) > 1 { + return errors.New("More than one return value.") + } else if len(returnParams) == 1 { + writer.Printf(getType(returnParams[0], options)) + } else { + writer.Printf("void") + } + } + + writer.Printf(";") + writer.EndLine() + return nil +} + +func writeTypescriptProperty( + class ComponentDefinitionClass, + method ComponentDefinitionMethod, + writer LanguageWriter, + options TypeScriptOptions, +) error { + if method.PropertySet != "" { + // Ignore setters + return nil + } + getter := &method + var setter *ComponentDefinitionMethod + for _, method := range class.Methods { + if method.PropertySet == getter.PropertyGet { + setter = &method + continue + } + } + returnParams := filterPass(getter.Params, "return") + if len(returnParams) != 1 { + return errors.New("Property getters should have a single return value.") + } + readOnly := "readonly " + if setter != nil { + readOnly = "" + } + writer.Writeln("") + writeCommentProperty(class, *getter, writer, options) + writer.Writeln( + "%s%s: %s;", + readOnly, + getName(getter.PropertyGet, options), + getType(returnParams[0], options), + ) + return nil +} + +func filterPass( + params []ComponentDefinitionParam, + pass string, +) []ComponentDefinitionParam { + var result []ComponentDefinitionParam + for _, param := range params { + if param.ParamPass == pass { + result = append(result, param) + } + } + return result +} + +func filterOptional(params []ComponentDefinitionParam) []ComponentDefinitionParam { + var result []ComponentDefinitionParam + for _, param := range params { + if param.ParamOptional == "true" { + result = append(result, param) + } + } + return result +} + +func getTypeId(identifier string, options TypeScriptOptions) string { + return identifier +} + +func getName(identifier string, options TypeScriptOptions) string { + if options.Camelize { + return camelize(identifier) + } + return identifier +} + +func getType( + param ComponentDefinitionParam, + options TypeScriptOptions, +) string { + return getTypeString(param.ParamType, param.ParamClass, options) +} + +func getTypeString( + paramType string, + paramClass string, + options TypeScriptOptions, +) string { + if paramType == "class" || paramType == "optionalclass" || paramType == "enum" { + if options.JsArrays && strings.HasSuffix(paramClass, "Vector") { + return strings.TrimSuffix(paramClass, "Vector") + "[]" + } + if paramType == "optionalclass" { + return paramClass + "|null" + } + return paramClass + } else if paramType == "basicarray" { + return getTypeString(paramClass, "", options) + "[]" + } else if paramType == "double" || + paramType == "int16" || + paramType == "int32" || + paramType == "int64" || + paramType == "uint16" || + paramType == "uint32" || + paramType == "uint64" { + return "number" + } else if paramType == "bool" { + return "boolean" + } + return paramType +} + +func camelize(str string) string { + r, _ := regexp.Compile("^([A-Z]+)([A-Z])(.*)") + result := r.FindStringSubmatch(str) + + if len(result) > 0 { + if len(result) > 1 { + if len(result) == 4 && result[3] == "" { + str = strings.ToLower(str) + } else { + str = strings.ToLower(result[1]) + strings.Join(result[2:], "") + } + } + } else { + r, _ := utf8.DecodeRuneInString(str) + str = strings.ToLower(string(r)) + str[len(string(r)):] + } + + return str +} + +func writeCommentEnumOption( + option ComponentDefinitionEnumOption, + writer LanguageWriter, + options TypeScriptOptions, +) { + writer.Writeln("/**") + lines := getCommentLines(" * ", option.Description, writer, options) + for _, line := range lines { + writer.Writeln(" * " + line) + } + writer.Writeln(" */") +} + +func writeCommentClass( + class ComponentDefinitionClass, + writer LanguageWriter, + options TypeScriptOptions, +) { + writer.Writeln("/**") + lines := getCommentLines(" * ", class.ClassDescription, writer, options) + for _, line := range lines { + writer.Writeln(" * " + line) + } + writer.Writeln(" */") +} + +func writeCommentMethod( + class ComponentDefinitionClass, + method ComponentDefinitionMethod, + writer LanguageWriter, + options TypeScriptOptions, +) { + writer.Writeln("/**") + lines := getCommentLines(" * ", method.MethodDescription, writer, options) + for _, line := range lines { + writer.Writeln(" * " + line) + } + inParams := filterPass(method.Params, "in") + outParams := filterPass(method.Params, "out") + returnParams := filterPass(method.Params, "return") + + writeCommentInParams(inParams, writer, options) + if len(outParams) > 0 { + writeCommentOutParams(outParams, writer, options) + } else { + writeCommentReturnParams(returnParams, writer, options) + } + writer.Writeln(" */") +} + +func writeCommentProperty( + class ComponentDefinitionClass, + method ComponentDefinitionMethod, + writer LanguageWriter, + options TypeScriptOptions, +) { + writer.Writeln("/**") + lines := getCommentLines(" * ", method.MethodDescription, writer, options) + for _, line := range lines { + writer.Writeln(" * " + line) + } + writer.Writeln(" */") +} + +func writeCommentInParams( + params []ComponentDefinitionParam, + writer LanguageWriter, + options TypeScriptOptions, +) { + for _, param := range params { + prefix := " * @param {" + getType(param, options) + "} " + + getName(param.ParamName, options) + " " + lines := getCommentLines(prefix, param.ParamDescription, writer, options) + if len(lines) > 0 { + writer.Writeln(prefix + lines[0]) + prefix = " * " + strings.Repeat(" ", len(prefix)-len(" * ")) + for i := 1; i < len(lines); i++ { + line := lines[i] + writer.Writeln(prefix + line) + } + } + } +} + +func writeCommentOutParams( + params []ComponentDefinitionParam, + writer LanguageWriter, + options TypeScriptOptions, +) { + for _, param := range params { + prefix := " * @returns {" + getType(param, options) + "} " + prefix2 := prefix + getName(param.ParamName, options) + " " + lines := getCommentLines(prefix2, param.ParamDescription, writer, options) + if len(lines) > 0 { + writer.Writeln(prefix2 + lines[0]) + prefix2 = " * " + strings.Repeat(" ", len(prefix2)-len(" * ")) + for i := 1; i < len(lines); i++ { + line := lines[i] + writer.Writeln(prefix2 + line) + } + } + } +} + +func writeCommentReturnParams( + params []ComponentDefinitionParam, + writer LanguageWriter, + options TypeScriptOptions, +) { + for _, param := range params { + prefix := " * @returns {" + getType(param, options) + "} " + lines := getCommentLines(prefix, param.ParamDescription, writer, options) + if len(lines) > 0 { + writer.Writeln(prefix + lines[0]) + prefix = " * " + strings.Repeat(" ", len(prefix)-len(" * ")) + for i := 1; i < len(lines); i++ { + line := lines[i] + writer.Writeln(prefix + line) + } + } + } +} + +func getCommentLines( + prefix string, + comment string, + writer LanguageWriter, + options TypeScriptOptions, +) []string { + indent := strings.Repeat(writer.IndentString, writer.Indentation) + lineLength := options.LineLength - len(indent) - len(prefix) + return getLines(comment, lineLength) +} + +func getLines(input string, width int) []string { + words := strings.Fields(input) + var lines []string + line := "" + for _, word := range words { + if len(line)+len(word) > width { + lines = append(lines, line) + line = word + " " + } else { + line += word + " " + } + } + lines = append(lines, line) + return lines +} diff --git a/Source/componentdefinition.go b/Source/componentdefinition.go index 24be9903..38b21d2a 100644 --- a/Source/componentdefinition.go +++ b/Source/componentdefinition.go @@ -50,56 +50,60 @@ import ( ) const ( - eSpecialMethodNone = 0 - eSpecialMethodVersion = 1 - eSpecialMethodRelease = 2 - eSpecialMethodAcquire = 3 - eSpecialMethodError = 4 - eSpecialMethodInjection = 5 + eSpecialMethodNone = 0 + eSpecialMethodVersion = 1 + eSpecialMethodRelease = 2 + eSpecialMethodAcquire = 3 + eSpecialMethodError = 4 + eSpecialMethodInjection = 5 eSpecialMethodSymbolLookup = 6 - eSpecialMethodJournal = 7 - eSpecialMethodPrerelease = 8 - eSpecialMethodBuildinfo = 9 + eSpecialMethodJournal = 7 + eSpecialMethodPrerelease = 8 + eSpecialMethodBuildinfo = 9 ) // ComponentDefinitionParam definition of a method parameter used in the component's API type ComponentDefinitionParam struct { ComponentDiffableElement - XMLName xml.Name `xml:"param"` - ParamName string `xml:"name,attr"` - ParamType string `xml:"type,attr"` - ParamPass string `xml:"pass,attr"` - ParamClass string `xml:"class,attr"` - ParamDescription string `xml:"description,attr"` + XMLName xml.Name `xml:"param"` + ParamName string `xml:"name,attr"` + ParamType string `xml:"type,attr"` + ParamPass string `xml:"pass,attr"` + ParamClass string `xml:"class,attr"` + ParamDefaultValue string `xml:"defaultvalue,attr"` + ParamOptional string `xml:"optional,attr"` + ParamDescription string `xml:"description,attr"` } // ComponentDefinitionMethod definition of a method provided by the component's API type ComponentDefinitionMethod struct { ComponentDiffableElement - XMLName xml.Name `xml:"method"` - MethodName string `xml:"name,attr"` - MethodDescription string `xml:"description,attr"` - DisableStringOutCache bool `xml:"disablestringoutcache,attr"` - Params []ComponentDefinitionParam `xml:"param"` + XMLName xml.Name `xml:"method"` + MethodName string `xml:"name,attr"` + MethodDescription string `xml:"description,attr"` + DisableStringOutCache bool `xml:"disablestringoutcache,attr"` + Params []ComponentDefinitionParam `xml:"param"` + PropertyGet string `xml:"propertyget,attr"` + PropertySet string `xml:"propertyset,attr"` } // ComponentDefinitionClass definition of a class provided by the component's API type ComponentDefinitionClass struct { ComponentDiffableElement - XMLName xml.Name `xml:"class"` - ClassName string `xml:"name,attr"` - ClassDescription string `xml:"description,attr"` - ParentClass string `xml:"parent,attr"` - Methods []ComponentDefinitionMethod `xml:"method"` + XMLName xml.Name `xml:"class"` + ClassName string `xml:"name,attr"` + ClassDescription string `xml:"description,attr"` + ParentClass string `xml:"parent,attr"` + Methods []ComponentDefinitionMethod `xml:"method"` } // ComponentDefinitionFunctionType definition of a function interface provided by the component's API type ComponentDefinitionFunctionType struct { ComponentDiffableElement - XMLName xml.Name `xml:"functiontype"` - FunctionName string `xml:"name,attr"` - FunctionDescription string `xml:"description,attr"` - Params []ComponentDefinitionParam `xml:"param"` + XMLName xml.Name `xml:"functiontype"` + FunctionName string `xml:"name,attr"` + FunctionDescription string `xml:"description,attr"` + Params []ComponentDefinitionParam `xml:"param"` } // ComponentDefinitionBindingList definition of the language bindings to be generated for the component's API @@ -117,101 +121,101 @@ type ComponentDefinitionImplementationList struct { // ComponentDefinitionGlobal definition of global functions provided the component's API type ComponentDefinitionGlobal struct { ComponentDiffableElement - XMLName xml.Name `xml:"global"` - BaseClassName string `xml:"baseclassname,attr"` - StringOutBaseClassName string `xml:"stringoutclassname,attr"` - ErrorMethod string `xml:"errormethod,attr"` - ClassTypeIdMethod string `xml:"classtypeidmethod,attr"` - ReleaseMethod string `xml:"releasemethod,attr"` - AcquireMethod string `xml:"acquiremethod,attr"` - SymbolLookupMethod string `xml:"symbollookupmethod,attr"` - InjectionMethod string `xml:"injectionmethod,attr"` - JournalMethod string `xml:"journalmethod,attr"` - VersionMethod string `xml:"versionmethod,attr"` - PrereleaseMethod string `xml:"prereleasemethod,attr"` - BuildinfoMethod string `xml:"buildinfomethod,attr"` - Methods []ComponentDefinitionMethod `xml:"method"` + XMLName xml.Name `xml:"global"` + BaseClassName string `xml:"baseclassname,attr"` + StringOutBaseClassName string `xml:"stringoutclassname,attr"` + ErrorMethod string `xml:"errormethod,attr"` + ClassTypeIdMethod string `xml:"classtypeidmethod,attr"` + ReleaseMethod string `xml:"releasemethod,attr"` + AcquireMethod string `xml:"acquiremethod,attr"` + SymbolLookupMethod string `xml:"symbollookupmethod,attr"` + InjectionMethod string `xml:"injectionmethod,attr"` + JournalMethod string `xml:"journalmethod,attr"` + VersionMethod string `xml:"versionmethod,attr"` + PrereleaseMethod string `xml:"prereleasemethod,attr"` + BuildinfoMethod string `xml:"buildinfomethod,attr"` + Methods []ComponentDefinitionMethod `xml:"method"` } // ComponentDefinitionBinding definition of a specific languages for which bindings to the component's API will be generated type ComponentDefinitionBinding struct { ComponentDiffableElement - XMLName xml.Name `xml:"binding"` - Language string `xml:"language,attr"` - Indentation string `xml:"indentation,attr"` - ClassIdentifier string `xml:"classidentifier,attr"` - Documentation string `xml:"documentation,attr"` - Version string `xml:"version,attr"` + XMLName xml.Name `xml:"binding"` + Language string `xml:"language,attr"` + Indentation string `xml:"indentation,attr"` + ClassIdentifier string `xml:"classidentifier,attr"` + Documentation string `xml:"documentation,attr"` + Version string `xml:"version,attr"` } // ComponentDefinitionImplementation definition of a specific languages for which bindings to the component's API will be generated type ComponentDefinitionImplementation struct { ComponentDiffableElement - XMLName xml.Name `xml:"implementation"` - Language string `xml:"language,attr"` - Indentation string `xml:"indentation,attr"` - ClassIdentifier string `xml:"classidentifier,attr"` - StubIdentifier string `xml:"stubidentifier,attr"` + XMLName xml.Name `xml:"implementation"` + Language string `xml:"language,attr"` + Indentation string `xml:"indentation,attr"` + ClassIdentifier string `xml:"classidentifier,attr"` + StubIdentifier string `xml:"stubidentifier,attr"` } // ComponentDefinitionEnumOption definition of an enum used in the component's API type ComponentDefinitionEnumOption struct { ComponentDiffableElement - XMLName xml.Name `xml:"option"` - Name string `xml:"name,attr"` - Value int `xml:"value,attr"` - Description string `xml:"description,attr"` + XMLName xml.Name `xml:"option"` + Name string `xml:"name,attr"` + Value int `xml:"value,attr"` + Description string `xml:"description,attr"` } // ComponentDefinitionEnum definition of all enums used in the component's API type ComponentDefinitionEnum struct { ComponentDiffableElement - XMLName xml.Name `xml:"enum"` - Name string `xml:"name,attr"` - Description string `xml:"description,attr"` - Options []ComponentDefinitionEnumOption `xml:"option"` + XMLName xml.Name `xml:"enum"` + Name string `xml:"name,attr"` + Description string `xml:"description,attr"` + Options []ComponentDefinitionEnumOption `xml:"option"` } // ComponentDefinitionError definition of an error used in the component's API type ComponentDefinitionError struct { ComponentDiffableElement - XMLName xml.Name `xml:"error"` - Name string `xml:"name,attr"` - Code int `xml:"code,attr"` - Description string `xml:"description,attr"` + XMLName xml.Name `xml:"error"` + Name string `xml:"name,attr"` + Code int `xml:"code,attr"` + Description string `xml:"description,attr"` } // ComponentDefinitionErrors definition of errors in the component's API type ComponentDefinitionErrors struct { ComponentDiffableElement - XMLName xml.Name `xml:"errors"` - Errors []ComponentDefinitionError `xml:"error"` + XMLName xml.Name `xml:"errors"` + Errors []ComponentDefinitionError `xml:"error"` } // ComponentDefinitionImportComponent definition of errors in the component's API type ComponentDefinitionImportComponent struct { ComponentDiffableElement - XMLName xml.Name `xml:"importcomponent"` - URI string `xml:"uri,attr"` - Namespace string `xml:"namespace,attr"` + XMLName xml.Name `xml:"importcomponent"` + URI string `xml:"uri,attr"` + Namespace string `xml:"namespace,attr"` } // ComponentDefinitionMember definition of a single struct provided by the component's API type ComponentDefinitionMember struct { ComponentDiffableElement XMLName xml.Name `xml:"member"` - Name string `xml:"name,attr"` - Type string `xml:"type,attr"` - Class string `xml:"class,attr"` - Rows int `xml:"rows,attr"` - Columns int `xml:"columns,attr"` + Name string `xml:"name,attr"` + Type string `xml:"type,attr"` + Class string `xml:"class,attr"` + Rows int `xml:"rows,attr"` + Columns int `xml:"columns,attr"` } // ComponentDefinitionStruct definition of all structs provided by the component's API type ComponentDefinitionStruct struct { ComponentDiffableElement - XMLName xml.Name `xml:"struct"` - Name string `xml:"name,attr"` + XMLName xml.Name `xml:"struct"` + Name string `xml:"name,attr"` Members []ComponentDefinitionMember `xml:"member"` } @@ -219,39 +223,39 @@ type ComponentDefinitionStruct struct { type ComponentDefinitionLicenseLine struct { ComponentDiffableElement XMLName xml.Name `xml:"line"` - Value string `xml:"value,attr"` + Value string `xml:"value,attr"` } // ComponentDefinitionLicense the component's license type ComponentDefinitionLicense struct { ComponentDiffableElement - XMLName xml.Name `xml:"license"` + XMLName xml.Name `xml:"license"` Lines []ComponentDefinitionLicenseLine `xml:"line"` } // ComponentDefinition the complete definition of the component's API type ComponentDefinition struct { - ACTVersion string - XMLName xml.Name `xml:"component"` - Version string `xml:"version,attr"` - Copyright string `xml:"copyright,attr"` - Year int `xml:"year,attr"` - NameSpace string `xml:"namespace,attr"` - LibraryName string `xml:"libraryname,attr"` - BaseName string `xml:"basename,attr"` - License ComponentDefinitionLicense `xml:"license"` - Classes []ComponentDefinitionClass `xml:"class"` - Functions []ComponentDefinitionFunctionType `xml:"functiontype"` - BindingList ComponentDefinitionBindingList `xml:"bindings"` + ACTVersion string + XMLName xml.Name `xml:"component"` + Version string `xml:"version,attr"` + Copyright string `xml:"copyright,attr"` + Year int `xml:"year,attr"` + NameSpace string `xml:"namespace,attr"` + LibraryName string `xml:"libraryname,attr"` + BaseName string `xml:"basename,attr"` + License ComponentDefinitionLicense `xml:"license"` + Classes []ComponentDefinitionClass `xml:"class"` + Functions []ComponentDefinitionFunctionType `xml:"functiontype"` + BindingList ComponentDefinitionBindingList `xml:"bindings"` ImplementationList ComponentDefinitionImplementationList `xml:"implementations"` - Enums []ComponentDefinitionEnum `xml:"enum"` - Structs []ComponentDefinitionStruct `xml:"struct"` - Global ComponentDefinitionGlobal `xml:"global"` - Errors ComponentDefinitionErrors `xml:"errors"` - ImportComponents []ComponentDefinitionImportComponent `xml:"importcomponent"` + Enums []ComponentDefinitionEnum `xml:"enum"` + Structs []ComponentDefinitionStruct `xml:"struct"` + Global ComponentDefinitionGlobal `xml:"global"` + Errors ComponentDefinitionErrors `xml:"errors"` + ImportComponents []ComponentDefinitionImportComponent `xml:"importcomponent"` ImportedComponentDefinitions map[string]ComponentDefinition - NameMapsLookup NameMaps + NameMapsLookup NameMaps } // Normalize adds default values, changes deprecated constants to their later versions @@ -260,8 +264,8 @@ func (component *ComponentDefinition) Normalize() { component.Classes[i].Normalize() } component.Global.Normalize() - - for _, importedComponent := range component.ImportedComponentDefinitions { + + for _, importedComponent := range component.ImportedComponentDefinitions { importedComponent.Normalize() } } @@ -299,10 +303,10 @@ func ReadComponentDefinition(FileName string, ACTVersion string) (ComponentDefin var component ComponentDefinition component.ImportedComponentDefinitions = make(map[string]ComponentDefinition, 0) component.NameMapsLookup = NameMaps{ - enumMap : make(map[string]bool, 0), - structMap : make(map[string]bool, 0), - classMap : make(map[string]bool, 0), - functionTypeMap : make(map[string]bool, 0), + enumMap: make(map[string]bool, 0), + structMap: make(map[string]bool, 0), + classMap: make(map[string]bool, 0), + functionTypeMap: make(map[string]bool, 0), } absFileName, err := filepath.Abs(FileName) @@ -335,8 +339,8 @@ func ReadComponentDefinition(FileName string, ACTVersion string) (ComponentDefin if err != nil { return component, err } - if (subComponent.NameSpace != importComponent.Namespace) { - return component, fmt.Errorf("Namespace of imported component \"%s\" does not match declared namespace \"%s\"", importComponent.Namespace, subComponent.NameSpace); + if subComponent.NameSpace != importComponent.Namespace { + return component, fmt.Errorf("Namespace of imported component \"%s\" does not match declared namespace \"%s\"", importComponent.Namespace, subComponent.NameSpace) } component.ImportedComponentDefinitions[importComponent.Namespace] = subComponent } @@ -347,25 +351,25 @@ func ReadComponentDefinition(FileName string, ACTVersion string) (ComponentDefin func getIndentationString(str string) string { if str == "tabs" { - return "\t"; + return "\t" } - index := strings.Index(str, "spaces"); - if (index < 1) { - log.Printf ("invalid indentation: \"%s\". Using \"tabs\" instead\n", str); - return "\t"; + index := strings.Index(str, "spaces") + if index < 1 { + log.Printf("invalid indentation: \"%s\". Using \"tabs\" instead\n", str) + return "\t" } - numSpaces, err := strconv.ParseUint(str[0:index], 10, 64); - if err!=nil { - log.Printf ("invalid indentation: \"%s\". Using \"4spaces\" instead\n", str); - return " "; + numSpaces, err := strconv.ParseUint(str[0:index], 10, 64) + if err != nil { + log.Printf("invalid indentation: \"%s\". Using \"4spaces\" instead\n", str) + return " " } - indentString := ""; - var i uint64; + indentString := "" + var i uint64 for i < numSpaces { - indentString = indentString + " "; - i++; + indentString = indentString + " " + i++ } - return indentString; + return indentString } func (component *ComponentDefinition) checkImplementations() error { @@ -375,12 +379,12 @@ func (component *ComponentDefinition) checkImplementations() error { if len(implementation.ClassIdentifier) > 0 { if !nameSpaceIsValid(implementation.ClassIdentifier) { - return fmt.Errorf ("Invalid ClassIdentifier in implementation \"%s\"", implementation.Language); + return fmt.Errorf("Invalid ClassIdentifier in implementation \"%s\"", implementation.Language) } } if len(implementation.StubIdentifier) > 0 { if !stubIdentifierIsValid(implementation.StubIdentifier) { - return fmt.Errorf ("Invalid StubIdentifier in implementation \"%s\"", implementation.Language); + return fmt.Errorf("Invalid StubIdentifier in implementation \"%s\"", implementation.Language) } } } @@ -388,68 +392,68 @@ func (component *ComponentDefinition) checkImplementations() error { } func (component *ComponentDefinition) checkErrors() error { - errorNameList := make(map[string]bool, 0); - errorCodeList := make(map[int]bool, 0); + errorNameList := make(map[string]bool, 0) + errorCodeList := make(map[int]bool, 0) errors := component.Errors for i := 0; i < len(errors.Errors); i++ { - merror := errors.Errors[i]; + merror := errors.Errors[i] if !nameIsValidIdentifier(merror.Name) { - return fmt.Errorf( "invalid error name \"%s\"", merror.Name); + return fmt.Errorf("invalid error name \"%s\"", merror.Name) } - if (errorNameList[strings.ToLower(merror.Name)]) { - return fmt.Errorf( "duplicate error name \"%s\"", merror.Name); + if errorNameList[strings.ToLower(merror.Name)] { + return fmt.Errorf("duplicate error name \"%s\"", merror.Name) } - errorNameList[strings.ToLower(merror.Name)] = true; + errorNameList[strings.ToLower(merror.Name)] = true - if (errorCodeList[merror.Code]) { - return fmt.Errorf( "duplicate error code \"%d\" for error \"%s\"", merror.Code, merror.Name); + if errorCodeList[merror.Code] { + return fmt.Errorf("duplicate error code \"%d\" for error \"%s\"", merror.Code, merror.Name) } errorCodeList[merror.Code] = true if !errorDescriptionIsValid(merror.Description) { - return fmt.Errorf( "invalid error description \"%s\" for error \"%s\"", merror.Description, merror.Name); + return fmt.Errorf("invalid error description \"%s\" for error \"%s\"", merror.Description, merror.Name) } } requiredErrors := []string{"NOTIMPLEMENTED", "INVALIDPARAM", - "INVALIDCAST", "BUFFERTOOSMALL", "GENERICEXCEPTION", "COULDNOTLOADLIBRARY", "COULDNOTFINDLIBRARYEXPORT", "INCOMPATIBLEBINARYVERSION"} - for _, req := range requiredErrors { - if (!errorNameList[strings.ToLower(req)]) { - return fmt.Errorf( "component is missing the required error \"%s\"", req); - } + "INVALIDCAST", "BUFFERTOOSMALL", "GENERICEXCEPTION", "COULDNOTLOADLIBRARY", "COULDNOTFINDLIBRARYEXPORT", "INCOMPATIBLEBINARYVERSION"} + for _, req := range requiredErrors { + if !errorNameList[strings.ToLower(req)] { + return fmt.Errorf("component is missing the required error \"%s\"", req) } + } return nil } -func errorDescriptionIsValid (name string) bool { +func errorDescriptionIsValid(name string) bool { var IsValidIdentifier = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9_+\\-:,.=!/ ]*$").MatchString - if (name != "") { - return IsValidIdentifier(name); + if name != "" { + return IsValidIdentifier(name) } - - return false; + + return false } -func checkOptions(options[] ComponentDefinitionEnumOption) (error) { - optionLowerNameList := make(map[string]bool, 0); - optionValueList := make(map[int]bool, 0); +func checkOptions(options []ComponentDefinitionEnumOption) error { + optionLowerNameList := make(map[string]bool, 0) + optionValueList := make(map[int]bool, 0) for j := 0; j < len(options); j++ { option := options[j] if !nameIsValidIdentifier(option.Name) { return fmt.Errorf("invalid option name \"%s\"", option.Name) } - if (math.Abs( float64(option.Value)) > math.Exp2(31) - 1) { + if math.Abs(float64(option.Value)) > math.Exp2(31)-1 { return fmt.Errorf("option value out of range \"%d\" in \"%s\"", option.Value, option.Name) } if optionValueList[option.Value] { - return fmt.Errorf("duplicate option value \"%d\" in \"%s\"", option.Value, option.Name); + return fmt.Errorf("duplicate option value \"%d\" in \"%s\"", option.Value, option.Name) } if optionLowerNameList[strings.ToLower(option.Name)] { - return fmt.Errorf("duplicate option name \"%s\"", option.Name); + return fmt.Errorf("duplicate option name \"%s\"", option.Name) } optionValueList[option.Value] = true optionLowerNameList[strings.ToLower(option.Name)] = true @@ -457,24 +461,24 @@ func checkOptions(options[] ComponentDefinitionEnumOption) (error) { return nil } -func (component *ComponentDefinition) checkEnums() (error) { +func (component *ComponentDefinition) checkEnums() error { enums := component.Enums var enumNameList = &component.NameMapsLookup.enumMap - enumLowerNameList := make(map[string]bool, 0); + enumLowerNameList := make(map[string]bool, 0) for i := 0; i < len(enums); i++ { - enum := enums[i]; + enum := enums[i] if !nameIsValidIdentifier(enum.Name) { - return fmt.Errorf( "invalid enum name \"%s\"", enum.Name); + return fmt.Errorf("invalid enum name \"%s\"", enum.Name) } - - if (enumLowerNameList[strings.ToLower(enum.Name)]) { - return fmt.Errorf("duplicate enum name \"%s\"", enum.Name); + + if enumLowerNameList[strings.ToLower(enum.Name)] { + return fmt.Errorf("duplicate enum name \"%s\"", enum.Name) } err := checkOptions(enum.Options) if err != nil { - return fmt.Errorf(err.Error() + " in enum = \"%s\"", enum.Name); + return fmt.Errorf(err.Error()+" in enum = \"%s\"", enum.Name) } enumLowerNameList[strings.ToLower(enum.Name)] = true @@ -483,20 +487,19 @@ func (component *ComponentDefinition) checkEnums() (error) { return nil } - -func (component *ComponentDefinition) checkStructs() (error) { + +func (component *ComponentDefinition) checkStructs() error { structs := component.Structs var structNameList = &component.NameMapsLookup.structMap structLowerNameList := make(map[string]bool, 0) - for i := 0; i < len(structs); i++ { - mstruct := structs[i]; + mstruct := structs[i] if !nameIsValidIdentifier(mstruct.Name) { - return fmt.Errorf ("invalid struct name \"%s\"", mstruct.Name) + return fmt.Errorf("invalid struct name \"%s\"", mstruct.Name) } if structLowerNameList[mstruct.Name] == true { - return fmt.Errorf ("duplicate struct name \"%s\"", mstruct.Name) + return fmt.Errorf("duplicate struct name \"%s\"", mstruct.Name) } (*structNameList)[mstruct.Name] = true structLowerNameList[strings.ToLower(mstruct.Name)] = true @@ -504,14 +507,14 @@ func (component *ComponentDefinition) checkStructs() (error) { for j := 0; j < len(mstruct.Members); j++ { member := mstruct.Members[j] if !nameIsValidIdentifier(member.Name) { - return fmt.Errorf ("invalid member name \"%s\"", member.Name); + return fmt.Errorf("invalid member name \"%s\"", member.Name) } } } return nil } -func (component *ComponentDefinition) checkClasses() (error) { +func (component *ComponentDefinition) checkClasses() error { classes := component.Classes baseClassName := component.Global.BaseClassName var classNameList = &component.NameMapsLookup.classMap @@ -520,22 +523,22 @@ func (component *ComponentDefinition) checkClasses() (error) { classNameIndex := make(map[string]int, 0) classTypeIdIndex := make(map[uint64]int, 0) for i := 0; i < len(classes); i++ { - class := classes[i]; - classTypeHash, _ := class.classTypeId(component.NameSpace); + class := classes[i] + classTypeHash, _ := class.classTypeId(component.NameSpace) if !nameIsValidIdentifier(class.ClassName) { - return fmt.Errorf ("invalid class name \"%s\"", class.ClassName); + return fmt.Errorf("invalid class name \"%s\"", class.ClassName) } if classLowerNameList[strings.ToLower(class.ClassName)] == true { - return fmt.Errorf ("duplicate class name \"%s\"", class.ClassName); + return fmt.Errorf("duplicate class name \"%s\"", class.ClassName) } if len(class.ClassDescription) > 0 && !descriptionIsValid(class.ClassDescription) { - return fmt.Errorf ("invalid class description \"%s\" in class \"%s\"", class.ClassDescription, class.ClassName); + return fmt.Errorf("invalid class description \"%s\" in class \"%s\"", class.ClassDescription, class.ClassName) } collision, hashExists := classTypeIdIndex[classTypeHash] if hashExists { - return fmt.Errorf ("Classes \"%s\" and \"%s\" have a collision in their Class Type Id. Change class name.", classes[collision].ClassName, class.ClassName); + return fmt.Errorf("Classes \"%s\" and \"%s\" have a collision in their Class Type Id. Change class name.", classes[collision].ClassName, class.ClassName) } - + classLowerNameList[strings.ToLower(class.ClassName)] = true (*classNameList)[class.ClassName] = true classNameIndex[class.ClassName] = i @@ -544,23 +547,23 @@ func (component *ComponentDefinition) checkClasses() (error) { // Check parent class definitions for i := 0; i < len(classes); i++ { - class := classes[i]; - parentClass := class.ParentClass; - if ((baseClassName != class.ClassName) && (len(parentClass) == 0) ) { + class := classes[i] + parentClass := class.ParentClass + if (baseClassName != class.ClassName) && (len(parentClass) == 0) { parentClass = baseClassName } - if (len(parentClass) > 0) { + if len(parentClass) > 0 { if !nameIsValidIdentifier(parentClass) { - return fmt.Errorf ("invalid parent class name \"%s\"", parentClass); + return fmt.Errorf("invalid parent class name \"%s\"", parentClass) } - if ( (*classNameList)[parentClass] == false) { - return fmt.Errorf ("unknown parent class \"%s\" for class \"%s\"", parentClass, class.ClassName); + if (*classNameList)[parentClass] == false { + return fmt.Errorf("unknown parent class \"%s\" for class \"%s\"", parentClass, class.ClassName) } - if (classNameIndex[parentClass] >= i) { - return fmt.Errorf ("parent class \"%s\" for class \"%s\" is defined after its child class", parentClass, class.ClassName); + if classNameIndex[parentClass] >= i { + return fmt.Errorf("parent class \"%s\" for class \"%s\" is defined after its child class", parentClass, class.ClassName) } - if (strings.ToLower(class.ClassName) == strings.ToLower(parentClass)) { - return fmt.Errorf ("class \"%s\" cannot be its own parent class \"%s\"", class.ClassName, parentClass); + if strings.ToLower(class.ClassName) == strings.ToLower(parentClass) { + return fmt.Errorf("class \"%s\" cannot be its own parent class \"%s\"", class.ClassName, parentClass) } } } @@ -568,41 +571,41 @@ func (component *ComponentDefinition) checkClasses() (error) { return nil } -func (component *ComponentDefinition) checkFunctionTypes() ( error) { +func (component *ComponentDefinition) checkFunctionTypes() error { functions := component.Functions var functionNameList = &component.NameMapsLookup.functionTypeMap functionLowerNameList := make(map[string]bool, 0) for i := 0; i < len(functions); i++ { - function := functions[i]; + function := functions[i] if !nameIsValidIdentifier(function.FunctionName) { - return fmt.Errorf ("invalid functiontype name \"%s\"", function.FunctionName); + return fmt.Errorf("invalid functiontype name \"%s\"", function.FunctionName) } if functionLowerNameList[strings.ToLower(function.FunctionName)] == true { - return fmt.Errorf ("duplicate functiontype name \"%s\"", function.FunctionName); + return fmt.Errorf("duplicate functiontype name \"%s\"", function.FunctionName) } if len(function.FunctionDescription) > 0 && !descriptionIsValid(function.FunctionDescription) { - return fmt.Errorf ("invalid function description \"%s\" in functiontype \"%s\"", function.FunctionDescription, function.FunctionName); + return fmt.Errorf("invalid function description \"%s\" in functiontype \"%s\"", function.FunctionDescription, function.FunctionName) } - + functionLowerNameList[strings.ToLower(function.FunctionName)] = true (*functionNameList)[function.FunctionName] = true } return nil } -func checkDuplicateNames(nameMaps NameMaps) (error) { +func checkDuplicateNames(nameMaps NameMaps) error { enumList := nameMaps.enumMap structList := nameMaps.structMap classList := nameMaps.classMap functionTypeList := nameMaps.functionTypeMap allLowerList := make(map[string]string, 0) - + for k := range structList { if val, ok := allLowerList[strings.ToLower(k)]; ok { - if (val == "struct") { - return fmt.Errorf ("duplicate struct name \"%s\"", k) + if val == "struct" { + return fmt.Errorf("duplicate struct name \"%s\"", k) } return fmt.Errorf("struct with name \"%s\" conflicts with %s of same name", k, val) } @@ -611,8 +614,8 @@ func checkDuplicateNames(nameMaps NameMaps) (error) { for k := range enumList { if val, ok := allLowerList[strings.ToLower(k)]; ok { - if (val == "enum") { - return fmt.Errorf ("duplicate class name \"%s\"", k) + if val == "enum" { + return fmt.Errorf("duplicate class name \"%s\"", k) } return fmt.Errorf("enum with name \"%s\" conflicts with %s of same name", k, val) } @@ -621,8 +624,8 @@ func checkDuplicateNames(nameMaps NameMaps) (error) { for k := range classList { if val, ok := allLowerList[strings.ToLower(k)]; ok { - if (val == "class") { - return fmt.Errorf ("duplicate class name \"%s\"", k) + if val == "class" { + return fmt.Errorf("duplicate class name \"%s\"", k) } return fmt.Errorf("class with name \"%s\" conflicts with %s of same name", k, val) } @@ -631,8 +634,8 @@ func checkDuplicateNames(nameMaps NameMaps) (error) { for k := range functionTypeList { if val, ok := allLowerList[strings.ToLower(k)]; ok { - if (val == "functiontype") { - return fmt.Errorf ("duplicate functiontype name \"%s\"", k) + if val == "functiontype" { + return fmt.Errorf("duplicate functiontype name \"%s\"", k) } return fmt.Errorf("functiontype with name \"%s\" conflicts with %s of same name", k, val) } @@ -641,33 +644,33 @@ func checkDuplicateNames(nameMaps NameMaps) (error) { return nil } -func (component *ComponentDefinition) checkMethod(method ComponentDefinitionMethod, className string) (error) { +func (component *ComponentDefinition) checkMethod(method ComponentDefinitionMethod, className string) error { if !nameIsValidIdentifier(method.MethodName) { - return fmt.Errorf ("invalid name for method \"%s.%s\"", className, method.MethodName); + return fmt.Errorf("invalid name for method \"%s.%s\"", className, method.MethodName) } if !descriptionIsValid(method.MethodDescription) { - return fmt.Errorf ("invalid description for method \"%s.%s\"", className, method.MethodName); + return fmt.Errorf("invalid description for method \"%s.%s\"", className, method.MethodName) } paramNameList := make(map[string]bool, 0) for k := 0; k < len(method.Params); k++ { param := method.Params[k] if !nameIsValidIdentifier(param.ParamName) { - return fmt.Errorf("invalid param name \"%s\" in method \"%s.%s\"", param.ParamName, className, method.MethodName); + return fmt.Errorf("invalid param name \"%s\" in method \"%s.%s\"", param.ParamName, className, method.MethodName) } if !descriptionIsValid(method.MethodDescription) { - return fmt.Errorf("invalid description for parameter \"%s.%s(... %s ...)\"", className, method.MethodName, param.ParamName); + return fmt.Errorf("invalid description for parameter \"%s.%s(... %s ...)\"", className, method.MethodName, param.ParamName) } - if (paramNameList[strings.ToLower(param.ParamName)]) { + if paramNameList[strings.ToLower(param.ParamName)] { return fmt.Errorf("duplicate name \"%s\" for parameter in method \"%s.%s\"", param.ParamName, className, method.MethodName) } paramNameList[strings.ToLower(param.ParamName)] = true - if (isScalarType(param.ParamType) || param.ParamType == "string") { + if isScalarType(param.ParamType) || param.ParamType == "string" { // okay - } else if (param.ParamType == "basicarray") { + } else if param.ParamType == "basicarray" { if !isScalarType(param.ParamClass) { - return fmt.Errorf("parameter \"%s\" for method \"%s.%s\" is an unknown basic type \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass); + return fmt.Errorf("parameter \"%s\" for method \"%s.%s\" is an unknown basic type \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass) } } else { currentNameMaps := component.NameMapsLookup @@ -676,7 +679,7 @@ func (component *ComponentDefinition) checkMethod(method ComponentDefinitionMeth if err != nil { return err } - if len(namespace)>0 { + if len(namespace) > 0 { if subComponent, ok := component.ImportedComponentDefinitions[namespace]; ok { currentNameMaps = subComponent.NameMapsLookup } else { @@ -684,20 +687,20 @@ func (component *ComponentDefinition) checkMethod(method ComponentDefinitionMeth } } - if (param.ParamType == "class" || param.ParamType == "optionalclass" ) { - if (currentNameMaps.classMap[paramClassName] != true) { + if param.ParamType == "class" || param.ParamType == "optionalclass" { + if currentNameMaps.classMap[paramClassName] != true { return fmt.Errorf("parameter \"%s\" of method \"%s.%s\" is of unknown class \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass) } } else if (param.ParamType == "enum") || (param.ParamType == "enumarray") { - if (currentNameMaps.enumMap[paramClassName] != true) { + if currentNameMaps.enumMap[paramClassName] != true { return fmt.Errorf("parameter \"%s\" for method \"%s.%s\" is an unknown enum \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass) } } else if (param.ParamType == "structarray") || (param.ParamType == "struct") { - if (currentNameMaps.structMap[paramClassName] != true) { + if currentNameMaps.structMap[paramClassName] != true { return fmt.Errorf("parameter \"%s\" for method \"%s.%s\" is an unknown struct \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass) } - } else if (param.ParamType == "functiontype") { - if (currentNameMaps.functionTypeMap[paramClassName] != true) { + } else if param.ParamType == "functiontype" { + if currentNameMaps.functionTypeMap[paramClassName] != true { return fmt.Errorf("parameter \"%s\" for method \"%s.%s\" is an unknown function type \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass) } } else { @@ -706,32 +709,30 @@ func (component *ComponentDefinition) checkMethod(method ComponentDefinitionMeth } } - - - if ((len (method.getStringOutParameters ()) > 0) && (len (method.getArrayOutParameters ()) > 0)) { - return fmt.Errorf ("String and Array out parameters for method \"%s.%s\"", className, method.MethodName); + + if (len(method.getStringOutParameters()) > 0) && (len(method.getArrayOutParameters()) > 0) { + return fmt.Errorf("String and Array out parameters for method \"%s.%s\"", className, method.MethodName) } return nil } - -func (component *ComponentDefinition) checkBaseClassMethods() (error) { +func (component *ComponentDefinition) checkBaseClassMethods() error { method := component.classTypeIdMethod() if method.MethodName == "" { - return fmt.Errorf ("ClassTypeId method is not defined in Base class"); + return fmt.Errorf("ClassTypeId method is not defined in Base class") } - if (method.MethodName == component.Global.ClassTypeIdMethod) { - if (len (method.Params) != 1) || (method.Params[0].ParamType != "uint64") || (method.Params[0].ParamPass != "return") { - return fmt.Errorf ("ClassTypeId method does not match the expected function template"); + if method.MethodName == component.Global.ClassTypeIdMethod { + if (len(method.Params) != 1) || (method.Params[0].ParamType != "uint64") || (method.Params[0].ParamPass != "return") { + return fmt.Errorf("ClassTypeId method does not match the expected function template") } } return nil } -func (component *ComponentDefinition) checkClassMethods() (error) { +func (component *ComponentDefinition) checkClassMethods() error { classes := component.Classes for i := 0; i < len(classes); i++ { @@ -740,14 +741,14 @@ func (component *ComponentDefinition) checkClassMethods() (error) { methodNameList := make(map[string]bool, 0) for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] - if (!component.isBaseClass(class) && (method.MethodName == component.Global.ClassTypeIdMethod)) { - return fmt.Errorf ("class type id method \"%s\" is redefined in \"%s\".%s\"", method.MethodName, class.ClassName) + if !component.isBaseClass(class) && (method.MethodName == component.Global.ClassTypeIdMethod) { + return fmt.Errorf("class type id method \"%s\" is redefined in \"%s\".%s\"", method.MethodName, class.ClassName) } - if (methodNameList[strings.ToLower(method.MethodName)]) { - return fmt.Errorf ("duplicate name for method \"%s.%s\"", class.ClassName, method.MethodName) + if methodNameList[strings.ToLower(method.MethodName)] { + return fmt.Errorf("duplicate name for method \"%s.%s\"", class.ClassName, method.MethodName) } methodNameList[strings.ToLower(method.MethodName)] = true - + err := component.checkMethod(method, class.ClassName) if err != nil { return err @@ -764,77 +765,77 @@ func decomposeParamClassName(paramClassName string) (string, string, error) { } namespaceRegexp := "[A-Z][a-zA-Z0-9_]{0,63}" - var IsValidParamClassName = regexp.MustCompile(fmt.Sprintf("^((%s):){0,1}([a-zA-Z0-9_]{0,64})$", namespaceRegexp) ) - + var IsValidParamClassName = regexp.MustCompile(fmt.Sprintf("^((%s):){0,1}([a-zA-Z0-9_]{0,64})$", namespaceRegexp)) + if !(IsValidParamClassName.MatchString(paramClassName)) { - return "","", fmt.Errorf("param class name \"%s\" is ill formatted", paramClassName); + return "", "", fmt.Errorf("param class name \"%s\" is ill formatted", paramClassName) } slices := IsValidParamClassName.FindStringSubmatch(paramClassName) - if (len(slices) != 4) { - return "","", fmt.Errorf("param class name \"%s\" is ill formatted", paramClassName); + if len(slices) != 4 { + return "", "", fmt.Errorf("param class name \"%s\" is ill formatted", paramClassName) } namespace := slices[2] className := slices[3] - + return namespace, className, nil } func nameIsValidIdentifier(name string) bool { var IsValidIdentifier = regexp.MustCompile("^[A-Z][a-zA-Z0-9_]{0,63}$").MatchString - if (name != "") { - return IsValidIdentifier(name); + if name != "" { + return IsValidIdentifier(name) } - return false; + return false } func descriptionIsValid(description string) bool { var IsValidMethodDescription = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9_\\\\/+\\-:,.=!?()'; |]*$").MatchString - if (description != "") { - return IsValidMethodDescription(description); + if description != "" { + return IsValidMethodDescription(description) } - return false; + return false } func isScalarType(typeStr string) bool { - switch (typeStr) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double", "pointer": - return true + switch typeStr { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double", "pointer": + return true } return false } func majorVersion(version string) int { isValid, versions, _ := decomposeVersionString(version) - if (!isValid) { + if !isValid { log.Fatal("invalid version") } return versions[0] } func minorVersion(version string) int { isValid, versions, _ := decomposeVersionString(version) - if (!isValid) { + if !isValid { log.Fatal("invalid version") } return versions[1] } func microVersion(version string) int { isValid, versions, _ := decomposeVersionString(version) - if (!isValid) { + if !isValid { log.Fatal("invalid version") } return versions[2] } func preReleaseInfo(version string) string { isValid, _, additionalData := decomposeVersionString(version) - if (!isValid) { + if !isValid { log.Fatal("invalid version") } return additionalData[0] } func buildInfo(version string) string { isValid, _, additionalData := decomposeVersionString(version) - if (!isValid) { + if !isValid { log.Fatal("invalid version") } return additionalData[1] @@ -843,101 +844,100 @@ func buildInfo(version string) string { func decomposeVersionString(version string) (bool, [3]int, [2]string) { var IsValidVersion = regexp.MustCompile("^([0-9]+)\\.([0-9]+)\\.([0-9]+)(\\-[a-zA-Z0-9.\\-]+)?(\\+[a-zA-Z0-9.\\-]+)?$") - var vers [3]int; - var data [2]string; + var vers [3]int + var data [2]string if !(IsValidVersion.MatchString(version)) { - return false, vers, data; + return false, vers, data } slices := IsValidVersion.FindStringSubmatch(version) - if (len(slices) != 6) { - return false, vers, data; + if len(slices) != 6 { + return false, vers, data } for i := 0; i < 3; i++ { ver, err := strconv.Atoi(slices[i+1]) if err != nil { - return false, vers, data; + return false, vers, data } vers[i] = ver } for i := 0; i < 2; i++ { slice := slices[i+4] - if (len(slice)>0) { + if len(slice) > 0 { data[i] = slice[1:] } } - return true, vers, data; + return true, vers, data } func nameSpaceIsValid(namespace string) bool { var IsValidNamespace = regexp.MustCompile("^[A-Z][a-zA-Z0-9_]{0,63}$").MatchString - if (namespace != "") { - return IsValidNamespace(namespace); + if namespace != "" { + return IsValidNamespace(namespace) } - return false; + return false } func stubIdentifierIsValid(stubIdentifier string) bool { var IsValidStubIdentifier = regexp.MustCompile("[a-zA-Z0-9_]{0,63}$").MatchString - if (stubIdentifier != "") { - return IsValidStubIdentifier (stubIdentifier); + if stubIdentifier != "" { + return IsValidStubIdentifier(stubIdentifier) } - return false; + return false } func libraryNameIsValid(libraryname string) bool { var IsLibraryNameValid = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9_+\\-:,.=!/ ]*$").MatchString - if (libraryname != "") { - return IsLibraryNameValid (libraryname); + if libraryname != "" { + return IsLibraryNameValid(libraryname) } - return false; + return false } func baseNameIsValid(baseName string) bool { var IsBaseNameValid = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9_\\-.]*$").MatchString - if (baseName != "") { - return IsBaseNameValid (baseName); + if baseName != "" { + return IsBaseNameValid(baseName) } - return false; + return false } -func (component *ComponentDefinition) checkComponentHeader() (error) { +func (component *ComponentDefinition) checkComponentHeader() error { versionIsValid, _, _ := decomposeVersionString(component.Version) if !versionIsValid { return fmt.Errorf("Version \"%s\" is invalid", component.Version) } if component.Copyright == "" { - return errors.New ("no Copyright information given"); + return errors.New("no Copyright information given") } if (component.Year < 2000) || (component.Year > 2100) { - return errors.New ("invalid year given"); + return errors.New("invalid year given") } if !nameSpaceIsValid(component.NameSpace) { - return errors.New ("Invalid Namespace"); + return errors.New("Invalid Namespace") } if !libraryNameIsValid(component.LibraryName) { - return errors.New ("Invalid LilbraryName"); + return errors.New("Invalid LilbraryName") } if component.BaseName == "" { - log.Fatal ("Invalid export basename"); + log.Fatal("Invalid export basename") } if !baseNameIsValid(component.BaseName) { - return errors.New ("Invalid BaseName"); + return errors.New("Invalid BaseName") } return nil } // NameMaps contains maps of names of elements in a component type NameMaps struct { - enumMap map[string]bool - structMap map[string]bool - classMap map[string]bool + enumMap map[string]bool + structMap map[string]bool + classMap map[string]bool functionTypeMap map[string]bool } - // CheckComponentDefinition checks a component and returns an error, if it fails -func (component *ComponentDefinition) CheckComponentDefinition() (error) { +func (component *ComponentDefinition) CheckComponentDefinition() error { err := component.checkComponentHeader() if err != nil { return err @@ -964,7 +964,7 @@ func (component *ComponentDefinition) CheckComponentDefinition() (error) { if err != nil { return err } - + err = component.checkStructs() if err != nil { return err @@ -999,8 +999,8 @@ func (component *ComponentDefinition) CheckComponentDefinition() (error) { for i := 0; i < len(component.Global.Methods); i++ { method := component.Global.Methods[i] - if (globalMethodNameList[strings.ToLower(method.MethodName)]) { - return fmt.Errorf ("duplicate name for method \"%s.%s\"", "global", method.MethodName) + if globalMethodNameList[strings.ToLower(method.MethodName)] { + return fmt.Errorf("duplicate name for method \"%s.%s\"", "global", method.MethodName) } globalMethodNameList[strings.ToLower(method.MethodName)] = true @@ -1015,192 +1015,189 @@ func (component *ComponentDefinition) CheckComponentDefinition() (error) { } } - if (component.Global.BaseClassName == "") { - return errors.New ("No base class name specified"); + if component.Global.BaseClassName == "" { + return errors.New("No base class name specified") } found := 0 for i := 0; i < len(component.Classes); i++ { - if (component.Classes[i].ClassName == component.Global.BaseClassName) { + if component.Classes[i].ClassName == component.Global.BaseClassName { found++ } } - if (found==0) { - return errors.New ("Specified base class not found"); - } else if (found>1) { - return errors.New ("Base clase defined more than once"); + if found == 0 { + return errors.New("Specified base class not found") + } else if found > 1 { + return errors.New("Base clase defined more than once") } return nil } - // CheckHeaderSpecialFunction checks a special function of the header against their required definitions func CheckHeaderSpecialFunction(method ComponentDefinitionMethod, global ComponentDefinitionGlobal) (int, error) { - if (global.ReleaseMethod == "") { - return eSpecialMethodNone, errors.New ("No release method specified"); + if global.ReleaseMethod == "" { + return eSpecialMethodNone, errors.New("No release method specified") } - if (global.AcquireMethod == "") { - return eSpecialMethodNone, errors.New ("No acquire method specified"); + if global.AcquireMethod == "" { + return eSpecialMethodNone, errors.New("No acquire method specified") } - if (global.VersionMethod == "") { - return eSpecialMethodNone, errors.New ("No version method specified"); + if global.VersionMethod == "" { + return eSpecialMethodNone, errors.New("No version method specified") } - if (global.ErrorMethod == "") { - return eSpecialMethodNone, errors.New ("No error method specified"); + if global.ErrorMethod == "" { + return eSpecialMethodNone, errors.New("No error method specified") } - if (global.ClassTypeIdMethod == "") { - return eSpecialMethodNone, errors.New ("No ClassTypeId method specified"); + if global.ClassTypeIdMethod == "" { + return eSpecialMethodNone, errors.New("No ClassTypeId method specified") } - if (global.ReleaseMethod == global.JournalMethod) { - return eSpecialMethodNone, errors.New ("Release method can not be the same as the Journal method"); + if global.ReleaseMethod == global.JournalMethod { + return eSpecialMethodNone, errors.New("Release method can not be the same as the Journal method") } - if (global.ReleaseMethod == global.VersionMethod) { - return eSpecialMethodNone, errors.New ("Release method can not be the same as the Version method"); + if global.ReleaseMethod == global.VersionMethod { + return eSpecialMethodNone, errors.New("Release method can not be the same as the Version method") } - if (global.ReleaseMethod == global.AcquireMethod) { - return eSpecialMethodNone, errors.New ("Release method can not be the same as the Acquire method"); + if global.ReleaseMethod == global.AcquireMethod { + return eSpecialMethodNone, errors.New("Release method can not be the same as the Acquire method") } - if (global.JournalMethod == global.VersionMethod) { - return eSpecialMethodNone, errors.New ("Journal method can not be the same as the Version method"); + if global.JournalMethod == global.VersionMethod { + return eSpecialMethodNone, errors.New("Journal method can not be the same as the Version method") } - if (global.JournalMethod == global.AcquireMethod) { - return eSpecialMethodNone, errors.New ("Journal method can not be the same as the Acquire method"); + if global.JournalMethod == global.AcquireMethod { + return eSpecialMethodNone, errors.New("Journal method can not be the same as the Acquire method") } - if (method.MethodName == global.ReleaseMethod) { - if (len (method.Params) != 1) { - return eSpecialMethodNone, errors.New ("Release method does not match the expected function template"); + if method.MethodName == global.ReleaseMethod { + if len(method.Params) != 1 { + return eSpecialMethodNone, errors.New("Release method does not match the expected function template") } - + if (method.Params[0].ParamType != "class") || (method.Params[0].ParamClass != global.BaseClassName) || (method.Params[0].ParamPass != "in") { - return eSpecialMethodNone, errors.New ("Release method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Release method does not match the expected function template") } - return eSpecialMethodRelease, nil; + return eSpecialMethodRelease, nil } - if (method.MethodName == global.AcquireMethod) { - if (len (method.Params) != 1) { - return eSpecialMethodNone, errors.New ("Acquire method does not match the expected function template"); + if method.MethodName == global.AcquireMethod { + if len(method.Params) != 1 { + return eSpecialMethodNone, errors.New("Acquire method does not match the expected function template") } - + if (method.Params[0].ParamType != "class") || (method.Params[0].ParamClass != global.BaseClassName) || (method.Params[0].ParamPass != "in") { - return eSpecialMethodNone, errors.New ("Acquire method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Acquire method does not match the expected function template") } - return eSpecialMethodAcquire, nil; + return eSpecialMethodAcquire, nil } - if (method.MethodName == global.SymbolLookupMethod) { - if (len (method.Params) != 1) { - return eSpecialMethodNone, errors.New ("SymbolLookup method does not match the expected function template"); + if method.MethodName == global.SymbolLookupMethod { + if len(method.Params) != 1 { + return eSpecialMethodNone, errors.New("SymbolLookup method does not match the expected function template") } if (method.Params[0].ParamType != "pointer") || (method.Params[0].ParamPass != "return") { - return eSpecialMethodNone, errors.New ("SymbolLookup method does not match the expected function template"); + return eSpecialMethodNone, errors.New("SymbolLookup method does not match the expected function template") } - + return eSpecialMethodSymbolLookup, nil } - if (method.MethodName == global.InjectionMethod) { - if (len (method.Params) != 2) { - return eSpecialMethodNone, errors.New ("Injection method does not match the expected function template"); + if method.MethodName == global.InjectionMethod { + if len(method.Params) != 2 { + return eSpecialMethodNone, errors.New("Injection method does not match the expected function template") } if (method.Params[0].ParamType != "string") || (method.Params[0].ParamPass != "in") || (method.Params[1].ParamType != "pointer") || (method.Params[1].ParamPass != "in") { - return eSpecialMethodNone, errors.New ("Injection method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Injection method does not match the expected function template") } - + return eSpecialMethodInjection, nil } - if (method.MethodName == global.JournalMethod) { - if (len (method.Params) != 1) { - return eSpecialMethodNone, errors.New ("Journal method does not match the expected function template"); + if method.MethodName == global.JournalMethod { + if len(method.Params) != 1 { + return eSpecialMethodNone, errors.New("Journal method does not match the expected function template") } - + if (method.Params[0].ParamType != "string") || (method.Params[0].ParamPass != "in") { - return eSpecialMethodNone, errors.New ("Journal method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Journal method does not match the expected function template") } - - return eSpecialMethodJournal, nil; + + return eSpecialMethodJournal, nil } - if (method.MethodName == global.VersionMethod) { - if (len (method.Params) != 3) { - return eSpecialMethodNone, errors.New ("Version method does not match the expected function template"); + if method.MethodName == global.VersionMethod { + if len(method.Params) != 3 { + return eSpecialMethodNone, errors.New("Version method does not match the expected function template") } - - if (method.Params[0].ParamType != "uint32") || (method.Params[0].ParamPass != "out") || - (method.Params[1].ParamType != "uint32") || (method.Params[1].ParamPass != "out") || + + if (method.Params[0].ParamType != "uint32") || (method.Params[0].ParamPass != "out") || + (method.Params[1].ParamType != "uint32") || (method.Params[1].ParamPass != "out") || (method.Params[2].ParamType != "uint32") || (method.Params[2].ParamPass != "out") { - return eSpecialMethodNone, errors.New ("Version method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Version method does not match the expected function template") } - - return eSpecialMethodVersion, nil; + + return eSpecialMethodVersion, nil } - - if (method.MethodName == global.ErrorMethod) { - if (len (method.Params) != 3) { - return eSpecialMethodNone, errors.New ("Error method does not match the expected function template"); + + if method.MethodName == global.ErrorMethod { + if len(method.Params) != 3 { + return eSpecialMethodNone, errors.New("Error method does not match the expected function template") } - - if (method.Params[0].ParamType != "class") || (method.Params[0].ParamPass != "in") || - (method.Params[1].ParamType != "string") || (method.Params[1].ParamPass != "out") || + + if (method.Params[0].ParamType != "class") || (method.Params[0].ParamPass != "in") || + (method.Params[1].ParamType != "string") || (method.Params[1].ParamPass != "out") || (method.Params[2].ParamType != "bool") || (method.Params[2].ParamPass != "return") || (method.Params[0].ParamClass != global.BaseClassName) { - return eSpecialMethodNone, errors.New ("Error method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Error method does not match the expected function template") } - - return eSpecialMethodError, nil; + + return eSpecialMethodError, nil } - if len(global.PrereleaseMethod)>0 && (global.PrereleaseMethod == global.BuildinfoMethod) { - return eSpecialMethodNone, errors.New ("Prerelease method can not be the same as the buildinfo method"); + if len(global.PrereleaseMethod) > 0 && (global.PrereleaseMethod == global.BuildinfoMethod) { + return eSpecialMethodNone, errors.New("Prerelease method can not be the same as the buildinfo method") } - - if (method.MethodName == global.PrereleaseMethod) { - if (len (method.Params) != 2) { - return eSpecialMethodNone, errors.New ("Prerelease method does not match the expected function template"); + + if method.MethodName == global.PrereleaseMethod { + if len(method.Params) != 2 { + return eSpecialMethodNone, errors.New("Prerelease method does not match the expected function template") } - - if (method.Params[0].ParamType != "bool") || (method.Params[0].ParamPass != "return") || + + if (method.Params[0].ParamType != "bool") || (method.Params[0].ParamPass != "return") || (method.Params[1].ParamType != "string") || (method.Params[1].ParamPass != "out") { - return eSpecialMethodNone, errors.New ("Prerelease method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Prerelease method does not match the expected function template") } - - return eSpecialMethodPrerelease, nil; + + return eSpecialMethodPrerelease, nil } - if (method.MethodName == global.BuildinfoMethod) { - if (len (method.Params) != 2) { - return eSpecialMethodNone, errors.New ("Buildinfo method does not match the expected function template"); + if method.MethodName == global.BuildinfoMethod { + if len(method.Params) != 2 { + return eSpecialMethodNone, errors.New("Buildinfo method does not match the expected function template") } - - if (method.Params[0].ParamType != "bool") || (method.Params[0].ParamPass != "return") || + + if (method.Params[0].ParamType != "bool") || (method.Params[0].ParamPass != "return") || (method.Params[1].ParamType != "string") || (method.Params[1].ParamPass != "out") { - return eSpecialMethodNone, errors.New ("Buildinfo method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Buildinfo method does not match the expected function template") } - - return eSpecialMethodBuildinfo, nil; - } - + return eSpecialMethodBuildinfo, nil + } - return eSpecialMethodNone, nil; + return eSpecialMethodNone, nil } // GetLastErrorMessageMethod returns the xml definition of the GetLastErrorMessage-method -func GetLastErrorMessageMethod() (ComponentDefinitionMethod) { +func GetLastErrorMessageMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod source := ` @@ -1211,7 +1208,7 @@ func GetLastErrorMessageMethod() (ComponentDefinitionMethod) { } // RegisterErrorMessageMethod returns the xml definition of the RegisterErrorMessage-method -func RegisterErrorMessageMethod() (ComponentDefinitionMethod) { +func RegisterErrorMessageMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod source := ` @@ -1221,7 +1218,7 @@ func RegisterErrorMessageMethod() (ComponentDefinitionMethod) { } // ClearErrorMessageMethod returns the xml definition of the ClearErrorMessage-method -func ClearErrorMessageMethod() (ComponentDefinitionMethod) { +func ClearErrorMessageMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod source := ` ` @@ -1230,7 +1227,7 @@ func ClearErrorMessageMethod() (ComponentDefinitionMethod) { } // IncRefCountMethod returns the xml definition of the IncRefCount-method -func IncRefCountMethod() (ComponentDefinitionMethod) { +func IncRefCountMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod source := ` ` @@ -1239,7 +1236,7 @@ func IncRefCountMethod() (ComponentDefinitionMethod) { } // DecRefCountMethod returns the xml definition of the DecRefCount-method -func DecRefCountMethod() (ComponentDefinitionMethod) { +func DecRefCountMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod source := ` @@ -1249,7 +1246,7 @@ func DecRefCountMethod() (ComponentDefinitionMethod) { } // ReleaseBaseClassInterfaceMethod returns the xml definition of a method that should decrease the reference count of a BaseClass interface. -func ReleaseBaseClassInterfaceMethod(baseClassName string) (ComponentDefinitionMethod) { +func ReleaseBaseClassInterfaceMethod(baseClassName string) ComponentDefinitionMethod { var method ComponentDefinitionMethod source := ` @@ -1259,7 +1256,7 @@ func ReleaseBaseClassInterfaceMethod(baseClassName string) (ComponentDefinitionM } // AcquireBaseClassInterfaceMethod returns the xml definition of a method that should increase the reference count of a BaseClass interface. -func AcquireBaseClassInterfaceMethod(baseClassName string) (ComponentDefinitionMethod) { +func AcquireBaseClassInterfaceMethod(baseClassName string) ComponentDefinitionMethod { var method ComponentDefinitionMethod source := ` @@ -1268,13 +1265,13 @@ func AcquireBaseClassInterfaceMethod(baseClassName string) (ComponentDefinitionM return method } -func (component *ComponentDefinition) isBaseClass(class ComponentDefinitionClass) (bool) { +func (component *ComponentDefinition) isBaseClass(class ComponentDefinitionClass) bool { return class.ClassName == component.Global.BaseClassName } -func (component *ComponentDefinition) baseClass() (ComponentDefinitionClass) { +func (component *ComponentDefinition) baseClass() ComponentDefinitionClass { for i := 0; i < len(component.Classes); i++ { - if (component.isBaseClass(component.Classes[i])) { + if component.isBaseClass(component.Classes[i]) { return component.Classes[i] } } @@ -1283,134 +1280,127 @@ func (component *ComponentDefinition) baseClass() (ComponentDefinitionClass) { return out } - -func (component *ComponentDefinition) isStringOutBaseClass(class ComponentDefinitionClass) (bool) { +func (component *ComponentDefinition) isStringOutBaseClass(class ComponentDefinitionClass) bool { return class.ClassName == component.Global.StringOutBaseClassName } +func (component *ComponentDefinition) isStringOutClass(class ComponentDefinitionClass) bool { -func (component *ComponentDefinition) isStringOutClass(class ComponentDefinitionClass) (bool) { - - if (component.isStringOutBaseClass (class)) { - return true; + if component.isStringOutBaseClass(class) { + return true } - - - parentClassName := class.ParentClass; - if ((parentClassName == "") && (class.ClassName != component.Global.BaseClassName)) { - parentClassName = component.Global.BaseClassName; + + parentClassName := class.ParentClass + if (parentClassName == "") && (class.ClassName != component.Global.BaseClassName) { + parentClassName = component.Global.BaseClassName } - - if (parentClassName != "") { - + + if parentClassName != "" { + for i := 0; i < len(component.Classes); i++ { - parentClass := component.Classes[i]; - if (parentClass.ClassName == parentClassName) { - return component.isStringOutClass (parentClass); + parentClass := component.Classes[i] + if parentClass.ClassName == parentClassName { + return component.isStringOutClass(parentClass) } } - - } - - return false; -} + } + return false +} -func (method *ComponentDefinitionMethod) countOutParameters() (uint32) { +func (method *ComponentDefinitionMethod) countOutParameters() uint32 { - var outParameters uint32; - outParameters = 0; + var outParameters uint32 + outParameters = 0 for i := 0; i < len(method.Params); i++ { - if ((method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return")) { - outParameters++; + if (method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return") { + outParameters++ } } - - return outParameters; -} + return outParameters +} -func (method *ComponentDefinitionMethod) getStringOutParameters() ([]string) { +func (method *ComponentDefinitionMethod) getStringOutParameters() []string { - var outParameters []string; + var outParameters []string for i := 0; i < len(method.Params); i++ { - if (method.Params[i].ParamType == "string") { - if ((method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return")) { - outParameters = append (outParameters, method.Params[i].ParamName); - } + if method.Params[i].ParamType == "string" { + if (method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return") { + outParameters = append(outParameters, method.Params[i].ParamName) + } } } - - return outParameters; + + return outParameters } -func (method *ComponentDefinitionMethod) getArrayOutParameters() ([]string) { +func (method *ComponentDefinitionMethod) getArrayOutParameters() []string { - var outParameters []string; + var outParameters []string for i := 0; i < len(method.Params); i++ { - if ((method.Params[i].ParamType == "basicarray") || (method.Params[i].ParamType == "structarray")) { - if ((method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return")) { - outParameters = append (outParameters, method.Params[i].ParamName); - } + if (method.Params[i].ParamType == "basicarray") || (method.Params[i].ParamType == "structarray") { + if (method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return") { + outParameters = append(outParameters, method.Params[i].ParamName) + } } } - - return outParameters; -} + return outParameters +} -func (class *ComponentDefinitionClass) countMaxOutParameters() (uint32) { +func (class *ComponentDefinitionClass) countMaxOutParameters() uint32 { - var maxOutParameters uint32; - maxOutParameters = 0; + var maxOutParameters uint32 + maxOutParameters = 0 for i := 0; i < len(class.Methods); i++ { - outParameters := class.Methods[i].countOutParameters (); - if (outParameters > maxOutParameters) { - maxOutParameters = outParameters; + outParameters := class.Methods[i].countOutParameters() + if outParameters > maxOutParameters { + maxOutParameters = outParameters } } - - return maxOutParameters; + + return maxOutParameters } -func (component *ComponentDefinition) countMaxOutParameters() (uint32) { +func (component *ComponentDefinition) countMaxOutParameters() uint32 { - var maxOutParameters uint32; - maxOutParameters = 0; + var maxOutParameters uint32 + maxOutParameters = 0 classes := component.Classes for i := 0; i < len(classes); i++ { class := classes[i] - - outParameters := class.countMaxOutParameters (); - if (outParameters > maxOutParameters) { - maxOutParameters = outParameters; + + outParameters := class.countMaxOutParameters() + if outParameters > maxOutParameters { + maxOutParameters = outParameters } } - - methods := component.Global.Methods; + + methods := component.Global.Methods for i := 0; i < len(methods); i++ { - outParameters := methods[i].countOutParameters (); - if (outParameters > maxOutParameters) { - maxOutParameters = outParameters; + outParameters := methods[i].countOutParameters() + if outParameters > maxOutParameters { + maxOutParameters = outParameters } } - return maxOutParameters; + return maxOutParameters } -func (component *ComponentDefinition) classTypeIdMethod() (ComponentDefinitionMethod) { +func (component *ComponentDefinition) classTypeIdMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod baseClass := component.baseClass() for j := 0; j < len(baseClass.Methods); j++ { - if (baseClass.Methods[j].MethodName == component.Global.ClassTypeIdMethod) { + if baseClass.Methods[j].MethodName == component.Global.ClassTypeIdMethod { return baseClass.Methods[j] break } diff --git a/Source/componentdiff.go b/Source/componentdiff.go index df3c5675..c5fa14e7 100644 --- a/Source/componentdiff.go +++ b/Source/componentdiff.go @@ -33,8 +33,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package main - - import ( "encoding/xml" ) @@ -47,13 +45,14 @@ type ComponentDiffBase struct { // ComponentDiffElementRemove encodes the removal or an element type ComponentDiffElementRemove struct { ComponentDiffBase - XMLName xml.Name `xml:"removeelement"` + XMLName xml.Name `xml:"removeelement"` Removal ComponentDiffableElement `xml:"diffable"` } + // ComponentDiffElementAdd encodes the change of an element type ComponentDiffElementAdd struct { ComponentDiffBase - XMLName xml.Name `xml:"addelement"` + XMLName xml.Name `xml:"addelement"` Addition ComponentDiffableElement `xml:"diffable"` } @@ -62,39 +61,40 @@ type ComponentDiffAttributeRemove struct { ComponentDiffBase XMLName xml.Name `xml:"removeattribute"` } + // ComponentDiffAttributeAdd encodes the change of a scalar attribute type ComponentDiffAttributeAdd struct { ComponentDiffBase XMLName xml.Name `xml:"addattribute"` } + // ComponentDiffAttributeChange encodes the change of a scalar attribute type ComponentDiffAttributeChange struct { ComponentDiffBase - XMLName xml.Name `xml:"changeattribute"` - OldValue string `xml:"oldvalue"` - NewValue string `xml:"newvalue"` + XMLName xml.Name `xml:"changeattribute"` + OldValue string `xml:"oldvalue"` + NewValue string `xml:"newvalue"` } // ComponentDiff contains the difference between two component definitions type ComponentDiff struct { - XMLName xml.Name `xml:"componentdiff"` - AttributeRemovals []ComponentDiffAttributeRemove `xml:"removeattribute"` - AttributeAdditions []ComponentDiffAttributeAdd `xml:"addattribute"` - AttributeChanges []ComponentDiffAttributeChange `xml:"changeattribute"` - ElementRemovals []ComponentDiffElementRemove `xml:"removeelement"` - ElementAdditions []ComponentDiffElementAdd `xml:"addelement"` + XMLName xml.Name `xml:"componentdiff"` + AttributeRemovals []ComponentDiffAttributeRemove `xml:"removeattribute"` + AttributeAdditions []ComponentDiffAttributeAdd `xml:"addattribute"` + AttributeChanges []ComponentDiffAttributeChange `xml:"changeattribute"` + ElementRemovals []ComponentDiffElementRemove `xml:"removeelement"` + ElementAdditions []ComponentDiffElementAdd `xml:"addelement"` } // ComponentDiffableElement is an interface for any element in a componentdefinition that can be diffed type ComponentDiffableElement interface { - } func diffParam(path string, paramA ComponentDefinitionParam, paramB ComponentDefinitionParam) ([]ComponentDiffAttributeChange, error) { changes := make([]ComponentDiffAttributeChange, 0) pathA := path + "/param[@name='" + paramA.ParamName + "']" - if (paramA.ParamDescription != paramB.ParamDescription) { + if paramA.ParamDescription != paramB.ParamDescription { var change ComponentDiffAttributeChange change.Path = pathA + "/description" change.OldValue = paramA.ParamDescription @@ -102,7 +102,7 @@ func diffParam(path string, paramA ComponentDefinitionParam, paramB ComponentDef changes = append(changes, change) } - if (paramA.ParamPass != paramB.ParamPass) { + if paramA.ParamPass != paramB.ParamPass { var change ComponentDiffAttributeChange change.Path = pathA + "/pass" change.OldValue = paramA.ParamPass @@ -110,7 +110,7 @@ func diffParam(path string, paramA ComponentDefinitionParam, paramB ComponentDef changes = append(changes, change) } - if (paramA.ParamType != paramB.ParamType) { + if paramA.ParamType != paramB.ParamType { var change ComponentDiffAttributeChange change.Path = pathA + "/type" change.OldValue = paramA.ParamType @@ -118,7 +118,7 @@ func diffParam(path string, paramA ComponentDefinitionParam, paramB ComponentDef changes = append(changes, change) } - if (paramA.ParamClass != paramB.ParamClass) { + if paramA.ParamClass != paramB.ParamClass { var change ComponentDiffAttributeChange change.Path = pathA + "/class" change.OldValue = paramA.ParamClass @@ -136,29 +136,29 @@ func diffMethod(path string, methodA ComponentDefinitionMethod, methodB Componen pathA := path + "/method[@name='" + methodA.MethodName + "']" pathB := path + "/method[@name='" + methodB.MethodName + "']" - if (methodA.MethodDescription != methodB.MethodDescription) { + if methodA.MethodDescription != methodB.MethodDescription { var change ComponentDiffAttributeChange change.Path = pathA + "/description" change.OldValue = methodA.MethodDescription change.NewValue = methodB.MethodDescription changes = append(changes, change) } - + IFirstChangedParam := len(methodA.Params) - for iA, paramA := range(methodA.Params) { + for iA, paramA := range methodA.Params { BHasParamA := false if (iA < IFirstChangedParam) && (iA < len(methodB.Params)) { paramB := methodB.Params[iA] - if (paramA.ParamName == paramB.ParamName) { + if paramA.ParamName == paramB.ParamName { Pchanges, err := diffParam(pathA, paramA, paramB) - if (err != nil) { + if err != nil { return adds, removes, changes, err } changes = append(changes, Pchanges...) BHasParamA = true } } - if (!BHasParamA) { + if !BHasParamA { IFirstChangedParam = iA var remove ComponentDiffElementRemove remove.Path = pathA @@ -167,15 +167,15 @@ func diffMethod(path string, methodA ComponentDefinitionMethod, methodB Componen } } - for iB, paramB := range(methodB.Params) { + for iB, paramB := range methodB.Params { AHasParamB := false if (iB < IFirstChangedParam) && (iB < len(methodA.Params)) { paramA := methodA.Params[iB] - if (paramA.ParamName == paramB.ParamName) { + if paramA.ParamName == paramB.ParamName { AHasParamB = true } } - if (!AHasParamB) { + if !AHasParamB { var add ComponentDiffElementAdd add.Path = pathB add.Addition = paramB @@ -190,9 +190,9 @@ func diffClass(path string, classA ComponentDefinitionClass, classB ComponentDef adds := make([]ComponentDiffElementAdd, 0) removes := make([]ComponentDiffElementRemove, 0) - pathA := path + "/class[@name='"+ classA.ClassName + "']" - pathB := path + "/class[@name='"+ classB.ClassName + "']" - if (classA.ClassDescription != classB.ClassDescription) { + pathA := path + "/class[@name='" + classA.ClassName + "']" + pathB := path + "/class[@name='" + classB.ClassName + "']" + if classA.ClassDescription != classB.ClassDescription { var change ComponentDiffAttributeChange change.Path = pathA + "/description" change.OldValue = classA.ClassDescription @@ -200,7 +200,7 @@ func diffClass(path string, classA ComponentDefinitionClass, classB ComponentDef changes = append(changes, change) } - if (classA.ParentClass != classB.ParentClass) { + if classA.ParentClass != classB.ParentClass { var change ComponentDiffAttributeChange change.Path = pathA + "/parent" change.OldValue = classA.ParentClass @@ -208,22 +208,22 @@ func diffClass(path string, classA ComponentDefinitionClass, classB ComponentDef changes = append(changes, change) } - for _, methodA := range(classA.Methods) { + for _, methodA := range classA.Methods { BHasMethodA := false - for _, methodB := range(classB.Methods) { + for _, methodB := range classB.Methods { if methodA.MethodName == methodB.MethodName { BHasMethodA = true Madds, Mremoves, Mchanges, err := diffMethod(pathA, methodA, methodB) - if (err != nil) { + if err != nil { return adds, removes, changes, err } adds = append(adds, Madds...) removes = append(removes, Mremoves...) changes = append(changes, Mchanges...) - break; + break } } - if (!BHasMethodA) { + if !BHasMethodA { var remove ComponentDiffElementRemove remove.Path = path remove.Removal = methodA @@ -231,15 +231,15 @@ func diffClass(path string, classA ComponentDefinitionClass, classB ComponentDef } } - for _, methodB := range(classB.Methods) { + for _, methodB := range classB.Methods { AHasMethodB := false - for _, methodA := range(classA.Methods) { + for _, methodA := range classA.Methods { if methodA.MethodName == methodB.MethodName { AHasMethodB = true - break; + break } } - if (!AHasMethodB) { + if !AHasMethodB { var add ComponentDiffElementAdd add.Path = pathB add.Addition = methodB @@ -250,28 +250,27 @@ func diffClass(path string, classA ComponentDefinitionClass, classB ComponentDef return adds, removes, changes, nil } - -func diffClasses(path string, classesA[] ComponentDefinitionClass, classesB[] ComponentDefinitionClass) ([]ComponentDiffElementAdd, []ComponentDiffElementRemove, []ComponentDiffAttributeChange, error) { +func diffClasses(path string, classesA []ComponentDefinitionClass, classesB []ComponentDefinitionClass) ([]ComponentDiffElementAdd, []ComponentDiffElementRemove, []ComponentDiffAttributeChange, error) { changes := make([]ComponentDiffAttributeChange, 0) adds := make([]ComponentDiffElementAdd, 0) removes := make([]ComponentDiffElementRemove, 0) - for _, classA := range(classesA) { + for _, classA := range classesA { BHasClassA := false - for _, classB := range(classesB) { + for _, classB := range classesB { if classA.ClassName == classB.ClassName { BHasClassA = true Cadds, Cremoves, Cchanges, err := diffClass(path, classA, classB) - if (err != nil) { + if err != nil { return adds, removes, changes, err } adds = append(adds, Cadds...) removes = append(removes, Cremoves...) changes = append(changes, Cchanges...) - break; + break } } - if (!BHasClassA) { + if !BHasClassA { var remove ComponentDiffElementRemove remove.Path = path remove.Removal = classA @@ -279,15 +278,15 @@ func diffClasses(path string, classesA[] ComponentDefinitionClass, classesB[] Co } } - for _, classB := range(classesB) { + for _, classB := range classesB { AHasClassB := false - for _, classA := range(classesA) { + for _, classA := range classesA { if classB.ClassName == classA.ClassName { AHasClassB = true - break; + break } } - if (!AHasClassB) { + if !AHasClassB { var add ComponentDiffElementAdd add.Path = path add.Addition = classB @@ -303,25 +302,25 @@ func diffEnum(path string, enumA ComponentDefinitionEnum, enumB ComponentDefinit adds := make([]ComponentDiffElementAdd, 0) removes := make([]ComponentDiffElementRemove, 0) - pathA := path + "/enum[@name='"+ enumA.Name + "']" - pathB := path + "/enum[@name='"+ enumB.Name + "']" + pathA := path + "/enum[@name='" + enumA.Name + "']" + pathB := path + "/enum[@name='" + enumB.Name + "']" - for _, optionA := range(enumA.Options) { + for _, optionA := range enumA.Options { BHasOptionA := false - for _, optionB := range(enumB.Options) { + for _, optionB := range enumB.Options { if optionA.Name == optionB.Name { BHasOptionA = true - if (optionA.Value != optionB.Value) { + if optionA.Value != optionB.Value { var change ComponentDiffAttributeChange change.Path = pathA + "/value" change.OldValue = string(optionA.Value) change.NewValue = string(optionB.Value) changes = append(changes, change) } - break; + break } } - if (!BHasOptionA) { + if !BHasOptionA { var remove ComponentDiffElementRemove remove.Path = path remove.Removal = optionA @@ -329,15 +328,15 @@ func diffEnum(path string, enumA ComponentDefinitionEnum, enumB ComponentDefinit } } - for _, optionB := range(enumB.Options) { + for _, optionB := range enumB.Options { AHasOptionB := false - for _, optionA := range(enumA.Options) { + for _, optionA := range enumA.Options { if optionA.Name == optionB.Name { AHasOptionB = true - break; + break } } - if (!AHasOptionB) { + if !AHasOptionB { var add ComponentDiffElementAdd add.Path = pathB add.Addition = enumB @@ -348,28 +347,27 @@ func diffEnum(path string, enumA ComponentDefinitionEnum, enumB ComponentDefinit return adds, removes, changes, nil } - -func diffEnums(path string, enumsA[] ComponentDefinitionEnum, enumsB[] ComponentDefinitionEnum) ([]ComponentDiffElementAdd, []ComponentDiffElementRemove, []ComponentDiffAttributeChange, error) { +func diffEnums(path string, enumsA []ComponentDefinitionEnum, enumsB []ComponentDefinitionEnum) ([]ComponentDiffElementAdd, []ComponentDiffElementRemove, []ComponentDiffAttributeChange, error) { changes := make([]ComponentDiffAttributeChange, 0) adds := make([]ComponentDiffElementAdd, 0) removes := make([]ComponentDiffElementRemove, 0) - for _, enumA := range(enumsA) { + for _, enumA := range enumsA { BHasEnumA := false - for _, enumB := range(enumsB) { + for _, enumB := range enumsB { if enumA.Name == enumB.Name { BHasEnumA = true Eadds, Eremoves, Echanges, err := diffEnum(path, enumA, enumB) - if (err != nil) { + if err != nil { return adds, removes, changes, err } adds = append(adds, Eadds...) removes = append(removes, Eremoves...) changes = append(changes, Echanges...) - break; + break } } - if (!BHasEnumA) { + if !BHasEnumA { var remove ComponentDiffElementRemove remove.Path = path remove.Removal = enumA @@ -377,15 +375,15 @@ func diffEnums(path string, enumsA[] ComponentDefinitionEnum, enumsB[] Component } } - for _, enumB := range(enumsB) { + for _, enumB := range enumsB { AHasEnumB := false - for _, enumA := range(enumsA) { + for _, enumA := range enumsA { if enumB.Name == enumA.Name { AHasEnumB = true - break; + break } } - if (!AHasEnumB) { + if !AHasEnumB { var add ComponentDiffElementAdd add.Path = path add.Addition = enumB @@ -396,12 +394,11 @@ func diffEnums(path string, enumsA[] ComponentDefinitionEnum, enumsB[] Component return adds, removes, changes, nil } - func diffError(path string, errorA ComponentDefinitionError, errorB ComponentDefinitionError) ([]ComponentDiffAttributeChange, error) { changes := make([]ComponentDiffAttributeChange, 0) pathA := path + "/error[@name='" + errorA.Name + "']" - if (errorA.Code != errorB.Code) { + if errorA.Code != errorB.Code { var change ComponentDiffAttributeChange change.Path = pathA + "/code" change.OldValue = string(errorA.Code) @@ -409,7 +406,7 @@ func diffError(path string, errorA ComponentDefinitionError, errorB ComponentDef changes = append(changes, change) } - if (errorA.Description != errorB.Description) { + if errorA.Description != errorB.Description { var change ComponentDiffAttributeChange change.Path = pathA + "/description" change.OldValue = errorA.Description @@ -420,25 +417,25 @@ func diffError(path string, errorA ComponentDefinitionError, errorB ComponentDef return changes, nil } -func diffErrors(path string, errorsA[] ComponentDefinitionError, errorsB[] ComponentDefinitionError) ([]ComponentDiffElementAdd, []ComponentDiffElementRemove, []ComponentDiffAttributeChange, error) { +func diffErrors(path string, errorsA []ComponentDefinitionError, errorsB []ComponentDefinitionError) ([]ComponentDiffElementAdd, []ComponentDiffElementRemove, []ComponentDiffAttributeChange, error) { changes := make([]ComponentDiffAttributeChange, 0) adds := make([]ComponentDiffElementAdd, 0) removes := make([]ComponentDiffElementRemove, 0) - for _, errorA := range(errorsA) { + for _, errorA := range errorsA { BHasErrorA := false - for _, errorB := range(errorsB) { + for _, errorB := range errorsB { if errorA.Name == errorB.Name { BHasErrorA = true Echanges, err := diffError(path, errorA, errorB) - if (err != nil) { + if err != nil { return adds, removes, changes, err } changes = append(changes, Echanges...) - break; + break } } - if (!BHasErrorA) { + if !BHasErrorA { var remove ComponentDiffElementRemove remove.Path = path remove.Removal = errorA @@ -446,15 +443,15 @@ func diffErrors(path string, errorsA[] ComponentDefinitionError, errorsB[] Compo } } - for _, errorB := range(errorsB) { + for _, errorB := range errorsB { AHasErrorB := false - for _, errorA := range(errorsA) { + for _, errorA := range errorsA { if errorB.Name == errorA.Name { AHasErrorB = true - break; + break } } - if (!AHasErrorB) { + if !AHasErrorB { var add ComponentDiffElementAdd add.Path = path add.Addition = errorB @@ -465,7 +462,6 @@ func diffErrors(path string, errorsA[] ComponentDefinitionError, errorsB[] Compo return adds, removes, changes, nil } - func diffGlobal(path string, globalA ComponentDefinitionGlobal, globalB ComponentDefinitionGlobal) ([]ComponentDiffElementAdd, []ComponentDiffElementRemove, []ComponentDiffAttributeChange, error) { changes := make([]ComponentDiffAttributeChange, 0) adds := make([]ComponentDiffElementAdd, 0) @@ -473,21 +469,21 @@ func diffGlobal(path string, globalA ComponentDefinitionGlobal, globalB Componen pathA := path + "/global" pathB := path + "/global" - if (globalA.JournalMethod != globalB.JournalMethod) { + if globalA.JournalMethod != globalB.JournalMethod { var change ComponentDiffAttributeChange change.Path = pathA + "/journalmethod" change.OldValue = globalA.JournalMethod change.NewValue = globalB.JournalMethod changes = append(changes, change) } - if (globalA.ReleaseMethod != globalB.ReleaseMethod) { + if globalA.ReleaseMethod != globalB.ReleaseMethod { var change ComponentDiffAttributeChange change.Path = pathA + "/releasemethod" change.OldValue = globalA.ReleaseMethod change.NewValue = globalB.ReleaseMethod changes = append(changes, change) } - if (globalA.VersionMethod != globalB.VersionMethod) { + if globalA.VersionMethod != globalB.VersionMethod { var change ComponentDiffAttributeChange change.Path = pathA + "/versionmethod" change.OldValue = globalA.VersionMethod @@ -495,22 +491,22 @@ func diffGlobal(path string, globalA ComponentDefinitionGlobal, globalB Componen changes = append(changes, change) } - for _, methodA := range(globalA.Methods) { + for _, methodA := range globalA.Methods { BHasMethodA := false - for _, methodB := range(globalB.Methods) { + for _, methodB := range globalB.Methods { if methodA.MethodName == methodB.MethodName { BHasMethodA = true Madds, Mremoves, Mchanges, err := diffMethod(pathA, methodA, methodB) - if (err != nil) { + if err != nil { return adds, removes, changes, err } adds = append(adds, Madds...) removes = append(removes, Mremoves...) changes = append(changes, Mchanges...) - break; + break } } - if (!BHasMethodA) { + if !BHasMethodA { var remove ComponentDiffElementRemove remove.Path = path remove.Removal = methodA @@ -518,15 +514,15 @@ func diffGlobal(path string, globalA ComponentDefinitionGlobal, globalB Componen } } - for _, methodB := range(globalB.Methods) { + for _, methodB := range globalB.Methods { AHasMethodB := false - for _, methodA := range(globalA.Methods) { + for _, methodA := range globalA.Methods { if methodA.MethodName == methodB.MethodName { AHasMethodB = true - break; + break } } - if (!AHasMethodB) { + if !AHasMethodB { var add ComponentDiffElementAdd add.Path = pathB add.Addition = methodB @@ -541,7 +537,7 @@ func diffMember(path string, memberA ComponentDefinitionMember, memberB Componen changes := make([]ComponentDiffAttributeChange, 0) pathA := path + "/member[@name='" + memberA.Name + "']" - if (memberA.Type != memberB.Type) { + if memberA.Type != memberB.Type { var change ComponentDiffAttributeChange change.Path = pathA + "/type" change.OldValue = memberA.Type @@ -549,7 +545,7 @@ func diffMember(path string, memberA ComponentDefinitionMember, memberB Componen changes = append(changes, change) } - if (memberA.Class != memberB.Class) { + if memberA.Class != memberB.Class { var change ComponentDiffAttributeChange change.Path = pathA + "/class" change.OldValue = memberA.Class @@ -557,7 +553,7 @@ func diffMember(path string, memberA ComponentDefinitionMember, memberB Componen changes = append(changes, change) } - if (memberA.Columns != memberB.Columns) { + if memberA.Columns != memberB.Columns { var change ComponentDiffAttributeChange change.Path = pathA + "/columns" change.OldValue = string(memberA.Columns) @@ -565,7 +561,7 @@ func diffMember(path string, memberA ComponentDefinitionMember, memberB Componen changes = append(changes, change) } - if (memberA.Rows != memberB.Rows) { + if memberA.Rows != memberB.Rows { var change ComponentDiffAttributeChange change.Path = pathA + "/rows" change.OldValue = string(memberA.Rows) @@ -581,24 +577,24 @@ func diffStruct(path string, structA ComponentDefinitionStruct, structB Componen adds := make([]ComponentDiffElementAdd, 0) removes := make([]ComponentDiffElementRemove, 0) - pathA := path + "/structA[@name='"+ structA.Name + "']" - pathB := path + "/structB[@name='"+ structB.Name + "']" + pathA := path + "/structA[@name='" + structA.Name + "']" + pathB := path + "/structB[@name='" + structB.Name + "']" IFirstChangedMember := len(structA.Members) - for iA, memberA := range(structA.Members) { + for iA, memberA := range structA.Members { BHasMemberA := false if (iA < IFirstChangedMember) && (iA < len(structB.Members)) { memberB := structB.Members[iA] - if (memberA.Name == memberB.Name) { + if memberA.Name == memberB.Name { Pchanges, err := diffMember(pathA, memberA, memberB) - if (err != nil) { + if err != nil { return adds, removes, changes, err } changes = append(changes, Pchanges...) BHasMemberA = true } } - if (!BHasMemberA) { + if !BHasMemberA { var remove ComponentDiffElementRemove remove.Path = path remove.Removal = memberA @@ -606,15 +602,15 @@ func diffStruct(path string, structA ComponentDefinitionStruct, structB Componen } } - for iB, memberB := range(structB.Members) { + for iB, memberB := range structB.Members { AHasMemberB := false if (iB < IFirstChangedMember) && (iB < len(structA.Members)) { memberA := structA.Members[iB] - if (memberB.Name == memberA.Name) { + if memberB.Name == memberA.Name { AHasMemberB = true } } - if (!AHasMemberB) { + if !AHasMemberB { var add ComponentDiffElementAdd add.Path = pathB add.Addition = memberB @@ -625,28 +621,27 @@ func diffStruct(path string, structA ComponentDefinitionStruct, structB Componen return adds, removes, changes, nil } - -func diffStructs(path string, structsA[] ComponentDefinitionStruct, structsB[] ComponentDefinitionStruct) ([]ComponentDiffElementAdd, []ComponentDiffElementRemove, []ComponentDiffAttributeChange, error) { +func diffStructs(path string, structsA []ComponentDefinitionStruct, structsB []ComponentDefinitionStruct) ([]ComponentDiffElementAdd, []ComponentDiffElementRemove, []ComponentDiffAttributeChange, error) { changes := make([]ComponentDiffAttributeChange, 0) adds := make([]ComponentDiffElementAdd, 0) removes := make([]ComponentDiffElementRemove, 0) - for _, structA := range(structsA) { + for _, structA := range structsA { BHasStructA := false - for _, structB := range(structsB) { + for _, structB := range structsB { if structA.Name == structB.Name { BHasStructA = true EAdds, ERemoves, Echanges, err := diffStruct(path, structA, structB) - if (err != nil) { + if err != nil { return adds, removes, changes, err } adds = append(adds, EAdds...) removes = append(removes, ERemoves...) changes = append(changes, Echanges...) - break; + break } } - if (!BHasStructA) { + if !BHasStructA { var remove ComponentDiffElementRemove remove.Path = path remove.Removal = structA @@ -654,15 +649,15 @@ func diffStructs(path string, structsA[] ComponentDefinitionStruct, structsB[] C } } - for _, structB := range(structsB) { + for _, structB := range structsB { AHasStructB := false - for _, structA := range(structsA) { + for _, structA := range structsA { if structB.Name == structA.Name { AHasStructB = true - break; + break } } - if (!AHasStructB) { + if !AHasStructB { var add ComponentDiffElementAdd add.Path = path add.Addition = structB @@ -673,32 +668,31 @@ func diffStructs(path string, structsA[] ComponentDefinitionStruct, structsB[] C return adds, removes, changes, nil } - func diffComponentAttributes(path string, componentA ComponentDefinition, componentB ComponentDefinition) ([]ComponentDiffAttributeChange, error) { changes := make([]ComponentDiffAttributeChange, 0) - if (componentA.Year != componentB.Year) { + if componentA.Year != componentB.Year { var change ComponentDiffAttributeChange change.Path = path + "/year" change.OldValue = string(componentA.Year) change.NewValue = string(componentB.Year) changes = append(changes, change) } - if (componentA.NameSpace != componentB.NameSpace) { + if componentA.NameSpace != componentB.NameSpace { var change ComponentDiffAttributeChange change.Path = path + "/namespace" change.OldValue = componentA.NameSpace change.NewValue = componentB.NameSpace changes = append(changes, change) } - if (componentA.LibraryName != componentB.LibraryName) { + if componentA.LibraryName != componentB.LibraryName { var change ComponentDiffAttributeChange change.Path = path + "/libraryname" change.OldValue = componentA.LibraryName change.NewValue = componentB.LibraryName changes = append(changes, change) } - if (componentA.BaseName != componentB.BaseName) { + if componentA.BaseName != componentB.BaseName { var change ComponentDiffAttributeChange change.Path = path + "/basename" change.OldValue = componentA.BaseName @@ -715,7 +709,7 @@ func DiffComponentDefinitions(A ComponentDefinition, B ComponentDefinition) (Com path := "/component" changes, err := diffComponentAttributes(path, A, B) - if (err != nil) { + if err != nil { return diff, err } @@ -723,7 +717,7 @@ func DiffComponentDefinitions(A ComponentDefinition, B ComponentDefinition) (Com // TODO: check bindings(!?) adds, removes, changes, err := diffGlobal(path, A.Global, B.Global) - if (err != nil) { + if err != nil { return diff, err } diff.ElementAdditions = append(diff.ElementAdditions, adds...) @@ -731,23 +725,23 @@ func DiffComponentDefinitions(A ComponentDefinition, B ComponentDefinition) (Com diff.AttributeChanges = append(diff.AttributeChanges, changes...) adds, removes, changes, err = diffClasses(path, A.Classes, B.Classes) - if (err != nil) { + if err != nil { return diff, err } diff.ElementAdditions = append(diff.ElementAdditions, adds...) diff.ElementRemovals = append(diff.ElementRemovals, removes...) diff.AttributeChanges = append(diff.AttributeChanges, changes...) - + adds, removes, changes, err = diffEnums(path, A.Enums, B.Enums) - if (err != nil) { + if err != nil { return diff, err } diff.ElementAdditions = append(diff.ElementAdditions, adds...) diff.ElementRemovals = append(diff.ElementRemovals, removes...) diff.AttributeChanges = append(diff.AttributeChanges, changes...) - - adds, removes, changes, err = diffErrors(path + "/Errors", A.Errors.Errors, B.Errors.Errors) - if (err != nil) { + + adds, removes, changes, err = diffErrors(path+"/Errors", A.Errors.Errors, B.Errors.Errors) + if err != nil { return diff, err } diff.ElementAdditions = append(diff.ElementAdditions, adds...) @@ -755,7 +749,7 @@ func DiffComponentDefinitions(A ComponentDefinition, B ComponentDefinition) (Com diff.AttributeChanges = append(diff.AttributeChanges, changes...) adds, removes, changes, err = diffStructs(path, A.Structs, B.Structs) - if (err != nil) { + if err != nil { return diff, err } diff.ElementAdditions = append(diff.ElementAdditions, adds...) diff --git a/Source/languagec.go b/Source/languagec.go index 6fa76007..8b21c23d 100644 --- a/Source/languagec.go +++ b/Source/languagec.go @@ -42,17 +42,17 @@ import ( // BuildBindingC builds C-bindings of a library's API in form of automatically generated C functions func BuildBindingC(component ComponentDefinition, outputFolderBindingC string) error { - CTypesHeaderName := path.Join(outputFolderBindingC, component.BaseName + "_types.h") + CTypesHeaderName := path.Join(outputFolderBindingC, component.BaseName+"_types.h") log.Printf("Creating \"%s\"", CTypesHeaderName) err := CreateCTypesHeader(component, CTypesHeaderName) - if (err != nil) { - return err; + if err != nil { + return err } - CHeaderName := path.Join(outputFolderBindingC, component.BaseName + ".h") + CHeaderName := path.Join(outputFolderBindingC, component.BaseName+".h") log.Printf("Creating \"%s\"", CTypesHeaderName) err = CreateCAbiHeader(component, CHeaderName) - if (err != nil) { + if err != nil { return err } @@ -60,824 +60,813 @@ func BuildBindingC(component ComponentDefinition, outputFolderBindingC string) e } // CreateCTypesHeader creates a C header file for the types in component's API -func CreateCTypesHeader (component ComponentDefinition, CTypesHeaderName string) (error) { - hTypesFile, err := CreateLanguageFile(CTypesHeaderName, " "); - if (err != nil) { - return err; +func CreateCTypesHeader(component ComponentDefinition, CTypesHeaderName string) error { + hTypesFile, err := CreateLanguageFile(CTypesHeaderName, " ") + if err != nil { + return err } - hTypesFile.WriteCLicenseHeader (component, - fmt.Sprintf ("This is an autogenerated plain C Header file with basic types in\norder to allow an easy use of %s", component.LibraryName), - true); + hTypesFile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated plain C Header file with basic types in\norder to allow an easy use of %s", component.LibraryName), + true) - err = buildCCPPTypesHeader(component, hTypesFile, component.NameSpace, false, false); - return err; + err = buildCCPPTypesHeader(component, hTypesFile, component.NameSpace, false, false) + return err } - - -func buildSharedCCPPTypesHeader(component ComponentDefinition, w LanguageWriter, NameSpace string, enforce64BitPointer bool) (error) { - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Scalar types definition"); +func buildSharedCCPPTypesHeader(component ComponentDefinition, w LanguageWriter, NameSpace string, enforce64BitPointer bool) error { + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Scalar types definition") w.Writeln("**************************************************************************************************************************/") w.Writeln("") - w.Writeln("#ifdef %s_USELEGACYINTEGERTYPES", strings.ToUpper(NameSpace)); + w.Writeln("#ifdef %s_USELEGACYINTEGERTYPES", strings.ToUpper(NameSpace)) w.Writeln("") - w.Writeln("typedef unsigned char %s_uint8;", NameSpace); - w.Writeln("typedef unsigned short %s_uint16 ;", NameSpace); - w.Writeln("typedef unsigned int %s_uint32;", NameSpace); - w.Writeln("typedef unsigned long long %s_uint64;", NameSpace); - w.Writeln("typedef char %s_int8;", NameSpace); - w.Writeln("typedef short %s_int16;", NameSpace); - w.Writeln("typedef int %s_int32;", NameSpace); - w.Writeln("typedef long long %s_int64;", NameSpace); + w.Writeln("typedef unsigned char %s_uint8;", NameSpace) + w.Writeln("typedef unsigned short %s_uint16 ;", NameSpace) + w.Writeln("typedef unsigned int %s_uint32;", NameSpace) + w.Writeln("typedef unsigned long long %s_uint64;", NameSpace) + w.Writeln("typedef char %s_int8;", NameSpace) + w.Writeln("typedef short %s_int16;", NameSpace) + w.Writeln("typedef int %s_int32;", NameSpace) + w.Writeln("typedef long long %s_int64;", NameSpace) w.Writeln("") - w.Writeln("#else // %s_USELEGACYINTEGERTYPES", strings.ToUpper(NameSpace)); + w.Writeln("#else // %s_USELEGACYINTEGERTYPES", strings.ToUpper(NameSpace)) w.Writeln("") w.Writeln("#include ") w.Writeln("") - w.Writeln("typedef uint8_t %s_uint8;", NameSpace); - w.Writeln("typedef uint16_t %s_uint16;", NameSpace); - w.Writeln("typedef uint32_t %s_uint32;", NameSpace); - w.Writeln("typedef uint64_t %s_uint64;", NameSpace); - w.Writeln("typedef int8_t %s_int8;", NameSpace); - w.Writeln("typedef int16_t %s_int16;", NameSpace); - w.Writeln("typedef int32_t %s_int32;", NameSpace); - w.Writeln("typedef int64_t %s_int64 ;", NameSpace); + w.Writeln("typedef uint8_t %s_uint8;", NameSpace) + w.Writeln("typedef uint16_t %s_uint16;", NameSpace) + w.Writeln("typedef uint32_t %s_uint32;", NameSpace) + w.Writeln("typedef uint64_t %s_uint64;", NameSpace) + w.Writeln("typedef int8_t %s_int8;", NameSpace) + w.Writeln("typedef int16_t %s_int16;", NameSpace) + w.Writeln("typedef int32_t %s_int32;", NameSpace) + w.Writeln("typedef int64_t %s_int64 ;", NameSpace) w.Writeln("") - w.Writeln("#endif // %s_USELEGACYINTEGERTYPES", strings.ToUpper(NameSpace)); + w.Writeln("#endif // %s_USELEGACYINTEGERTYPES", strings.ToUpper(NameSpace)) w.Writeln("") - w.Writeln("typedef float %s_single;", NameSpace); - w.Writeln("typedef double %s_double;", NameSpace); + w.Writeln("typedef float %s_single;", NameSpace) + w.Writeln("typedef double %s_double;", NameSpace) w.Writeln("") + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" General type definitions") + w.Writeln("**************************************************************************************************************************/") - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" General type definitions"); - w.Writeln("**************************************************************************************************************************/"); - - w.Writeln(""); - w.Writeln("typedef %s_int32 %sResult;", NameSpace, NameSpace); - if (enforce64BitPointer) { - w.Writeln("typedef %s_uint64 %sHandle;", NameSpace, NameSpace); - w.Writeln("typedef %s_uint64 %s_pvoid;", NameSpace, NameSpace); + w.Writeln("") + w.Writeln("typedef %s_int32 %sResult;", NameSpace, NameSpace) + if enforce64BitPointer { + w.Writeln("typedef %s_uint64 %sHandle;", NameSpace, NameSpace) + w.Writeln("typedef %s_uint64 %s_pvoid;", NameSpace, NameSpace) } else { - w.Writeln("typedef void * %sHandle;", NameSpace); - w.Writeln("typedef void * %s_pvoid;", NameSpace); - } - - w.Writeln(""); - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Version for %s", NameSpace); - w.Writeln("**************************************************************************************************************************/"); - w.Writeln(""); - w.Writeln("#define %s_VERSION_MAJOR %d", strings.ToUpper(NameSpace), majorVersion(component.Version)); - w.Writeln("#define %s_VERSION_MINOR %d", strings.ToUpper(NameSpace), minorVersion(component.Version)); - w.Writeln("#define %s_VERSION_MICRO %d", strings.ToUpper(NameSpace), microVersion(component.Version)); - w.Writeln("#define %s_VERSION_PRERELEASEINFO \"%s\"", strings.ToUpper(NameSpace), preReleaseInfo(component.Version)); - w.Writeln("#define %s_VERSION_BUILDINFO \"%s\"", strings.ToUpper(NameSpace), buildInfo(component.Version)); - - w.Writeln(""); - - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Error constants for %s", NameSpace); - w.Writeln("**************************************************************************************************************************/"); - w.Writeln(""); - w.Writeln("#define %s_SUCCESS 0", strings.ToUpper (NameSpace)); + w.Writeln("typedef void * %sHandle;", NameSpace) + w.Writeln("typedef void * %s_pvoid;", NameSpace) + } + + w.Writeln("") + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Version for %s", NameSpace) + w.Writeln("**************************************************************************************************************************/") + w.Writeln("") + w.Writeln("#define %s_VERSION_MAJOR %d", strings.ToUpper(NameSpace), majorVersion(component.Version)) + w.Writeln("#define %s_VERSION_MINOR %d", strings.ToUpper(NameSpace), minorVersion(component.Version)) + w.Writeln("#define %s_VERSION_MICRO %d", strings.ToUpper(NameSpace), microVersion(component.Version)) + w.Writeln("#define %s_VERSION_PRERELEASEINFO \"%s\"", strings.ToUpper(NameSpace), preReleaseInfo(component.Version)) + w.Writeln("#define %s_VERSION_BUILDINFO \"%s\"", strings.ToUpper(NameSpace), buildInfo(component.Version)) + + w.Writeln("") + + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Error constants for %s", NameSpace) + w.Writeln("**************************************************************************************************************************/") + w.Writeln("") + w.Writeln("#define %s_SUCCESS 0", strings.ToUpper(NameSpace)) for i := 0; i < len(component.Errors.Errors); i++ { - errorcode := component.Errors.Errors[i]; - if (errorcode.Description != "") { - w.Writeln("#define %s_ERROR_%s %d /** %s */", strings.ToUpper (NameSpace), errorcode.Name, errorcode.Code, errorcode.Description); + errorcode := component.Errors.Errors[i] + if errorcode.Description != "" { + w.Writeln("#define %s_ERROR_%s %d /** %s */", strings.ToUpper(NameSpace), errorcode.Name, errorcode.Code, errorcode.Description) } else { - w.Writeln("#define %s_ERROR_%s %d", strings.ToUpper (NameSpace), errorcode.Name, errorcode.Code); + w.Writeln("#define %s_ERROR_%s %d", strings.ToUpper(NameSpace), errorcode.Name, errorcode.Code) } } - w.Writeln(""); + w.Writeln("") - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Error strings for %s", NameSpace); - w.Writeln("**************************************************************************************************************************/"); - w.Writeln(""); - w.Writeln("inline const char * %s_GETERRORSTRING (%sResult nErrorCode) {", strings.ToUpper (NameSpace), NameSpace); - w.Writeln(" switch (nErrorCode) {"); - w.Writeln(" case %s_SUCCESS: return \"no error\";", strings.ToUpper (NameSpace)); + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Error strings for %s", NameSpace) + w.Writeln("**************************************************************************************************************************/") + w.Writeln("") + w.Writeln("inline const char * %s_GETERRORSTRING (%sResult nErrorCode) {", strings.ToUpper(NameSpace), NameSpace) + w.Writeln(" switch (nErrorCode) {") + w.Writeln(" case %s_SUCCESS: return \"no error\";", strings.ToUpper(NameSpace)) for i := 0; i < len(component.Errors.Errors); i++ { - errorcode := component.Errors.Errors[i]; - w.Writeln(" case %s_ERROR_%s: return \"%s\";", strings.ToUpper (NameSpace), errorcode.Name, errorcode.Description); - } - w.Writeln(" default: return \"unknown error\";"); - w.Writeln(" }"); - w.Writeln("}"); - w.Writeln(""); - - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Declaration of handle classes "); - w.Writeln("**************************************************************************************************************************/"); - w.Writeln(""); - + errorcode := component.Errors.Errors[i] + w.Writeln(" case %s_ERROR_%s: return \"%s\";", strings.ToUpper(NameSpace), errorcode.Name, errorcode.Description) + } + w.Writeln(" default: return \"unknown error\";") + w.Writeln(" }") + w.Writeln("}") + w.Writeln("") + + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Declaration of handle classes ") + w.Writeln("**************************************************************************************************************************/") + w.Writeln("") + for i := 0; i < len(component.Classes); i++ { - class := component.Classes[i]; - w.Writeln("typedef %sHandle %s_%s;", NameSpace, NameSpace, class.ClassName); + class := component.Classes[i] + w.Writeln("typedef %sHandle %s_%s;", NameSpace, NameSpace, class.ClassName) } - w.Writeln(""); - + w.Writeln("") + return nil } func getCMemberLine(member ComponentDefinitionMember, NameSpace string, arraysuffix string, structName string) (string, error) { - switch (member.Type) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double", "bool", "pointer": - typeName, err := getCParameterTypeName(member.Type, NameSpace, "") - if (err != nil) { - return "", err - } - return fmt.Sprintf("%s m_%s%s;", typeName, member.Name, arraysuffix), nil - case "enum": - return fmt.Sprintf("structEnum%s%s m_%s%s;", NameSpace, member.Class, member.Name, arraysuffix), nil - default: - return "", fmt.Errorf ("it is not possible for struct %s to contain a %s member", structName, member.Type); + switch member.Type { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double", "bool", "pointer": + typeName, err := getCParameterTypeName(member.Type, NameSpace, "") + if err != nil { + return "", err + } + return fmt.Sprintf("%s m_%s%s;", typeName, member.Name, arraysuffix), nil + case "enum": + return fmt.Sprintf("structEnum%s%s m_%s%s;", NameSpace, member.Class, member.Name, arraysuffix), nil + default: + return "", fmt.Errorf("it is not possible for struct %s to contain a %s member", structName, member.Type) } } -func buildCCPPTypesHeader(component ComponentDefinition, w LanguageWriter, NameSpace string, useCPPTypes bool, enforce64BitPointer bool) (error) { - sIncludeGuard := "__"+strings.ToUpper(NameSpace)+"_TYPES_HEADER" +func buildCCPPTypesHeader(component ComponentDefinition, w LanguageWriter, NameSpace string, useCPPTypes bool, enforce64BitPointer bool) error { + sIncludeGuard := "__" + strings.ToUpper(NameSpace) + "_TYPES_HEADER" if useCPPTypes { sIncludeGuard += "_CPP" } - - w.Writeln("#ifndef %s", sIncludeGuard); - w.Writeln("#define %s", sIncludeGuard); - w.Writeln(""); - if (!useCPPTypes) { - w.Writeln("#include "); + w.Writeln("#ifndef %s", sIncludeGuard) + w.Writeln("#define %s", sIncludeGuard) + w.Writeln("") + + if !useCPPTypes { + w.Writeln("#include ") } - w.Writeln(""); + w.Writeln("") err := buildSharedCCPPTypesHeader(component, w, NameSpace, enforce64BitPointer) - if (err != nil) { + if err != nil { return err } - + if useCPPTypes { - w.Writeln("namespace %s {", NameSpace); - w.Writeln(""); - w.AddIndentationLevel(1); + w.Writeln("namespace %s {", NameSpace) + w.Writeln("") + w.AddIndentationLevel(1) } err = buildCCPPEnums(component, w, NameSpace, useCPPTypes) - if (err!=nil) { + if err != nil { return err } err = buildCCPPStructs(component, w, NameSpace, useCPPTypes) - if (err!=nil) { + if err != nil { return err } err = buildCCPPFunctionPointers(component, w, NameSpace, useCPPTypes) - if (err != nil) { + if err != nil { return err } - - if (useCPPTypes) { - w.AddIndentationLevel(-1); - w.Writeln("} // namespace %s;", NameSpace); + + if useCPPTypes { + w.AddIndentationLevel(-1) + w.Writeln("} // namespace %s;", NameSpace) w.Writeln("") w.Writeln("// define legacy C-names for enums, structs and function types") for i := 0; i < len(component.Enums); i++ { - enum := component.Enums[i]; - w.Writeln("typedef %s::e%s e%s%s;", NameSpace, enum.Name, NameSpace, enum.Name); + enum := component.Enums[i] + w.Writeln("typedef %s::e%s e%s%s;", NameSpace, enum.Name, NameSpace, enum.Name) } for i := 0; i < len(component.Structs); i++ { - structinfo := component.Structs[i]; - w.Writeln("typedef %s::s%s s%s%s;", NameSpace, structinfo.Name, NameSpace, structinfo.Name); + structinfo := component.Structs[i] + w.Writeln("typedef %s::s%s s%s%s;", NameSpace, structinfo.Name, NameSpace, structinfo.Name) } for i := 0; i < len(component.Functions); i++ { functiontype := component.Functions[i] - w.Writeln("typedef %s::%s %s%s;", NameSpace, functiontype.FunctionName, NameSpace, functiontype.FunctionName); + w.Writeln("typedef %s::%s %s%s;", NameSpace, functiontype.FunctionName, NameSpace, functiontype.FunctionName) } } - w.Writeln(""); - w.Writeln("#endif // %s", sIncludeGuard); + w.Writeln("") + w.Writeln("#endif // %s", sIncludeGuard) - return nil; + return nil } // GetCMemberDefaultValue returns the defailt value of a member in C-based-languages func GetCMemberDefaultValue(memberType string, memberClass string, NameSpace string) (string, error) { - switch (memberType) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": - return "0", nil; - case "bool": - return "false", nil; - case "single": - return "0.0f", nil; - case "double": - return "0.0", nil; - case "pointer": - return "nullptr", nil; - case "enum": - return "0", nil; - case "string": - return "", fmt.Errorf ("it is not possible for a struct to contain a string value"); - case "class", "optionalclass": - return "", fmt.Errorf ("it is not possible for a struct to contain a handle value"); - default: - return "", fmt.Errorf ("unknown member type %s", memberType); + switch memberType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": + return "0", nil + case "bool": + return "false", nil + case "single": + return "0.0f", nil + case "double": + return "0.0", nil + case "pointer": + return "nullptr", nil + case "enum": + return "0", nil + case "string": + return "", fmt.Errorf("it is not possible for a struct to contain a string value") + case "class", "optionalclass": + return "", fmt.Errorf("it is not possible for a struct to contain a handle value") + default: + return "", fmt.Errorf("unknown member type %s", memberType) } } - // CreateCAbiHeader creates a C header file for the component's API -func CreateCAbiHeader(component ComponentDefinition, CHeaderName string) (error) { - hfile, err := CreateLanguageFile(CHeaderName, " "); - if (err != nil) { - return err; - } - hfile.WriteCLicenseHeader (component, - fmt.Sprintf ("This is an autogenerated plain C Header file in order to allow an easy\n use of %s", component.LibraryName), - true); - err = buildCAbiHeader(component, hfile, component.NameSpace, component.BaseName, false); - return err; +func CreateCAbiHeader(component ComponentDefinition, CHeaderName string) error { + hfile, err := CreateLanguageFile(CHeaderName, " ") + if err != nil { + return err + } + hfile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated plain C Header file in order to allow an easy\n use of %s", component.LibraryName), + true) + err = buildCAbiHeader(component, hfile, component.NameSpace, component.BaseName, false) + return err } -func writeClassMethodsIntoCCPPHeader(component ComponentDefinition, class ComponentDefinitionClass, w LanguageWriter, NameSpace string, useCPPTypes bool) (error) { - w.Writeln(""); - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Class definition for %s", class.ClassName); - w.Writeln("**************************************************************************************************************************/"); +func writeClassMethodsIntoCCPPHeader(component ComponentDefinition, class ComponentDefinitionClass, w LanguageWriter, NameSpace string, useCPPTypes bool) error { + w.Writeln("") + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Class definition for %s", class.ClassName) + w.Writeln("**************************************************************************************************************************/") for j := 0; j < len(class.Methods); j++ { - method := class.Methods[j]; - err := WriteCCPPAbiMethod (method, w, NameSpace, class.ClassName, false, false, useCPPTypes); - if (err != nil) { - return err; + method := class.Methods[j] + err := WriteCCPPAbiMethod(method, w, NameSpace, class.ClassName, false, false, useCPPTypes) + if err != nil { + return err } } return nil } -func buildCAbiHeader(component ComponentDefinition, w LanguageWriter, NameSpace string, BaseName string, useCPPTypes bool) (error) { - sIncludeGuard := "__"+strings.ToUpper(NameSpace)+"_HEADER" - if (useCPPTypes) { +func buildCAbiHeader(component ComponentDefinition, w LanguageWriter, NameSpace string, BaseName string, useCPPTypes bool) error { + sIncludeGuard := "__" + strings.ToUpper(NameSpace) + "_HEADER" + if useCPPTypes { sIncludeGuard += "_CPP" } - w.Writeln("#ifndef %s", sIncludeGuard); - w.Writeln("#define %s", sIncludeGuard); - w.Writeln(""); - - w.Writeln("#ifdef __%s_EXPORTS", strings.ToUpper (NameSpace)); - w.Writeln("#ifdef _WIN32"); - w.Writeln("#define %s_DECLSPEC __declspec (dllexport)", strings.ToUpper (NameSpace)); - w.Writeln("#else // _WIN32"); - w.Writeln("#define %s_DECLSPEC __attribute__((visibility(\"default\")))", strings.ToUpper (NameSpace)); - w.Writeln("#endif // _WIN32"); - - w.Writeln("#else // __%s_EXPORTS", strings.ToUpper (NameSpace)); - w.Writeln("#define %s_DECLSPEC", strings.ToUpper (NameSpace)); - w.Writeln("#endif // __%s_EXPORTS", strings.ToUpper (NameSpace)); - w.Writeln(""); - - if (useCPPTypes) { - w.Writeln("#include \"%s_types.hpp\"", BaseName); + w.Writeln("#ifndef %s", sIncludeGuard) + w.Writeln("#define %s", sIncludeGuard) + w.Writeln("") + + w.Writeln("#ifdef __%s_EXPORTS", strings.ToUpper(NameSpace)) + w.Writeln("#ifdef _WIN32") + w.Writeln("#define %s_DECLSPEC __declspec (dllexport)", strings.ToUpper(NameSpace)) + w.Writeln("#else // _WIN32") + w.Writeln("#define %s_DECLSPEC __attribute__((visibility(\"default\")))", strings.ToUpper(NameSpace)) + w.Writeln("#endif // _WIN32") + + w.Writeln("#else // __%s_EXPORTS", strings.ToUpper(NameSpace)) + w.Writeln("#define %s_DECLSPEC", strings.ToUpper(NameSpace)) + w.Writeln("#endif // __%s_EXPORTS", strings.ToUpper(NameSpace)) + w.Writeln("") + + if useCPPTypes { + w.Writeln("#include \"%s_types.hpp\"", BaseName) } else { - w.Writeln("#include \"%s_types.h\"", BaseName); + w.Writeln("#include \"%s_types.h\"", BaseName) } - w.Writeln(""); - for _, subComponent := range(component.ImportedComponentDefinitions) { + w.Writeln("") + for _, subComponent := range component.ImportedComponentDefinitions { w.Writeln("#include \"%s_dynamic.hpp\"", subComponent.BaseName) } w.Writeln("") - - w.Writeln("#ifdef __cplusplus"); - w.Writeln("extern \"C\" {"); - w.Writeln("#endif"); + w.Writeln("#ifdef __cplusplus") + w.Writeln("extern \"C\" {") + w.Writeln("#endif") for i := 0; i < len(component.Classes); i++ { - class := component.Classes[i]; + class := component.Classes[i] err := writeClassMethodsIntoCCPPHeader(component, class, w, NameSpace, useCPPTypes) - if (err != nil) { - return err; + if err != nil { + return err } } - w.Writeln(""); - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Global functions"); - w.Writeln("**************************************************************************************************************************/"); - - global := component.Global; + w.Writeln("") + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Global functions") + w.Writeln("**************************************************************************************************************************/") + + global := component.Global for j := 0; j < len(global.Methods); j++ { - method := global.Methods[j]; - err := WriteCCPPAbiMethod(method, w, NameSpace, "Wrapper", true, false, useCPPTypes); - if (err != nil) { - return err; + method := global.Methods[j] + err := WriteCCPPAbiMethod(method, w, NameSpace, "Wrapper", true, false, useCPPTypes) + if err != nil { + return err } } - - w.Writeln(""); - w.Writeln("#ifdef __cplusplus"); - w.Writeln("}"); - w.Writeln("#endif"); - w.Writeln(""); - w.Writeln("#endif // %s", sIncludeGuard); - w.Writeln(""); - - return nil; -} + w.Writeln("") + w.Writeln("#ifdef __cplusplus") + w.Writeln("}") + w.Writeln("#endif") + w.Writeln("") + w.Writeln("#endif // %s", sIncludeGuard) + w.Writeln("") + + return nil +} // GetCExportName How do we name the exports in the plain C DLL -func GetCExportName (NameSpace string, ClassName string, method ComponentDefinitionMethod, isGlobal bool) (string) { - CMethodName := ""; +func GetCExportName(NameSpace string, ClassName string, method ComponentDefinitionMethod, isGlobal bool) string { + CMethodName := "" if isGlobal { CMethodName = fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), strings.ToLower(method.MethodName)) } else { CMethodName = fmt.Sprintf("%s_%s_%s", strings.ToLower(NameSpace), strings.ToLower(ClassName), strings.ToLower(method.MethodName)) } - - return CMethodName; -} + return CMethodName +} // WriteCCPPAbiMethod writes an ABI method as a C-function -func WriteCCPPAbiMethod(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string, ClassName string, isGlobal bool, writeCallbacks bool, useCPPTypes bool) (error) { - CMethodName := ""; - CCallbackName := ""; - parameters := ""; - if (isGlobal) { - CMethodName = fmt.Sprintf ("%s_%s", strings.ToLower (NameSpace), strings.ToLower (method.MethodName)); - CCallbackName = fmt.Sprintf ("P%s%sPtr", NameSpace, method.MethodName); +func WriteCCPPAbiMethod(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string, ClassName string, isGlobal bool, writeCallbacks bool, useCPPTypes bool) error { + CMethodName := "" + CCallbackName := "" + parameters := "" + if isGlobal { + CMethodName = fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), strings.ToLower(method.MethodName)) + CCallbackName = fmt.Sprintf("P%s%sPtr", NameSpace, method.MethodName) } else { - CMethodName = fmt.Sprintf ("%s_%s_%s", strings.ToLower (NameSpace), strings.ToLower (ClassName), strings.ToLower (method.MethodName)); - CCallbackName = fmt.Sprintf ("P%s%s_%sPtr", NameSpace, ClassName, method.MethodName); - parameters = fmt.Sprintf ("%s_%s p%s", NameSpace, ClassName, ClassName); + CMethodName = fmt.Sprintf("%s_%s_%s", strings.ToLower(NameSpace), strings.ToLower(ClassName), strings.ToLower(method.MethodName)) + CCallbackName = fmt.Sprintf("P%s%s_%sPtr", NameSpace, ClassName, method.MethodName) + parameters = fmt.Sprintf("%s_%s p%s", NameSpace, ClassName, ClassName) } - w.Writeln(""); - w.Writeln("/**"); - w.Writeln("* %s", method.MethodDescription); - w.Writeln("*"); - if (!isGlobal) { - w.Writeln("* @param[in] p%s - %s instance.", ClassName, ClassName); + w.Writeln("") + w.Writeln("/**") + w.Writeln("* %s", method.MethodDescription) + w.Writeln("*") + if !isGlobal { + w.Writeln("* @param[in] p%s - %s instance.", ClassName, ClassName) } - for k := 0; k < len(method.Params); k++ { - param := method.Params [k]; - cParams, err := generateCCPPParameter(param, ClassName, method.MethodName, NameSpace, useCPPTypes); - if (err != nil) { - return err; + param := method.Params[k] + cParams, err := generateCCPPParameter(param, ClassName, method.MethodName, NameSpace, useCPPTypes) + if err != nil { + return err } for _, cParam := range cParams { - w.Writeln(cParam.ParamComment); - if (parameters != "") { - parameters = parameters + ", "; + w.Writeln(cParam.ParamComment) + if parameters != "" { + parameters = parameters + ", " } - parameters = parameters + cParam.ParamType + " " + cParam.ParamName; + parameters = parameters + cParam.ParamType + " " + cParam.ParamName } } - - w.Writeln("* @return error code or 0 (success)"); - w.Writeln("*/"); - - if (writeCallbacks) { - w.Writeln("typedef %sResult (*%s) (%s);", NameSpace, CCallbackName, parameters); + + w.Writeln("* @return error code or 0 (success)") + w.Writeln("*/") + + if writeCallbacks { + w.Writeln("typedef %sResult (*%s) (%s);", NameSpace, CCallbackName, parameters) } else { - w.Writeln("%s_DECLSPEC %sResult %s(%s);", strings.ToUpper(NameSpace), NameSpace, CMethodName, parameters); + w.Writeln("%s_DECLSPEC %sResult %s(%s);", strings.ToUpper(NameSpace), NameSpace, CMethodName, parameters) } - - return nil; + + return nil } -func buildCCPPStructs(component ComponentDefinition, w LanguageWriter, NameSpace string, useCPPTypes bool) (error) { - if (len(component.Structs) == 0) { +func buildCCPPStructs(component ComponentDefinition, w LanguageWriter, NameSpace string, useCPPTypes bool) error { + if len(component.Structs) == 0 { return nil } var err error - - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Declaration of structs"); - w.Writeln("**************************************************************************************************************************/"); - w.Writeln(""); - - w.Writeln("#pragma pack (1)"); - w.Writeln(""); + + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Declaration of structs") + w.Writeln("**************************************************************************************************************************/") + w.Writeln("") + + w.Writeln("#pragma pack (1)") + w.Writeln("") for i := 0; i < len(component.Structs); i++ { - structinfo := component.Structs[i]; - if (useCPPTypes) { - w.Writeln("typedef struct s%s {", structinfo.Name); + structinfo := component.Structs[i] + if useCPPTypes { + w.Writeln("typedef struct s%s {", structinfo.Name) } else { - w.Writeln("typedef struct s%s%s {", NameSpace, structinfo.Name); + w.Writeln("typedef struct s%s%s {", NameSpace, structinfo.Name) } - + for j := 0; j < len(structinfo.Members); j++ { - member := structinfo.Members[j]; - arraysuffix := ""; - if (member.Rows > 0) { - if (member.Columns > 0) { - arraysuffix = fmt.Sprintf ("[%d][%d]", member.Columns, member.Rows) + member := structinfo.Members[j] + arraysuffix := "" + if member.Rows > 0 { + if member.Columns > 0 { + arraysuffix = fmt.Sprintf("[%d][%d]", member.Columns, member.Rows) } else { - arraysuffix = fmt.Sprintf ("[%d]",member.Rows) + arraysuffix = fmt.Sprintf("[%d]", member.Rows) } } var memberLine string - if (useCPPTypes) { - memberLine, err= getCPPMemberLine(member, NameSpace, arraysuffix, structinfo.Name, ";") + if useCPPTypes { + memberLine, err = getCPPMemberLine(member, NameSpace, arraysuffix, structinfo.Name, ";") } else { - memberLine, err= getCMemberLine(member, NameSpace, arraysuffix, structinfo.Name) + memberLine, err = getCMemberLine(member, NameSpace, arraysuffix, structinfo.Name) } - if (err!=nil) { + if err != nil { return err } w.Writeln(" %s", memberLine) } - if (useCPPTypes) { - w.Writeln("} s%s;", structinfo.Name); + if useCPPTypes { + w.Writeln("} s%s;", structinfo.Name) } else { - w.Writeln("} s%s%s;", NameSpace, structinfo.Name); + w.Writeln("} s%s%s;", NameSpace, structinfo.Name) } - w.Writeln(""); + w.Writeln("") } - w.Writeln("#pragma pack ()"); - w.Writeln(""); + w.Writeln("#pragma pack ()") + w.Writeln("") return nil } -func buildCCPPEnums(component ComponentDefinition, w LanguageWriter, NameSpace string, useCPPTypes bool) (error) { - if (len(component.Enums) == 0) { +func buildCCPPEnums(component ComponentDefinition, w LanguageWriter, NameSpace string, useCPPTypes bool) error { + if len(component.Enums) == 0 { return nil } - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Declaration of enums"); - w.Writeln("**************************************************************************************************************************/"); - w.Writeln(""); + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Declaration of enums") + w.Writeln("**************************************************************************************************************************/") + w.Writeln("") for i := 0; i < len(component.Enums); i++ { - enum := component.Enums[i]; - if (useCPPTypes) { - if (enum.Description != "") { - w.Writeln("/**"); - w.Writeln("* enum class e%s - %s", enum.Name, enum.Description); - w.Writeln("*/"); + enum := component.Enums[i] + if useCPPTypes { + if enum.Description != "" { + w.Writeln("/**") + w.Writeln("* enum class e%s - %s", enum.Name, enum.Description) + w.Writeln("*/") } - w.Writeln("enum class e%s : %s_int32 {", enum.Name, NameSpace); + w.Writeln("enum class e%s : %s_int32 {", enum.Name, NameSpace) } else { - if (enum.Description != "") { - w.Writeln("/**"); - w.Writeln("* enum e%s%s - %s", NameSpace, enum.Name, enum.Description); - w.Writeln("*/"); + if enum.Description != "" { + w.Writeln("/**") + w.Writeln("* enum e%s%s - %s", NameSpace, enum.Name, enum.Description) + w.Writeln("*/") } - w.Writeln("typedef enum e%s%s {", NameSpace, enum.Name); + w.Writeln("typedef enum e%s%s {", NameSpace, enum.Name) } - + for j := 0; j < len(enum.Options); j++ { - comma := ""; - if (j < len(enum.Options) - 1) { - comma = ","; + comma := "" + if j < len(enum.Options)-1 { + comma = "," } - option := enum.Options[j]; - if (useCPPTypes) { - if (option.Description != "") { - w.Writeln(" %s = %d%s /** %s */", option.Name, option.Value, comma, option.Description); + option := enum.Options[j] + if useCPPTypes { + if option.Description != "" { + w.Writeln(" %s = %d%s /** %s */", option.Name, option.Value, comma, option.Description) } else { - w.Writeln(" %s = %d%s", option.Name, option.Value, comma); + w.Writeln(" %s = %d%s", option.Name, option.Value, comma) } } else { - if (option.Description != "") { - w.Writeln(" e%s%s = %d%s /** %s */", enum.Name, option.Name, option.Value, comma, option.Description); + if option.Description != "" { + w.Writeln(" e%s%s = %d%s /** %s */", enum.Name, option.Name, option.Value, comma, option.Description) } else { - w.Writeln(" e%s%s = %d%s", enum.Name, option.Name, option.Value, comma); + w.Writeln(" e%s%s = %d%s", enum.Name, option.Name, option.Value, comma) } } } - if (useCPPTypes) { - w.Writeln("};"); + if useCPPTypes { + w.Writeln("};") } else { - w.Writeln("} e%s%s;", NameSpace, enum.Name); + w.Writeln("} e%s%s;", NameSpace, enum.Name) } - w.Writeln(""); + w.Writeln("") } - - if (!useCPPTypes) { - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Declaration of enum members for 4 byte struct alignment"); - w.Writeln("**************************************************************************************************************************/"); - w.Writeln(""); + + if !useCPPTypes { + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Declaration of enum members for 4 byte struct alignment") + w.Writeln("**************************************************************************************************************************/") + w.Writeln("") for i := 0; i < len(component.Enums); i++ { - enum := component.Enums[i]; - w.Writeln("typedef union {"); - w.Writeln(" e%s%s m_enum;", NameSpace, enum.Name); - w.Writeln(" int m_code;"); - w.Writeln("} structEnum%s%s;", NameSpace, enum.Name); - w.Writeln(""); + enum := component.Enums[i] + w.Writeln("typedef union {") + w.Writeln(" e%s%s m_enum;", NameSpace, enum.Name) + w.Writeln(" int m_code;") + w.Writeln("} structEnum%s%s;", NameSpace, enum.Name) + w.Writeln("") } } return nil } - -func buildCCPPFunctionPointers(component ComponentDefinition, w LanguageWriter, NameSpace string, useCPPTypes bool) (error) { +func buildCCPPFunctionPointers(component ComponentDefinition, w LanguageWriter, NameSpace string, useCPPTypes bool) error { if len(component.Functions) == 0 { return nil } - w.Writeln("/*************************************************************************************************************************"); - w.Writeln(" Declaration of function pointers "); - w.Writeln("**************************************************************************************************************************/"); + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Declaration of function pointers ") + w.Writeln("**************************************************************************************************************************/") for i := 0; i < len(component.Functions); i++ { functiontype := component.Functions[i] returnType := "void" parameters := "" - w.Writeln(""); - w.Writeln("/**"); - if (useCPPTypes) { - w.Writeln("* %s - %s", functiontype.FunctionName, functiontype.FunctionDescription ) + w.Writeln("") + w.Writeln("/**") + if useCPPTypes { + w.Writeln("* %s - %s", functiontype.FunctionName, functiontype.FunctionDescription) } else { - w.Writeln("* %s%s - %s", NameSpace, functiontype.FunctionName, functiontype.FunctionDescription ) + w.Writeln("* %s%s - %s", NameSpace, functiontype.FunctionName, functiontype.FunctionDescription) } - + w.Writeln("*") for j := 0; j < len(functiontype.Params); j++ { param := functiontype.Params[j] cParams, err := generateCCPPParameter(param, "", functiontype.FunctionName, NameSpace, useCPPTypes) - if (err != nil) { - return err; + if err != nil { + return err } for _, cParam := range cParams { - w.Writeln(cParam.ParamComment); + w.Writeln(cParam.ParamComment) - if (parameters != "") { + if parameters != "" { parameters = parameters + ", " } parameters = parameters + cParam.ParamType } } - w.Writeln("*/"); - if (useCPPTypes) { - w.Writeln("typedef %s(*%s)(%s);", returnType, functiontype.FunctionName, parameters); + w.Writeln("*/") + if useCPPTypes { + w.Writeln("typedef %s(*%s)(%s);", returnType, functiontype.FunctionName, parameters) } else { - w.Writeln("typedef %s(*%s%s)(%s);", returnType, NameSpace, functiontype.FunctionName, parameters); + w.Writeln("typedef %s(*%s%s)(%s);", returnType, NameSpace, functiontype.FunctionName, parameters) } } - w.Writeln(""); + w.Writeln("") return nil } -func getCParameterTypeName(ParamTypeName string, NameSpace string, ParamClass string)(string, error) { +func getCParameterTypeName(ParamTypeName string, NameSpace string, ParamClass string) (string, error) { paramNameSpace, paramClassName, err := decomposeParamClassName(ParamClass) - if (err != nil) { + if err != nil { return "", err } if len(paramNameSpace) == 0 { paramNameSpace = NameSpace } - - cParamTypeName := ""; - switch (ParamTypeName) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": - cParamTypeName = fmt.Sprintf ("%s_%s", paramNameSpace, ParamTypeName); - case "bool": - cParamTypeName = "bool"; - case "pointer": - cParamTypeName = fmt.Sprintf ("%s_pvoid", paramNameSpace); - case "string": - cParamTypeName = "char *"; - case "enum": - cParamTypeName = fmt.Sprintf ("e%s%s", paramNameSpace, paramClassName); - case "struct": - cParamTypeName = fmt.Sprintf ("s%s%s *", paramNameSpace, paramClassName); - case "basicarray": - basicTypeName, err := getCParameterTypeName(paramClassName, paramNameSpace, ""); - if (err != nil) { - return "", err; - } - cParamTypeName = fmt.Sprintf ("%s *", basicTypeName); - case "structarray": - cParamTypeName = fmt.Sprintf ("s%s%s *", paramNameSpace, paramClassName) - case "class", "optionalclass": - cParamTypeName = fmt.Sprintf ("%s_%s", paramNameSpace, paramClassName) - case "functiontype": - cParamTypeName = fmt.Sprintf ("%s%s", paramNameSpace, paramClassName) - default: - return "", fmt.Errorf ("invalid parameter type \"%s\" for C-parameter", ParamTypeName); + cParamTypeName := "" + switch ParamTypeName { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": + cParamTypeName = fmt.Sprintf("%s_%s", paramNameSpace, ParamTypeName) + case "bool": + cParamTypeName = "bool" + case "pointer": + cParamTypeName = fmt.Sprintf("%s_pvoid", paramNameSpace) + case "string": + cParamTypeName = "char *" + case "enum": + cParamTypeName = fmt.Sprintf("e%s%s", paramNameSpace, paramClassName) + case "struct": + cParamTypeName = fmt.Sprintf("s%s%s *", paramNameSpace, paramClassName) + case "basicarray": + basicTypeName, err := getCParameterTypeName(paramClassName, paramNameSpace, "") + if err != nil { + return "", err + } + cParamTypeName = fmt.Sprintf("%s *", basicTypeName) + case "structarray": + cParamTypeName = fmt.Sprintf("s%s%s *", paramNameSpace, paramClassName) + case "class", "optionalclass": + cParamTypeName = fmt.Sprintf("%s_%s", paramNameSpace, paramClassName) + case "functiontype": + cParamTypeName = fmt.Sprintf("%s%s", paramNameSpace, paramClassName) + default: + return "", fmt.Errorf("invalid parameter type \"%s\" for C-parameter", ParamTypeName) } - return cParamTypeName, nil; + return cParamTypeName, nil } // CParameter is a handy representation of a function parameter in C type CParameter struct { - ParamType string - ParamName string - ParamComment string + ParamType string + ParamName string + ParamComment string ParamDocumentationLine string } - func generateCCPPParameter(param ComponentDefinitionParam, className string, methodName string, NameSpace string, useCPPTypes bool) ([]CParameter, error) { - cParams := make([]CParameter,1) + cParams := make([]CParameter, 1) var cParamTypeName string var err error - if (useCPPTypes) { - cParamTypeName, err = getCPPParameterTypeName(param.ParamType, NameSpace, param.ParamClass); + if useCPPTypes { + cParamTypeName, err = getCPPParameterTypeName(param.ParamType, NameSpace, param.ParamClass) } else { - cParamTypeName, err = getCParameterTypeName(param.ParamType, NameSpace, param.ParamClass); + cParamTypeName, err = getCParameterTypeName(param.ParamType, NameSpace, param.ParamClass) } - if (err != nil) { - return nil, err; + if err != nil { + return nil, err } - switch (param.ParamPass) { + switch param.ParamPass { case "in": - switch (param.ParamType) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": - cParams[0].ParamType = cParamTypeName; - cParams[0].ParamName = "n" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": + cParams[0].ParamType = cParamTypeName + cParams[0].ParamName = "n" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - case "bool": - cParams[0].ParamType = cParamTypeName; - cParams[0].ParamName = "b" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - - case "single": - cParams[0].ParamType = cParamTypeName; - cParams[0].ParamName = "f" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + case "bool": + cParams[0].ParamType = cParamTypeName + cParams[0].ParamName = "b" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - case "double": - cParams[0].ParamType = cParamTypeName; - cParams[0].ParamName = "d" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + case "single": + cParams[0].ParamType = cParamTypeName + cParams[0].ParamName = "f" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - case "pointer": - cParams[0].ParamType = cParamTypeName; - cParams[0].ParamName = "p" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - - case "string": - cParams[0].ParamType = "const " + cParamTypeName; - cParams[0].ParamName = "p" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + case "double": + cParams[0].ParamType = cParamTypeName + cParams[0].ParamName = "d" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - case "enum": - cParams[0].ParamType = cParamTypeName; - cParams[0].ParamName = "e" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + case "pointer": + cParams[0].ParamType = cParamTypeName + cParams[0].ParamName = "p" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - case "struct": - cParams[0].ParamType = "const " + cParamTypeName; - cParams[0].ParamName = "p" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + case "string": + cParams[0].ParamType = "const " + cParamTypeName + cParams[0].ParamName = "p" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - case "basicarray", "structarray": - cParams = make([]CParameter,2) - cParams[0].ParamType = fmt.Sprintf ("%s_uint64", NameSpace); - cParams[0].ParamName = "n" + param.ParamName + "BufferSize"; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - Number of elements in buffer", cParams[0].ParamName); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + case "enum": + cParams[0].ParamType = cParamTypeName + cParams[0].ParamName = "e" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - cParams[1].ParamType = "const " + cParamTypeName; - cParams[1].ParamName = "p" + param.ParamName + "Buffer"; - cParams[1].ParamComment = fmt.Sprintf("* @param[in] %s - %s buffer of %s", cParams[1].ParamName, param.ParamClass, param.ParamDescription); - cParams[1].ParamDocumentationLine = fmt.Sprintf(":param %s: buffer of %s", cParams[0].ParamName, param.ParamDescription) + case "struct": + cParams[0].ParamType = "const " + cParamTypeName + cParams[0].ParamName = "p" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + + case "basicarray", "structarray": + cParams = make([]CParameter, 2) + cParams[0].ParamType = fmt.Sprintf("%s_uint64", NameSpace) + cParams[0].ParamName = "n" + param.ParamName + "BufferSize" + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - Number of elements in buffer", cParams[0].ParamName) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + + cParams[1].ParamType = "const " + cParamTypeName + cParams[1].ParamName = "p" + param.ParamName + "Buffer" + cParams[1].ParamComment = fmt.Sprintf("* @param[in] %s - %s buffer of %s", cParams[1].ParamName, param.ParamClass, param.ParamDescription) + cParams[1].ParamDocumentationLine = fmt.Sprintf(":param %s: buffer of %s", cParams[0].ParamName, param.ParamDescription) - case "class", "optionalclass": - cParams[0].ParamType = cParamTypeName; - cParams[0].ParamName = "p" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + case "class", "optionalclass": + cParams[0].ParamType = cParamTypeName + cParams[0].ParamName = "p" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - case "functiontype": - cParams[0].ParamType = cParamTypeName; - cParams[0].ParamName = "p" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription); - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + case "functiontype": + cParams[0].ParamType = cParamTypeName + cParams[0].ParamName = "p" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, param.ParamDescription) + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - default: - return nil, fmt.Errorf ("invalid method parameter type \"%s\" for %s.%s (%s)", param.ParamType, className, methodName, param.ParamName); + default: + return nil, fmt.Errorf("invalid method parameter type \"%s\" for %s.%s (%s)", param.ParamType, className, methodName, param.ParamName) } - + case "out", "return": - - switch (param.ParamType) { - - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double", "pointer", "enum": - cParams[0].ParamType = cParamTypeName + " *"; - cParams[0].ParamName = "p" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[out] %s - %s", cParams[0].ParamName, param.ParamDescription); - if ("out" == param.ParamPass) { - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - } else { - cParams[0].ParamDocumentationLine = fmt.Sprintf(":return: %s", param.ParamDescription) - } - case "struct": - cParams[0].ParamType = cParamTypeName; - cParams[0].ParamName = "p" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[out] %s - %s", cParams[0].ParamName, param.ParamDescription); - if ("out" == param.ParamPass) { - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - } else { - cParams[0].ParamDocumentationLine = fmt.Sprintf(":return: %s", param.ParamDescription) - } - - case "basicarray", "structarray": - cParams = make([]CParameter,3) - cParams[0].ParamType = fmt.Sprintf("const %s_uint64", NameSpace) - cParams[0].ParamName = "n" + param.ParamName + "BufferSize"; - paramComment0 := "Number of elements in buffer" - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, paramComment0); - - cParams[1].ParamType = fmt.Sprintf("%s_uint64*", NameSpace) - cParams[1].ParamName = "p" + param.ParamName + "NeededCount"; - paramComment1 := "will be filled with the count of the written elements, or needed buffer size." - cParams[1].ParamComment = fmt.Sprintf("* @param[out] %s - %s", cParams[1].ParamName, paramComment1); - - cParams[2].ParamType = cParamTypeName; - cParams[2].ParamName = "p" + param.ParamName + "Buffer"; - paramComment2 := "buffer of " + param.ParamDescription - cParams[2].ParamComment = fmt.Sprintf("* @param[out] %s - %s %s", cParams[2].ParamName, param.ParamClass, paramComment2); - - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, paramComment0) - cParams[1].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[1].ParamName, paramComment1) - cParams[2].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[2].ParamName, paramComment2) - - case "string": - cParams = make([]CParameter,3) - cParams[0].ParamType = fmt.Sprintf("const %s_uint32", NameSpace) - cParams[0].ParamName = "n" + param.ParamName + "BufferSize"; - paramComment0 := "size of the buffer (including trailing 0)" - cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, paramComment0); - - cParams[1].ParamType = fmt.Sprintf("%s_uint32*", NameSpace) - cParams[1].ParamName = "p" + param.ParamName + "NeededChars"; - paramComment1 := "will be filled with the count of the written bytes, or needed buffer size." - cParams[1].ParamComment = fmt.Sprintf("* @param[out] %s - %s", cParams[1].ParamName, paramComment1); - - cParams[2].ParamType = cParamTypeName; - cParams[2].ParamName = "p" + param.ParamName + "Buffer"; - paramComment2 := fmt.Sprintf("buffer of %s, may be NULL", param.ParamDescription) - cParams[2].ParamComment = fmt.Sprintf("* @param[out] %s - %s %s", cParams[2].ParamName, param.ParamClass, paramComment2); - - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, paramComment0) - cParams[1].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[1].ParamName, paramComment1) - cParams[2].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[2].ParamName, paramComment2) - - case "class", "optionalclass": - cParams[0].ParamType = cParamTypeName + " *"; - cParams[0].ParamName = "p" + param.ParamName; - cParams[0].ParamComment = fmt.Sprintf("* @param[out] %s - %s", cParams[0].ParamName, param.ParamDescription); - - if ("out" == param.ParamPass) { - cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) - } else { - cParams[0].ParamDocumentationLine = fmt.Sprintf(":return: %s", param.ParamDescription) - } + switch param.ParamType { + + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double", "pointer", "enum": + cParams[0].ParamType = cParamTypeName + " *" + cParams[0].ParamName = "p" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[out] %s - %s", cParams[0].ParamName, param.ParamDescription) + if "out" == param.ParamPass { + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + } else { + cParams[0].ParamDocumentationLine = fmt.Sprintf(":return: %s", param.ParamDescription) + } + + case "struct": + cParams[0].ParamType = cParamTypeName + cParams[0].ParamName = "p" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[out] %s - %s", cParams[0].ParamName, param.ParamDescription) + if "out" == param.ParamPass { + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + } else { + cParams[0].ParamDocumentationLine = fmt.Sprintf(":return: %s", param.ParamDescription) + } + + case "basicarray", "structarray": + cParams = make([]CParameter, 3) + cParams[0].ParamType = fmt.Sprintf("const %s_uint64", NameSpace) + cParams[0].ParamName = "n" + param.ParamName + "BufferSize" + paramComment0 := "Number of elements in buffer" + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, paramComment0) + + cParams[1].ParamType = fmt.Sprintf("%s_uint64*", NameSpace) + cParams[1].ParamName = "p" + param.ParamName + "NeededCount" + paramComment1 := "will be filled with the count of the written elements, or needed buffer size." + cParams[1].ParamComment = fmt.Sprintf("* @param[out] %s - %s", cParams[1].ParamName, paramComment1) + + cParams[2].ParamType = cParamTypeName + cParams[2].ParamName = "p" + param.ParamName + "Buffer" + paramComment2 := "buffer of " + param.ParamDescription + cParams[2].ParamComment = fmt.Sprintf("* @param[out] %s - %s %s", cParams[2].ParamName, param.ParamClass, paramComment2) + + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, paramComment0) + cParams[1].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[1].ParamName, paramComment1) + cParams[2].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[2].ParamName, paramComment2) - default: - return nil, fmt.Errorf ("invalid method parameter type \"%s\" for %s.%s (%s)", param.ParamType, className, methodName, param.ParamName); + case "string": + cParams = make([]CParameter, 3) + cParams[0].ParamType = fmt.Sprintf("const %s_uint32", NameSpace) + cParams[0].ParamName = "n" + param.ParamName + "BufferSize" + paramComment0 := "size of the buffer (including trailing 0)" + cParams[0].ParamComment = fmt.Sprintf("* @param[in] %s - %s", cParams[0].ParamName, paramComment0) + + cParams[1].ParamType = fmt.Sprintf("%s_uint32*", NameSpace) + cParams[1].ParamName = "p" + param.ParamName + "NeededChars" + paramComment1 := "will be filled with the count of the written bytes, or needed buffer size." + cParams[1].ParamComment = fmt.Sprintf("* @param[out] %s - %s", cParams[1].ParamName, paramComment1) + + cParams[2].ParamType = cParamTypeName + cParams[2].ParamName = "p" + param.ParamName + "Buffer" + paramComment2 := fmt.Sprintf("buffer of %s, may be NULL", param.ParamDescription) + cParams[2].ParamComment = fmt.Sprintf("* @param[out] %s - %s %s", cParams[2].ParamName, param.ParamClass, paramComment2) + + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, paramComment0) + cParams[1].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[1].ParamName, paramComment1) + cParams[2].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[2].ParamName, paramComment2) + + case "class", "optionalclass": + cParams[0].ParamType = cParamTypeName + " *" + cParams[0].ParamName = "p" + param.ParamName + cParams[0].ParamComment = fmt.Sprintf("* @param[out] %s - %s", cParams[0].ParamName, param.ParamDescription) + + if "out" == param.ParamPass { + cParams[0].ParamDocumentationLine = fmt.Sprintf(":param %s: %s", cParams[0].ParamName, param.ParamDescription) + } else { + cParams[0].ParamDocumentationLine = fmt.Sprintf(":return: %s", param.ParamDescription) + } + + default: + return nil, fmt.Errorf("invalid method parameter type \"%s\" for %s.%s (%s)", param.ParamType, className, methodName, param.ParamName) } - + default: - return nil, fmt.Errorf ("invalid method parameter passing \"%s\" for %s.%s (%s)", param.ParamPass, className, methodName, param.ParamName); + return nil, fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s (%s)", param.ParamPass, className, methodName, param.ParamName) } - return cParams, nil; + return cParams, nil } // GenerateCParameters generates an array of cParameters for a method func GenerateCParameters(method ComponentDefinitionMethod, className string, NameSpace string) ([]CParameter, error) { parameters := []CParameter{} for k := 0; k < len(method.Params); k++ { - param := method.Params [k] - - cParam, err := generateCCPPParameter(param, className, method.MethodName, NameSpace, false); + param := method.Params[k] + + cParam, err := generateCCPPParameter(param, className, method.MethodName, NameSpace, false) if err != nil { return nil, err } parameters = append(parameters, cParam...) } - return parameters, nil; + return parameters, nil } diff --git a/Source/languagecpp.go b/Source/languagecpp.go index b37a4168..7d6edadc 100644 --- a/Source/languagecpp.go +++ b/Source/languagecpp.go @@ -38,75 +38,75 @@ import ( ) // CreateCPPTypesHeader creates a CPP header file for the types in component's API -func CreateCPPTypesHeader(component ComponentDefinition, CTypesHeaderName string, enforce64BitPointer bool) (error) { - hTypesFile, err := CreateLanguageFile(CTypesHeaderName, " "); - if (err != nil) { - return err; +func CreateCPPTypesHeader(component ComponentDefinition, CTypesHeaderName string, enforce64BitPointer bool) error { + hTypesFile, err := CreateLanguageFile(CTypesHeaderName, " ") + if err != nil { + return err } - hTypesFile.WriteCLicenseHeader (component, - fmt.Sprintf ("This is an autogenerated C++-Header file with basic types in\norder to allow an easy use of %s", component.LibraryName), - true); + hTypesFile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated C++-Header file with basic types in\norder to allow an easy use of %s", component.LibraryName), + true) err = buildCCPPTypesHeader(component, hTypesFile, component.NameSpace, true, enforce64BitPointer) - return err; + return err } func getCPPMemberLine(member ComponentDefinitionMember, NameSpace string, arraysuffix string, structName string, endCharacter string) (string, error) { - switch (member.Type) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double", "bool", "pointer": - typeName, err := getCPPParameterTypeName(member.Type, NameSpace, "") - if (err != nil) { - return "", err - } - return fmt.Sprintf("%s m_%s%s%s", typeName, member.Name, arraysuffix, endCharacter), nil - case "enum": - return fmt.Sprintf("e%s m_%s%s%s", member.Class, member.Name, arraysuffix, endCharacter), nil - default: - return "", fmt.Errorf ("it is not possible for struct %s to contain a %s member", structName, member.Type); - + switch member.Type { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double", "bool", "pointer": + typeName, err := getCPPParameterTypeName(member.Type, NameSpace, "") + if err != nil { + return "", err + } + return fmt.Sprintf("%s m_%s%s%s", typeName, member.Name, arraysuffix, endCharacter), nil + case "enum": + return fmt.Sprintf("e%s m_%s%s%s", member.Class, member.Name, arraysuffix, endCharacter), nil + default: + return "", fmt.Errorf("it is not possible for struct %s to contain a %s member", structName, member.Type) + } } // CreateCPPAbiHeader creates a CPP header file for the component's API -func CreateCPPAbiHeader(component ComponentDefinition, CHeaderName string) (error) { - hfile, err := CreateLanguageFile(CHeaderName, " "); - if (err != nil) { - return err; +func CreateCPPAbiHeader(component ComponentDefinition, CHeaderName string) error { + hfile, err := CreateLanguageFile(CHeaderName, " ") + if err != nil { + return err } - hfile.WriteCLicenseHeader (component, - fmt.Sprintf ("This is an autogenerated C++-Header file in order to allow an easy\n use of %s", component.LibraryName), - true); - err = buildCAbiHeader(component, hfile, component.NameSpace, component.BaseName, true); - return err; + hfile.WriteCLicenseHeader(component, + fmt.Sprintf("This is an autogenerated C++-Header file in order to allow an easy\n use of %s", component.LibraryName), + true) + err = buildCAbiHeader(component, hfile, component.NameSpace, component.BaseName, true) + return err } -func getCPPParameterTypeName(ParamTypeName string, NameSpace string, ParamClass string)(string, error) { +func getCPPParameterTypeName(ParamTypeName string, NameSpace string, ParamClass string) (string, error) { paramNameSpace, paramClassName, err := decomposeParamClassName(ParamClass) - if (err != nil) { + if err != nil { return "", err } if len(paramNameSpace) == 0 { paramNameSpace = NameSpace } - cppParamTypeName := ""; - switch (ParamTypeName) { - case "enum": - cppParamTypeName = fmt.Sprintf ("%s::e%s", paramNameSpace, paramClassName); - case "struct": - cppParamTypeName = fmt.Sprintf ("%s::s%s *", paramNameSpace, paramClassName); - case "structarray": - cppParamTypeName = fmt.Sprintf ("%s::s%s *", paramNameSpace, paramClassName) - case "class", "optionalclass": - cppParamTypeName = fmt.Sprintf ("%s_%s", paramNameSpace, paramClassName) - case "functiontype": - cppParamTypeName = fmt.Sprintf ("%s::%s", paramNameSpace, paramClassName) - default: - cParamTypeName, err := getCParameterTypeName(ParamTypeName, paramNameSpace, paramClassName) - if (err != nil) { - return "", err - } - cppParamTypeName = cParamTypeName + cppParamTypeName := "" + switch ParamTypeName { + case "enum": + cppParamTypeName = fmt.Sprintf("%s::e%s", paramNameSpace, paramClassName) + case "struct": + cppParamTypeName = fmt.Sprintf("%s::s%s *", paramNameSpace, paramClassName) + case "structarray": + cppParamTypeName = fmt.Sprintf("%s::s%s *", paramNameSpace, paramClassName) + case "class", "optionalclass": + cppParamTypeName = fmt.Sprintf("%s_%s", paramNameSpace, paramClassName) + case "functiontype": + cppParamTypeName = fmt.Sprintf("%s::%s", paramNameSpace, paramClassName) + default: + cParamTypeName, err := getCParameterTypeName(ParamTypeName, paramNameSpace, paramClassName) + if err != nil { + return "", err + } + cppParamTypeName = cParamTypeName } - return cppParamTypeName, nil; + return cppParamTypeName, nil } diff --git a/Source/languagewriter.go b/Source/languagewriter.go index e2df7fa3..c1aa5ce1 100644 --- a/Source/languagewriter.go +++ b/Source/languagewriter.go @@ -42,10 +42,10 @@ import ( // LanguageWriter is a wrapper around a io.Writer that handles indentation type LanguageWriter struct { - Indentation int + Indentation int IndentString string - Writer io.Writer - CurrentLine string + Writer io.Writer + CurrentLine string } func max(x, y int) int { @@ -56,144 +56,142 @@ func max(x, y int) int { } // AddIndentationLevel adds number of indentation the writers output -func (writer *LanguageWriter) AddIndentationLevel (levels int) (error) { - writer.Indentation = max(writer.Indentation + levels, 0) +func (writer *LanguageWriter) AddIndentationLevel(levels int) error { + writer.Indentation = max(writer.Indentation+levels, 0) return nil } // ResetIndentationLevel adds indentation to all output -func (writer *LanguageWriter) ResetIndentationLevel () (error) { +func (writer *LanguageWriter) ResetIndentationLevel() error { writer.Indentation = 0 return nil } // Writeln formats a string and writes it to a line. Pairs of leading spaces will be replaced by the indent IndentString. -func (writer *LanguageWriter) Writeln (format string, a ...interface{}) (int, error) { +func (writer *LanguageWriter) Writeln(format string, a ...interface{}) (int, error) { - leadingSpaces := 0; + leadingSpaces := 0 for _, rune := range format { if rune == ' ' { - leadingSpaces = leadingSpaces + 1; + leadingSpaces = leadingSpaces + 1 } else { - break; + break } } - leadingIndents := leadingSpaces / 2; - - indentedFormat := strings.Repeat (writer.IndentString, leadingIndents + writer.Indentation) + format[leadingIndents * 2:]; - return fmt.Fprintf (writer.Writer, indentedFormat + "\n", a...); + leadingIndents := leadingSpaces / 2 + + indentedFormat := strings.Repeat(writer.IndentString, leadingIndents+writer.Indentation) + format[leadingIndents*2:] + return fmt.Fprintf(writer.Writer, indentedFormat+"\n", a...) } // Writelns writes multiple lines and processes indentation -func (writer *LanguageWriter) Writelns (prefix string, lines []string) (error) { +func (writer *LanguageWriter) Writelns(prefix string, lines []string) error { for idx := 0; idx < len(lines); idx++ { - _, err := writer.Writeln (prefix + lines[idx]); + _, err := writer.Writeln(prefix + lines[idx]) if err != nil { - return err; + return err } } - - return nil; + + return nil } - + // BeginLine clears the CurrentLine buffer -func (writer *LanguageWriter) BeginLine () () { - writer.CurrentLine = ""; +func (writer *LanguageWriter) BeginLine() { + writer.CurrentLine = "" } // Printf formats a string and appends it to the CurrentLine buffer -func (writer *LanguageWriter) Printf (format string, a ...interface{}) () { - writer.CurrentLine = writer.CurrentLine + fmt.Sprintf (format, a...); +func (writer *LanguageWriter) Printf(format string, a ...interface{}) { + writer.CurrentLine = writer.CurrentLine + fmt.Sprintf(format, a...) } // EndLine flushes the CurrentBuffer to the internal writer -func (writer *LanguageWriter) EndLine () (int, error) { - return writer.Writeln (writer.CurrentLine); +func (writer *LanguageWriter) EndLine() (int, error) { + return writer.Writeln(writer.CurrentLine) } - // WriteCMakeLicenseHeader writes a license header into a writer with CMake-style comments -func (writer *LanguageWriter) WriteCMakeLicenseHeader (component ComponentDefinition, abstract string, includeVersion bool) { - writeLicenseHeaderEx (writer.Writer, component, abstract, includeVersion, "#[[", "\n]]"); +func (writer *LanguageWriter) WriteCMakeLicenseHeader(component ComponentDefinition, abstract string, includeVersion bool) { + writeLicenseHeaderEx(writer.Writer, component, abstract, includeVersion, "#[[", "\n]]") } // WriteCLicenseHeader writes a license header into a writer with C-style comments -func (writer *LanguageWriter) WriteCLicenseHeader (component ComponentDefinition, abstract string, includeVersion bool) { - writeLicenseHeaderEx (writer.Writer, component, abstract, includeVersion, "/*", "*/"); +func (writer *LanguageWriter) WriteCLicenseHeader(component ComponentDefinition, abstract string, includeVersion bool) { + writeLicenseHeaderEx(writer.Writer, component, abstract, includeVersion, "/*", "*/") } // WritePascalLicenseHeader writes a license header into a writer Pascal-style comments -func (writer *LanguageWriter) WritePascalLicenseHeader (component ComponentDefinition, abstract string, includeVersion bool) { - writeLicenseHeaderEx (writer.Writer, component, abstract, includeVersion, "(*", "*)"); +func (writer *LanguageWriter) WritePascalLicenseHeader(component ComponentDefinition, abstract string, includeVersion bool) { + writeLicenseHeaderEx(writer.Writer, component, abstract, includeVersion, "(*", "*)") } // WritePythonLicenseHeader writes a license header into a writer Python-style comments -func (writer *LanguageWriter) WritePythonLicenseHeader (component ComponentDefinition, abstract string, includeVersion bool) { - writeLicenseHeaderEx (writer.Writer, component, abstract, includeVersion, "'''", "'''"); +func (writer *LanguageWriter) WritePythonLicenseHeader(component ComponentDefinition, abstract string, includeVersion bool) { + writeLicenseHeaderEx(writer.Writer, component, abstract, includeVersion, "'''", "'''") } // WriteJavaLicenseHeader writes a license header into a writer Java-style comments -func (writer *LanguageWriter) WriteJavaLicenseHeader (component ComponentDefinition, abstract string, includeVersion bool) { - writeLicenseHeaderEx (writer.Writer, component, abstract, includeVersion, "/*", "*/"); +func (writer *LanguageWriter) WriteJavaLicenseHeader(component ComponentDefinition, abstract string, includeVersion bool) { + writeLicenseHeaderEx(writer.Writer, component, abstract, includeVersion, "/*", "*/") } // WritePlainLicenseHeader writes a license header into a writer without comments -func (writer *LanguageWriter) WritePlainLicenseHeader (component ComponentDefinition, abstract string, includeVersion bool) { - writeLicenseHeaderEx (writer.Writer, component, abstract, includeVersion, "", ""); +func (writer *LanguageWriter) WritePlainLicenseHeader(component ComponentDefinition, abstract string, includeVersion bool) { + writeLicenseHeaderEx(writer.Writer, component, abstract, includeVersion, "", "") } // WriteLicenseHeader writes a license header into a writer with C-style comments -func WriteLicenseHeader (w io.Writer, component ComponentDefinition, abstract string, includeVersion bool) { - writeLicenseHeaderEx (w, component, abstract, includeVersion, "/*", "*/"); +func WriteLicenseHeader(w io.Writer, component ComponentDefinition, abstract string, includeVersion bool) { + writeLicenseHeaderEx(w, component, abstract, includeVersion, "/*", "*/") } // writeLicenseHeaderEx writes a license header into a writer. -func writeLicenseHeaderEx (w io.Writer, component ComponentDefinition, abstract string, includeVersion bool, CommandStart string, CommandEnd string) { - ACTVersion := component.ACTVersion; - version := component.Version; - copyright := component.Copyright; - year := component.Year; - - if (len(CommandStart) > 0) { - fmt.Fprintf (w, "%s++\n", CommandStart); - fmt.Fprintf (w, "\n"); +func writeLicenseHeaderEx(w io.Writer, component ComponentDefinition, abstract string, includeVersion bool, CommandStart string, CommandEnd string) { + ACTVersion := component.ACTVersion + version := component.Version + copyright := component.Copyright + year := component.Year + + if len(CommandStart) > 0 { + fmt.Fprintf(w, "%s++\n", CommandStart) + fmt.Fprintf(w, "\n") } - fmt.Fprintf (w, "Copyright (C) %d %s\n", year, copyright); - fmt.Fprintf (w, "\n"); + fmt.Fprintf(w, "Copyright (C) %d %s\n", year, copyright) + fmt.Fprintf(w, "\n") for i := 0; i < len(component.License.Lines); i++ { - line := component.License.Lines[i]; - fmt.Fprintf (w, "%s\n", line.Value); + line := component.License.Lines[i] + fmt.Fprintf(w, "%s\n", line.Value) } - fmt.Fprintf (w, "\n"); - if (includeVersion) { - fmt.Fprintf (w, "This file has been generated by the Automatic Component Toolkit (ACT) version %s.\n", ACTVersion) - fmt.Fprintf (w, "\n"); + fmt.Fprintf(w, "\n") + if includeVersion { + fmt.Fprintf(w, "This file has been generated by the Automatic Component Toolkit (ACT) version %s.\n", ACTVersion) + fmt.Fprintf(w, "\n") } - if (len(abstract) > 0 ) { - fmt.Fprintf (w, "Abstract: %s\n", abstract); - if (includeVersion) { - fmt.Fprintf (w, "\nInterface version: %d.%d.%d\n", majorVersion(version), minorVersion(version), microVersion(version)) + if len(abstract) > 0 { + fmt.Fprintf(w, "Abstract: %s\n", abstract) + if includeVersion { + fmt.Fprintf(w, "\nInterface version: %d.%d.%d\n", majorVersion(version), minorVersion(version), microVersion(version)) } } - fmt.Fprintf (w, "\n"); - if (len(CommandEnd) > 0) { - fmt.Fprintf (w, "%s\n", CommandEnd); - fmt.Fprintf (w, "\n"); + fmt.Fprintf(w, "\n") + if len(CommandEnd) > 0 { + fmt.Fprintf(w, "%s\n", CommandEnd) + fmt.Fprintf(w, "\n") } } - // CreateLanguageFile creates a LanguageWriter and sets its indent string -func CreateLanguageFile (fileName string, indentString string) (LanguageWriter, error) { - var result LanguageWriter; - var err error; - +func CreateLanguageFile(fileName string, indentString string) (LanguageWriter, error) { + var result LanguageWriter + var err error + result.IndentString = indentString result.Indentation = 0 result.Writer, err = os.Create(fileName) if err != nil { - return result, err; + return result, err } - - return result, nil; + + return result, nil } diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..f2a17a7c --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module Source + +go 1.20