From bbfcebe10626f08837424fb2a35f29445b7936bd Mon Sep 17 00:00:00 2001 From: Ed Date: Mon, 4 Sep 2023 11:23:51 +0100 Subject: [PATCH 1/8] format go files --- Source/actutils.go | 8 +- Source/automaticcomponenttoolkit.go | 238 +++-- Source/buildbindingccpp.go | 293 +++--- Source/buildbindingccppdocumentation.go | 127 ++- Source/buildbindingcsharp.go | 14 +- Source/buildbindinggo.go | 2 +- Source/buildbindingjava.go | 346 ++++--- Source/buildbindingnode.go | 1 - Source/buildbindingpascal.go | 8 +- Source/buildbindingpython.go | 882 +++++++++--------- Source/buildimplementationpascal.go | 20 +- Source/componentdiff.go | 268 +++--- Source/languagec.go | 1107 +++++++++++------------ Source/languagecpp.go | 100 +- Source/languagewriter.go | 146 ++- 15 files changed, 1756 insertions(+), 1804 deletions(-) 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 8dc94fbb..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,7 +548,7 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin { log.Printf("Implementation in language \"%s\" is not yet supported.", implementation.Language) } - + case "JS": { @@ -560,61 +557,59 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin outputFolderImplementationJSStub := outputFolderImplementations + "/JS/Stub" outputFolderImplementationJSDocumentation := outputFolderImplementations + "/JS/Documentation" - if (!suppressStub) { - if (stubDirectoryOverride != "") { - outputFolderImplementationJSStub = stubDirectoryOverride; + if !suppressStub { + if stubDirectoryOverride != "" { + outputFolderImplementationJSStub = stubDirectoryOverride } - + err = os.MkdirAll(outputFolderImplementationJSStub, os.ModePerm) if err != nil { return err } } - - if (!suppressInterfaces) { - if (interfacesDirectoryOverride != "") { - outputFolderImplementationJS = interfacesDirectoryOverride; + 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, + component, + output, + implementation, ) if err != nil { return err - } - } - + } + } default: log.Fatal("Unknown export") @@ -624,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]") @@ -674,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 { @@ -794,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 1c1fb1b5..21de07b6 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 {")) @@ -843,7 +839,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) @@ -899,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) } @@ -967,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") @@ -978,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") @@ -1001,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") @@ -1050,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") @@ -1111,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 @@ -1151,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) @@ -1210,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) } @@ -1289,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();") @@ -1299,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("") @@ -1414,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 @@ -1425,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)&" @@ -1468,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(" {") @@ -1492,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" } @@ -1508,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("") @@ -1554,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("") @@ -1580,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) @@ -1611,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 } @@ -1622,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)) @@ -1639,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) @@ -1652,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) @@ -1668,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 } @@ -1748,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, @@ -1782,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 { @@ -1798,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 @@ -1810,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 { @@ -1822,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" } @@ -1848,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 += ", " } @@ -1856,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" } @@ -1891,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 = "*" @@ -1899,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("}")) @@ -1915,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(" ") @@ -1951,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("") @@ -1977,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));") @@ -2036,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) @@ -2047,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) @@ -2074,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 @@ -2101,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("") @@ -2114,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") } @@ -2133,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 @@ -2145,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 @@ -2176,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 @@ -2207,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 } @@ -2221,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)) @@ -2238,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) @@ -2260,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 } @@ -2277,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("") @@ -2296,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;") @@ -2344,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) @@ -2354,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)") @@ -2364,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 @@ -2378,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) @@ -2417,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);") @@ -2433,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;") @@ -2444,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);") @@ -2455,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;") @@ -2495,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) @@ -2506,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/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/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 } From c4de763c93ef38d30655ff9923d9f7c8b40f0f70 Mon Sep 17 00:00:00 2001 From: Ed Date: Thu, 20 Jul 2023 19:26:20 +0100 Subject: [PATCH 2/8] case stuff --- Source/buildimplementationjs.go | 3 +++ Source/buildimplementationts.go | 28 ++++++++++++++++------------ copy.sh | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 12 deletions(-) create mode 100755 copy.sh diff --git a/Source/buildimplementationjs.go b/Source/buildimplementationjs.go index ed980d85..06aa9026 100644 --- a/Source/buildimplementationjs.go +++ b/Source/buildimplementationjs.go @@ -477,11 +477,14 @@ func buildJSInjectionClass(component ComponentDefinition, subComponent Component } 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("") diff --git a/Source/buildimplementationts.go b/Source/buildimplementationts.go index 4dfb7810..239076e0 100644 --- a/Source/buildimplementationts.go +++ b/Source/buildimplementationts.go @@ -57,7 +57,7 @@ func BuildImplementationTS( log.Printf("Creating TypeScript Implementation") options := TypeScriptOptions{ - Camelize: false, + Camelize: true, JsArrays: false, LineLength: 80, } @@ -106,11 +106,11 @@ func writeTypescriptEnum( writer LanguageWriter, options TypeScriptOptions, ) error { - writer.Writeln("const enum %s {", getId(enum.Name, options)) + writer.Writeln("const enum %s {", getTypeId(enum.Name, options)) writer.Indentation++ for _, option := range enum.Options { writeCommentEnumOption(option, writer, options) - identifier := getId(option.Name, options) + identifier := getTypeId(option.Name, options) value := option.Value writer.Writeln("%s = %d,", identifier, value) } @@ -140,7 +140,7 @@ func writeTypescriptInterface( options TypeScriptOptions, ) error { writeCommentClass(class, writer, options) - identifier := getId(class.ClassName, options) + identifier := getTypeId(class.ClassName, options) extends := "" if class.ParentClass != "" { extends = "extends " + class.ParentClass + " " @@ -178,18 +178,18 @@ func writeTypescriptMethod( writer.Writeln("") writeCommentMethod(class, method, writer, options) writer.BeginLine() - writer.Printf("%s: (", getId(method.MethodName, options)) + writer.Printf("%s: (", getName(method.MethodName, options)) for i, param := range inParams { if param.ParamOptional == "true" { writer.Printf( "%s?: %s", - getId(param.ParamName, options), + getName(param.ParamName, options), getType(param, options), ) } else { writer.Printf( "%s: %s", - getId(param.ParamName, options), + getName(param.ParamName, options), getType(param, options), ) } @@ -204,7 +204,7 @@ func writeTypescriptMethod( for i, param := range outParams { writer.Printf( "%s: %s", - getId(param.ParamName, options), + getName(param.ParamName, options), getType(param, options), ) if i+1 < len(outParams) { @@ -258,7 +258,7 @@ func writeTypescriptProperty( writer.Writeln( "%s%s: %s;", readOnly, - getId(getter.PropertyGet, options), + getName(getter.PropertyGet, options), getType(returnParams[0], options), ) return nil @@ -287,7 +287,11 @@ func filterOptional(params []ComponentDefinitionParam) []ComponentDefinitionPara return result } -func getId(identifier string, options TypeScriptOptions) string { +func getTypeId(identifier string, options TypeScriptOptions) string { + return identifier +} + +func getName(identifier string, options TypeScriptOptions) string { if options.Camelize { return camelize(identifier) } @@ -407,7 +411,7 @@ func writeCommentInParams( ) { for _, param := range params { prefix := " * @param {" + getType(param, options) + "} " + - getId(param.ParamName, options) + " " + getName(param.ParamName, options) + " " lines := getCommentLines(prefix, param.ParamDescription, writer, options) if len(lines) > 0 { writer.Writeln(prefix + lines[0]) @@ -427,7 +431,7 @@ func writeCommentOutParams( ) { for _, param := range params { prefix := " * @returns {" + getType(param, options) + "} " - prefix2 := prefix + getId(param.ParamName, options) + " " + prefix2 := prefix + getName(param.ParamName, options) + " " lines := getCommentLines(prefix2, param.ParamDescription, writer, options) if len(lines) > 0 { writer.Writeln(prefix2 + lines[0]) diff --git a/copy.sh b/copy.sh new file mode 100755 index 00000000..bd289cb0 --- /dev/null +++ b/copy.sh @@ -0,0 +1,32 @@ + +#!/bin/bash + +# Source and destination directories +source_dir="." +dest_dir="../FusionAutomationService/SandboxAddIn/ACT" + +# Source file name +source_file="act.darwin" + +# Destination file name (with modified name) +dest_file="act" + +# Copy the file to the destination directory +cp "${source_dir}/${source_file}" "${dest_dir}/${dest_file}" + +# Modify the file permissions to make it executable +chmod +x "${dest_dir}/${dest_file}" + +# Source file name +source_file="act.win64.exe" + +# Destination file name (with modified name) +dest_file="act.exe" + +# Copy the file to the destination directory +cp "${source_dir}/${source_file}" "${dest_dir}/${dest_file}" + +# Modify the file permissions to make it executable +chmod +x "${dest_dir}/${dest_file}" + +echo "File copied and modified successfully." From ea9be9ad5455e0be32220dce59f9e38dabefb8fd Mon Sep 17 00:00:00 2001 From: Ed Date: Fri, 21 Jul 2023 12:12:35 +0100 Subject: [PATCH 3/8] remove copy script --- copy.sh | 32 -------------------------------- 1 file changed, 32 deletions(-) delete mode 100755 copy.sh diff --git a/copy.sh b/copy.sh deleted file mode 100755 index bd289cb0..00000000 --- a/copy.sh +++ /dev/null @@ -1,32 +0,0 @@ - -#!/bin/bash - -# Source and destination directories -source_dir="." -dest_dir="../FusionAutomationService/SandboxAddIn/ACT" - -# Source file name -source_file="act.darwin" - -# Destination file name (with modified name) -dest_file="act" - -# Copy the file to the destination directory -cp "${source_dir}/${source_file}" "${dest_dir}/${dest_file}" - -# Modify the file permissions to make it executable -chmod +x "${dest_dir}/${dest_file}" - -# Source file name -source_file="act.win64.exe" - -# Destination file name (with modified name) -dest_file="act.exe" - -# Copy the file to the destination directory -cp "${source_dir}/${source_file}" "${dest_dir}/${dest_file}" - -# Modify the file permissions to make it executable -chmod +x "${dest_dir}/${dest_file}" - -echo "File copied and modified successfully." From 236d6fb720855bb51ddb52f7326bfaf9daf948eb Mon Sep 17 00:00:00 2001 From: Ed Date: Fri, 21 Jul 2023 12:04:31 +0100 Subject: [PATCH 4/8] better methods --- Source/buildimplementationts.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/buildimplementationts.go b/Source/buildimplementationts.go index 239076e0..5762fb9b 100644 --- a/Source/buildimplementationts.go +++ b/Source/buildimplementationts.go @@ -178,7 +178,7 @@ func writeTypescriptMethod( writer.Writeln("") writeCommentMethod(class, method, writer, options) writer.BeginLine() - writer.Printf("%s: (", getName(method.MethodName, options)) + writer.Printf("%s(", getName(method.MethodName, options)) for i, param := range inParams { if param.ParamOptional == "true" { writer.Printf( @@ -197,7 +197,7 @@ func writeTypescriptMethod( writer.Printf(", ") } } - writer.Printf(") => ") + writer.Printf("): ") if len(outParams) > 0 { writer.Printf("[") From fd282377b46827ba4f0f73133b2b622e9fe6468b Mon Sep 17 00:00:00 2001 From: Ed Date: Sat, 5 Aug 2023 11:57:21 +0100 Subject: [PATCH 5/8] fix camel case --- Source/buildimplementationts.go | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/Source/buildimplementationts.go b/Source/buildimplementationts.go index 5762fb9b..dd18a2c0 100644 --- a/Source/buildimplementationts.go +++ b/Source/buildimplementationts.go @@ -37,8 +37,9 @@ import ( "errors" "log" "path" + "regexp" "strings" - "unicode" + "unicode/utf8" ) type TypeScriptOptions struct { @@ -331,13 +332,24 @@ func getTypeString( return paramType } -func camelize(identifier string) string { - if len(identifier) == 0 { - return identifier +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)):] } - result := []rune(identifier) - result[0] = unicode.ToLower(result[0]) - return string(result) + + return str } func writeCommentEnumOption( From 4c1b5282b80f9b5ff483ad07a9f7cdd2c60113de Mon Sep 17 00:00:00 2001 From: Ed Date: Mon, 4 Sep 2023 11:14:14 +0100 Subject: [PATCH 6/8] nullable --- Source/buildbindingccpp.go | 10 +++++++--- Source/buildimplementationjs.go | 2 +- Source/buildimplementationts.go | 8 ++++++-- Source/componentdefinition.go | 1 + 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/Source/buildbindingccpp.go b/Source/buildbindingccpp.go index 21de07b6..13f4c3d3 100644 --- a/Source/buildbindingccpp.go +++ b/Source/buildbindingccpp.go @@ -827,9 +827,13 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N returnCodeLines = append(returnCodeLines, fmt.Sprintf(" return nullptr;")) returnCodeLines = append(returnCodeLines, fmt.Sprintf("}")) } else { - 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("}")) + if param.ParamNullable != "true" { + 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("}")) + } else { + returnCodeLines = append(returnCodeLines, fmt.Sprintf("if (!h%s) return nullptr;", param.ParamName)) + } returnCodeLines = append(returnCodeLines, fmt.Sprintf("return std::shared_ptr<%s>(dynamic_cast<%s*>(%s->polymorphicFactory(h%s)));", CPPClass, CPPClass, makeSharedParameter, param.ParamName)) } diff --git a/Source/buildimplementationjs.go b/Source/buildimplementationjs.go index 06aa9026..a3d4798d 100644 --- a/Source/buildimplementationjs.go +++ b/Source/buildimplementationjs.go @@ -767,7 +767,7 @@ func v8TypeString(paramType string) string { func generateReturnValue(param ComponentDefinitionParam, subComponent ComponentDefinition) string { returnValue := "" if param.ParamType == "class" { - returnValue = fmt.Sprintf("createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s()))", param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + returnValue = fmt.Sprintf("param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local()", param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) // Very bad } else if param.ParamType == "optionalclass" { returnValue = fmt.Sprintf("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 == "enum" { diff --git a/Source/buildimplementationts.go b/Source/buildimplementationts.go index dd18a2c0..d33b4744 100644 --- a/Source/buildimplementationts.go +++ b/Source/buildimplementationts.go @@ -303,21 +303,25 @@ func getType( param ComponentDefinitionParam, options TypeScriptOptions, ) string { - return getTypeString(param.ParamType, param.ParamClass, options) + return getTypeString(param.ParamType, param.ParamClass, param.ParamNullable, options) } func getTypeString( paramType string, paramClass string, + paramNullable string, options TypeScriptOptions, ) string { if paramType == "class" || paramType == "enum" { if options.JsArrays && strings.HasSuffix(paramClass, "Vector") { return strings.TrimSuffix(paramClass, "Vector") + "[]" } + if paramNullable == "true" { + return paramClass + "|undefined" + } return paramClass } else if paramType == "basicarray" { - return getTypeString(paramClass, "", options) + "[]" + return getTypeString(paramClass, "", "false", options) + "[]" } else if paramType == "double" || paramType == "int16" || paramType == "int32" || diff --git a/Source/componentdefinition.go b/Source/componentdefinition.go index 38b21d2a..cd6e6de7 100644 --- a/Source/componentdefinition.go +++ b/Source/componentdefinition.go @@ -73,6 +73,7 @@ type ComponentDefinitionParam struct { ParamDefaultValue string `xml:"defaultvalue,attr"` ParamOptional string `xml:"optional,attr"` ParamDescription string `xml:"description,attr"` + ParamNullable string `xml:"nullable,attr"` } // ComponentDefinitionMethod definition of a method provided by the component's API From f8e1e6b1abf58dc78608f521b6b863fd49f5420c Mon Sep 17 00:00:00 2001 From: Ed Date: Wed, 6 Sep 2023 23:55:35 +0100 Subject: [PATCH 7/8] optionalclass --- Source/buildbindingccpp.go | 12 ++++-------- Source/buildimplementationjs.go | 23 ++++++++++++++--------- Source/buildimplementationts.go | 11 +++++------ Source/componentdefinition.go | 1 - 4 files changed, 23 insertions(+), 24 deletions(-) diff --git a/Source/buildbindingccpp.go b/Source/buildbindingccpp.go index 13f4c3d3..70be8194 100644 --- a/Source/buildbindingccpp.go +++ b/Source/buildbindingccpp.go @@ -827,15 +827,11 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N returnCodeLines = append(returnCodeLines, fmt.Sprintf(" return nullptr;")) returnCodeLines = append(returnCodeLines, fmt.Sprintf("}")) } else { - if param.ParamNullable != "true" { - 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("}")) - } else { - returnCodeLines = append(returnCodeLines, fmt.Sprintf("if (!h%s) return nullptr;", 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("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)) case "basicarray": requiresInitCall = true diff --git a/Source/buildimplementationjs.go b/Source/buildimplementationjs.go index a3d4798d..8b4a8e6c 100644 --- a/Source/buildimplementationjs.go +++ b/Source/buildimplementationjs.go @@ -620,8 +620,8 @@ func buildJSInjectionClass(component ComponentDefinition, subComponent Component param := method.Params[k] if param.ParamPass == "return" { if method.PropertySet == "" { - returnValueArg := generateReturnValue(param, subComponent) - cppw.Writeln("setReturnValue(isolate, args, %s);", returnValueArg) + writeReturnValue(cppw, param, subComponent) + cppw.Writeln("setReturnValue(isolate, args, retVal);") } } } @@ -764,18 +764,23 @@ func v8TypeString(paramType string) string { return v8type } -func generateReturnValue(param ComponentDefinitionParam, subComponent ComponentDefinition) string { - returnValue := "" +func writeReturnValue(writer LanguageWriter, param ComponentDefinitionParam, subComponent ComponentDefinition) { if param.ParamType == "class" { - returnValue = fmt.Sprintf("param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local()", param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) // Very bad + 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" { - returnValue = fmt.Sprintf("param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local()", param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + 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" { - returnValue = "(uint32_t) param" + param.ParamName + writer.Writeln("auto retVal = (uint32_t) param%s;", param.ParamName) } else { - returnValue = "param" + param.ParamName + writer.Writeln("auto retVal = param%s;", param.ParamName) } - return returnValue } func cppParamType( diff --git a/Source/buildimplementationts.go b/Source/buildimplementationts.go index d33b4744..f5ce2786 100644 --- a/Source/buildimplementationts.go +++ b/Source/buildimplementationts.go @@ -303,25 +303,24 @@ func getType( param ComponentDefinitionParam, options TypeScriptOptions, ) string { - return getTypeString(param.ParamType, param.ParamClass, param.ParamNullable, options) + return getTypeString(param.ParamType, param.ParamClass, options) } func getTypeString( paramType string, paramClass string, - paramNullable string, options TypeScriptOptions, ) string { - if paramType == "class" || paramType == "enum" { + if paramType == "class" || paramType == "optionalclass" || paramType == "enum" { if options.JsArrays && strings.HasSuffix(paramClass, "Vector") { return strings.TrimSuffix(paramClass, "Vector") + "[]" } - if paramNullable == "true" { - return paramClass + "|undefined" + if paramType == "optionalclass" { + return paramClass + "|null" } return paramClass } else if paramType == "basicarray" { - return getTypeString(paramClass, "", "false", options) + "[]" + return getTypeString(paramClass, "", options) + "[]" } else if paramType == "double" || paramType == "int16" || paramType == "int32" || diff --git a/Source/componentdefinition.go b/Source/componentdefinition.go index cd6e6de7..38b21d2a 100644 --- a/Source/componentdefinition.go +++ b/Source/componentdefinition.go @@ -73,7 +73,6 @@ type ComponentDefinitionParam struct { ParamDefaultValue string `xml:"defaultvalue,attr"` ParamOptional string `xml:"optional,attr"` ParamDescription string `xml:"description,attr"` - ParamNullable string `xml:"nullable,attr"` } // ComponentDefinitionMethod definition of a method provided by the component's API From 67c2744a456a8fb343be6b6af94a206c7128e53d Mon Sep 17 00:00:00 2001 From: Ed Date: Wed, 13 Sep 2023 12:58:20 +0100 Subject: [PATCH 8/8] improve error string --- Source/buildbindingccpp.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/buildbindingccpp.go b/Source/buildbindingccpp.go index 70be8194..7a8d6ab1 100644 --- a/Source/buildbindingccpp.go +++ b/Source/buildbindingccpp.go @@ -1321,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("};")