From 76a111d1d7383c1dcbf6e6961118469625eff617 Mon Sep 17 00:00:00 2001 From: Ed <edwin.kilday@autodesk.com> Date: Thu, 20 Jul 2023 09:11:22 +0100 Subject: [PATCH 1/5] formatting --- Source/buildimplementationcpp.go | 2286 +++++++++++++++--------------- Source/buildimplementationjs.go | 1269 ++++++++--------- Source/componentdefinition.go | 912 ++++++------ 3 files changed, 2200 insertions(+), 2267 deletions(-) diff --git a/Source/buildimplementationcpp.go b/Source/buildimplementationcpp.go index c5bc2b1f..0ee11ea4 100644 --- a/Source/buildimplementationcpp.go +++ b/Source/buildimplementationcpp.go @@ -46,12 +46,12 @@ import ( func BuildImplementationCPP(component ComponentDefinition, outputFolder string, stubOutputFolder string, projectOutputFolder string, implementation ComponentDefinitionImplementation, suppressStub bool, suppressInterfaces bool) error { forceRecreation := false - doJournal := len (component.Global.JournalMethod) > 0; - - NameSpace := component.NameSpace; + doJournal := len(component.Global.JournalMethod) > 0 + + NameSpace := component.NameSpace ImplementationSubNameSpace := "Impl" - LibraryName := component.LibraryName; - BaseName := component.BaseName; + LibraryName := component.LibraryName + BaseName := component.BaseName indentString := getIndentationString(implementation.Indentation) stubIdentifier := "" @@ -59,11 +59,11 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, stubIdentifier = "_" + strings.ToLower(implementation.StubIdentifier) } - if (!suppressInterfaces) { + if !suppressInterfaces { - IntfExceptionHeaderName := path.Join(outputFolder, BaseName+"_interfaceexception.hpp"); + IntfExceptionHeaderName := path.Join(outputFolder, BaseName+"_interfaceexception.hpp") log.Printf("Creating \"%s\"", IntfExceptionHeaderName) - hInternalExceptionHeaderFile, err := CreateLanguageFile (IntfExceptionHeaderName, indentString) + hInternalExceptionHeaderFile, err := CreateLanguageFile(IntfExceptionHeaderName, indentString) if err != nil { return err } @@ -71,9 +71,9 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, fmt.Sprintf("This is an autogenerated C++ Header file with the basic internal\n exception type in order to allow an easy use of %s", LibraryName), true) - IntfExceptionImplName := path.Join(outputFolder, BaseName+"_interfaceexception.cpp"); + IntfExceptionImplName := path.Join(outputFolder, BaseName+"_interfaceexception.cpp") log.Printf("Creating \"%s\"", IntfExceptionImplName) - hInternalExceptionImplFile, err := CreateLanguageFile (IntfExceptionImplName, indentString) + hInternalExceptionImplFile, err := CreateLanguageFile(IntfExceptionImplName, indentString) if err != nil { return err } @@ -81,14 +81,14 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, fmt.Sprintf("This is an autogenerated C++ Implementation file with the basic internal\n exception type in order to allow an easy use of %s", LibraryName), true) - err = buildCPPInternalException(hInternalExceptionHeaderFile, hInternalExceptionImplFile, NameSpace, BaseName ) + err = buildCPPInternalException(hInternalExceptionHeaderFile, hInternalExceptionImplFile, NameSpace, BaseName) if err != nil { return err } - IntfHeaderName := path.Join(outputFolder, BaseName+"_interfaces.hpp"); + IntfHeaderName := path.Join(outputFolder, BaseName+"_interfaces.hpp") log.Printf("Creating \"%s\"", IntfHeaderName) - interfaceshppfile, err := CreateLanguageFile (IntfHeaderName, indentString) + interfaceshppfile, err := CreateLanguageFile(IntfHeaderName, indentString) if err != nil { return err } @@ -100,7 +100,7 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, return err } - IntfWrapperImplName := path.Join(outputFolder, BaseName+"_interfacewrapper.cpp"); + IntfWrapperImplName := path.Join(outputFolder, BaseName+"_interfacewrapper.cpp") log.Printf("Creating \"%s\"", IntfWrapperImplName) cppWrapperfile, err := CreateLanguageFile(IntfWrapperImplName, indentString) if err != nil { @@ -114,18 +114,18 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, return err } - if (doJournal) { - IntfJournalHeaderName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.hpp"); + if doJournal { + IntfJournalHeaderName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.hpp") log.Printf("Creating \"%s\"", IntfJournalHeaderName) - interfacejournalhppfile, err := CreateLanguageFile (IntfJournalHeaderName, indentString) + interfacejournalhppfile, err := CreateLanguageFile(IntfJournalHeaderName, indentString) if err != nil { return err } interfacejournalhppfile.WriteCLicenseHeader(component, fmt.Sprintf("This is an autogenerated C++ header file in order to allow easy\ndevelopment of %s. It provides an automatic Journaling mechanism for the library implementation.", LibraryName), true) - - IntfJournalImplName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.cpp"); + + IntfJournalImplName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.cpp") log.Printf("Creating \"%s\"", IntfJournalImplName) interfacejournalcppfile, err := CreateLanguageFile(IntfJournalImplName, indentString) if err != nil { @@ -134,33 +134,33 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, interfacejournalcppfile.WriteCLicenseHeader(component, fmt.Sprintf("This is an autogenerated C++ implementation file in order to allow easy\ndevelopment of %s. It provides an automatic Journaling mechanism for the library implementation.", LibraryName), true) - + err = buildJournalingCPP(component, interfacejournalhppfile, interfacejournalcppfile) if err != nil { return err } } - + } - if (!suppressStub) { + if !suppressStub { err := buildCPPStub(component, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier, forceRecreation) if err != nil { return err } - IntfWrapperStubName := path.Join(stubOutputFolder, BaseName + stubIdentifier + ".cpp") - if forceRecreation || (!FileExists(IntfWrapperStubName) ) { + IntfWrapperStubName := path.Join(stubOutputFolder, BaseName+stubIdentifier+".cpp") + if forceRecreation || (!FileExists(IntfWrapperStubName)) { log.Printf("Creating \"%s\"", IntfWrapperStubName) - stubfile, err := CreateLanguageFile (IntfWrapperStubName, indentString) + stubfile, err := CreateLanguageFile(IntfWrapperStubName, indentString) if err != nil { return err } stubfile.WriteCLicenseHeader(component, fmt.Sprintf("This is an autogenerated C++ implementation file in order to allow easy\ndevelopment of %s. It needs to be generated only once.", LibraryName), true) - + err = buildCPPGlobalStubFile(component, stubfile, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName) if err != nil { return err @@ -169,8 +169,8 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, log.Printf("Omitting recreation of implementation stub \"%s\"", IntfWrapperStubName) } - if ( len(projectOutputFolder) > 0 ) { - CMakeListsFileName := path.Join(projectOutputFolder, "CMakeLists.txt"); + if len(projectOutputFolder) > 0 { + CMakeListsFileName := path.Join(projectOutputFolder, "CMakeLists.txt") if forceRecreation || !FileExists(CMakeListsFileName) { log.Printf("Creating CMake-Project \"%s\" for CPP Implementation", CMakeListsFileName) CMakeListsFile, err := CreateLanguageFile(CMakeListsFileName, indentString) @@ -185,98 +185,97 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, log.Printf("Omitting recreation of CMake-Project \"%s\" for CPP Implementation", CMakeListsFileName) } } - + } return nil } -func buildCPPInternalException(wHeader LanguageWriter, wImpl LanguageWriter, NameSpace string, BaseName string) (error) { - wHeader.Writeln("#ifndef __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)); - wHeader.Writeln("#define __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)); - wHeader.Writeln(""); - - wHeader.Writeln("#include <string>"); - wHeader.Writeln("#include <exception>"); - wHeader.Writeln("#include <stdexcept>"); - - wHeader.Writeln("#include \"%s_types.hpp\"", BaseName); - wHeader.Writeln(""); - - wHeader.Writeln("/*************************************************************************************************************************"); - wHeader.Writeln(" Class E%sInterfaceException", NameSpace); - wHeader.Writeln("**************************************************************************************************************************/"); - wHeader.Writeln(""); - wHeader.Writeln(""); - wHeader.Writeln("class E%sInterfaceException : public std::exception {", NameSpace); - wHeader.Writeln("protected:"); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Error code for the Exception."); - wHeader.Writeln(" */"); - wHeader.Writeln(" %sResult m_errorCode;", NameSpace); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Error message for the Exception."); - wHeader.Writeln(" */"); - wHeader.Writeln(" std::string m_errorMessage;"); +func buildCPPInternalException(wHeader LanguageWriter, wImpl LanguageWriter, NameSpace string, BaseName string) error { + wHeader.Writeln("#ifndef __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)) + wHeader.Writeln("#define __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)) + wHeader.Writeln("") + + wHeader.Writeln("#include <string>") + wHeader.Writeln("#include <exception>") + wHeader.Writeln("#include <stdexcept>") + + wHeader.Writeln("#include \"%s_types.hpp\"", BaseName) + wHeader.Writeln("") + + wHeader.Writeln("/*************************************************************************************************************************") + wHeader.Writeln(" Class E%sInterfaceException", NameSpace) + wHeader.Writeln("**************************************************************************************************************************/") + wHeader.Writeln("") + wHeader.Writeln("") + wHeader.Writeln("class E%sInterfaceException : public std::exception {", NameSpace) + wHeader.Writeln("protected:") + wHeader.Writeln(" /**") + wHeader.Writeln(" * Error code for the Exception.") + wHeader.Writeln(" */") + wHeader.Writeln(" %sResult m_errorCode;", NameSpace) + wHeader.Writeln(" /**") + wHeader.Writeln(" * Error message for the Exception.") + wHeader.Writeln(" */") + wHeader.Writeln(" std::string m_errorMessage;") + wHeader.Writeln("") + wHeader.Writeln("public:") + wHeader.Writeln(" /**") + wHeader.Writeln(" * Exception Constructor.") + wHeader.Writeln(" */") + wHeader.Writeln(" E%sInterfaceException(%sResult errorCode);", NameSpace, NameSpace) + wHeader.Writeln("") + wHeader.Writeln(" /**") + wHeader.Writeln(" * Custom Exception Constructor.") + wHeader.Writeln(" */") + wHeader.Writeln(" E%sInterfaceException(%sResult errorCode, std::string errorMessage);", NameSpace, NameSpace) wHeader.Writeln("") - wHeader.Writeln("public:"); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Exception Constructor."); - wHeader.Writeln(" */"); - wHeader.Writeln(" E%sInterfaceException(%sResult errorCode);", NameSpace, NameSpace); - wHeader.Writeln(""); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Custom Exception Constructor."); - wHeader.Writeln(" */"); - wHeader.Writeln(" E%sInterfaceException(%sResult errorCode, std::string errorMessage);", NameSpace, NameSpace); - wHeader.Writeln(""); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Returns error code"); - wHeader.Writeln(" */"); - wHeader.Writeln(" %sResult getErrorCode();", NameSpace); - wHeader.Writeln(" /**"); - wHeader.Writeln(" * Returns error message"); - wHeader.Writeln(" */"); - wHeader.Writeln(" const char* what() const noexcept override;"); - wHeader.Writeln("};"); - wHeader.Writeln(""); - - wHeader.Writeln("#endif // __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)); - - - wImpl.Writeln(""); - wImpl.Writeln("#include <string>"); - wImpl.Writeln(""); - wImpl.Writeln("#include \"%s_interfaceexception.hpp\"", BaseName); - wImpl.Writeln(""); - - wImpl.Writeln("/*************************************************************************************************************************"); - wImpl.Writeln(" Class E%sInterfaceException", NameSpace); - wImpl.Writeln("**************************************************************************************************************************/"); - wImpl.Writeln("E%sInterfaceException::E%sInterfaceException(%sResult errorCode)", NameSpace, NameSpace, NameSpace); - wImpl.Writeln(" : m_errorMessage(%s_GETERRORSTRING (errorCode))", strings.ToUpper (NameSpace)); - wImpl.Writeln("{"); - wImpl.Writeln(" m_errorCode = errorCode;"); - wImpl.Writeln("}"); - wImpl.Writeln(""); - wImpl.Writeln("E%sInterfaceException::E%sInterfaceException(%sResult errorCode, std::string errorMessage)", NameSpace, NameSpace, NameSpace); - wImpl.Writeln(" : m_errorMessage(errorMessage + \" (\" + std::to_string (errorCode) + \")\")"); - wImpl.Writeln("{"); - wImpl.Writeln(" m_errorCode = errorCode;"); - wImpl.Writeln("}"); - wImpl.Writeln(""); - wImpl.Writeln("%sResult E%sInterfaceException::getErrorCode ()", NameSpace, NameSpace); - wImpl.Writeln("{"); - wImpl.Writeln(" return m_errorCode;"); - wImpl.Writeln("}"); - wImpl.Writeln(""); - wImpl.Writeln("const char * E%sInterfaceException::what () const noexcept", NameSpace); - wImpl.Writeln("{"); - wImpl.Writeln(" return m_errorMessage.c_str();"); - wImpl.Writeln("}"); - wImpl.Writeln(""); - - return nil; + wHeader.Writeln(" /**") + wHeader.Writeln(" * Returns error code") + wHeader.Writeln(" */") + wHeader.Writeln(" %sResult getErrorCode();", NameSpace) + wHeader.Writeln(" /**") + wHeader.Writeln(" * Returns error message") + wHeader.Writeln(" */") + wHeader.Writeln(" const char* what() const noexcept override;") + wHeader.Writeln("};") + wHeader.Writeln("") + + wHeader.Writeln("#endif // __%s_INTERFACEEXCEPTION_HEADER", strings.ToUpper(NameSpace)) + + wImpl.Writeln("") + wImpl.Writeln("#include <string>") + wImpl.Writeln("") + wImpl.Writeln("#include \"%s_interfaceexception.hpp\"", BaseName) + wImpl.Writeln("") + + wImpl.Writeln("/*************************************************************************************************************************") + wImpl.Writeln(" Class E%sInterfaceException", NameSpace) + wImpl.Writeln("**************************************************************************************************************************/") + wImpl.Writeln("E%sInterfaceException::E%sInterfaceException(%sResult errorCode)", NameSpace, NameSpace, NameSpace) + wImpl.Writeln(" : m_errorMessage(%s_GETERRORSTRING (errorCode))", strings.ToUpper(NameSpace)) + wImpl.Writeln("{") + wImpl.Writeln(" m_errorCode = errorCode;") + wImpl.Writeln("}") + wImpl.Writeln("") + wImpl.Writeln("E%sInterfaceException::E%sInterfaceException(%sResult errorCode, std::string errorMessage)", NameSpace, NameSpace, NameSpace) + wImpl.Writeln(" : m_errorMessage(errorMessage + \" (\" + std::to_string (errorCode) + \")\")") + wImpl.Writeln("{") + wImpl.Writeln(" m_errorCode = errorCode;") + wImpl.Writeln("}") + wImpl.Writeln("") + wImpl.Writeln("%sResult E%sInterfaceException::getErrorCode ()", NameSpace, NameSpace) + wImpl.Writeln("{") + wImpl.Writeln(" return m_errorCode;") + wImpl.Writeln("}") + wImpl.Writeln("") + wImpl.Writeln("const char * E%sInterfaceException::what () const noexcept", NameSpace) + wImpl.Writeln("{") + wImpl.Writeln(" return m_errorMessage.c_str();") + wImpl.Writeln("}") + wImpl.Writeln("") + + return nil } func writeSharedPtrTemplate(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) { @@ -315,34 +314,34 @@ func writeSharedPtrTemplate(component ComponentDefinition, w LanguageWriter, Cla w.Writeln("") } -func writeCPPClassInterface(component ComponentDefinition, class ComponentDefinitionClass, w LanguageWriter, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string) (error) { +func writeCPPClassInterface(component ComponentDefinition, class ComponentDefinitionClass, w LanguageWriter, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string) error { w.Writeln("") w.Writeln("/*************************************************************************************************************************") w.Writeln(" Class interface for %s ", class.ClassName) w.Writeln("**************************************************************************************************************************/") w.Writeln("") parentClassString := " " - if (!component.isBaseClass(class)) { + if !component.isBaseClass(class) { parentClassString = " : public virtual " - if (class.ParentClass == "") { + if class.ParentClass == "" { parentClassString += fmt.Sprintf("I%s%s ", ClassIdentifier, component.Global.BaseClassName) } else { parentClassString += fmt.Sprintf("I%s%s ", ClassIdentifier, class.ParentClass) } } - + classInterfaceName := fmt.Sprintf("I%s%s", ClassIdentifier, class.ClassName) w.Writeln("class %s%s{", classInterfaceName, parentClassString) - if (component.isStringOutBaseClass(class)) { + if component.isStringOutBaseClass(class) { w.Writeln("private:") w.Writeln(" std::unique_ptr<ParameterCache> m_ParameterCache;") - + } w.Writeln("public:") - if (component.isBaseClass(class)) { + if component.isBaseClass(class) { w.Writeln(" /**") w.Writeln(" * %s::~%s - virtual destructor of %s", classInterfaceName, classInterfaceName, classInterfaceName) w.Writeln(" */") @@ -355,7 +354,7 @@ func writeCPPClassInterface(component ComponentDefinition, class ComponentDefini return err } w.Writeln("%s", methodstring) - argument := "p"+releaseBaseClassInterfaceMethod.Params[0].ParamName + argument := "p" + releaseBaseClassInterfaceMethod.Params[0].ParamName w.Writeln(" {") w.Writeln(" if (%s) {", argument) w.Writeln(" %s->%s();", argument, DecRefCountMethod().MethodName) @@ -369,7 +368,7 @@ func writeCPPClassInterface(component ComponentDefinition, class ComponentDefini return err } w.Writeln("%s", methodstring) - argument = "p"+acquireBaseClassInterfaceMethod.Params[0].ParamName + argument = "p" + acquireBaseClassInterfaceMethod.Params[0].ParamName w.Writeln(" {") w.Writeln(" if (%s) {", argument) w.Writeln(" %s->%s();", argument, IncRefCountMethod().MethodName) @@ -393,36 +392,36 @@ func writeCPPClassInterface(component ComponentDefinition, class ComponentDefini } } - if (component.isStringOutBaseClass(class)) { - - w.Writeln("") + if component.isStringOutBaseClass(class) { + + w.Writeln("") w.Writeln(" /**") w.Writeln(" * %s::_setCache - set parameter cache of object", classInterfaceName) w.Writeln(" */") - w.Writeln(" void _setCache(ParameterCache * pCache)") - w.Writeln(" {") - w.Writeln(" m_ParameterCache.reset(pCache);") - w.Writeln(" }") - w.Writeln("") - + w.Writeln(" void _setCache(ParameterCache * pCache)") + w.Writeln(" {") + w.Writeln(" m_ParameterCache.reset(pCache);") + w.Writeln(" }") + w.Writeln("") + w.Writeln(" /**") w.Writeln(" * %s::_getCache - returns parameter cache of object", classInterfaceName) w.Writeln(" */") - w.Writeln(" ParameterCache* _getCache()") - w.Writeln(" {") - w.Writeln(" return m_ParameterCache.get();") - w.Writeln(" }") - w.Writeln("") + w.Writeln(" ParameterCache* _getCache()") + w.Writeln(" {") + w.Writeln(" return m_ParameterCache.get();") + w.Writeln(" }") + w.Writeln("") } - if (component.isBaseClass(class)) { + if component.isBaseClass(class) { methodstring, _, err := buildCPPInterfaceMethodDeclaration(component.classTypeIdMethod(), class.ClassName, NameSpace, ClassIdentifier, BaseName, w.IndentString, false, true, true) if err != nil { return err } // Only IBase class has pure virtual ClassTypeId method. It's needed for proper interpretation of "override" in deriver interface classes. w.Writeln("%s;", methodstring) - + } else { methodstring, _, err := buildCPPInterfaceMethodDeclaration(component.classTypeIdMethod(), class.ClassName, NameSpace, ClassIdentifier, BaseName, w.IndentString, false, false, true) if err != nil { @@ -432,8 +431,8 @@ func writeCPPClassInterface(component ComponentDefinition, class ComponentDefini w.Writeln("%s", methodstring) w.Writeln(" {") w.Writeln(" return 0x%XUL; // First 64 bits of SHA1 of a string: \"%s\"", classTypeId, chashHashString) - w.Writeln(" }") - w.Writeln("") + w.Writeln(" }") + w.Writeln("") } for j := 0; j < len(class.Methods); j++ { @@ -471,7 +470,6 @@ func writeClassDefinitions(component ComponentDefinition, w LanguageWriter, Name } } - func writeParameterCacheDefinitions(component ComponentDefinition, w LanguageWriter, NameSpaceImplementation string, ClassIdentifier string) { w.Writeln("") @@ -484,23 +482,23 @@ func writeParameterCacheDefinitions(component ComponentDefinition, w LanguageWri w.Writeln(" virtual ~ParameterCache() {}") w.Writeln("};") w.Writeln("") - - maxParamCount := component.countMaxOutParameters (); - + + maxParamCount := component.countMaxOutParameters() + for paramCount := uint32(1); paramCount <= maxParamCount; paramCount++ { - - classString := "class T1"; - constructorString := "const T1 & param1"; - assignmentString := "m_param1 (param1)"; - retrieveString := "T1 & param1"; + + classString := "class T1" + constructorString := "const T1 & param1" + assignmentString := "m_param1 (param1)" + retrieveString := "T1 & param1" for paramIdx := uint32(2); paramIdx <= paramCount; paramIdx++ { - classString += fmt.Sprintf (", class T%d", paramIdx); - constructorString += fmt.Sprintf (", const T%d & param%d", paramIdx, paramIdx); - assignmentString += fmt.Sprintf (", m_param%d (param%d)", paramIdx, paramIdx); - retrieveString += fmt.Sprintf (", T%d & param%d", paramIdx, paramIdx); + classString += fmt.Sprintf(", class T%d", paramIdx) + constructorString += fmt.Sprintf(", const T%d & param%d", paramIdx, paramIdx) + assignmentString += fmt.Sprintf(", m_param%d (param%d)", paramIdx, paramIdx) + retrieveString += fmt.Sprintf(", T%d & param%d", paramIdx, paramIdx) } - w.Writeln("template <%s> class ParameterCache_%d : public ParameterCache {", classString, paramCount); + w.Writeln("template <%s> class ParameterCache_%d : public ParameterCache {", classString, paramCount) w.Writeln(" private:") for paramIdx := uint32(1); paramIdx <= paramCount; paramIdx++ { w.Writeln(" T%d m_param%d;", paramIdx, paramIdx) @@ -521,9 +519,8 @@ func writeParameterCacheDefinitions(component ComponentDefinition, w LanguageWri w.Writeln("") } - -} +} func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpaceImplementation string, ClassIdentifier string) error { NameSpace := component.NameSpace @@ -540,7 +537,7 @@ func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpa w.Writeln("#include \"%s_types.hpp\"", BaseName) w.Writeln("") w.Writeln("") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { w.Writeln("#include \"%s_dynamic.hpp\"", subComponent.BaseName) } w.Writeln("") @@ -555,7 +552,7 @@ func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpa w.Writeln("*/") for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] - w.Writeln("class I%s%s;", ClassIdentifier, class.ClassName); + w.Writeln("class I%s%s;", ClassIdentifier, class.ClassName) } w.Writeln("") w.Writeln("") @@ -574,19 +571,19 @@ func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpa if len(component.ImportedComponentDefinitions) > 0 { w.Writeln(" // Injected Components") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { subNameSpace := subComponent.NameSpace w.Writeln(" static %s::PWrapper sP%sWrapper;", subNameSpace, subNameSpace) } w.Writeln("") } - global := component.Global; + global := component.Global for j := 0; j < len(global.Methods); j++ { method := global.Methods[j] // Omit special functions that are automatically implemented - isSpecialFunction, err := CheckHeaderSpecialFunction(method, global); + isSpecialFunction, err := CheckHeaderSpecialFunction(method, global) if err != nil { return err } @@ -604,10 +601,10 @@ func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpa } w.Writeln("};") w.Writeln("") - + w.Writeln("%sResult %s_GetProcAddress (const char * pProcName, void ** ppProcAddress);", NameSpace, NameSpace) w.Writeln("") - + w.Writeln("} // namespace %s", NameSpaceImplementation) w.Writeln("} // namespace %s", NameSpace) w.Writeln("") @@ -631,7 +628,7 @@ func buildCPPGlobalStubFile(component ComponentDefinition, stubfile LanguageWrit if len(component.ImportedComponentDefinitions) > 0 { stubfile.Writeln("// Injected Components") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { subNameSpace := subComponent.NameSpace stubfile.Writeln("%s::PWrapper C%sWrapper::sP%sWrapper;", subNameSpace, ClassIdentifier, subNameSpace) } @@ -642,9 +639,9 @@ func buildCPPGlobalStubFile(component ComponentDefinition, stubfile LanguageWrit method := component.Global.Methods[j] thisMethodDefaultImpl := defaultImplementation - + // Omit special functions that are automatically implemented - isSpecialFunction, err := CheckHeaderSpecialFunction(method, component.Global); + isSpecialFunction, err := CheckHeaderSpecialFunction(method, component.Global) if err != nil { return err } @@ -652,31 +649,31 @@ func buildCPPGlobalStubFile(component ComponentDefinition, stubfile LanguageWrit (isSpecialFunction == eSpecialMethodSymbolLookup) { continue } - if (isSpecialFunction == eSpecialMethodVersion) { + if isSpecialFunction == eSpecialMethodVersion { var versionImplementation []string versionImplementation = append(versionImplementation, fmt.Sprintf("n%s = %s_VERSION_MAJOR;", method.Params[0].ParamName, strings.ToUpper(NameSpace)), fmt.Sprintf("n%s = %s_VERSION_MINOR;", method.Params[1].ParamName, strings.ToUpper(NameSpace)), - fmt.Sprintf("n%s = %s_VERSION_MICRO;", method.Params[2].ParamName, strings.ToUpper(NameSpace)) ) + fmt.Sprintf("n%s = %s_VERSION_MICRO;", method.Params[2].ParamName, strings.ToUpper(NameSpace))) thisMethodDefaultImpl = versionImplementation } - if (isSpecialFunction == eSpecialMethodError) { + if isSpecialFunction == eSpecialMethodError { var errorImplementation []string errorImplementation = append(errorImplementation, fmt.Sprintf("if (p%s) {", method.Params[0].ParamName), fmt.Sprintf(" return p%s->%s (s%s);", method.Params[0].ParamName, GetLastErrorMessageMethod().MethodName, method.Params[1].ParamName), "} else {", " return false;", - "}"); + "}") thisMethodDefaultImpl = errorImplementation } - if (isSpecialFunction == eSpecialMethodRelease) { + if isSpecialFunction == eSpecialMethodRelease { var releaseImplementation []string releaseImplementation = append(releaseImplementation, fmt.Sprintf("I%s%s::%s(p%s);", ClassIdentifier, component.Global.BaseClassName, ReleaseBaseClassInterfaceMethod(component.Global.BaseClassName).MethodName, method.Params[0].ParamName)) thisMethodDefaultImpl = releaseImplementation } - if (isSpecialFunction == eSpecialMethodAcquire) { + if isSpecialFunction == eSpecialMethodAcquire { var acquireImplementation []string acquireImplementation = append(acquireImplementation, fmt.Sprintf("I%s%s::%s(p%s);", ClassIdentifier, component.Global.BaseClassName, AcquireBaseClassInterfaceMethod(component.Global.BaseClassName).MethodName, method.Params[0].ParamName)) @@ -708,7 +705,7 @@ func buildCPPInterfaceWrapperMethods(component ComponentDefinition, class Compon for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] - err := writeCImplementationMethod(component, method, w, BaseName, NameSpace, NameSpaceImplementation, ClassIdentifier, class.ClassName, component.Global.BaseClassName, false, doJournal, eSpecialMethodNone, component.isStringOutClass (class)) + err := writeCImplementationMethod(component, method, w, BaseName, NameSpace, NameSpaceImplementation, ClassIdentifier, class.ClassName, component.Global.BaseClassName, false, doJournal, eSpecialMethodNone, component.isStringOutClass(class)) if err != nil { return err } @@ -723,40 +720,39 @@ func buildCPPGetSymbolAddressMethod(component ComponentDefinition, w LanguageWri w.Writeln(" Function table lookup implementation") w.Writeln("**************************************************************************************************************************/") w.Writeln("") - + w.Writeln("%sResult %s::%s::%s_GetProcAddress (const char * pProcName, void ** ppProcAddress)", NameSpace, NameSpace, NameSpaceImplementation, NameSpace) w.Writeln("{") w.AddIndentationLevel(1) - - var processfuncMap []string; - - global := component.Global; + + var processfuncMap []string + + global := component.Global for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] procName := strings.ToLower(class.ClassName + "_" + method.MethodName) - processfuncMap = append (processfuncMap, fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), procName)); + processfuncMap = append(processfuncMap, fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), procName)) } } for j := 0; j < len(global.Methods); j++ { method := global.Methods[j] procName := strings.ToLower(method.MethodName) - processfuncMap = append (processfuncMap, fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), procName)); + processfuncMap = append(processfuncMap, fmt.Sprintf("%s_%s", strings.ToLower(NameSpace), procName)) } - - w.Writeln("if (pProcName == nullptr)") + w.Writeln("if (pProcName == nullptr)") w.Writeln(" return %s_ERROR_INVALIDPARAM;", strings.ToUpper(NameSpace)) - w.Writeln("if (ppProcAddress == nullptr)") + w.Writeln("if (ppProcAddress == nullptr)") w.Writeln(" return %s_ERROR_INVALIDPARAM;", strings.ToUpper(NameSpace)) w.Writeln("*ppProcAddress = nullptr;") w.Writeln("std::string sProcName (pProcName);") w.Writeln("") - for j := 0; j < len (processfuncMap); j++ { + for j := 0; j < len(processfuncMap); j++ { w.Writeln("if (sProcName == \"%s\") ", processfuncMap[j]) w.Writeln(" *ppProcAddress = (void*) &%s;", processfuncMap[j]) } @@ -764,17 +760,17 @@ func buildCPPGetSymbolAddressMethod(component ComponentDefinition, w LanguageWri w.Writeln("") w.Writeln("if (*ppProcAddress == nullptr) ") w.Writeln(" return %s_ERROR_COULDNOTFINDLIBRARYEXPORT;", strings.ToUpper(NameSpace)) - w.Writeln("return %s_SUCCESS;", strings.ToUpper (NameSpace)) + w.Writeln("return %s_SUCCESS;", strings.ToUpper(NameSpace)) w.AddIndentationLevel(-1) w.Writeln("}") - return nil; + return nil } func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, doJournal bool) error { w.Writeln("#include \"%s_abi.hpp\"", strings.ToLower(BaseName)) w.Writeln("#include \"%s_interfaces.hpp\"", strings.ToLower(BaseName)) w.Writeln("#include \"%s_interfaceexception.hpp\"", strings.ToLower(BaseName)) - if (doJournal) { + if doJournal { w.Writeln("#include \"%s_interfacejournal.hpp\"", strings.ToLower(BaseName)) } w.Writeln("") @@ -783,15 +779,14 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N w.Writeln("using namespace %s::%s;", NameSpace, NameSpaceImplementation) w.Writeln("") - if (doJournal) { + if doJournal { w.Writeln("P%sInterfaceJournal m_GlobalJournal;", NameSpace) w.Writeln("") } - - journalParameter := ""; - if (doJournal) { - journalParameter = fmt.Sprintf (", C%sInterfaceJournalEntry * pJournalEntry = nullptr", NameSpace); + journalParameter := "" + if doJournal { + journalParameter = fmt.Sprintf(", C%sInterfaceJournalEntry * pJournalEntry = nullptr", NameSpace) } IBaseClassName := "I" + ClassIdentifier + component.Global.BaseClassName @@ -800,14 +795,14 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N w.Writeln("{") w.Writeln(" %sResult errorCode = Exception.getErrorCode();", NameSpace) w.Writeln("") - if (doJournal) { + if doJournal { w.Writeln(" if (pJournalEntry != nullptr)") w.Writeln(" pJournalEntry->writeError(errorCode);") w.Writeln("") } w.Writeln(" if (pIBaseClass != nullptr)") - + w.Writeln(" pIBaseClass->%s(Exception.what());", registerErrorMethod.MethodName) w.Writeln("") @@ -819,7 +814,7 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N w.Writeln("{") w.Writeln(" %sResult errorCode = %s_ERROR_GENERICEXCEPTION;", NameSpace, strings.ToUpper(NameSpace)) w.Writeln("") - if (doJournal) { + if doJournal { w.Writeln(" if (pJournalEntry != nullptr)") w.Writeln(" pJournalEntry->writeError(errorCode);") w.Writeln("") @@ -837,32 +832,31 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N w.Writeln("{") w.Writeln(" %sResult errorCode = %s_ERROR_GENERICEXCEPTION;", NameSpace, strings.ToUpper(NameSpace)) w.Writeln("") - if (doJournal) { + if doJournal { w.Writeln(" if (pJournalEntry != nullptr)") w.Writeln(" pJournalEntry->writeError(errorCode);") w.Writeln("") } - + w.Writeln(" if (pIBaseClass != nullptr)") w.Writeln(" pIBaseClass->%s(\"Unhandled Exception\");", registerErrorMethod.MethodName) - + w.Writeln("") w.Writeln(" return errorCode;") w.Writeln("}") w.Writeln("") - - + w.Writeln("") for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] err := buildCPPInterfaceWrapperMethods(component, class, w, NameSpace, NameSpaceImplementation, ClassIdentifier, BaseName, doJournal) - if (err != nil) { + if err != nil { return err } } w.Writeln("") - err := buildCPPGetSymbolAddressMethod(component, w, NameSpace, NameSpaceImplementation); + err := buildCPPGetSymbolAddressMethod(component, w, NameSpace, NameSpaceImplementation) if err != nil { return err } @@ -871,20 +865,20 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N w.Writeln("/*************************************************************************************************************************") w.Writeln(" Global functions implementation") w.Writeln("**************************************************************************************************************************/") - global := component.Global; + global := component.Global for j := 0; j < len(global.Methods); j++ { method := global.Methods[j] - + // Check for special functions - isSpecialFunction, err := CheckHeaderSpecialFunction(method, global); + isSpecialFunction, err := CheckHeaderSpecialFunction(method, global) if err != nil { return err } - + // Do not self-journal Journal special method - doMethodJournal := doJournal; - if (isSpecialFunction == eSpecialMethodJournal) { - doMethodJournal = false; + doMethodJournal := doJournal + if isSpecialFunction == eSpecialMethodJournal { + doMethodJournal = false } // Write Static function implementation @@ -899,31 +893,28 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N return nil } +func buildOutCacheTemplateParameters(method ComponentDefinitionMethod, NameSpace string, BaseClassName string, ClassIdentifier string) (string, error) { + result := "" + + for i := 0; i < len(method.Params); i++ { + param := method.Params[i] -func buildOutCacheTemplateParameters (method ComponentDefinitionMethod, NameSpace string, BaseClassName string, ClassIdentifier string) (string, error) { - result := ""; - - for i := 0; i < len (method.Params); i++ { - param := method.Params[i]; - - if ((param.ParamPass == "out") || (param.ParamPass == "return")) { - if (result != "") { - result += ", "; + if (param.ParamPass == "out") || (param.ParamPass == "return") { + if result != "" { + result += ", " } - - cppParamType := getCppParamType(param, NameSpace, true); + + cppParamType := getCppParamType(param, NameSpace, true) if param.ParamType == "class" || param.ParamType == "optionalclass" { cppParamType = fmt.Sprintf("I%s%s*", ClassIdentifier, param.ParamClass) } - result += cppParamType; + result += cppParamType } - - + } - - return result, nil; -} + return result, nil +} func writeCImplementationMethod(component ComponentDefinition, method ComponentDefinitionMethod, w LanguageWriter, BaseName string, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, ClassName string, BaseClassName string, isGlobal bool, doJournal bool, isSpecialFunction int, isStringOutClass bool) error { CMethodName := "" @@ -951,27 +942,27 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD } callCPPFunctionCode := make([]string, 0) - + checkInputCPPFunctionCode, preCallCPPFunctionCode, postCallCPPFunctionCode, returnVariable, callParameters, outCallParameters, err := generatePrePostCallCPPFunctionCode(component, method, NameSpace, ClassIdentifier, ClassName, BaseClassName) if err != nil { return err } - - if (isSpecialFunction == eSpecialMethodJournal) { + + if isSpecialFunction == eSpecialMethodJournal { callCPPFunctionCode = append(callCPPFunctionCode, "m_GlobalJournal = nullptr;") callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("if (s%s != \"\") {", method.Params[0].ParamName)) callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" m_GlobalJournal = std::make_shared<C%sInterfaceJournal> (s%s);", NameSpace, method.Params[0].ParamName)) callCPPFunctionCode = append(callCPPFunctionCode, "}") - } else if (isSpecialFunction == eSpecialMethodInjection) { + } else if isSpecialFunction == eSpecialMethodInjection { callCPPFunctionCode = append(callCPPFunctionCode, "") callCPPFunctionCode = append(callCPPFunctionCode, "bool bNameSpaceFound = false;") callCPPFunctionCode = append(callCPPFunctionCode, "") - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { theNameSpace := subComponent.NameSpace callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("if (s%s == \"%s\") {", method.Params[0].ParamName, theNameSpace)) wrapperName := "C" + ClassIdentifier + "Wrapper" callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" if (%s::sP%sWrapper.get() != nullptr) {", wrapperName, theNameSpace)) - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_COULDNOTLOADLIBRARY);", NameSpace, strings.ToUpper(NameSpace)) ) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_COULDNOTLOADLIBRARY);", NameSpace, strings.ToUpper(NameSpace))) callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" }")) callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" %s::sP%sWrapper = %s::CWrapper::loadLibraryFromSymbolLookupMethod(p%s);", wrapperName, theNameSpace, theNameSpace, method.Params[1].ParamName)) callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" bNameSpaceFound = true;")) @@ -979,89 +970,87 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD } callCPPFunctionCode = append(callCPPFunctionCode, "") callCPPFunctionCode = append(callCPPFunctionCode, "if (!bNameSpaceFound)") - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_COULDNOTLOADLIBRARY);", NameSpace, strings.ToUpper(NameSpace)) ) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_COULDNOTLOADLIBRARY);", NameSpace, strings.ToUpper(NameSpace))) callCPPFunctionCode = append(callCPPFunctionCode, "") - } else if (isSpecialFunction == eSpecialMethodSymbolLookup) { + } else if isSpecialFunction == eSpecialMethodSymbolLookup { callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("*p%s = (void*)&%s::%s::%s_GetProcAddress;", method.Params[0].ParamName, NameSpace, NameSpaceImplementation, NameSpace)) } else { callCode, err := generateCallCPPFunctionCode(method, NameSpace, ClassIdentifier, ClassName, returnVariable, callParameters, isGlobal) if err != nil { return err } - - stringOutParameters := method.getStringOutParameters (); - outParameterCount := method.countOutParameters (); - - + + stringOutParameters := method.getStringOutParameters() + outParameterCount := method.countOutParameters() + // Special functions are an exception for string outs in global functions! - bHasCacheCall := (len (stringOutParameters) > 0) && (isSpecialFunction != eSpecialMethodError) && (isSpecialFunction != eSpecialMethodBuildinfo) && (isSpecialFunction != eSpecialMethodPrerelease); - if (method.DisableStringOutCache) { - bHasCacheCall = false; + bHasCacheCall := (len(stringOutParameters) > 0) && (isSpecialFunction != eSpecialMethodError) && (isSpecialFunction != eSpecialMethodBuildinfo) && (isSpecialFunction != eSpecialMethodPrerelease) + if method.DisableStringOutCache { + bHasCacheCall = false } - - if (bHasCacheCall) { - - if (isGlobal) { - return errors.New ("String out parameter not allowed in global functions: " + method.MethodName); + + if bHasCacheCall { + + if isGlobal { + return errors.New("String out parameter not allowed in global functions: " + method.MethodName) } - - if (!isStringOutClass) { - return errors.New ("String out parameter without being the string out base class: " + method.MethodName) + + if !isStringOutClass { + return errors.New("String out parameter without being the string out base class: " + method.MethodName) } - - templateParameters, err := buildOutCacheTemplateParameters (method, NameSpace, BaseClassName, ClassIdentifier); + + templateParameters, err := buildOutCacheTemplateParameters(method, NameSpace, BaseClassName, ClassIdentifier) if err != nil { return err } - - cacheClassName := fmt.Sprintf ("ParameterCache_%d<%s>", outParameterCount, templateParameters); - cacheClassParameters := outCallParameters; - cacheCallCondition := ""; - - for i := 0; i < len (stringOutParameters); i++ { - if (i > 0) { - cacheCallCondition = cacheCallCondition + " || "; + + cacheClassName := fmt.Sprintf("ParameterCache_%d<%s>", outParameterCount, templateParameters) + cacheClassParameters := outCallParameters + cacheCallCondition := "" + + for i := 0; i < len(stringOutParameters); i++ { + if i > 0 { + cacheCallCondition = cacheCallCondition + " || " } - - cacheCallCondition += fmt.Sprintf ("(p%sBuffer == nullptr)", stringOutParameters[i]); + + cacheCallCondition += fmt.Sprintf("(p%sBuffer == nullptr)", stringOutParameters[i]) } - - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("bool isCacheCall = %s;", cacheCallCondition)); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("if (isCacheCall) {")); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" " + callCode)) - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" pI%s->_setCache (new %s (%s));", ClassName, cacheClassName, cacheClassParameters)); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("}")); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("else {")); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" auto cache = dynamic_cast<%s*> (pI%s->_getCache ());", cacheClassName, ClassName)); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" if (cache == nullptr)")); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" throw E%sInterfaceException(%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace)) ); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" cache->retrieveData (%s);", cacheClassParameters)); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf (" pI%s->_setCache (nullptr);", ClassName)); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("}")); - callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf ("")); - + + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("bool isCacheCall = %s;", cacheCallCondition)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("if (isCacheCall) {")) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" "+callCode)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" pI%s->_setCache (new %s (%s));", ClassName, cacheClassName, cacheClassParameters)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("}")) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("else {")) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" auto cache = dynamic_cast<%s*> (pI%s->_getCache ());", cacheClassName, ClassName)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" if (cache == nullptr)")) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace))) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" cache->retrieveData (%s);", cacheClassParameters)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf(" pI%s->_setCache (nullptr);", ClassName)) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("}")) + callCPPFunctionCode = append(callCPPFunctionCode, fmt.Sprintf("")) + } else { - - callCPPFunctionCode = append(callCPPFunctionCode, callCode); - + + callCPPFunctionCode = append(callCPPFunctionCode, callCode) + } - + } - + journalInitFunctionCode := make([]string, 0) journalSuccessFunctionCode := make([]string, 0) - if (doJournal) { + if doJournal { journalInitFunctionCode, journalSuccessFunctionCode, err = generateJournalFunctionCode(method, NameSpace, ClassName, isGlobal) if err != nil { return err } } - if !isGlobal { preCallCPPFunctionCode = append(preCallCPPFunctionCode, fmt.Sprintf("I%s%s* pI%s = dynamic_cast<I%s%s*>(pIBaseClass);", ClassIdentifier, ClassName, ClassName, ClassIdentifier, ClassName)) preCallCPPFunctionCode = append(preCallCPPFunctionCode, fmt.Sprintf("if (!pI%s)", ClassName)) - preCallCPPFunctionCode = append(preCallCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace)) ) + preCallCPPFunctionCode = append(preCallCPPFunctionCode, fmt.Sprintf(" throw E%sInterfaceException(%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace))) preCallCPPFunctionCode = append(preCallCPPFunctionCode, "") } @@ -1070,19 +1059,18 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD IBaseClassName := fmt.Sprintf("I%s%s", ClassIdentifier, BaseClassName) if !isGlobal { - w.Writeln (" %s* pIBaseClass = (%s *)p%s;\n", IBaseClassName, IBaseClassName, ClassName); + w.Writeln(" %s* pIBaseClass = (%s *)p%s;\n", IBaseClassName, IBaseClassName, ClassName) } else { - w.Writeln (" %s* pIBaseClass = nullptr;\n", IBaseClassName); + w.Writeln(" %s* pIBaseClass = nullptr;\n", IBaseClassName) } - - - if (doJournal) { - w.Writeln(" P%sInterfaceJournalEntry pJournalEntry;", NameSpace); + + if doJournal { + w.Writeln(" P%sInterfaceJournalEntry pJournalEntry;", NameSpace) } - + w.Writeln(" try {") - if (doJournal) { + if doJournal { w.Writelns(" ", journalInitFunctionCode) } @@ -1091,13 +1079,13 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD w.Writelns(" ", callCPPFunctionCode) w.Writelns(" ", postCallCPPFunctionCode) - journalHandleParam := ""; - - if (doJournal) { + journalHandleParam := "" + + if doJournal { w.Writelns(" ", journalSuccessFunctionCode) - journalHandleParam = ", pJournalEntry.get()"; + journalHandleParam = ", pJournalEntry.get()" } - + w.Writeln(" return %s_SUCCESS;", strings.ToUpper(NameSpace)) w.Writeln(" }") w.Writeln(" catch (E%sInterfaceException & Exception) {", NameSpace) @@ -1115,181 +1103,155 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD return nil } - func buildCPPStubClass(component ComponentDefinition, class ComponentDefinitionClass, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string, forceRecreation bool) error { - outClassName := "C" + ClassIdentifier + class.ClassName + outClassName := "C" + ClassIdentifier + class.ClassName - StubHeaderFileName := path.Join(outputFolder, BaseName + stubIdentifier + "_" +strings.ToLower(class.ClassName)+".hpp"); - StubImplFileName := path.Join(outputFolder, BaseName + stubIdentifier + "_" + strings.ToLower(class.ClassName)+".cpp"); - if !forceRecreation && ( FileExists(StubHeaderFileName) || FileExists(StubImplFileName) ) { - log.Printf("Omitting recreation of Stub implementation for \"%s\"", outClassName) - return nil - } + StubHeaderFileName := path.Join(outputFolder, BaseName+stubIdentifier+"_"+strings.ToLower(class.ClassName)+".hpp") + StubImplFileName := path.Join(outputFolder, BaseName+stubIdentifier+"_"+strings.ToLower(class.ClassName)+".cpp") + if !forceRecreation && (FileExists(StubHeaderFileName) || FileExists(StubImplFileName)) { + log.Printf("Omitting recreation of Stub implementation for \"%s\"", outClassName) + return nil + } - log.Printf("Creating \"%s\"", StubHeaderFileName) - stubheaderw, err := CreateLanguageFile(StubHeaderFileName, indentString) - if err != nil { - return err - } - stubheaderw.WriteCLicenseHeader(component, - fmt.Sprintf("This is the class declaration of %s", outClassName), - false) - - log.Printf("Creating \"%s\"", StubImplFileName) - stubimplw, err := CreateLanguageFile(StubImplFileName, indentString) - if err != nil { - return err - } - stubimplw.WriteCLicenseHeader(component, - fmt.Sprintf("This is a stub class definition of %s", outClassName), - false) + log.Printf("Creating \"%s\"", StubHeaderFileName) + stubheaderw, err := CreateLanguageFile(StubHeaderFileName, indentString) + if err != nil { + return err + } + stubheaderw.WriteCLicenseHeader(component, + fmt.Sprintf("This is the class declaration of %s", outClassName), + false) - stubheaderw.Writeln("") - stubheaderw.Writeln("#ifndef __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) - stubheaderw.Writeln("#define __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) - stubheaderw.Writeln("") + log.Printf("Creating \"%s\"", StubImplFileName) + stubimplw, err := CreateLanguageFile(StubImplFileName, indentString) + if err != nil { + return err + } + stubimplw.WriteCLicenseHeader(component, + fmt.Sprintf("This is a stub class definition of %s", outClassName), + false) - stubheaderw.Writeln("#include \"%s_interfaces.hpp\"", BaseName) - if (component.isBaseClass(class)) { - stubheaderw.Writeln("#include <vector>") - stubheaderw.Writeln("#include <list>") - stubheaderw.Writeln("#include <memory>") - } - stubheaderw.Writeln("") + stubheaderw.Writeln("") + stubheaderw.Writeln("#ifndef __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) + stubheaderw.Writeln("#define __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) + stubheaderw.Writeln("") - if (!component.isBaseClass(class)) { - if (class.ParentClass == "") { - class.ParentClass = component.Global.BaseClassName - } - } + stubheaderw.Writeln("#include \"%s_interfaces.hpp\"", BaseName) + if component.isBaseClass(class) { + stubheaderw.Writeln("#include <vector>") + stubheaderw.Writeln("#include <list>") + stubheaderw.Writeln("#include <memory>") + } + stubheaderw.Writeln("") - if class.ParentClass != "" { - stubheaderw.Writeln("// Parent classes") - stubheaderw.Writeln("#include \"%s%s_%s.hpp\"", BaseName, stubIdentifier, strings.ToLower(class.ParentClass)) - stubheaderw.Writeln("#ifdef _MSC_VER") - stubheaderw.Writeln("#pragma warning(push)") - stubheaderw.Writeln("#pragma warning(disable : 4250)") - stubheaderw.Writeln("#endif") + if !component.isBaseClass(class) { + if class.ParentClass == "" { + class.ParentClass = component.Global.BaseClassName } - stubheaderw.Writeln("") - - stubheaderw.Writeln("// Include custom headers here.") - stubheaderw.Writeln("") - - stubheaderw.Writeln("") - stubheaderw.Writeln("namespace %s {", NameSpace) - stubheaderw.Writeln("namespace %s {", NameSpaceImplementation) - stubheaderw.Writeln("") + } - stubheaderw.Writeln("") - stubheaderw.Writeln("/*************************************************************************************************************************") - stubheaderw.Writeln(" Class declaration of %s ", outClassName) - stubheaderw.Writeln("**************************************************************************************************************************/") - stubheaderw.Writeln("") - parentClassName := fmt.Sprintf("I%s%s", ClassIdentifier, class.ClassName) - if "" != class.ParentClass { - parentClassName = parentClassName + ", " + fmt.Sprintf("public virtual C%s%s", ClassIdentifier, class.ParentClass) - } - stubheaderw.Writeln("class %s : public virtual %s {", outClassName, parentClassName) - stubheaderw.Writeln("private:") - stubheaderw.Writeln("") - - if (component.isBaseClass(class)) { - stubheaderw.Writeln(" std::unique_ptr<std::string> m_pLastError;") - stubheaderw.Writeln(" uint32_t m_nReferenceCount = 1;") - stubheaderw.Writeln("") - } - stubheaderw.Writeln(" /**") - stubheaderw.Writeln(" * Put private members here.") - stubheaderw.Writeln(" */") - stubheaderw.Writeln("") + if class.ParentClass != "" { + stubheaderw.Writeln("// Parent classes") + stubheaderw.Writeln("#include \"%s%s_%s.hpp\"", BaseName, stubIdentifier, strings.ToLower(class.ParentClass)) + stubheaderw.Writeln("#ifdef _MSC_VER") + stubheaderw.Writeln("#pragma warning(push)") + stubheaderw.Writeln("#pragma warning(disable : 4250)") + stubheaderw.Writeln("#endif") + } + stubheaderw.Writeln("") + + stubheaderw.Writeln("// Include custom headers here.") + stubheaderw.Writeln("") + + stubheaderw.Writeln("") + stubheaderw.Writeln("namespace %s {", NameSpace) + stubheaderw.Writeln("namespace %s {", NameSpaceImplementation) + stubheaderw.Writeln("") + + stubheaderw.Writeln("") + stubheaderw.Writeln("/*************************************************************************************************************************") + stubheaderw.Writeln(" Class declaration of %s ", outClassName) + stubheaderw.Writeln("**************************************************************************************************************************/") + stubheaderw.Writeln("") + parentClassName := fmt.Sprintf("I%s%s", ClassIdentifier, class.ClassName) + if "" != class.ParentClass { + parentClassName = parentClassName + ", " + fmt.Sprintf("public virtual C%s%s", ClassIdentifier, class.ParentClass) + } + stubheaderw.Writeln("class %s : public virtual %s {", outClassName, parentClassName) + stubheaderw.Writeln("private:") + stubheaderw.Writeln("") - stubheaderw.Writeln("protected:") - stubheaderw.Writeln("") - stubheaderw.Writeln(" /**") - stubheaderw.Writeln(" * Put protected members here.") - stubheaderw.Writeln(" */") - stubheaderw.Writeln("") - stubheaderw.Writeln("public:") - stubheaderw.Writeln("") - stubheaderw.Writeln(" /**") - stubheaderw.Writeln(" * Put additional public members here. They will not be visible in the external API.") - stubheaderw.Writeln(" */") + if component.isBaseClass(class) { + stubheaderw.Writeln(" std::unique_ptr<std::string> m_pLastError;") + stubheaderw.Writeln(" uint32_t m_nReferenceCount = 1;") stubheaderw.Writeln("") + } + stubheaderw.Writeln(" /**") + stubheaderw.Writeln(" * Put private members here.") + stubheaderw.Writeln(" */") + stubheaderw.Writeln("") + + stubheaderw.Writeln("protected:") + stubheaderw.Writeln("") + stubheaderw.Writeln(" /**") + stubheaderw.Writeln(" * Put protected members here.") + stubheaderw.Writeln(" */") + stubheaderw.Writeln("") + stubheaderw.Writeln("public:") + stubheaderw.Writeln("") + stubheaderw.Writeln(" /**") + stubheaderw.Writeln(" * Put additional public members here. They will not be visible in the external API.") + stubheaderw.Writeln(" */") + stubheaderw.Writeln("") + + stubimplw.Writeln("#include \"%s%s_%s.hpp\"", BaseName, stubIdentifier, strings.ToLower(class.ClassName)) + stubimplw.Writeln("#include \"%s_interfaceexception.hpp\"", BaseName) + stubimplw.Writeln("") + stubimplw.Writeln("// Include custom headers here.") + stubimplw.Writeln("") + + stubimplw.Writeln("") + stubimplw.Writeln("using namespace %s::%s;", NameSpace, NameSpaceImplementation) + stubimplw.Writeln("") + + stubimplw.Writeln("/*************************************************************************************************************************") + stubimplw.Writeln(" Class definition of %s ", outClassName) + stubimplw.Writeln("**************************************************************************************************************************/") + stubimplw.Writeln("") + if component.isBaseClass(class) { + var methods [5]ComponentDefinitionMethod + methods[0] = GetLastErrorMessageMethod() + methods[1] = ClearErrorMessageMethod() + methods[2] = RegisterErrorMessageMethod() + methods[3] = IncRefCountMethod() + methods[4] = DecRefCountMethod() - stubimplw.Writeln("#include \"%s%s_%s.hpp\"", BaseName, stubIdentifier, strings.ToLower(class.ClassName)) - stubimplw.Writeln("#include \"%s_interfaceexception.hpp\"", BaseName) - stubimplw.Writeln("") - stubimplw.Writeln("// Include custom headers here.") - stubimplw.Writeln("") - - - stubimplw.Writeln("") - stubimplw.Writeln("using namespace %s::%s;", NameSpace, NameSpaceImplementation) - stubimplw.Writeln("") - - stubimplw.Writeln("/*************************************************************************************************************************") - stubimplw.Writeln(" Class definition of %s ", outClassName) - stubimplw.Writeln("**************************************************************************************************************************/") - stubimplw.Writeln("") - - if (component.isBaseClass(class)) { - var methods [5]ComponentDefinitionMethod - methods[0] = GetLastErrorMessageMethod() - methods[1] = ClearErrorMessageMethod() - methods[2] = RegisterErrorMessageMethod() - methods[3] = IncRefCountMethod() - methods[4] = DecRefCountMethod() - - var implementations [5][]string - implementations[0] = append(implementations[0], "if (m_pLastError.get() != nullptr) {") - implementations[0] = append(implementations[0], " sErrorMessage = *m_pLastError;") - implementations[0] = append(implementations[0], " return true;") - implementations[0] = append(implementations[0], "} else {") - implementations[0] = append(implementations[0], " sErrorMessage = \"\";") - implementations[0] = append(implementations[0], " return false;") - implementations[0] = append(implementations[0], "}") - implementations[1] = append(implementations[1], "m_pLastError.reset();") - - implementations[2] = append(implementations[2], "if (m_pLastError.get() == nullptr) {") - implementations[2] = append(implementations[2], " m_pLastError.reset(new std::string());") - implementations[2] = append(implementations[2], "}") - implementations[2] = append(implementations[2], "*m_pLastError = sErrorMessage;") - - implementations[3] = append(implementations[3], "++m_nReferenceCount;") - - implementations[4] = append(implementations[4], "m_nReferenceCount--;") - implementations[4] = append(implementations[4], "if (!m_nReferenceCount) {") - implementations[4] = append(implementations[4], " delete this;") - implementations[4] = append(implementations[4], " return true;") - implementations[4] = append(implementations[4], "}") - implementations[4] = append(implementations[4], "return false;") - for i := 0; i < len(methods); i++ { - methodstring, implementationdeclaration, err := buildCPPInterfaceMethodDeclaration(methods[i], class.ClassName, NameSpace, ClassIdentifier, BaseName, stubimplw.IndentString, false, false, false) - if (err!=nil) { - return err - } - stubheaderw.Writeln("%s;", methodstring) - stubheaderw.Writeln("") - - stubimplw.Writeln("%s", implementationdeclaration) - stubimplw.Writeln("{") - stubimplw.Writelns(" ", implementations[i]) - stubimplw.Writeln("}") - stubimplw.Writeln("") - } - } - - stubheaderw.Writeln("") - stubheaderw.Writeln(" /**") - stubheaderw.Writeln(" * Public member functions to implement.") - stubheaderw.Writeln(" */") - stubheaderw.Writeln("") - - for j := 0; j < len(class.Methods); j++ { - method := class.Methods[j] - methodstring, implementationdeclaration, err := buildCPPInterfaceMethodDeclaration(method, class.ClassName, NameSpace, ClassIdentifier, BaseName, stubimplw.IndentString, false, false, false) + var implementations [5][]string + implementations[0] = append(implementations[0], "if (m_pLastError.get() != nullptr) {") + implementations[0] = append(implementations[0], " sErrorMessage = *m_pLastError;") + implementations[0] = append(implementations[0], " return true;") + implementations[0] = append(implementations[0], "} else {") + implementations[0] = append(implementations[0], " sErrorMessage = \"\";") + implementations[0] = append(implementations[0], " return false;") + implementations[0] = append(implementations[0], "}") + implementations[1] = append(implementations[1], "m_pLastError.reset();") + + implementations[2] = append(implementations[2], "if (m_pLastError.get() == nullptr) {") + implementations[2] = append(implementations[2], " m_pLastError.reset(new std::string());") + implementations[2] = append(implementations[2], "}") + implementations[2] = append(implementations[2], "*m_pLastError = sErrorMessage;") + + implementations[3] = append(implementations[3], "++m_nReferenceCount;") + + implementations[4] = append(implementations[4], "m_nReferenceCount--;") + implementations[4] = append(implementations[4], "if (!m_nReferenceCount) {") + implementations[4] = append(implementations[4], " delete this;") + implementations[4] = append(implementations[4], " return true;") + implementations[4] = append(implementations[4], "}") + implementations[4] = append(implementations[4], "return false;") + for i := 0; i < len(methods); i++ { + methodstring, implementationdeclaration, err := buildCPPInterfaceMethodDeclaration(methods[i], class.ClassName, NameSpace, ClassIdentifier, BaseName, stubimplw.IndentString, false, false, false) if err != nil { return err } @@ -1298,24 +1260,47 @@ func buildCPPStubClass(component ComponentDefinition, class ComponentDefinitionC stubimplw.Writeln("%s", implementationdeclaration) stubimplw.Writeln("{") - stubimplw.Writeln(" throw E%sInterfaceException(%s_ERROR_NOTIMPLEMENTED);", NameSpace, strings.ToUpper(NameSpace)) + stubimplw.Writelns(" ", implementations[i]) stubimplw.Writeln("}") stubimplw.Writeln("") } + } - stubheaderw.Writeln("};") - stubheaderw.Writeln("") + stubheaderw.Writeln("") + stubheaderw.Writeln(" /**") + stubheaderw.Writeln(" * Public member functions to implement.") + stubheaderw.Writeln(" */") + stubheaderw.Writeln("") - stubheaderw.Writeln("} // namespace %s", NameSpaceImplementation) - stubheaderw.Writeln("} // namespace %s", NameSpace) + for j := 0; j < len(class.Methods); j++ { + method := class.Methods[j] + methodstring, implementationdeclaration, err := buildCPPInterfaceMethodDeclaration(method, class.ClassName, NameSpace, ClassIdentifier, BaseName, stubimplw.IndentString, false, false, false) + if err != nil { + return err + } + stubheaderw.Writeln("%s;", methodstring) stubheaderw.Writeln("") - if class.ParentClass != "" { - stubheaderw.Writeln("#ifdef _MSC_VER") - stubheaderw.Writeln("#pragma warning(pop)") - stubheaderw.Writeln("#endif") - } - stubheaderw.Writeln("#endif // __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) + stubimplw.Writeln("%s", implementationdeclaration) + stubimplw.Writeln("{") + stubimplw.Writeln(" throw E%sInterfaceException(%s_ERROR_NOTIMPLEMENTED);", NameSpace, strings.ToUpper(NameSpace)) + stubimplw.Writeln("}") + stubimplw.Writeln("") + } + + stubheaderw.Writeln("};") + stubheaderw.Writeln("") + + stubheaderw.Writeln("} // namespace %s", NameSpaceImplementation) + stubheaderw.Writeln("} // namespace %s", NameSpace) + stubheaderw.Writeln("") + + if class.ParentClass != "" { + stubheaderw.Writeln("#ifdef _MSC_VER") + stubheaderw.Writeln("#pragma warning(pop)") + stubheaderw.Writeln("#endif") + } + stubheaderw.Writeln("#endif // __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) return nil } @@ -1323,7 +1308,7 @@ func buildCPPStub(component ComponentDefinition, NameSpace string, NameSpaceImpl for i := 0; i < len(component.Classes); i++ { class := component.Classes[i] - err := buildCPPStubClass(component, class, NameSpace, NameSpaceImplementation, ClassIdentifier, BaseName, outputFolder, indentString, stubIdentifier, forceRecreation) + err := buildCPPStubClass(component, class, NameSpace, NameSpaceImplementation, ClassIdentifier, BaseName, outputFolder, indentString, stubIdentifier, forceRecreation) if err != nil { return err } @@ -1332,42 +1317,42 @@ func buildCPPStub(component ComponentDefinition, NameSpace string, NameSpaceImpl return nil } -func getCppVariableName (param ComponentDefinitionParam) (string) { - switch (param.ParamType) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": - return "n" + param.ParamName; - case "string": - return "s" + param.ParamName; - case "bool": - return "b" + param.ParamName; - case "single": - return "f" + param.ParamName; - case "basicarray", "structarray": - return "p" + param.ParamName + "Buffer"; - case "double": - return "d" + param.ParamName; - case "pointer": - return "p" + param.ParamName; - case "enum": - return "e" + param.ParamName; - case "struct": - return param.ParamName; - case "class", "optionalclass": - return "p" + param.ParamName; - case "functiontype": - return "p" + param.ParamName; - } - - log.Fatal ("Invalid parameter type: ", param.ParamType); - - return ""; +func getCppVariableName(param ComponentDefinitionParam) string { + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": + return "n" + param.ParamName + case "string": + return "s" + param.ParamName + case "bool": + return "b" + param.ParamName + case "single": + return "f" + param.ParamName + case "basicarray", "structarray": + return "p" + param.ParamName + "Buffer" + case "double": + return "d" + param.ParamName + case "pointer": + return "p" + param.ParamName + case "enum": + return "e" + param.ParamName + case "struct": + return param.ParamName + case "class", "optionalclass": + return "p" + param.ParamName + case "functiontype": + return "p" + param.ParamName + } + + log.Fatal("Invalid parameter type: ", param.ParamType) + + return "" } func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, className string, NameSpace string, ClassIdentifier string, BaseName string, indentString string, isGlobal bool, isVirtual bool, writeComment bool) (string, string, error) { parameters := "" returntype := "void" commentcode := "" - + templateimplementation := "" for k := 0; k < len(method.Params); k++ { @@ -1386,39 +1371,39 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN switch param.ParamType { case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s n%s", cppParamType, param.ParamName) case "string": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] s%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] s%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const std::string & s%s", param.ParamName) case "bool": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] b%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] b%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s b%s", cppParamType, param.ParamName) case "single": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] f%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] f%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s f%s", cppParamType, param.ParamName) case "double": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] d%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] d%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s d%s", cppParamType, param.ParamName) case "pointer": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s p%s", cppParamType, param.ParamName) case "enum": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] e%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] e%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s e%s", cppParamType, param.ParamName) case "struct": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] %s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] %s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s %s", cppParamType, param.ParamName) case "class", "optionalclass": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] p%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] p%s - %s\n", param.ParamName, param.ParamDescription) if len(paramNameSpaceCPP) > 0 { // TODO: ClassIdentifier is incorrect! get via // component.ImportedComponentDefinitions[paramNameSpace].Bindings parameters = parameters + fmt.Sprintf("%sP%s%s p%s", paramNameSpaceCPP, ClassIdentifier, paramClassNameCPP, param.ParamName) @@ -1427,17 +1412,17 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN } case "basicarray": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] p%sBuffer - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] p%sBuffer - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s_uint64 n%sBufferSize, const %s p%sBuffer", NameSpace, param.ParamName, cppParamType, param.ParamName) case "structarray": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] p%sBuffer - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] p%sBuffer - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("const %s_uint64 n%sBufferSize, const %s p%sBuffer", NameSpace, param.ParamName, cppParamType, param.ParamName) case "functiontype": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] p%s - callback function\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] p%s - callback function\n", param.ParamName) parameters = parameters + fmt.Sprintf("const %s p%s", cppParamType, param.ParamName) default: @@ -1454,58 +1439,57 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN switch param.ParamType { case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] n%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] n%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & n%s", cppParamType, param.ParamName) case "bool": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] b%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] b%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & b%s", cppParamType, param.ParamName) case "single": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] f%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] f%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & f%s", cppParamType, param.ParamName) case "double": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] d%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] d%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & d%s", cppParamType, param.ParamName) case "pointer": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] d%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] d%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & p%s", cppParamType, param.ParamName) case "string": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] s%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] s%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("std::string & s%s", param.ParamName) case "enum": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] e%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] e%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & e%s", cppParamType, param.ParamName) case "struct": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] s%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] s%s - %s\n", param.ParamName, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s & s%s", cppParamType, param.ParamName) case "basicarray": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s_uint64 n%sBufferSize, %s_uint64* p%sNeededCount, %s p%sBuffer", NameSpace, param.ParamName, NameSpace, param.ParamName, cppParamType, param.ParamName) case "structarray": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s_uint64 n%sBufferSize, %s_uint64* p%sNeededCount, %s p%sBuffer", NameSpace, param.ParamName, NameSpace, param.ParamName, cppParamType, param.ParamName) case "class", "optionalclass": - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%s - %s\n", param.ParamName, param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%s - %s\n", param.ParamName, param.ParamDescription) if len(paramNameSpaceCPP) > 0 { // TODO: ClassIdentifier is incorrect! get via // component.ImportedComponentDefinitions[paramNameSpace].Bindings parameters = parameters + fmt.Sprintf("%sP%s%s p%s", paramNameSpaceCPP, ClassIdentifier, paramClassNameCPP, param.ParamName) } else { parameters = parameters + fmt.Sprintf("I%s%s*& p%s", ClassIdentifier, param.ParamClass, param.ParamName) } - default: return "", "", fmt.Errorf("invalid method parameter type \"%s\" for %s.%s(%s)", param.ParamType, className, method.MethodName, param.ParamName) @@ -1516,10 +1500,10 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN switch param.ParamType { case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double", "pointer", "string", "enum", "struct": returntype = currentReturnType - commentcode = commentcode + fmt.Sprintf(indentString + "* @return %s\n", param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @return %s\n", param.ParamDescription) case "class", "optionalclass": - commentcode = commentcode + fmt.Sprintf(indentString + "* @return %s\n", param.ParamDescription) + commentcode = commentcode + fmt.Sprintf(indentString+"* @return %s\n", param.ParamDescription) if len(paramNameSpaceCPP) > 0 { // TODO: ClassIdentifier is incorrect! get via // component.ImportedComponentDefinitions[paramNameSpace].Bindings returntype = fmt.Sprintf("%sP%s%s", paramNameSpaceCPP, ClassIdentifier, paramClassNameCPP) @@ -1529,13 +1513,12 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN case "basicarray": cppParamType := getCppParamType(param, NameSpace, false) - - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) - commentcode = commentcode + fmt.Sprintf(indentString + "* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) + + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[in] n%sBufferSize - Number of elements in buffer\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sNeededCount - will be filled with the count of the written structs, or needed buffer size.\n", param.ParamName) + commentcode = commentcode + fmt.Sprintf(indentString+"* @param[out] p%sBuffer - %s buffer of %s\n", param.ParamName, param.ParamClass, param.ParamDescription) parameters = parameters + fmt.Sprintf("%s_uint64 n%sBufferSize, %s_uint64* p%sNeededCount, %s p%sBuffer", NameSpace, param.ParamName, NameSpace, param.ParamName, cppParamType, param.ParamName) - default: return "", "", fmt.Errorf("invalid method parameter type \"%s\" for %s.%s(%s)", param.ParamType, className, method.MethodName, param.ParamName) } @@ -1544,24 +1527,24 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN return "", "", fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s(%s)", param.ParamPass, className, method.MethodName, param.ParamName) } } - outstring := ""; - if (writeComment) { + outstring := "" + if writeComment { outstring = indentString + "/**\n" - outstring = outstring + fmt.Sprintf(indentString + "* I%s%s::%s - %s\n", ClassIdentifier, className, method.MethodName, method.MethodDescription) + outstring = outstring + fmt.Sprintf(indentString+"* I%s%s::%s - %s\n", ClassIdentifier, className, method.MethodName, method.MethodDescription) outstring = outstring + commentcode outstring = outstring + indentString + "*/\n" } - + if isGlobal { if isVirtual { return "", "", fmt.Errorf("Method \"%s\"can not be virtual static", method.MethodName) } - outstring = outstring + fmt.Sprintf(indentString + "static %s %s(%s)", returntype, method.MethodName, parameters) + outstring = outstring + fmt.Sprintf(indentString+"static %s %s(%s)", returntype, method.MethodName, parameters) } else { if isVirtual { - outstring = outstring + fmt.Sprintf(indentString + "virtual %s %s(%s) = 0", returntype, method.MethodName, parameters) + outstring = outstring + fmt.Sprintf(indentString+"virtual %s %s(%s) = 0", returntype, method.MethodName, parameters) } else { - outstring = outstring + fmt.Sprintf(indentString + "%s %s(%s) override", returntype, method.MethodName, parameters) + outstring = outstring + fmt.Sprintf(indentString+"%s %s(%s) override", returntype, method.MethodName, parameters) } } @@ -1574,55 +1557,55 @@ func buildCPPInterfaceMethodDeclaration(method ComponentDefinitionMethod, classN return outstring, templateimplementation, nil } -func getCppParamType (param ComponentDefinitionParam, NameSpace string, isInput bool) (string) { - cppClassPrefix := "C" + NameSpace; - switch (param.ParamType) { +func getCppParamType(param ComponentDefinitionParam, NameSpace string, isInput bool) string { + cppClassPrefix := "C" + NameSpace + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": + return fmt.Sprintf("%s_%s", NameSpace, param.ParamType) + case "string": + return fmt.Sprintf("std::string") + case "bool": + return fmt.Sprintf("bool") + case "pointer": + return fmt.Sprintf("%s_pvoid", NameSpace) + + case "basicarray": + cppBasicType := "" + switch param.ParamClass { case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": - return fmt.Sprintf ("%s_%s", NameSpace, param.ParamType); - case "string": - return fmt.Sprintf ("std::string"); + cppBasicType = fmt.Sprintf("%s_%s", NameSpace, param.ParamClass) case "bool": - return fmt.Sprintf ("bool"); + cppBasicType = "bool" case "pointer": - return fmt.Sprintf ("%s_pvoid", NameSpace); - - case "basicarray": - cppBasicType := ""; - switch (param.ParamClass) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": - cppBasicType = fmt.Sprintf ("%s_%s", NameSpace, param.ParamClass); - case "bool": - cppBasicType = "bool"; - case "pointer": - cppBasicType = fmt.Sprintf ("%s_pvoid", NameSpace); - default: - log.Fatal ("Invalid parameter type: ", param.ParamClass); - } - return fmt.Sprintf ("%s *", cppBasicType); - case "structarray": - return fmt.Sprintf ("%s::s%s *", NameSpace, param.ParamClass); - case "enum": - return fmt.Sprintf ("%s::e%s", NameSpace, param.ParamClass); - case "struct": - return fmt.Sprintf ("%s::s%s", NameSpace, param.ParamClass); - case "class", "optionalclass": - if (isInput) { - return fmt.Sprintf ("%s%s *", cppClassPrefix, param.ParamClass); - } - return fmt.Sprintf ("P%s", param.ParamClass); - case "functiontype": - return fmt.Sprintf ("%s::%s", NameSpace, param.ParamClass); + cppBasicType = fmt.Sprintf("%s_pvoid", NameSpace) + default: + log.Fatal("Invalid parameter type: ", param.ParamClass) + } + return fmt.Sprintf("%s *", cppBasicType) + case "structarray": + return fmt.Sprintf("%s::s%s *", NameSpace, param.ParamClass) + case "enum": + return fmt.Sprintf("%s::e%s", NameSpace, param.ParamClass) + case "struct": + return fmt.Sprintf("%s::s%s", NameSpace, param.ParamClass) + case "class", "optionalclass": + if isInput { + return fmt.Sprintf("%s%s *", cppClassPrefix, param.ParamClass) + } + return fmt.Sprintf("P%s", param.ParamClass) + case "functiontype": + return fmt.Sprintf("%s::%s", NameSpace, param.ParamClass) } - - log.Fatal ("Invalid parameter type: ", param.ParamType); - return ""; + + log.Fatal("Invalid parameter type: ", param.ParamType) + return "" } func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method ComponentDefinitionMethod, NameSpace string, ClassIdentifier string, ClassName string, BaseClassName string) ([]string, []string, []string, string, string, string, error) { preCallCode := make([]string, 0) postCallCode := make([]string, 0) callParameters := "" - outCallParameters := ""; + outCallParameters := "" returnVariable := "" checkInputCode := make([]string, 0) IBaseClassName := fmt.Sprintf("I%s%s", ClassIdentifier, BaseClassName) @@ -1664,13 +1647,13 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co preCallCode = append(preCallCode, fmt.Sprintf("%s* pIBaseClass%s = (%s *)p%s;", IBaseClassName, param.ParamName, IBaseClassName, param.ParamName)) preCallCode = append(preCallCode, fmt.Sprintf("I%s%s* pI%s = dynamic_cast<I%s%s*>(pIBaseClass%s);", ClassIdentifier, param.ParamClass, param.ParamName, ClassIdentifier, param.ParamClass, param.ParamName)) } - - if (param.ParamType == "class") { + + if param.ParamType == "class" { preCallCode = append(preCallCode, fmt.Sprintf("if (!pI%s)", param.ParamName)) preCallCode = append(preCallCode, fmt.Sprintf(" throw E%sInterfaceException (%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace))) preCallCode = append(preCallCode, "") } - + callParameters = callParameters + fmt.Sprintf("pI%s", param.ParamName) case "string": checkInputCode = append(checkInputCode, fmt.Sprintf("if (p%s == nullptr)", param.ParamName)) @@ -1693,7 +1676,6 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co outCallParameters = outCallParameters + ", " } - switch param.ParamType { case "bool", "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double", "enum", "struct", "pointer": @@ -1728,7 +1710,7 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co case "class", "optionalclass": checkInputCode = append(checkInputCode, fmt.Sprintf("if (p%s == nullptr)", param.ParamName)) checkInputCode = append(checkInputCode, fmt.Sprintf(" throw E%sInterfaceException (%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper(NameSpace))) - + paramNameSpace, paramClassName, _ := decomposeParamClassName(param.ParamClass) if len(paramNameSpace) > 0 { outVarName := fmt.Sprintf("p%s%s", paramNameSpace, param.ParamName) @@ -1736,23 +1718,22 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co theWrapper := "C" + ClassIdentifier + "Wrapper::sP" + paramNameSpace + "Wrapper" acqurireMethod := component.ImportedComponentDefinitions[paramNameSpace].Global.AcquireMethod postCallCode = append(postCallCode, fmt.Sprintf("%s->%s(%s.get());", theWrapper, acqurireMethod, outVarName)) - postCallCode = append(postCallCode, fmt.Sprintf("*%s = %s->handle();", variableName, outVarName)); + postCallCode = append(postCallCode, fmt.Sprintf("*%s = %s->handle();", variableName, outVarName)) callParameters = callParameters + outVarName outCallParameters = outCallParameters + outVarName } else { preCallCode = append(preCallCode, fmt.Sprintf("I%s* pClass%s(nullptr);", paramClassName, param.ParamName)) - postCallCode = append(postCallCode, fmt.Sprintf("*%s = (%s*)(pClass%s);", variableName, IBaseClassName, param.ParamName)); + postCallCode = append(postCallCode, fmt.Sprintf("*%s = (%s*)(pClass%s);", variableName, IBaseClassName, param.ParamName)) callParameters = callParameters + "pClass" + param.ParamName outCallParameters = fmt.Sprintf("%s pClass%s", outCallParameters, param.ParamName) } - default: return checkInputCode, preCallCode, postCallCode, "", "", "", fmt.Errorf("method parameter type \"%s\" of param pass \"%s\" is not implemented for %s::%s(%s) )", param.ParamType, param.ParamPass, ClassName, method.MethodName, param.ParamName) } case "return": - + if outCallParameters != "" { outCallParameters = outCallParameters + ", " } @@ -1764,14 +1745,14 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co checkInputCode = append(checkInputCode, fmt.Sprintf(" throw E%sInterfaceException (%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper(NameSpace))) returnVariable = fmt.Sprintf("*p%s", param.ParamName) - outCallParameters = outCallParameters + returnVariable; + outCallParameters = outCallParameters + returnVariable case "struct": checkInputCode = append(checkInputCode, fmt.Sprintf("if (p%s == nullptr)", param.ParamName)) checkInputCode = append(checkInputCode, fmt.Sprintf("throw E%sInterfaceException (%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper(NameSpace))) returnVariable = fmt.Sprintf("*p%s", param.ParamName) - outCallParameters = outCallParameters + returnVariable; + outCallParameters = outCallParameters + returnVariable case "basicarray": checkInputCode = append(checkInputCode, fmt.Sprintf("if ((!p%sBuffer) && !(p%sNeededCount))", param.ParamName, param.ParamName)) @@ -1784,7 +1765,7 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co preCallCode = append(preCallCode, fmt.Sprintf("std::string %s(\"\");", variableName)) returnVariable = variableName - outCallParameters = outCallParameters + returnVariable; + outCallParameters = outCallParameters + returnVariable postCallCode = append(postCallCode, fmt.Sprintf("if (p%sNeededChars)", param.ParamName)) postCallCode = append(postCallCode, fmt.Sprintf(" *p%sNeededChars = (%s_uint32) (%s.size()+1);", param.ParamName, NameSpace, variableName)) @@ -1807,14 +1788,13 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co acqurireMethod := component.ImportedComponentDefinitions[paramNameSpace].Global.AcquireMethod returnVariable = fmt.Sprintf("p%s%s", paramNameSpace, param.ParamName) postCallCode = append(postCallCode, fmt.Sprintf("%s->%s(p%s%s.get());", theWrapper, acqurireMethod, paramNameSpace, param.ParamName)) - postCallCode = append(postCallCode, fmt.Sprintf("*%s = p%s%s->handle();", variableName, paramNameSpace, param.ParamName)); + postCallCode = append(postCallCode, fmt.Sprintf("*%s = p%s%s->handle();", variableName, paramNameSpace, param.ParamName)) } else { preCallCode = append(preCallCode, fmt.Sprintf("%s* pBase%s(nullptr);", IBaseClassName, param.ParamName)) returnVariable = fmt.Sprintf("pBase%s", param.ParamName) - postCallCode = append(postCallCode, fmt.Sprintf("*%s = (%s*)(pBase%s);", variableName, IBaseClassName, param.ParamName)); + postCallCode = append(postCallCode, fmt.Sprintf("*%s = (%s*)(pBase%s);", variableName, IBaseClassName, param.ParamName)) } - outCallParameters = outCallParameters + returnVariable; - + outCallParameters = outCallParameters + returnVariable default: return checkInputCode, preCallCode, postCallCode, "", "", "", fmt.Errorf("invalid method parameter type \"%s\" for %s.%s(%s)", param.ParamType, ClassName, method.MethodName, param.ParamName) @@ -1842,150 +1822,148 @@ func generateCallCPPFunctionCode(method ComponentDefinitionMethod, NameSpace str return callFunctionCode, nil } - func generateJournalFunctionCode(method ComponentDefinitionMethod, NameSpace string, ClassName string, isGlobal bool) ([]string, []string, error) { - journalInitFunctionCode := make([]string,0) - journalSuccessFunctionCode := make([]string,0) - - + journalInitFunctionCode := make([]string, 0) + journalSuccessFunctionCode := make([]string, 0) + journalInitFunctionCode = append(journalInitFunctionCode, fmt.Sprintf("if (m_GlobalJournal.get() != nullptr) {")) - if (isGlobal) { + if isGlobal { journalInitFunctionCode = append(journalInitFunctionCode, fmt.Sprintf(" pJournalEntry = m_GlobalJournal->beginStaticFunction(\"%s\");", method.MethodName)) } else { journalInitFunctionCode = append(journalInitFunctionCode, fmt.Sprintf(" pJournalEntry = m_GlobalJournal->beginClassMethod(p%s, \"%s\", \"%s\");", ClassName, ClassName, method.MethodName)) } - + for k := 0; k < len(method.Params); k++ { param := method.Params[k] variableName := getCppVariableName(param) - - if (param.ParamPass == "in") { - journalCall := ""; - - switch (param.ParamType) { - case "bool": - journalCall = "addBooleanParameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "uint8": - journalCall = "addUInt8Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "uint16": - journalCall = "addUInt16Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "uint32": - journalCall = "addUInt32Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "uint64": - journalCall = "addUInt64Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "int8": - journalCall = "addInt8Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "int16": - journalCall = "addInt16Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "int32": - journalCall = "addInt32Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "int64": - journalCall = "addInt64Parameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "single": - journalCall = "addSingleParameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "double": - journalCall = "addDoubleParameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "pointer": - journalCall = "addPointerParameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "string": - journalCall = "addStringParameter(\"" + param.ParamName+ "\", p" + param.ParamName + ")"; - - case "enum": - journalCall = "addEnumParameter(\"" + param.ParamName+ "\", \"" + param.ParamClass + "\", (" + NameSpace + "_int32)(" + variableName + "))"; - - case "class", "optionalclass": - journalCall = "addHandleParameter(\"" + param.ParamName+ "\", " + variableName + ")"; - - case "struct": - case "basicarray": - case "structarray": - case "functiontype": - - default: - return journalInitFunctionCode, journalSuccessFunctionCode, fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s(%s)", param.ParamPass, ClassName, method.MethodName, param.ParamName) - + + if param.ParamPass == "in" { + journalCall := "" + + switch param.ParamType { + case "bool": + journalCall = "addBooleanParameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "uint8": + journalCall = "addUInt8Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "uint16": + journalCall = "addUInt16Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "uint32": + journalCall = "addUInt32Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "uint64": + journalCall = "addUInt64Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "int8": + journalCall = "addInt8Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "int16": + journalCall = "addInt16Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "int32": + journalCall = "addInt32Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "int64": + journalCall = "addInt64Parameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "single": + journalCall = "addSingleParameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "double": + journalCall = "addDoubleParameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "pointer": + journalCall = "addPointerParameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "string": + journalCall = "addStringParameter(\"" + param.ParamName + "\", p" + param.ParamName + ")" + + case "enum": + journalCall = "addEnumParameter(\"" + param.ParamName + "\", \"" + param.ParamClass + "\", (" + NameSpace + "_int32)(" + variableName + "))" + + case "class", "optionalclass": + journalCall = "addHandleParameter(\"" + param.ParamName + "\", " + variableName + ")" + + case "struct": + case "basicarray": + case "structarray": + case "functiontype": + + default: + return journalInitFunctionCode, journalSuccessFunctionCode, fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s(%s)", param.ParamPass, ClassName, method.MethodName, param.ParamName) + } if journalCall != "" { journalInitFunctionCode = append(journalInitFunctionCode, fmt.Sprintf(" pJournalEntry->%s;", journalCall)) } - } + } } - + journalInitFunctionCode = append(journalInitFunctionCode, fmt.Sprintf("}")) journalSuccessFunctionCode = append(journalSuccessFunctionCode, fmt.Sprintf("if (pJournalEntry.get() != nullptr) {")) for k := 0; k < len(method.Params); k++ { param := method.Params[k] - + if (param.ParamPass == "out") || (param.ParamPass == "return") { - journalCall := ""; - - switch (param.ParamType) { - case "bool": - journalCall = "addBooleanResult(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "uint8": - journalCall = "addUInt8Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "uint16": - journalCall = "addUInt16Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "uint32": - journalCall = "addUInt32Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "uint64": - journalCall = "addUInt64Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "int8": - journalCall = "addInt8Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "int16": - journalCall = "addInt16Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "int32": - journalCall = "addInt32Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "int64": - journalCall = "addInt64Result(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "single": - journalCall = "addSingleResult(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "double": - journalCall = "addDoubleResult(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "pointer": - journalCall = "addPointerResult(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "string": - journalCall = "addStringResult(\"" + param.ParamName+ "\", s" + param.ParamName + ".c_str())"; - - case "enum": - journalCall = "addEnumResult(\"" + param.ParamName+ "\", \"" + param.ParamClass + "\", (" + NameSpace + "_int32)(*p" + param.ParamName + "))"; - - case "class", "optionalclass": - journalCall = "addHandleResult(\"" + param.ParamName+ "\", *p" + param.ParamName + ")"; - - case "struct": - case "basicarray": - case "structarray": - - default: - return journalInitFunctionCode, journalSuccessFunctionCode, fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s(%s)", param.ParamPass, ClassName, method.MethodName, param.ParamName) - + journalCall := "" + + switch param.ParamType { + case "bool": + journalCall = "addBooleanResult(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "uint8": + journalCall = "addUInt8Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "uint16": + journalCall = "addUInt16Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "uint32": + journalCall = "addUInt32Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "uint64": + journalCall = "addUInt64Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "int8": + journalCall = "addInt8Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "int16": + journalCall = "addInt16Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "int32": + journalCall = "addInt32Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "int64": + journalCall = "addInt64Result(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "single": + journalCall = "addSingleResult(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "double": + journalCall = "addDoubleResult(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "pointer": + journalCall = "addPointerResult(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "string": + journalCall = "addStringResult(\"" + param.ParamName + "\", s" + param.ParamName + ".c_str())" + + case "enum": + journalCall = "addEnumResult(\"" + param.ParamName + "\", \"" + param.ParamClass + "\", (" + NameSpace + "_int32)(*p" + param.ParamName + "))" + + case "class", "optionalclass": + journalCall = "addHandleResult(\"" + param.ParamName + "\", *p" + param.ParamName + ")" + + case "struct": + case "basicarray": + case "structarray": + + default: + return journalInitFunctionCode, journalSuccessFunctionCode, fmt.Errorf("invalid method parameter passing \"%s\" for %s.%s(%s)", param.ParamPass, ClassName, method.MethodName, param.ParamName) + } if journalCall != "" { journalSuccessFunctionCode = append(journalSuccessFunctionCode, fmt.Sprintf(" pJournalEntry->%s;", journalCall)) @@ -1995,15 +1973,15 @@ func generateJournalFunctionCode(method ComponentDefinitionMethod, NameSpace str journalSuccessFunctionCode = append(journalSuccessFunctionCode, fmt.Sprintf(" pJournalEntry->writeSuccess();")) journalSuccessFunctionCode = append(journalSuccessFunctionCode, fmt.Sprintf("}")) - - return journalInitFunctionCode, journalSuccessFunctionCode, nil; + + return journalInitFunctionCode, journalSuccessFunctionCode, nil } func buildCMakeForCPPImplementation(component ComponentDefinition, w LanguageWriter, doJournal bool) { NameSpace := component.NameSpace BaseName := component.BaseName - + w.Writeln("cmake_minimum_required(VERSION 3.5)") w.Writeln("") @@ -2012,9 +1990,9 @@ func buildCMakeForCPPImplementation(component ComponentDefinition, w LanguageWri w.Writeln("") w.Writeln("set (CMAKE_CXX_STANDARD 11)") w.Writeln("") - + w.Writeln("# The location of autogenerated interfaces") - w.Writeln("set(CMAKE_CURRENT_AUTOGENERATED_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Interfaces)",) + w.Writeln("set(CMAKE_CURRENT_AUTOGENERATED_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Interfaces)") w.Writeln("") w.Writeln("file(GLOB %s_SRC", strings.ToUpper(NameSpace)) @@ -2027,7 +2005,7 @@ func buildCMakeForCPPImplementation(component ComponentDefinition, w LanguageWri w.Writeln("set(%s_SRC ${%s_SRC} ${%s_SRC}", strings.ToUpper(NameSpace), strings.ToUpper(NameSpace), strings.ToUpper(NameSpace)) w.Writeln(" ${CMAKE_CURRENT_AUTOGENERATED_DIR}/%s_interfaceexception.cpp", strings.ToLower(BaseName)) w.Writeln(" ${CMAKE_CURRENT_AUTOGENERATED_DIR}/%s_interfacewrapper.cpp", strings.ToLower(BaseName)) - if (doJournal) { + if doJournal { w.Writeln(" ${CMAKE_CURRENT_AUTOGENERATED_DIR}/%s_interfacejournal.cpp", strings.ToLower(BaseName)) } w.Writeln(")") @@ -2044,7 +2022,7 @@ func buildCMakeForCPPImplementation(component ComponentDefinition, w LanguageWri w.Writeln("target_compile_options(%s PRIVATE \"-D__%s_EXPORTS\")", targetName, strings.ToUpper(NameSpace)) w.Writeln("target_include_directories(%s PRIVATE ${CMAKE_CURRENT_AUTOGENERATED_DIR})", targetName) w.Writeln("target_include_directories(%s PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/Stub)", targetName) - for _, subComponent := range(component.ImportedComponentDefinitions) { + for _, subComponent := range component.ImportedComponentDefinitions { w.Writeln("target_include_directories(%s PRIVATE \"${CMAKE_CURRENT_SOURCE_DIR}/../../../%s_component/Bindings/CppDynamic\")", targetName, subComponent.NameSpace) } } @@ -2054,430 +2032,426 @@ func buildJournalingCPP(component ComponentDefinition, headerw LanguageWriter, i NameSpace := component.NameSpace BaseName := component.BaseName - headerw.Writeln("#ifndef __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper (NameSpace)); - headerw.Writeln("#define __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper (NameSpace)); - headerw.Writeln(""); - headerw.Writeln("#include <iostream>"); - headerw.Writeln("#include <fstream>"); - headerw.Writeln("#include <string>"); - headerw.Writeln("#include <memory>"); - headerw.Writeln("#include <list>"); - headerw.Writeln("#include <mutex>"); - headerw.Writeln("#include <chrono>"); - headerw.Writeln("#include \"%s_types.hpp\"", BaseName); - headerw.Writeln(""); - headerw.Writeln("/*************************************************************************************************************************"); - headerw.Writeln(" Class C%sInterfaceJournal ", NameSpace); - headerw.Writeln("**************************************************************************************************************************/"); - headerw.Writeln(""); - headerw.Writeln("class C%sInterfaceJournal;", NameSpace); - headerw.Writeln(""); - headerw.Writeln("class C%sInterfaceJournalEntry {", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" protected:"); - headerw.Writeln(""); - headerw.Writeln(" C%sInterfaceJournal * m_pJournal;", NameSpace); - headerw.Writeln(" %sResult m_ErrorCode;", NameSpace); - headerw.Writeln(" std::string m_sClassName;"); - headerw.Writeln(" std::string m_sMethodName;"); - headerw.Writeln(" std::string m_sInstanceHandle;"); - headerw.Writeln(" %s_uint64 m_nInitTimeStamp;", NameSpace); - headerw.Writeln(" %s_uint64 m_nFinishTimeStamp;", NameSpace); - headerw.Writeln(" std::list<std::pair<std::pair<std::string, std::string>, std::string>> m_sParameters;"); - headerw.Writeln(" std::list<std::pair<std::pair<std::string, std::string>, std::string>> m_sResultValues;"); - headerw.Writeln(""); - headerw.Writeln(" std::string getXMLString();"); - headerw.Writeln(" void addParameter (const std::string & sName, const std::string & sParameterType, const std::string & sParameterValue);"); - headerw.Writeln(" void addResult (const std::string & sName, const std::string & sResultType, const std::string & sResultValue);"); - - headerw.Writeln(""); - headerw.Writeln(" public:"); - headerw.Writeln(" C%sInterfaceJournalEntry(C%sInterfaceJournal * pJournal, std::string sClassName, std::string sMethodName, %sHandle pInstanceHandle);", NameSpace, NameSpace, NameSpace); - headerw.Writeln(" ~C%sInterfaceJournalEntry();", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" void writeSuccess ();"); - headerw.Writeln(" void writeError (%sResult nErrorCode);", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" void addBooleanParameter(const std::string & sName, const bool bValue);"); - headerw.Writeln(" void addUInt8Parameter(const std::string & sName, const %s_uint8 nValue);", NameSpace); - headerw.Writeln(" void addUInt16Parameter(const std::string & sName, const %s_uint16 nValue);", NameSpace); - headerw.Writeln(" void addUInt32Parameter(const std::string & sName, const %s_uint32 nValue);", NameSpace); - headerw.Writeln(" void addUInt64Parameter(const std::string & sName, const %s_uint64 nValue);", NameSpace); - headerw.Writeln(" void addInt8Parameter(const std::string & sName, const %s_int8 nValue);", NameSpace); - headerw.Writeln(" void addInt16Parameter(const std::string & sName, const %s_int16 nValue);", NameSpace); - headerw.Writeln(" void addInt32Parameter(const std::string & sName, const %s_int32 nValue);", NameSpace); - headerw.Writeln(" void addInt64Parameter(const std::string & sName, const %s_int64 nValue);", NameSpace); - headerw.Writeln(" void addSingleParameter(const std::string & sName, const %s_single fValue);", NameSpace); - headerw.Writeln(" void addDoubleParameter(const std::string & sName, const %s_double dValue);", NameSpace); - headerw.Writeln(" void addPointerParameter(const std::string & sName, const %s_pvoid pValue);", NameSpace); - headerw.Writeln(" void addStringParameter(const std::string & sName, const char * pValue);"); - headerw.Writeln(" void addHandleParameter(const std::string & sName, const %sHandle pHandle);", NameSpace); - headerw.Writeln(" void addEnumParameter(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue);", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" void addBooleanResult(const std::string & sName, const bool bValue);"); - headerw.Writeln(" void addUInt8Result(const std::string & sName, const %s_uint8 nValue);", NameSpace); - headerw.Writeln(" void addUInt16Result(const std::string & sName, const %s_uint16 nValue);", NameSpace); - headerw.Writeln(" void addUInt32Result(const std::string & sName, const %s_uint32 nValue);", NameSpace); - headerw.Writeln(" void addUInt64Result(const std::string & sName, const %s_uint64 nValue);", NameSpace); - headerw.Writeln(" void addInt8Result(const std::string & sName, const %s_int8 nValue);", NameSpace); - headerw.Writeln(" void addInt16Result(const std::string & sName, const %s_int16 nValue);", NameSpace); - headerw.Writeln(" void addInt32Result(const std::string & sName, const %s_int32 nValue);", NameSpace); - headerw.Writeln(" void addInt64Result(const std::string & sName, const %s_int64 nValue);", NameSpace); - headerw.Writeln(" void addSingleResult(const std::string & sName, const %s_single fValue);", NameSpace); - headerw.Writeln(" void addDoubleResult(const std::string & sName, const %s_double dValue);", NameSpace); - headerw.Writeln(" void addPointerResult(const std::string & sName, const %s_pvoid pValue);", NameSpace); - headerw.Writeln(" void addStringResult(const std::string & sName, const char * pValue);"); - headerw.Writeln(" void addHandleResult(const std::string & sName, const %sHandle pHandle);", NameSpace); - headerw.Writeln(" void addEnumResult(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue);", NameSpace); - headerw.Writeln(""); - headerw.Writeln("friend class C%sInterfaceJournal;", NameSpace); - headerw.Writeln(""); - headerw.Writeln("};"); - headerw.Writeln(""); - headerw.Writeln("typedef std::shared_ptr<C%sInterfaceJournalEntry> P%sInterfaceJournalEntry;", NameSpace, NameSpace); - headerw.Writeln(""); - headerw.Writeln(""); - headerw.Writeln(""); - - - headerw.Writeln("class C%sInterfaceJournal {", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" protected:"); - headerw.Writeln(""); - headerw.Writeln(" std::string m_sFileName;"); - headerw.Writeln(" std::mutex m_Mutex;"); - headerw.Writeln(" std::ofstream m_Stream;"); - headerw.Writeln(" std::chrono::time_point<std::chrono::high_resolution_clock> m_StartTime;"); - headerw.Writeln(" void writeEntry (C%sInterfaceJournalEntry * pEntry);", NameSpace); - headerw.Writeln(" %s_uint64 getTimeStamp ();", NameSpace); - headerw.Writeln(""); - headerw.Writeln(" public:"); - headerw.Writeln(""); - headerw.Writeln(" C%sInterfaceJournal (const std::string & sFileName);", NameSpace); - headerw.Writeln(" ~C%sInterfaceJournal ();", NameSpace); - headerw.Writeln(" P%sInterfaceJournalEntry beginClassMethod (const %sHandle pHandle, const std::string & sClassName, const std::string & sMethodName);", NameSpace, NameSpace); - headerw.Writeln(" P%sInterfaceJournalEntry beginStaticFunction (const std::string & sMethodName);", NameSpace); - headerw.Writeln(" friend class C%sInterfaceJournalEntry;", NameSpace); - headerw.Writeln("};"); - headerw.Writeln(""); - headerw.Writeln("typedef std::shared_ptr<C%sInterfaceJournal> P%sInterfaceJournal;", NameSpace, NameSpace); - headerw.Writeln(""); - headerw.Writeln("#endif // __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper (NameSpace)); - headerw.Writeln(""); - - - implw.Writeln(""); - implw.Writeln("#include <string>"); - implw.Writeln("#include <sstream>"); - implw.Writeln("#include <iomanip>"); - implw.Writeln(""); - implw.Writeln("#include \"%s_interfacejournal.hpp\"", strings.ToLower(BaseName)); - implw.Writeln("#include \"%s_interfaceexception.hpp\"", strings.ToLower(BaseName)); - implw.Writeln(""); - implw.Writeln(""); - - implw.Writeln("std::string %sHandleToHex (%sHandle pHandle)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" std::stringstream stream;"); - implw.Writeln(" stream << std::setfill('0') << std::setw(sizeof(%s_uint64) * 2)", NameSpace); - implw.Writeln(" << std::hex << (%s_uint64) pHandle;", NameSpace); - implw.Writeln(" return stream.str();"); - implw.Writeln("}"); - implw.Writeln(""); - - implw.Writeln("C%sInterfaceJournalEntry::C%sInterfaceJournalEntry(C%sInterfaceJournal * pJournal, std::string sClassName, std::string sMethodName, %sHandle pInstanceHandle)", NameSpace, NameSpace, NameSpace, NameSpace); + headerw.Writeln("#ifndef __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper(NameSpace)) + headerw.Writeln("#define __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper(NameSpace)) + headerw.Writeln("") + headerw.Writeln("#include <iostream>") + headerw.Writeln("#include <fstream>") + headerw.Writeln("#include <string>") + headerw.Writeln("#include <memory>") + headerw.Writeln("#include <list>") + headerw.Writeln("#include <mutex>") + headerw.Writeln("#include <chrono>") + headerw.Writeln("#include \"%s_types.hpp\"", BaseName) + headerw.Writeln("") + headerw.Writeln("/*************************************************************************************************************************") + headerw.Writeln(" Class C%sInterfaceJournal ", NameSpace) + headerw.Writeln("**************************************************************************************************************************/") + headerw.Writeln("") + headerw.Writeln("class C%sInterfaceJournal;", NameSpace) + headerw.Writeln("") + headerw.Writeln("class C%sInterfaceJournalEntry {", NameSpace) + headerw.Writeln("") + headerw.Writeln(" protected:") + headerw.Writeln("") + headerw.Writeln(" C%sInterfaceJournal * m_pJournal;", NameSpace) + headerw.Writeln(" %sResult m_ErrorCode;", NameSpace) + headerw.Writeln(" std::string m_sClassName;") + headerw.Writeln(" std::string m_sMethodName;") + headerw.Writeln(" std::string m_sInstanceHandle;") + headerw.Writeln(" %s_uint64 m_nInitTimeStamp;", NameSpace) + headerw.Writeln(" %s_uint64 m_nFinishTimeStamp;", NameSpace) + headerw.Writeln(" std::list<std::pair<std::pair<std::string, std::string>, std::string>> m_sParameters;") + headerw.Writeln(" std::list<std::pair<std::pair<std::string, std::string>, std::string>> m_sResultValues;") + headerw.Writeln("") + headerw.Writeln(" std::string getXMLString();") + headerw.Writeln(" void addParameter (const std::string & sName, const std::string & sParameterType, const std::string & sParameterValue);") + headerw.Writeln(" void addResult (const std::string & sName, const std::string & sResultType, const std::string & sResultValue);") + + headerw.Writeln("") + headerw.Writeln(" public:") + headerw.Writeln(" C%sInterfaceJournalEntry(C%sInterfaceJournal * pJournal, std::string sClassName, std::string sMethodName, %sHandle pInstanceHandle);", NameSpace, NameSpace, NameSpace) + headerw.Writeln(" ~C%sInterfaceJournalEntry();", NameSpace) + headerw.Writeln("") + headerw.Writeln(" void writeSuccess ();") + headerw.Writeln(" void writeError (%sResult nErrorCode);", NameSpace) + headerw.Writeln("") + headerw.Writeln(" void addBooleanParameter(const std::string & sName, const bool bValue);") + headerw.Writeln(" void addUInt8Parameter(const std::string & sName, const %s_uint8 nValue);", NameSpace) + headerw.Writeln(" void addUInt16Parameter(const std::string & sName, const %s_uint16 nValue);", NameSpace) + headerw.Writeln(" void addUInt32Parameter(const std::string & sName, const %s_uint32 nValue);", NameSpace) + headerw.Writeln(" void addUInt64Parameter(const std::string & sName, const %s_uint64 nValue);", NameSpace) + headerw.Writeln(" void addInt8Parameter(const std::string & sName, const %s_int8 nValue);", NameSpace) + headerw.Writeln(" void addInt16Parameter(const std::string & sName, const %s_int16 nValue);", NameSpace) + headerw.Writeln(" void addInt32Parameter(const std::string & sName, const %s_int32 nValue);", NameSpace) + headerw.Writeln(" void addInt64Parameter(const std::string & sName, const %s_int64 nValue);", NameSpace) + headerw.Writeln(" void addSingleParameter(const std::string & sName, const %s_single fValue);", NameSpace) + headerw.Writeln(" void addDoubleParameter(const std::string & sName, const %s_double dValue);", NameSpace) + headerw.Writeln(" void addPointerParameter(const std::string & sName, const %s_pvoid pValue);", NameSpace) + headerw.Writeln(" void addStringParameter(const std::string & sName, const char * pValue);") + headerw.Writeln(" void addHandleParameter(const std::string & sName, const %sHandle pHandle);", NameSpace) + headerw.Writeln(" void addEnumParameter(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue);", NameSpace) + headerw.Writeln("") + headerw.Writeln(" void addBooleanResult(const std::string & sName, const bool bValue);") + headerw.Writeln(" void addUInt8Result(const std::string & sName, const %s_uint8 nValue);", NameSpace) + headerw.Writeln(" void addUInt16Result(const std::string & sName, const %s_uint16 nValue);", NameSpace) + headerw.Writeln(" void addUInt32Result(const std::string & sName, const %s_uint32 nValue);", NameSpace) + headerw.Writeln(" void addUInt64Result(const std::string & sName, const %s_uint64 nValue);", NameSpace) + headerw.Writeln(" void addInt8Result(const std::string & sName, const %s_int8 nValue);", NameSpace) + headerw.Writeln(" void addInt16Result(const std::string & sName, const %s_int16 nValue);", NameSpace) + headerw.Writeln(" void addInt32Result(const std::string & sName, const %s_int32 nValue);", NameSpace) + headerw.Writeln(" void addInt64Result(const std::string & sName, const %s_int64 nValue);", NameSpace) + headerw.Writeln(" void addSingleResult(const std::string & sName, const %s_single fValue);", NameSpace) + headerw.Writeln(" void addDoubleResult(const std::string & sName, const %s_double dValue);", NameSpace) + headerw.Writeln(" void addPointerResult(const std::string & sName, const %s_pvoid pValue);", NameSpace) + headerw.Writeln(" void addStringResult(const std::string & sName, const char * pValue);") + headerw.Writeln(" void addHandleResult(const std::string & sName, const %sHandle pHandle);", NameSpace) + headerw.Writeln(" void addEnumResult(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue);", NameSpace) + headerw.Writeln("") + headerw.Writeln("friend class C%sInterfaceJournal;", NameSpace) + headerw.Writeln("") + headerw.Writeln("};") + headerw.Writeln("") + headerw.Writeln("typedef std::shared_ptr<C%sInterfaceJournalEntry> P%sInterfaceJournalEntry;", NameSpace, NameSpace) + headerw.Writeln("") + headerw.Writeln("") + headerw.Writeln("") + + headerw.Writeln("class C%sInterfaceJournal {", NameSpace) + headerw.Writeln("") + headerw.Writeln(" protected:") + headerw.Writeln("") + headerw.Writeln(" std::string m_sFileName;") + headerw.Writeln(" std::mutex m_Mutex;") + headerw.Writeln(" std::ofstream m_Stream;") + headerw.Writeln(" std::chrono::time_point<std::chrono::high_resolution_clock> m_StartTime;") + headerw.Writeln(" void writeEntry (C%sInterfaceJournalEntry * pEntry);", NameSpace) + headerw.Writeln(" %s_uint64 getTimeStamp ();", NameSpace) + headerw.Writeln("") + headerw.Writeln(" public:") + headerw.Writeln("") + headerw.Writeln(" C%sInterfaceJournal (const std::string & sFileName);", NameSpace) + headerw.Writeln(" ~C%sInterfaceJournal ();", NameSpace) + headerw.Writeln(" P%sInterfaceJournalEntry beginClassMethod (const %sHandle pHandle, const std::string & sClassName, const std::string & sMethodName);", NameSpace, NameSpace) + headerw.Writeln(" P%sInterfaceJournalEntry beginStaticFunction (const std::string & sMethodName);", NameSpace) + headerw.Writeln(" friend class C%sInterfaceJournalEntry;", NameSpace) + headerw.Writeln("};") + headerw.Writeln("") + headerw.Writeln("typedef std::shared_ptr<C%sInterfaceJournal> P%sInterfaceJournal;", NameSpace, NameSpace) + headerw.Writeln("") + headerw.Writeln("#endif // __%s_INTERFACEJOURNAL_HEADER", strings.ToUpper(NameSpace)) + headerw.Writeln("") + + implw.Writeln("") + implw.Writeln("#include <string>") + implw.Writeln("#include <sstream>") + implw.Writeln("#include <iomanip>") + implw.Writeln("") + implw.Writeln("#include \"%s_interfacejournal.hpp\"", strings.ToLower(BaseName)) + implw.Writeln("#include \"%s_interfaceexception.hpp\"", strings.ToLower(BaseName)) + implw.Writeln("") + implw.Writeln("") + + implw.Writeln("std::string %sHandleToHex (%sHandle pHandle)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" std::stringstream stream;") + implw.Writeln(" stream << std::setfill('0') << std::setw(sizeof(%s_uint64) * 2)", NameSpace) + implw.Writeln(" << std::hex << (%s_uint64) pHandle;", NameSpace) + implw.Writeln(" return stream.str();") + implw.Writeln("}") + implw.Writeln("") + + implw.Writeln("C%sInterfaceJournalEntry::C%sInterfaceJournalEntry(C%sInterfaceJournal * pJournal, std::string sClassName, std::string sMethodName, %sHandle pInstanceHandle)", NameSpace, NameSpace, NameSpace, NameSpace) implw.Writeln(" : m_pJournal(pJournal), m_ErrorCode(%s_SUCCESS), m_sClassName(sClassName), m_sMethodName(sMethodName), m_nInitTimeStamp(0), m_nFinishTimeStamp(0)", strings.ToUpper(NameSpace)) - implw.Writeln("{"); - implw.Writeln(" if (pJournal == nullptr)"); - implw.Writeln(" throw E%sInterfaceException(%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper (NameSpace)); - implw.Writeln(" m_nInitTimeStamp = m_pJournal->getTimeStamp ();"); - implw.Writeln(" m_sInstanceHandle = %sHandleToHex (pInstanceHandle);", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("C%sInterfaceJournalEntry::~C%sInterfaceJournalEntry()", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addParameter(const std::string & sName, const std::string & sParameterType, const std::string & sParameterValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" m_sParameters.push_back(std::make_pair(std::make_pair(sName, sParameterType), sParameterValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addResult(const std::string & sName, const std::string & sResultType, const std::string & sResultValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" m_sResultValues.push_back(std::make_pair(std::make_pair(sName, sResultType), sResultValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("std::string C%sInterfaceJournalEntry::getXMLString()", NameSpace); - implw.Writeln("{"); - implw.Writeln(" std::stringstream sStream;"); - implw.Writeln(" %s_uint64 nDuration = 0;", NameSpace); - implw.Writeln(""); - implw.Writeln(" if (m_nFinishTimeStamp > m_nInitTimeStamp)"); - implw.Writeln(" nDuration = m_nFinishTimeStamp - m_nInitTimeStamp;"); - implw.Writeln(""); - implw.Writeln(" sStream << \" <entry\";"); - implw.Writeln(" if (m_sClassName != \"\")"); - implw.Writeln(" sStream << \" class=\\\"\" << m_sClassName << \"\\\"\";"); - implw.Writeln(" sStream << \" method=\\\"\" << m_sMethodName << \"\\\"\";"); - implw.Writeln(" if (m_ErrorCode != %s_SUCCESS)", strings.ToUpper (NameSpace)); - implw.Writeln(" sStream << \" errorcode=\\\"\" << m_ErrorCode << \"\\\"\";"); - implw.Writeln(" sStream << \" timestamp=\\\"\" << m_nInitTimeStamp << \"\\\" duration=\\\"\" << nDuration << \"\\\">\\n\";"); - implw.Writeln(""); - implw.Writeln(" if (m_sClassName != \"\")"); - implw.Writeln(" sStream << \" <instance handle=\\\"\" << m_sInstanceHandle << \"\\\" />\\n\";"); - implw.Writeln(""); - implw.Writeln(" auto iParamIter = m_sParameters.begin();"); - implw.Writeln(" while (iParamIter != m_sParameters.end()) {"); - implw.Writeln(" sStream << \" <parameter name=\\\"\" << iParamIter->first.first << \"\\\" type=\\\"\" << iParamIter->first.second << \"\\\" value=\\\"\" << iParamIter->second <<\"\\\" />\\n\";"); - implw.Writeln(" iParamIter++;"); - implw.Writeln(" }"); - implw.Writeln(""); - implw.Writeln(" auto iResultIter = m_sResultValues.begin();",); - implw.Writeln(" while (iResultIter != m_sResultValues.end()) {"); - implw.Writeln(" sStream << \" <result name=\\\"\" << iResultIter->first.first << \"\\\" type=\\\"\" << iResultIter->first.second << \"\\\" value=\\\"\" << iResultIter->second << \"\\\" />\\n\";"); - implw.Writeln(" iResultIter++;"); - implw.Writeln(" }"); - implw.Writeln(""); - implw.Writeln(" sStream << \" </entry>\\n\";"); - implw.Writeln(" return sStream.str ();"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::writeSuccess()", NameSpace); - implw.Writeln("{"); - implw.Writeln(" writeError(%s_SUCCESS);", strings.ToUpper (NameSpace)); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::writeError(%sResult nErrorCode)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" m_ErrorCode = nErrorCode;"); - implw.Writeln(" m_nFinishTimeStamp = m_pJournal->getTimeStamp();"); - implw.Writeln(" m_pJournal->writeEntry(this);"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addBooleanParameter(const std::string & sName, const bool bValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter (sName, \"bool\", std::to_string((int)bValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt8Parameter(const std::string & sName, const %s_uint8 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"uint8\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt16Parameter(const std::string & sName, const %s_uint16 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"uint16\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt32Parameter(const std::string & sName, const %s_uint32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"uint32\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt64Parameter(const std::string & sName, const %s_uint64 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"uint64\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt8Parameter(const std::string & sName, const %s_int8 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"int8\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt16Parameter(const std::string & sName, const %s_int16 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"int16\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt32Parameter(const std::string & sName, const %s_int32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"uint32\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt64Parameter(const std::string & sName, const %s_int64 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"int64\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addSingleParameter(const std::string & sName, const %s_single fValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"single\", std::to_string(fValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addDoubleParameter(const std::string & sName, const %s_double dValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"double\", std::to_string(dValue));"); - implw.Writeln("}"); - implw.Writeln("void C%sInterfaceJournalEntry::addPointerParameter(const std::string & sName, const %s_pvoid pValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"pointer\", std::to_string(reinterpret_cast<const %s_uint64>(pValue)));", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addStringParameter(const std::string & sName, const char * pValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" if (pValue != nullptr) {"); - implw.Writeln(" addParameter(sName, \"string\", pValue);"); - implw.Writeln(" }"); - implw.Writeln(" else {"); - implw.Writeln(" addParameter(sName, \"nullstring\", \"\");"); - implw.Writeln(" }"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addHandleParameter(const std::string & sName, const %sHandle pHandle)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"handle\", %sHandleToHex(pHandle));", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addEnumParameter(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addParameter(sName, \"enum\" + sEnumType, std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addBooleanResult(const std::string & sName, const bool bValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"bool\", std::to_string((int)bValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt8Result(const std::string & sName, const %s_uint8 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"uint8\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt16Result(const std::string & sName, const %s_uint16 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"uint16\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt32Result(const std::string & sName, const %s_uint32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"uint32\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addUInt64Result(const std::string & sName, const %s_uint64 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"uint64\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt8Result(const std::string & sName, const %s_int8 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"int8\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt16Result(const std::string & sName, const %s_int16 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"int16\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt32Result(const std::string & sName, const %s_int32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"uint32\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addInt64Result(const std::string & sName, const %s_int64 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"int64\", std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addSingleResult(const std::string & sName, const %s_single fValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"single\", std::to_string(fValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addDoubleResult(const std::string & sName, const %s_double dValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"double\", std::to_string(dValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addPointerResult(const std::string & sName, const %s_pvoid pValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"pointer\", std::to_string(reinterpret_cast<const %s_uint64>(pValue)));", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addStringResult(const std::string & sName, const char * pValue)", NameSpace); - implw.Writeln("{"); - implw.Writeln(" if (pValue != nullptr) {"); - implw.Writeln(" addResult(sName, \"string\", pValue);"); - implw.Writeln(" }"); - implw.Writeln(" else {"); - implw.Writeln(" addResult(sName, \"nullstring\", \"\");"); - implw.Writeln(" }"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addHandleResult(const std::string & sName, const %sHandle pHandle)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"handle\", %sHandleToHex(pHandle));", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournalEntry::addEnumResult(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" addResult(sName, \"enum\" + sEnumType, std::to_string(nValue));"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln(""); - implw.Writeln("C%sInterfaceJournal::C%sInterfaceJournal (const std::string & sFileName)", NameSpace, NameSpace); - implw.Writeln(" : m_sFileName (sFileName)"); - implw.Writeln("{"); - implw.Writeln(" m_StartTime = std::chrono::high_resolution_clock::now();"); - implw.Writeln(" m_Stream.open (sFileName, std::ios::out);"); - implw.Writeln(" m_Stream << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\";"); + implw.Writeln("{") + implw.Writeln(" if (pJournal == nullptr)") + implw.Writeln(" throw E%sInterfaceException(%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper(NameSpace)) + implw.Writeln(" m_nInitTimeStamp = m_pJournal->getTimeStamp ();") + implw.Writeln(" m_sInstanceHandle = %sHandleToHex (pInstanceHandle);", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("C%sInterfaceJournalEntry::~C%sInterfaceJournalEntry()", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addParameter(const std::string & sName, const std::string & sParameterType, const std::string & sParameterValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" m_sParameters.push_back(std::make_pair(std::make_pair(sName, sParameterType), sParameterValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addResult(const std::string & sName, const std::string & sResultType, const std::string & sResultValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" m_sResultValues.push_back(std::make_pair(std::make_pair(sName, sResultType), sResultValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("std::string C%sInterfaceJournalEntry::getXMLString()", NameSpace) + implw.Writeln("{") + implw.Writeln(" std::stringstream sStream;") + implw.Writeln(" %s_uint64 nDuration = 0;", NameSpace) + implw.Writeln("") + implw.Writeln(" if (m_nFinishTimeStamp > m_nInitTimeStamp)") + implw.Writeln(" nDuration = m_nFinishTimeStamp - m_nInitTimeStamp;") + implw.Writeln("") + implw.Writeln(" sStream << \" <entry\";") + implw.Writeln(" if (m_sClassName != \"\")") + implw.Writeln(" sStream << \" class=\\\"\" << m_sClassName << \"\\\"\";") + implw.Writeln(" sStream << \" method=\\\"\" << m_sMethodName << \"\\\"\";") + implw.Writeln(" if (m_ErrorCode != %s_SUCCESS)", strings.ToUpper(NameSpace)) + implw.Writeln(" sStream << \" errorcode=\\\"\" << m_ErrorCode << \"\\\"\";") + implw.Writeln(" sStream << \" timestamp=\\\"\" << m_nInitTimeStamp << \"\\\" duration=\\\"\" << nDuration << \"\\\">\\n\";") + implw.Writeln("") + implw.Writeln(" if (m_sClassName != \"\")") + implw.Writeln(" sStream << \" <instance handle=\\\"\" << m_sInstanceHandle << \"\\\" />\\n\";") + implw.Writeln("") + implw.Writeln(" auto iParamIter = m_sParameters.begin();") + implw.Writeln(" while (iParamIter != m_sParameters.end()) {") + implw.Writeln(" sStream << \" <parameter name=\\\"\" << iParamIter->first.first << \"\\\" type=\\\"\" << iParamIter->first.second << \"\\\" value=\\\"\" << iParamIter->second <<\"\\\" />\\n\";") + implw.Writeln(" iParamIter++;") + implw.Writeln(" }") + implw.Writeln("") + implw.Writeln(" auto iResultIter = m_sResultValues.begin();") + implw.Writeln(" while (iResultIter != m_sResultValues.end()) {") + implw.Writeln(" sStream << \" <result name=\\\"\" << iResultIter->first.first << \"\\\" type=\\\"\" << iResultIter->first.second << \"\\\" value=\\\"\" << iResultIter->second << \"\\\" />\\n\";") + implw.Writeln(" iResultIter++;") + implw.Writeln(" }") + implw.Writeln("") + implw.Writeln(" sStream << \" </entry>\\n\";") + implw.Writeln(" return sStream.str ();") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::writeSuccess()", NameSpace) + implw.Writeln("{") + implw.Writeln(" writeError(%s_SUCCESS);", strings.ToUpper(NameSpace)) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::writeError(%sResult nErrorCode)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" m_ErrorCode = nErrorCode;") + implw.Writeln(" m_nFinishTimeStamp = m_pJournal->getTimeStamp();") + implw.Writeln(" m_pJournal->writeEntry(this);") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addBooleanParameter(const std::string & sName, const bool bValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter (sName, \"bool\", std::to_string((int)bValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt8Parameter(const std::string & sName, const %s_uint8 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"uint8\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt16Parameter(const std::string & sName, const %s_uint16 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"uint16\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt32Parameter(const std::string & sName, const %s_uint32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"uint32\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt64Parameter(const std::string & sName, const %s_uint64 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"uint64\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt8Parameter(const std::string & sName, const %s_int8 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"int8\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt16Parameter(const std::string & sName, const %s_int16 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"int16\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt32Parameter(const std::string & sName, const %s_int32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"uint32\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt64Parameter(const std::string & sName, const %s_int64 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"int64\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addSingleParameter(const std::string & sName, const %s_single fValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"single\", std::to_string(fValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addDoubleParameter(const std::string & sName, const %s_double dValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"double\", std::to_string(dValue));") + implw.Writeln("}") + implw.Writeln("void C%sInterfaceJournalEntry::addPointerParameter(const std::string & sName, const %s_pvoid pValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"pointer\", std::to_string(reinterpret_cast<const %s_uint64>(pValue)));", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addStringParameter(const std::string & sName, const char * pValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" if (pValue != nullptr) {") + implw.Writeln(" addParameter(sName, \"string\", pValue);") + implw.Writeln(" }") + implw.Writeln(" else {") + implw.Writeln(" addParameter(sName, \"nullstring\", \"\");") + implw.Writeln(" }") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addHandleParameter(const std::string & sName, const %sHandle pHandle)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"handle\", %sHandleToHex(pHandle));", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addEnumParameter(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addParameter(sName, \"enum\" + sEnumType, std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addBooleanResult(const std::string & sName, const bool bValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"bool\", std::to_string((int)bValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt8Result(const std::string & sName, const %s_uint8 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"uint8\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt16Result(const std::string & sName, const %s_uint16 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"uint16\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt32Result(const std::string & sName, const %s_uint32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"uint32\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addUInt64Result(const std::string & sName, const %s_uint64 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"uint64\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt8Result(const std::string & sName, const %s_int8 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"int8\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt16Result(const std::string & sName, const %s_int16 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"int16\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt32Result(const std::string & sName, const %s_int32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"uint32\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addInt64Result(const std::string & sName, const %s_int64 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"int64\", std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addSingleResult(const std::string & sName, const %s_single fValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"single\", std::to_string(fValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addDoubleResult(const std::string & sName, const %s_double dValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"double\", std::to_string(dValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addPointerResult(const std::string & sName, const %s_pvoid pValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"pointer\", std::to_string(reinterpret_cast<const %s_uint64>(pValue)));", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addStringResult(const std::string & sName, const char * pValue)", NameSpace) + implw.Writeln("{") + implw.Writeln(" if (pValue != nullptr) {") + implw.Writeln(" addResult(sName, \"string\", pValue);") + implw.Writeln(" }") + implw.Writeln(" else {") + implw.Writeln(" addResult(sName, \"nullstring\", \"\");") + implw.Writeln(" }") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addHandleResult(const std::string & sName, const %sHandle pHandle)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"handle\", %sHandleToHex(pHandle));", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournalEntry::addEnumResult(const std::string & sName, const std::string & sEnumType, const %s_int32 nValue)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" addResult(sName, \"enum\" + sEnumType, std::to_string(nValue));") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("") + implw.Writeln("C%sInterfaceJournal::C%sInterfaceJournal (const std::string & sFileName)", NameSpace, NameSpace) + implw.Writeln(" : m_sFileName (sFileName)") + implw.Writeln("{") + implw.Writeln(" m_StartTime = std::chrono::high_resolution_clock::now();") + implw.Writeln(" m_Stream.open (sFileName, std::ios::out);") + implw.Writeln(" m_Stream << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n\";") implw.Writeln(" m_Stream << \"<journal library=\\\"%s\\\" version=\\\"%s\\\" xmlns=\\\"http://schemas.autodesk.com/components/%s/%s\\\">\\n\";", - NameSpace, component.Version, NameSpace, component.Version); - implw.Writeln(" m_Stream << \"\\n\";"); - implw.Writeln(""); - - - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("C%sInterfaceJournal::~C%sInterfaceJournal ()", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" m_Stream << \"</journal>\\n\";"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("P%sInterfaceJournalEntry C%sInterfaceJournal::beginClassMethod(const %sHandle pHandle, const std::string & sClassName, const std::string & sMethodName)", NameSpace, NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" return std::make_shared<C%sInterfaceJournalEntry>(this, sClassName, sMethodName, pHandle);", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("P%sInterfaceJournalEntry C%sInterfaceJournal::beginStaticFunction(const std::string & sMethodName)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" return std::make_shared<C%sInterfaceJournalEntry>(this, \"\", sMethodName, nullptr);", NameSpace); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("void C%sInterfaceJournal::writeEntry (C%sInterfaceJournalEntry * pEntry)", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" if (pEntry == nullptr)"); - implw.Writeln(" throw E%sInterfaceException (%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper (NameSpace)); - implw.Writeln(""); - implw.Writeln(" std::string sXMLString = pEntry->getXMLString();"); - implw.Writeln(" m_Mutex.lock();"); - implw.Writeln(" try {"); - implw.Writeln(" m_Stream << sXMLString;"); - implw.Writeln(" m_Stream << \"\\n\";"); - implw.Writeln(""); - implw.Writeln(" m_Mutex.unlock();"); - implw.Writeln(" }"); - implw.Writeln(" catch (...) {"); - implw.Writeln(" m_Mutex.unlock();"); - implw.Writeln(" }"); - implw.Writeln("}"); - implw.Writeln(""); - implw.Writeln("%s_uint64 C%sInterfaceJournal::getTimeStamp ()", NameSpace, NameSpace); - implw.Writeln("{"); - implw.Writeln(" auto currentTime = std::chrono::high_resolution_clock::now();"); - implw.Writeln(" if (m_StartTime < currentTime) {"); - implw.Writeln(" auto duration = currentTime - m_StartTime;"); - implw.Writeln(" auto milliSeconds = std::chrono::duration_cast<std::chrono::milliseconds> (duration);"); - implw.Writeln(""); - implw.Writeln(" return (%s_uint64) milliSeconds.count();", NameSpace); - implw.Writeln(" }"); - implw.Writeln(" else {"); - implw.Writeln(" return 0;"); - implw.Writeln(" }"); - implw.Writeln(""); - implw.Writeln("}"); - implw.Writeln(""); - - return nil; -} + NameSpace, component.Version, NameSpace, component.Version) + implw.Writeln(" m_Stream << \"\\n\";") + implw.Writeln("") + + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("C%sInterfaceJournal::~C%sInterfaceJournal ()", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" m_Stream << \"</journal>\\n\";") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("P%sInterfaceJournalEntry C%sInterfaceJournal::beginClassMethod(const %sHandle pHandle, const std::string & sClassName, const std::string & sMethodName)", NameSpace, NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" return std::make_shared<C%sInterfaceJournalEntry>(this, sClassName, sMethodName, pHandle);", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("P%sInterfaceJournalEntry C%sInterfaceJournal::beginStaticFunction(const std::string & sMethodName)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" return std::make_shared<C%sInterfaceJournalEntry>(this, \"\", sMethodName, nullptr);", NameSpace) + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("void C%sInterfaceJournal::writeEntry (C%sInterfaceJournalEntry * pEntry)", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" if (pEntry == nullptr)") + implw.Writeln(" throw E%sInterfaceException (%s_ERROR_INVALIDPARAM);", NameSpace, strings.ToUpper(NameSpace)) + implw.Writeln("") + implw.Writeln(" std::string sXMLString = pEntry->getXMLString();") + implw.Writeln(" m_Mutex.lock();") + implw.Writeln(" try {") + implw.Writeln(" m_Stream << sXMLString;") + implw.Writeln(" m_Stream << \"\\n\";") + implw.Writeln("") + implw.Writeln(" m_Mutex.unlock();") + implw.Writeln(" }") + implw.Writeln(" catch (...) {") + implw.Writeln(" m_Mutex.unlock();") + implw.Writeln(" }") + implw.Writeln("}") + implw.Writeln("") + implw.Writeln("%s_uint64 C%sInterfaceJournal::getTimeStamp ()", NameSpace, NameSpace) + implw.Writeln("{") + implw.Writeln(" auto currentTime = std::chrono::high_resolution_clock::now();") + implw.Writeln(" if (m_StartTime < currentTime) {") + implw.Writeln(" auto duration = currentTime - m_StartTime;") + implw.Writeln(" auto milliSeconds = std::chrono::duration_cast<std::chrono::milliseconds> (duration);") + implw.Writeln("") + implw.Writeln(" return (%s_uint64) milliSeconds.count();", NameSpace) + implw.Writeln(" }") + implw.Writeln(" else {") + implw.Writeln(" return 0;") + implw.Writeln(" }") + implw.Writeln("") + implw.Writeln("}") + implw.Writeln("") + return nil +} diff --git a/Source/buildimplementationjs.go b/Source/buildimplementationjs.go index c9feb1c7..09c66c55 100644 --- a/Source/buildimplementationjs.go +++ b/Source/buildimplementationjs.go @@ -45,11 +45,11 @@ import ( // BuildImplementationJS builds C++ interface classes, implementation stubs and wrapper code that maps to the C-header func BuildImplementationJS(component ComponentDefinition, outputFolder string, stubOutputFolder string, projectOutputFolder string, implementation ComponentDefinitionImplementation, suppressStub bool, suppressInterfaces bool, outputFolderDocumentation string) error { - doJournal := len (component.Global.JournalMethod) > 0; - - NameSpace := component.NameSpace; - LibraryName := component.LibraryName; - BaseName := component.BaseName; + doJournal := len(component.Global.JournalMethod) > 0 + + NameSpace := component.NameSpace + LibraryName := component.LibraryName + BaseName := component.BaseName ImplementationSubNameSpace := "Impl" log.Printf("Creating JavaScript Implementation") @@ -60,11 +60,11 @@ func BuildImplementationJS(component ComponentDefinition, outputFolder string, s stubIdentifier = "_" + strings.ToLower(implementation.StubIdentifier) } - if (!suppressInterfaces) { + if !suppressInterfaces { - IntfExceptionHeaderName := path.Join(outputFolder, BaseName+"_interfaceexception.hpp"); + IntfExceptionHeaderName := path.Join(outputFolder, BaseName+"_interfaceexception.hpp") log.Printf("Creating \"%s\"", IntfExceptionHeaderName) - hInternalExceptionHeaderFile, err := CreateLanguageFile (IntfExceptionHeaderName, indentString) + hInternalExceptionHeaderFile, err := CreateLanguageFile(IntfExceptionHeaderName, indentString) if err != nil { return err } @@ -72,9 +72,9 @@ func BuildImplementationJS(component ComponentDefinition, outputFolder string, s fmt.Sprintf("This is an autogenerated C++ Header file with the basic internal\n exception type in order to allow an easy use of %s", LibraryName), true) - IntfExceptionImplName := path.Join(outputFolder, BaseName+"_interfaceexception.cpp"); + IntfExceptionImplName := path.Join(outputFolder, BaseName+"_interfaceexception.cpp") log.Printf("Creating \"%s\"", IntfExceptionImplName) - hInternalExceptionImplFile, err := CreateLanguageFile (IntfExceptionImplName, indentString) + hInternalExceptionImplFile, err := CreateLanguageFile(IntfExceptionImplName, indentString) if err != nil { return err } @@ -82,14 +82,14 @@ func BuildImplementationJS(component ComponentDefinition, outputFolder string, s fmt.Sprintf("This is an autogenerated C++ Implementation file with the basic internal\n exception type in order to allow an easy use of %s", LibraryName), true) - err = buildCPPInternalException(hInternalExceptionHeaderFile, hInternalExceptionImplFile, NameSpace, BaseName ) + err = buildCPPInternalException(hInternalExceptionHeaderFile, hInternalExceptionImplFile, NameSpace, BaseName) if err != nil { return err } - IntfHeaderName := path.Join(outputFolder, BaseName+"_interfaces.hpp"); + IntfHeaderName := path.Join(outputFolder, BaseName+"_interfaces.hpp") log.Printf("Creating \"%s\"", IntfHeaderName) - interfaceshppfile, err := CreateLanguageFile (IntfHeaderName, indentString) + interfaceshppfile, err := CreateLanguageFile(IntfHeaderName, indentString) if err != nil { return err } @@ -101,7 +101,7 @@ func BuildImplementationJS(component ComponentDefinition, outputFolder string, s return err } - IntfWrapperImplName := path.Join(outputFolder, BaseName+"_interfacewrapper.cpp"); + IntfWrapperImplName := path.Join(outputFolder, BaseName+"_interfacewrapper.cpp") log.Printf("Creating \"%s\"", IntfWrapperImplName) cppWrapperfile, err := CreateLanguageFile(IntfWrapperImplName, indentString) if err != nil { @@ -115,18 +115,18 @@ func BuildImplementationJS(component ComponentDefinition, outputFolder string, s return err } - if (doJournal) { - IntfJournalHeaderName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.hpp"); + if doJournal { + IntfJournalHeaderName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.hpp") log.Printf("Creating \"%s\"", IntfJournalHeaderName) - interfacejournalhppfile, err := CreateLanguageFile (IntfJournalHeaderName, indentString) + interfacejournalhppfile, err := CreateLanguageFile(IntfJournalHeaderName, indentString) if err != nil { return err } interfacejournalhppfile.WriteCLicenseHeader(component, fmt.Sprintf("This is an autogenerated C++ header file in order to allow easy\ndevelopment of %s. It provides an automatic Journaling mechanism for the library implementation.", LibraryName), true) - - IntfJournalImplName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.cpp"); + + IntfJournalImplName := path.Join(outputFolder, strings.ToLower(BaseName)+"_interfacejournal.cpp") log.Printf("Creating \"%s\"", IntfJournalImplName) interfacejournalcppfile, err := CreateLanguageFile(IntfJournalImplName, indentString) if err != nil { @@ -135,629 +135,611 @@ func BuildImplementationJS(component ComponentDefinition, outputFolder string, s interfacejournalcppfile.WriteCLicenseHeader(component, fmt.Sprintf("This is an autogenerated C++ implementation file in order to allow easy\ndevelopment of %s. It provides an automatic Journaling mechanism for the library implementation.", LibraryName), true) - + err = buildJournalingCPP(component, interfacejournalhppfile, interfacejournalcppfile) if err != nil { return err } } - + } - - + //if (!suppressStub) { - err := buildJSTypesFiles (component, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier); - if err != nil { - return err - } - - for _, subComponent := range(component.ImportedComponentDefinitions) { - - for i := 0; i < len(subComponent.Classes); i++ { - class := subComponent.Classes[i] - err := buildJSInjectionClass (component, subComponent, class, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier); - if err != nil { - return err - } + err := buildJSTypesFiles(component, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier) + if err != nil { + return err + } + + for _, subComponent := range component.ImportedComponentDefinitions { + + for i := 0; i < len(subComponent.Classes); i++ { + class := subComponent.Classes[i] + err := buildJSInjectionClass(component, subComponent, class, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier) + if err != nil { + return err } - } - + + } + //} - - if (outputFolderDocumentation != "") { + + if outputFolderDocumentation != "" { err = BuildJSDocumentation(component, outputFolderDocumentation, implementation.ClassIdentifier) if err != nil { return err } - - } + } return nil } func buildJSTypesFiles(component ComponentDefinition, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string) error { - TypesDefinitionFileName := path.Join(outputFolder, BaseName + stubIdentifier + "_v8types.hpp"); - ClassDefinitionFileName := path.Join(outputFolder, BaseName + stubIdentifier + "_v8classes.hpp"); + TypesDefinitionFileName := path.Join(outputFolder, BaseName+stubIdentifier+"_v8types.hpp") + ClassDefinitionFileName := path.Join(outputFolder, BaseName+stubIdentifier+"_v8classes.hpp") - log.Printf("Creating \"%s\"", TypesDefinitionFileName) - typesdefinitionw, err := CreateLanguageFile(TypesDefinitionFileName, indentString) - if err != nil { - return err - } - typesdefinitionw.WriteCLicenseHeader(component, - "JavaScript injection type definitions", false); - - log.Printf("Creating \"%s\"", ClassDefinitionFileName) - classdefinitionw, err := CreateLanguageFile(ClassDefinitionFileName, indentString) - if err != nil { - return err - } - classdefinitionw.WriteCLicenseHeader(component, - "JavaScript injection class definitions", false); - - typesdefinitionw.Writeln("") - typesdefinitionw.Writeln("#ifndef __%s_V8TYPES", strings.ToUpper(NameSpace)) - typesdefinitionw.Writeln("#define __%s_V8TYPES", strings.ToUpper(NameSpace)) - typesdefinitionw.Writeln("") - typesdefinitionw.Writeln("#include <stdint.h>") - typesdefinitionw.Writeln("") - - typeEnumID := 1; - - typesdefinitionw.Writeln("namespace v8%s {", NameSpace ); - typesdefinitionw.Writeln(" namespace %s {", NameSpaceImplementation ); - typesdefinitionw.Writeln("") - typesdefinitionw.Writeln(" enum class eInjectionClassType {") - typesdefinitionw.Writeln(" e_Injection_Invalid = 0," ) - for _, subComponent := range(component.ImportedComponentDefinitions) { - - for i := 0; i < len(subComponent.Classes); i++ { - class := subComponent.Classes[i] - typesdefinitionw.Writeln(" e_v8%s_%s = %d,", subComponent.NameSpace, class.ClassName, typeEnumID); - typeEnumID = typeEnumID + 1; - } - - - } - typesdefinitionw.Writeln(" e_Injection_enumMax" ) - typesdefinitionw.Writeln(" };") - typesdefinitionw.Writeln("") - typesdefinitionw.Writeln(" }") - typesdefinitionw.Writeln("}") - typesdefinitionw.Writeln("") - typesdefinitionw.Writeln("#endif // __%s_V8TYPES", strings.ToUpper(NameSpace)) - typesdefinitionw.Writeln("") - - - + log.Printf("Creating \"%s\"", TypesDefinitionFileName) + typesdefinitionw, err := CreateLanguageFile(TypesDefinitionFileName, indentString) + if err != nil { + return err + } + typesdefinitionw.WriteCLicenseHeader(component, + "JavaScript injection type definitions", false) - classdefinitionw.Writeln("") - classdefinitionw.Writeln("#ifndef __%s_V8CLASSES", strings.ToUpper(NameSpace)) - classdefinitionw.Writeln("#define __%s_V8CLASSES", strings.ToUpper(NameSpace)) - classdefinitionw.Writeln("") - for _, subComponent := range(component.ImportedComponentDefinitions) { - - for i := 0; i < len(subComponent.Classes); i++ { - class := subComponent.Classes[i] - classdefinitionw.Writeln("#include \"%s_v8_%s_%s.hpp\"", component.BaseName + stubIdentifier, subComponent.BaseName, strings.ToLower(class.ClassName)) - } - + log.Printf("Creating \"%s\"", ClassDefinitionFileName) + classdefinitionw, err := CreateLanguageFile(ClassDefinitionFileName, indentString) + if err != nil { + return err + } + classdefinitionw.WriteCLicenseHeader(component, + "JavaScript injection class definitions", false) + + typesdefinitionw.Writeln("") + typesdefinitionw.Writeln("#ifndef __%s_V8TYPES", strings.ToUpper(NameSpace)) + typesdefinitionw.Writeln("#define __%s_V8TYPES", strings.ToUpper(NameSpace)) + typesdefinitionw.Writeln("") + typesdefinitionw.Writeln("#include <stdint.h>") + typesdefinitionw.Writeln("") + + typeEnumID := 1 + + typesdefinitionw.Writeln("namespace v8%s {", NameSpace) + typesdefinitionw.Writeln(" namespace %s {", NameSpaceImplementation) + typesdefinitionw.Writeln("") + typesdefinitionw.Writeln(" enum class eInjectionClassType {") + typesdefinitionw.Writeln(" e_Injection_Invalid = 0,") + for _, subComponent := range component.ImportedComponentDefinitions { + + for i := 0; i < len(subComponent.Classes); i++ { + class := subComponent.Classes[i] + typesdefinitionw.Writeln(" e_v8%s_%s = %d,", subComponent.NameSpace, class.ClassName, typeEnumID) + typeEnumID = typeEnumID + 1 } - classdefinitionw.Writeln("") - classdefinitionw.Writeln("namespace v8%s {", NameSpace ); - classdefinitionw.Writeln(" namespace %s {", NameSpaceImplementation ); - classdefinitionw.Writeln("") - classdefinitionw.Writeln(" inline void registerInjectionClasses (std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> pTarget)", ) - classdefinitionw.Writeln(" {") - for _, subComponent := range(component.ImportedComponentDefinitions) { - - for i := 0; i < len(subComponent.Classes); i++ { - class := subComponent.Classes[i] - classdefinitionw.Writeln(" v8%s::Cv8%s%s::internalV8Register(pObjectCreator, pTarget);", subComponent.NameSpace, ClassIdentifier, class.ClassName); - } - + } + typesdefinitionw.Writeln(" e_Injection_enumMax") + typesdefinitionw.Writeln(" };") + typesdefinitionw.Writeln("") + typesdefinitionw.Writeln(" }") + typesdefinitionw.Writeln("}") + typesdefinitionw.Writeln("") + typesdefinitionw.Writeln("#endif // __%s_V8TYPES", strings.ToUpper(NameSpace)) + typesdefinitionw.Writeln("") + + classdefinitionw.Writeln("") + classdefinitionw.Writeln("#ifndef __%s_V8CLASSES", strings.ToUpper(NameSpace)) + classdefinitionw.Writeln("#define __%s_V8CLASSES", strings.ToUpper(NameSpace)) + classdefinitionw.Writeln("") + for _, subComponent := range component.ImportedComponentDefinitions { + + for i := 0; i < len(subComponent.Classes); i++ { + class := subComponent.Classes[i] + classdefinitionw.Writeln("#include \"%s_v8_%s_%s.hpp\"", component.BaseName+stubIdentifier, subComponent.BaseName, strings.ToLower(class.ClassName)) } - classdefinitionw.Writeln(" }") - classdefinitionw.Writeln("") - - - classdefinitionw.AddIndentationLevel(2); - for _, subComponent := range(component.ImportedComponentDefinitions) { - writeMapClassIdtoInjectionClassTypeFunction(classdefinitionw, subComponent, subComponent.NameSpace) - classdefinitionw.Writeln("") + + } + classdefinitionw.Writeln("") + + classdefinitionw.Writeln("namespace v8%s {", NameSpace) + classdefinitionw.Writeln(" namespace %s {", NameSpaceImplementation) + classdefinitionw.Writeln("") + classdefinitionw.Writeln(" inline void registerInjectionClasses (std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> pTarget)") + classdefinitionw.Writeln(" {") + for _, subComponent := range component.ImportedComponentDefinitions { + + for i := 0; i < len(subComponent.Classes); i++ { + class := subComponent.Classes[i] + classdefinitionw.Writeln(" v8%s::Cv8%s%s::internalV8Register(pObjectCreator, pTarget);", subComponent.NameSpace, ClassIdentifier, class.ClassName) } - classdefinitionw.AddIndentationLevel(-2); - classdefinitionw.Writeln(" }") - classdefinitionw.Writeln("}") - classdefinitionw.Writeln("") - classdefinitionw.Writeln("#endif // __%s_V8CLASSES", strings.ToUpper(NameSpace)) + } + classdefinitionw.Writeln(" }") + classdefinitionw.Writeln("") + + classdefinitionw.AddIndentationLevel(2) + for _, subComponent := range component.ImportedComponentDefinitions { + writeMapClassIdtoInjectionClassTypeFunction(classdefinitionw, subComponent, subComponent.NameSpace) classdefinitionw.Writeln("") - + } + classdefinitionw.AddIndentationLevel(-2) + + classdefinitionw.Writeln(" }") + classdefinitionw.Writeln("}") + classdefinitionw.Writeln("") + classdefinitionw.Writeln("#endif // __%s_V8CLASSES", strings.ToUpper(NameSpace)) + classdefinitionw.Writeln("") return nil } +func buildJSInjectionClass(component ComponentDefinition, subComponent ComponentDefinition, class ComponentDefinitionClass, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string) error { + baseFileName := fmt.Sprintf("%s_v8_%s_%s", component.BaseName+stubIdentifier, subComponent.BaseName, strings.ToLower(class.ClassName)) + HeaderFileName := path.Join(outputFolder, baseFileName+".hpp") + CppFileName := path.Join(outputFolder, baseFileName+".cpp") + log.Printf("Creating \"%s\"", HeaderFileName) + headerw, err := CreateLanguageFile(HeaderFileName, indentString) + if err != nil { + return err + } -func buildJSInjectionClass(component ComponentDefinition, subComponent ComponentDefinition, class ComponentDefinitionClass, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string) error { - baseFileName := fmt.Sprintf ("%s_v8_%s_%s", component.BaseName + stubIdentifier, subComponent.BaseName, strings.ToLower(class.ClassName)); - HeaderFileName := path.Join(outputFolder, baseFileName + ".hpp"); - CppFileName := path.Join(outputFolder, baseFileName + ".cpp"); + headerw.WriteCLicenseHeader(component, + "JavaScript definition for injection class "+subComponent.NameSpace+"::"+class.ClassName, false) - log.Printf("Creating \"%s\"", HeaderFileName) - headerw, err := CreateLanguageFile(HeaderFileName, indentString) - if err != nil { - return err - } - - headerw.WriteCLicenseHeader(component, - "JavaScript definition for injection class " + subComponent.NameSpace + "::" + class.ClassName, false); - - log.Printf("Creating \"%s\"", CppFileName) - cppw, err := CreateLanguageFile(CppFileName, indentString) - if err != nil { - return err - } - cppw.WriteCLicenseHeader(component, - "JavaScript implementation for injection class " + subComponent.NameSpace + "::" + class.ClassName, false); - - - headerw.Writeln("") - headerw.Writeln("") - headerw.Writeln("#ifndef __%s_V8_%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(subComponent.NameSpace), strings.ToUpper(class.ClassName)) - headerw.Writeln("#define __%s_V8_%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(subComponent.NameSpace), strings.ToUpper(class.ClassName)) - headerw.Writeln("") - headerw.Writeln ("#include \"%s_v8objectcreator.hpp\"", component.BaseName); - headerw.Writeln ("#include \"%s_v8objectwrapper.hpp\"", component.BaseName); - headerw.Writeln("") - - headerw.Writeln("namespace v8%s {", NameSpace ); - headerw.Writeln(" namespace %s {", NameSpaceImplementation ); - headerw.Writeln(" namespace v8%s {", subComponent.NameSpace ); - headerw.Writeln("") - - headerw.Writeln(" class Cv8%s : public Cv8objectWrapper", class.ClassName); - headerw.Writeln(" {"); - headerw.Writeln(" public:"); - headerw.Writeln("") - headerw.Writeln(" /* constructors, destructor and operators */"); - headerw.Writeln(" Cv8%s();", class.ClassName); - headerw.Writeln(" Cv8%s(v8::Local<v8::Object> localObject);", class.ClassName); - headerw.Writeln(" Cv8%s(const Cv8%s& valueReference);", class.ClassName, class.ClassName); - headerw.Writeln(" virtual ~Cv8%s();", class.ClassName); - headerw.Writeln("") - headerw.Writeln(" Cv8%s& operator=(const Cv8%s& valueReference);", class.ClassName, class.ClassName); - headerw.Writeln(" static Cv8%s* Cast(Cv8objectWrapper* objectWrapper);", class.ClassName); - headerw.Writeln(""); - headerw.Writeln(" /* class helper methods */"); - headerw.Writeln(" static eInjectionClassType getClassType();"); - headerw.Writeln(""); - headerw.Writeln(" static %s::P%s getInstance(const v8::FunctionCallbackInfo<v8::Value>& args);", subComponent.NameSpace, class.ClassName); - headerw.Writeln(""); - headerw.Writeln(" /* V8 Registration commands */"); - headerw.Writeln(" static void internalV8RegisterMethods(v8::Local<v8::FunctionTemplate> localClassTemplate, std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> target);"); - headerw.Writeln(" static void internalV8Register(std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> target);"); - headerw.Writeln(" static void internalV8New(const v8::FunctionCallbackInfo<v8::Value>& args);"); - headerw.Writeln(""); - headerw.Writeln(" /* V8 Method implementations */"); - - for j := 0; j < len(class.Methods); j++ { - method := class.Methods[j] - headerw.Writeln(" static void v8%s(const v8::FunctionCallbackInfo<v8::Value>& args);", method.MethodName); - + log.Printf("Creating \"%s\"", CppFileName) + cppw, err := CreateLanguageFile(CppFileName, indentString) + if err != nil { + return err + } + cppw.WriteCLicenseHeader(component, + "JavaScript implementation for injection class "+subComponent.NameSpace+"::"+class.ClassName, false) + + headerw.Writeln("") + headerw.Writeln("") + headerw.Writeln("#ifndef __%s_V8_%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(subComponent.NameSpace), strings.ToUpper(class.ClassName)) + headerw.Writeln("#define __%s_V8_%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(subComponent.NameSpace), strings.ToUpper(class.ClassName)) + headerw.Writeln("") + headerw.Writeln("#include \"%s_v8objectcreator.hpp\"", component.BaseName) + headerw.Writeln("#include \"%s_v8objectwrapper.hpp\"", component.BaseName) + headerw.Writeln("") + + headerw.Writeln("namespace v8%s {", NameSpace) + headerw.Writeln(" namespace %s {", NameSpaceImplementation) + headerw.Writeln(" namespace v8%s {", subComponent.NameSpace) + headerw.Writeln("") + + headerw.Writeln(" class Cv8%s : public Cv8objectWrapper", class.ClassName) + headerw.Writeln(" {") + headerw.Writeln(" public:") + headerw.Writeln("") + headerw.Writeln(" /* constructors, destructor and operators */") + headerw.Writeln(" Cv8%s();", class.ClassName) + headerw.Writeln(" Cv8%s(v8::Local<v8::Object> localObject);", class.ClassName) + headerw.Writeln(" Cv8%s(const Cv8%s& valueReference);", class.ClassName, class.ClassName) + headerw.Writeln(" virtual ~Cv8%s();", class.ClassName) + headerw.Writeln("") + headerw.Writeln(" Cv8%s& operator=(const Cv8%s& valueReference);", class.ClassName, class.ClassName) + headerw.Writeln(" static Cv8%s* Cast(Cv8objectWrapper* objectWrapper);", class.ClassName) + headerw.Writeln("") + headerw.Writeln(" /* class helper methods */") + headerw.Writeln(" static eInjectionClassType getClassType();") + headerw.Writeln("") + headerw.Writeln(" static %s::P%s getInstance(const v8::FunctionCallbackInfo<v8::Value>& args);", subComponent.NameSpace, class.ClassName) + headerw.Writeln("") + headerw.Writeln(" /* V8 Registration commands */") + headerw.Writeln(" static void internalV8RegisterMethods(v8::Local<v8::FunctionTemplate> localClassTemplate, std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> target);") + headerw.Writeln(" static void internalV8Register(std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> target);") + headerw.Writeln(" static void internalV8New(const v8::FunctionCallbackInfo<v8::Value>& args);") + headerw.Writeln("") + headerw.Writeln(" /* V8 Method implementations */") + + for j := 0; j < len(class.Methods); j++ { + method := class.Methods[j] + headerw.Writeln(" static void v8%s(const v8::FunctionCallbackInfo<v8::Value>& args);", method.MethodName) + + } + + //static void V8Data(const v8::FunctionCallbackInfo<v8::Value>& args); + headerw.Writeln("") + headerw.Writeln(" };") + + headerw.Writeln("") + headerw.Writeln(" }") + headerw.Writeln(" }") + headerw.Writeln("}") + headerw.Writeln("") + headerw.Writeln("#endif // __%s_V8_%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(subComponent.NameSpace), strings.ToUpper(class.ClassName)) + headerw.Writeln("") + + cppw.Writeln("") + cppw.Writeln("#include \"%s.hpp\"", baseFileName) + cppw.Writeln("") + cppw.Writeln("#include \"%s_v8utils.hpp\"", component.BaseName) + cppw.Writeln("#include \"%s_v8objectcreator.hpp\"", component.BaseName) + cppw.Writeln("#include \"%s%s_v8classes.hpp\"", component.BaseName, stubIdentifier) + cppw.Writeln("") + cppw.Writeln("") + + cppw.Writeln("using namespace v8%s::%s;", NameSpace, NameSpaceImplementation) + cppw.Writeln("using namespace v8%s::%s::v8%s;", NameSpace, NameSpaceImplementation, subComponent.NameSpace) + cppw.Writeln("") + + cppw.Writeln("Cv8%s::Cv8%s()", class.ClassName, class.ClassName) + cppw.Writeln(" : Cv8objectWrapper(getClassType())") + cppw.Writeln("{") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("Cv8%s::Cv8%s(v8::Local<v8::Object> localObject)", class.ClassName, class.ClassName) + cppw.Writeln(" : Cv8objectWrapper(getClassType())") + cppw.Writeln("{") + cppw.Writeln(" Wrap(localObject);") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("Cv8%s::Cv8%s(const Cv8%s& valueReference)", class.ClassName, class.ClassName, class.ClassName) + cppw.Writeln(" : Cv8objectWrapper(getClassType())") + cppw.Writeln("{") + cppw.Writeln(" setObjectInstances(valueReference.m_pObjectCreator, valueReference.m_pObjectInstance);") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("Cv8%s::~Cv8%s()", class.ClassName, class.ClassName) + cppw.Writeln("{") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("eInjectionClassType Cv8%s::getClassType()", class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" return eInjectionClassType::e_v8%s_%s;", subComponent.NameSpace, class.ClassName) + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("Cv8%s* Cv8%s::Cast(Cv8objectWrapper* objectWrapper)", class.ClassName, class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" if (objectWrapper != nullptr) {") + cppw.Writeln(" if (objectWrapper->get_type() == getClassType())") + cppw.Writeln(" return static_cast<Cv8%s*>(objectWrapper);", class.ClassName) + cppw.Writeln(" }") + cppw.Writeln(" return nullptr;") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("%s::P%s Cv8%s::getInstance(const v8::FunctionCallbackInfo<v8::Value>& args)", subComponent.NameSpace, class.ClassName, class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" auto objectWrapper = UnwrapBase(args.Holder());") + cppw.Writeln(" if (objectWrapper == nullptr)") + cppw.Writeln(" throw std::runtime_error (\"could not get %s instance wrapper.\");", class.ClassName) + cppw.Writeln("") + cppw.Writeln(" auto pInstance = objectWrapper->getObjectInstance ();") + cppw.Writeln(" if (pInstance.get () == nullptr)") + cppw.Writeln(" throw std::runtime_error (\"could not get %s instance.\");", class.ClassName) + cppw.Writeln("") + cppw.Writeln(" auto pCastInstance = std::dynamic_pointer_cast<%s::C%s> (pInstance);", subComponent.NameSpace, class.ClassName) + cppw.Writeln(" if (pCastInstance.get () == nullptr)") + cppw.Writeln(" throw std::runtime_error (\"invalid %s instance type.\");", class.ClassName) + cppw.Writeln("") + cppw.Writeln(" return pCastInstance;") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("Cv8%s& Cv8%s::operator=(const Cv8%s& valueReference)", class.ClassName, class.ClassName, class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" if (this != &valueReference)") + cppw.Writeln(" {") + cppw.Writeln(" setObjectInstances(valueReference.m_pObjectCreator, valueReference.m_pObjectInstance);") + cppw.Writeln(" }") + cppw.Writeln(" return *this;") + cppw.Writeln("}") + cppw.Writeln("") + + cppw.Writeln("void Cv8%s::internalV8Register(std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> target)", class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" v8::Isolate* isolate = v8::Isolate::GetCurrent();") + cppw.Writeln(" if (isolate == nullptr)") + cppw.Writeln(" return;") + cppw.Writeln("") + cppw.Writeln(" // Create class template") + cppw.Writeln(" v8::HandleScope handle_scope(isolate);") + cppw.Writeln("") + cppw.Writeln(" v8::Local<v8::FunctionTemplate> localClassTemplate = createClassTemplate (isolate, \"%s\", Cv8%s::internalV8New);", class.ClassName, class.ClassName) + cppw.Writeln("") + cppw.Writeln(" Cv8%s::internalV8RegisterMethods(localClassTemplate, pObjectCreator, target);", class.ClassName) + cppw.Writeln("") + cppw.Writeln(" pObjectCreator->setTemplate(getClassType(), localClassTemplate);") + cppw.Writeln("}") + cppw.Writeln("") + cppw.Writeln("void Cv8%s::internalV8RegisterMethods(v8::Local<v8::FunctionTemplate> localClassTemplate,", class.ClassName) + cppw.Writeln(" std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> target)") + cppw.Writeln("{") + if (class.ParentClass != "") && (class.ClassName != "Base") { + cppw.Writeln(" Cv8%s::internalV8RegisterMethods(localClassTemplate, pObjectCreator, target);", class.ParentClass) + } + cppw.Writeln(" // Add functions to prototype object") + for i := 0; i < len(class.Methods); i++ { + method := class.Methods[i] + + lowerCaseMethodName := strings.ToLower(method.MethodName[:1]) + method.MethodName[1:] + + 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);", lowerCaseMethodName, class.ClassName, method.MethodName) + } + cppw.Writeln("") + cppw.Writeln("}") + + cppw.Writeln("void Cv8%s::internalV8New(const v8::FunctionCallbackInfo<v8::Value>& args)", class.ClassName) + cppw.Writeln("{") + cppw.Writeln(" if (!args.IsConstructCall())") + cppw.Writeln(" {") + cppw.Writeln(" Cv8toolsUtils::Throw_error(\"Expected constructor call type\");") + cppw.Writeln(" return;") + cppw.Writeln(" }") + cppw.Writeln(" new Cv8%s(args.This());", class.ClassName) + cppw.Writeln("}") + cppw.Writeln("") + cppw.Writeln("") + + for j := 0; j < len(class.Methods); j++ { + method := class.Methods[j] + + argCount := 0 + argString := "" + for k := 0; k < len(method.Params); k++ { + if method.Params[k].ParamPass != "return" { + if argCount != 0 { + argString = argString + ", " + } + + argString = argString + method.Params[k].ParamName + + argCount = argCount + 1 + } } - //static void V8Data(const v8::FunctionCallbackInfo<v8::Value>& args); - headerw.Writeln(""); - headerw.Writeln(" };"); - - headerw.Writeln("") - headerw.Writeln(" }") - headerw.Writeln(" }") - headerw.Writeln("}") - headerw.Writeln("") - headerw.Writeln("#endif // __%s_V8_%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(subComponent.NameSpace), strings.ToUpper(class.ClassName)) - headerw.Writeln("") - - cppw.Writeln (""); - cppw.Writeln ("#include \"%s.hpp\"", baseFileName); - cppw.Writeln (""); - cppw.Writeln ("#include \"%s_v8utils.hpp\"", component.BaseName); - cppw.Writeln ("#include \"%s_v8objectcreator.hpp\"", component.BaseName); - cppw.Writeln ("#include \"%s%s_v8classes.hpp\"", component.BaseName, stubIdentifier); - cppw.Writeln(""); - cppw.Writeln(""); - - cppw.Writeln("using namespace v8%s::%s;", NameSpace, NameSpaceImplementation); - cppw.Writeln("using namespace v8%s::%s::v8%s;", NameSpace, NameSpaceImplementation, subComponent.NameSpace ); - cppw.Writeln("") - - cppw.Writeln("Cv8%s::Cv8%s()", class.ClassName, class.ClassName); - cppw.Writeln(" : Cv8objectWrapper(getClassType())"); - cppw.Writeln("{"); - cppw.Writeln("}"); - cppw.Writeln(""); - - cppw.Writeln("Cv8%s::Cv8%s(v8::Local<v8::Object> localObject)", class.ClassName, class.ClassName); - cppw.Writeln(" : Cv8objectWrapper(getClassType())"); - cppw.Writeln("{"); - cppw.Writeln(" Wrap(localObject);"); - cppw.Writeln("}"); - cppw.Writeln(""); - - cppw.Writeln("Cv8%s::Cv8%s(const Cv8%s& valueReference)", class.ClassName, class.ClassName, class.ClassName); - cppw.Writeln(" : Cv8objectWrapper(getClassType())"); - cppw.Writeln("{"); - cppw.Writeln(" setObjectInstances(valueReference.m_pObjectCreator, valueReference.m_pObjectInstance);"); - cppw.Writeln("}"); - cppw.Writeln(""); - - - cppw.Writeln("Cv8%s::~Cv8%s()", class.ClassName, class.ClassName); - cppw.Writeln("{"); - cppw.Writeln("}"); - cppw.Writeln(""); - - cppw.Writeln("eInjectionClassType Cv8%s::getClassType()", class.ClassName); - cppw.Writeln("{"); - cppw.Writeln(" return eInjectionClassType::e_v8%s_%s;", subComponent.NameSpace, class.ClassName); - cppw.Writeln("}"); - cppw.Writeln(""); - - cppw.Writeln("Cv8%s* Cv8%s::Cast(Cv8objectWrapper* objectWrapper)", class.ClassName, class.ClassName); - cppw.Writeln("{"); - cppw.Writeln(" if (objectWrapper != nullptr) {"); - cppw.Writeln(" if (objectWrapper->get_type() == getClassType())"); - cppw.Writeln(" return static_cast<Cv8%s*>(objectWrapper);", class.ClassName); - cppw.Writeln(" }"); - cppw.Writeln(" return nullptr;"); - cppw.Writeln("}"); - cppw.Writeln(""); - - cppw.Writeln("%s::P%s Cv8%s::getInstance(const v8::FunctionCallbackInfo<v8::Value>& args)", subComponent.NameSpace, class.ClassName, class.ClassName); - cppw.Writeln("{"); - cppw.Writeln(" auto objectWrapper = UnwrapBase(args.Holder());"); - cppw.Writeln(" if (objectWrapper == nullptr)"); - cppw.Writeln(" throw std::runtime_error (\"could not get %s instance wrapper.\");", class.ClassName); - cppw.Writeln(""); - cppw.Writeln(" auto pInstance = objectWrapper->getObjectInstance ();"); - cppw.Writeln(" if (pInstance.get () == nullptr)"); - cppw.Writeln(" throw std::runtime_error (\"could not get %s instance.\");", class.ClassName); - cppw.Writeln(""); - cppw.Writeln(" auto pCastInstance = std::dynamic_pointer_cast<%s::C%s> (pInstance);", subComponent.NameSpace, class.ClassName); - cppw.Writeln(" if (pCastInstance.get () == nullptr)"); - cppw.Writeln(" throw std::runtime_error (\"invalid %s instance type.\");", class.ClassName); - cppw.Writeln(""); - cppw.Writeln(" return pCastInstance;"); - cppw.Writeln("}"); - cppw.Writeln(""); - - cppw.Writeln("Cv8%s& Cv8%s::operator=(const Cv8%s& valueReference)", class.ClassName, class.ClassName, class.ClassName); - cppw.Writeln("{"); - cppw.Writeln(" if (this != &valueReference)"); - cppw.Writeln(" {"); - cppw.Writeln(" setObjectInstances(valueReference.m_pObjectCreator, valueReference.m_pObjectInstance);"); - cppw.Writeln(" }"); - cppw.Writeln(" return *this;"); - cppw.Writeln("}"); - cppw.Writeln(""); - - cppw.Writeln("void Cv8%s::internalV8Register(std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> target)", class.ClassName) + cppw.Writeln("void Cv8%s::v8%s(const v8::FunctionCallbackInfo<v8::Value>& args)", class.ClassName, method.MethodName) cppw.Writeln("{") cppw.Writeln(" v8::Isolate* isolate = v8::Isolate::GetCurrent();") - cppw.Writeln(" if (isolate == nullptr)") - cppw.Writeln(" return;") cppw.Writeln("") - cppw.Writeln(" // Create class template") - cppw.Writeln(" v8::HandleScope handle_scope(isolate);") + cppw.Writeln(" try {") + cppw.Writeln(" checkArgumentParameters(args, %d, \"%s.%s (%s)\");", argCount, class.ClassName, method.MethodName, argString) cppw.Writeln("") - cppw.Writeln(" v8::Local<v8::FunctionTemplate> localClassTemplate = createClassTemplate (isolate, \"%s\", Cv8%s::internalV8New);", class.ClassName, class.ClassName) + cppw.Writeln(" auto instancePtr = getInstance(args);") cppw.Writeln("") - cppw.Writeln(" Cv8%s::internalV8RegisterMethods(localClassTemplate, pObjectCreator, target);", class.ClassName) + cppw.Writeln(" auto v8instance = UnwrapBase(args.Holder());") + cppw.Writeln(" if (v8instance == nullptr)") + cppw.Writeln(" throw std::runtime_error(\"could not get %s instance.\");", class.ClassName) cppw.Writeln("") - cppw.Writeln(" pObjectCreator->setTemplate(getClassType(), localClassTemplate);") - cppw.Writeln("}") + cppw.Writeln(" auto objectCreator = v8instance->getObjectCreator();") + cppw.Writeln(" if (objectCreator == nullptr)") + cppw.Writeln(" throw std::runtime_error(\"invalid object creator.\");") cppw.Writeln("") - cppw.Writeln("void Cv8%s::internalV8RegisterMethods(v8::Local<v8::FunctionTemplate> localClassTemplate,", class.ClassName) - cppw.Writeln(" std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> target)") - cppw.Writeln("{") - if (class.ParentClass != "") && (class.ClassName != "Base") { - cppw.Writeln(" Cv8%s::internalV8RegisterMethods(localClassTemplate, pObjectCreator, target);", class.ParentClass) - } - cppw.Writeln(" // Add functions to prototype object") - for i := 0; i < len(class.Methods); i++ { - method := class.Methods[i] - lowerCaseMethodName := strings.ToLower(method.MethodName[:1]) + method.MethodName[1:] + resultString := "" + argumentString := "" + returnValueCall := "" + returnValueParameter := "" + cppArrayClass := "" - 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);", lowerCaseMethodName, class.ClassName, method.MethodName) + baseClassName := "P" + component.Global.BaseClassName + + outOrResultParameterCount := 0 + + for k := 0; k < len(method.Params); k++ { + param := method.Params[k] + if (param.ParamPass == "out") || (param.ParamPass == "return") { + outOrResultParameterCount = outOrResultParameterCount + 1 + } } - cppw.Writeln("") - cppw.Writeln("}") - - - cppw.Writeln("void Cv8%s::internalV8New(const v8::FunctionCallbackInfo<v8::Value>& args)", class.ClassName); - cppw.Writeln("{"); - cppw.Writeln(" if (!args.IsConstructCall())"); - cppw.Writeln(" {"); - cppw.Writeln(" Cv8toolsUtils::Throw_error(\"Expected constructor call type\");"); - cppw.Writeln(" return;"); - cppw.Writeln(" }"); - cppw.Writeln(" new Cv8%s(args.This());", class.ClassName); - cppw.Writeln("}"); - cppw.Writeln(""); - cppw.Writeln(""); - - for j := 0; j < len(class.Methods); j++ { - method := class.Methods[j] - - argCount := 0; - argString := ""; - for k := 0; k < len(method.Params); k++ { - if (method.Params[k].ParamPass != "return") { - if (argCount != 0) { - argString = argString + ", "; - } - - argString = argString + method.Params[k].ParamName; - - argCount = argCount + 1; + + for k := 0; k < len(method.Params); k++ { + param := method.Params[k] + + cppParamType := "" + argumentMethodCallType := "" + argumentDefault := "" + cppReturnValueCast := "" + + switch param.ParamType { + case "uint8": + cppParamType = param.ParamType + "_t" + argumentMethodCallType = "Uint8" + argumentDefault = "0" + case "uint16": + cppParamType = param.ParamType + "_t" + argumentMethodCallType = "Uint16" + argumentDefault = "0" + case "uint32": + cppParamType = param.ParamType + "_t" + argumentMethodCallType = "Uint32" + argumentDefault = "0" + case "uint64": + cppParamType = param.ParamType + "_t" + argumentMethodCallType = "Uint64" + argumentDefault = "0" + case "int8": + cppParamType = param.ParamType + "_t" + argumentMethodCallType = "Int8" + argumentDefault = "0" + case "int16": + cppParamType = param.ParamType + "_t" + argumentMethodCallType = "Int16" + argumentDefault = "0" + case "int32": + cppParamType = param.ParamType + "_t" + argumentMethodCallType = "Int32" + argumentDefault = "0" + case "int64": + cppParamType = param.ParamType + "_t" + argumentMethodCallType = "Int64" + argumentDefault = "0" + case "single": + cppParamType = "float" + argumentMethodCallType = "Float" + argumentDefault = "0.0f" + case "double": + cppParamType = "double" + argumentMethodCallType = "Double" + argumentDefault = "0.0" + case "string": + cppParamType = "std::string" + argumentMethodCallType = "String" + argumentDefault = "\"\"" + case "bool": + cppParamType = "bool" + argumentMethodCallType = "Bool" + argumentDefault = "false" + case "pointer": + cppParamType = "void *" + argumentMethodCallType = "Pointer" + argumentDefault = "nullptr" + case "class", "optionalclass": + cppParamType = subComponent.NameSpace + "::P" + param.ParamClass + argumentMethodCallType = "Object" + argumentDefault = "nullptr" + case "enum": + cppParamType = subComponent.NameSpace + "::e" + param.ParamClass + argumentMethodCallType = "Int32" + argumentDefault = "(" + subComponent.NameSpace + "::e" + param.ParamClass + ") 0" + cppReturnValueCast = "(" + subComponent.NameSpace + "::e" + param.ParamClass + ")" + case "basicarray": + switch param.ParamClass { + case "uint8": + argumentMethodCallType = "Uint8Array" + cppArrayClass = param.ParamClass + "_t" + case "uint16": + argumentMethodCallType = "Uint16Array" + cppArrayClass = param.ParamClass + "_t" + case "uint32": + argumentMethodCallType = "Uint32Array" + cppArrayClass = param.ParamClass + "_t" + case "uint64": + argumentMethodCallType = "Uint64Array" + cppArrayClass = param.ParamClass + "_t" + case "int8": + argumentMethodCallType = "Int8Array" + cppArrayClass = param.ParamClass + "_t" + case "int16": + argumentMethodCallType = "Int16Array" + cppArrayClass = param.ParamClass + "_t" + case "int32": + argumentMethodCallType = "Int32Array" + cppArrayClass = param.ParamClass + "_t" + case "int64": + argumentMethodCallType = "Int64Array" + cppArrayClass = param.ParamClass + "_t" + case "single": + argumentMethodCallType = "FloatArray" + cppArrayClass = "float" + case "double": + argumentMethodCallType = "DoubleArray" + cppArrayClass = "double" + case "bool": + argumentMethodCallType = "BoolArray" + cppArrayClass = "uint8_t" + default: + return errors.New("Invalid array class: " + param.ParamClass) } + + default: + return errors.New("Invalid parameter type: " + param.ParamType) + + /* case "structarray": + case "struct": + case "functiontype": */ } - - - cppw.Writeln("void Cv8%s::v8%s(const v8::FunctionCallbackInfo<v8::Value>& args)", class.ClassName, method.MethodName); - cppw.Writeln("{"); - cppw.Writeln(" v8::Isolate* isolate = v8::Isolate::GetCurrent();"); - cppw.Writeln(""); - cppw.Writeln(" try {"); - cppw.Writeln(" checkArgumentParameters(args, %d, \"%s.%s (%s)\");", argCount, class.ClassName, method.MethodName, argString); - cppw.Writeln(""); - cppw.Writeln(" auto instancePtr = getInstance(args);"); - cppw.Writeln(""); - cppw.Writeln(" auto v8instance = UnwrapBase(args.Holder());"); - cppw.Writeln(" if (v8instance == nullptr)"); - cppw.Writeln(" throw std::runtime_error(\"could not get %s instance.\");", class.ClassName); - cppw.Writeln(""); - cppw.Writeln(" auto objectCreator = v8instance->getObjectCreator();"); - cppw.Writeln(" if (objectCreator == nullptr)"); - cppw.Writeln(" throw std::runtime_error(\"invalid object creator.\");"); - cppw.Writeln(""); - - resultString := ""; - argumentString := ""; - returnValueCall := ""; - returnValueParameter := ""; - cppArrayClass := ""; - - baseClassName := "P" + component.Global.BaseClassName; - - outOrResultParameterCount := 0; - - for k := 0; k < len(method.Params); k++ { - param := method.Params[k]; - if ((param.ParamPass == "out") || (param.ParamPass == "return")) { - outOrResultParameterCount = outOrResultParameterCount + 1; + + if param.ParamPass == "in" { + if argumentString != "" { + argumentString = argumentString + ", " + } + argumentString = argumentString + "param" + param.ParamName + + if param.ParamType == "class" { + cppw.Writeln(" %s::%s object%s = v8instance->get%sArgument (isolate, args, %d);", subComponent.NameSpace, baseClassName, param.ParamName, argumentMethodCallType, k) + cppw.Writeln(" %s param%s = std::dynamic_pointer_cast<%s::C%s> (object%s);", cppParamType, param.ParamName, subComponent.NameSpace, param.ParamClass, param.ParamName) + } else if param.ParamType == "optionalclass" { + cppw.Writeln(" %s::%s object%s = v8instance->get%sArgument (isolate, args, %d);", subComponent.NameSpace, baseClassName, param.ParamName, argumentMethodCallType, k) + cppw.Writeln(" %s param%s = std::dynamic_pointer_cast<%s::C%s> (object%s);", cppParamType, param.ParamName, subComponent.NameSpace, param.ParamClass, param.ParamName) + } else if param.ParamType == "basicarray" { + cppw.Writeln(" std::vector<%s> param%s;", cppArrayClass, param.ParamName) + cppw.Writeln(" v8instance->get%sArgument (isolate, args, param%s, %d);", argumentMethodCallType, param.ParamName, k) + } else { + cppw.Writeln(" %s param%s = %sv8instance->get%sArgument (isolate, args, %d);", cppParamType, param.ParamName, cppReturnValueCast, argumentMethodCallType, k) } } + if param.ParamPass == "out" { + if argumentString != "" { + argumentString = argumentString + ", " + } + argumentString = argumentString + "param" + param.ParamName + + if param.ParamType == "basicarray" { + cppw.Writeln(" std::vector<%s> param%s;", cppArrayClass, param.ParamName) + } else { + cppw.Writeln(" %s param%s = %s;", cppParamType, param.ParamName, argumentDefault) + } + + returnValueCall = "set" + argumentMethodCallType + "ReturnValue" + + if param.ParamType == "class" { + returnValueParameter = fmt.Sprintf("createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s()))", param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + } else if param.ParamType == "optionalclass" { + returnValueParameter = fmt.Sprintf("param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local<v8::Object>()", param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + } else if param.ParamType == "enum" { + returnValueParameter = "(uint32_t) param" + param.ParamName + } else { + returnValueParameter = "param" + param.ParamName + } - for k := 0; k < len(method.Params); k++ { - param := method.Params[k]; - - cppParamType := ""; - argumentMethodCallType := ""; - argumentDefault := ""; - cppReturnValueCast := ""; - - switch (param.ParamType) { - case "uint8": - cppParamType = param.ParamType + "_t"; - argumentMethodCallType = "Uint8"; - argumentDefault = "0"; - case "uint16": - cppParamType = param.ParamType + "_t"; - argumentMethodCallType = "Uint16"; - argumentDefault = "0"; - case "uint32": - cppParamType = param.ParamType + "_t"; - argumentMethodCallType = "Uint32"; - argumentDefault = "0"; - case "uint64": - cppParamType = param.ParamType + "_t"; - argumentMethodCallType = "Uint64"; - argumentDefault = "0"; - case "int8": - cppParamType = param.ParamType + "_t"; - argumentMethodCallType = "Int8"; - argumentDefault = "0"; - case "int16": - cppParamType = param.ParamType + "_t"; - argumentMethodCallType = "Int16"; - argumentDefault = "0"; - case "int32": - cppParamType = param.ParamType + "_t"; - argumentMethodCallType = "Int32"; - argumentDefault = "0"; - case "int64": - cppParamType = param.ParamType + "_t"; - argumentMethodCallType = "Int64"; - argumentDefault = "0"; - case "single": - cppParamType = "float"; - argumentMethodCallType = "Float"; - argumentDefault = "0.0f"; - case "double": - cppParamType = "double"; - argumentMethodCallType = "Double"; - argumentDefault = "0.0"; - case "string": - cppParamType = "std::string"; - argumentMethodCallType = "String"; - argumentDefault = "\"\""; - case "bool": - cppParamType = "bool"; - argumentMethodCallType = "Bool"; - argumentDefault = "false"; - case "pointer": - cppParamType = "void *"; - argumentMethodCallType = "Pointer"; - argumentDefault = "nullptr"; - case "class", "optionalclass": - cppParamType = subComponent.NameSpace + "::P" + param.ParamClass; - argumentMethodCallType = "Object"; - argumentDefault = "nullptr"; - case "enum": - cppParamType = subComponent.NameSpace + "::e" + param.ParamClass; - argumentMethodCallType = "Int32"; - argumentDefault = "(" + subComponent.NameSpace + "::e" + param.ParamClass + ") 0"; - cppReturnValueCast = "(" + subComponent.NameSpace + "::e" + param.ParamClass + ")" - case "basicarray": - switch (param.ParamClass) { - case "uint8": - argumentMethodCallType = "Uint8Array"; - cppArrayClass = param.ParamClass + "_t"; - case "uint16": - argumentMethodCallType = "Uint16Array"; - cppArrayClass = param.ParamClass + "_t"; - case "uint32": - argumentMethodCallType = "Uint32Array"; - cppArrayClass = param.ParamClass + "_t"; - case "uint64": - argumentMethodCallType = "Uint64Array"; - cppArrayClass = param.ParamClass + "_t"; - case "int8": - argumentMethodCallType = "Int8Array"; - cppArrayClass = param.ParamClass + "_t"; - case "int16": - argumentMethodCallType = "Int16Array"; - cppArrayClass = param.ParamClass + "_t"; - case "int32": - argumentMethodCallType = "Int32Array"; - cppArrayClass = param.ParamClass + "_t"; - case "int64": - argumentMethodCallType = "Int64Array"; - cppArrayClass = param.ParamClass + "_t"; - case "single": - argumentMethodCallType = "FloatArray"; - cppArrayClass = "float"; - case "double": - argumentMethodCallType = "DoubleArray"; - cppArrayClass = "double"; - case "bool": - argumentMethodCallType = "BoolArray"; - cppArrayClass = "uint8_t"; - default: - return errors.New ("Invalid array class: " + param.ParamClass); - } - - - default: - return errors.New ("Invalid parameter type: " + param.ParamType); - -/* case "structarray": - case "struct": - case "functiontype": */ - } - - if (param.ParamPass == "in") { - if (argumentString != "") { - argumentString = argumentString + ", "; - } - argumentString = argumentString + "param" + param.ParamName; - - if (param.ParamType == "class") { - cppw.Writeln(" %s::%s object%s = v8instance->get%sArgument (isolate, args, %d);", subComponent.NameSpace, baseClassName, param.ParamName, argumentMethodCallType, k); - cppw.Writeln(" %s param%s = std::dynamic_pointer_cast<%s::C%s> (object%s);", cppParamType, param.ParamName, subComponent.NameSpace, param.ParamClass, param.ParamName); - } else if (param.ParamType == "optionalclass") { - cppw.Writeln(" %s::%s object%s = v8instance->get%sArgument (isolate, args, %d);", subComponent.NameSpace, baseClassName, param.ParamName, argumentMethodCallType, k); - cppw.Writeln(" %s param%s = std::dynamic_pointer_cast<%s::C%s> (object%s);", cppParamType, param.ParamName, subComponent.NameSpace, param.ParamClass, param.ParamName); - } else if (param.ParamType == "basicarray") { - cppw.Writeln(" std::vector<%s> param%s;", cppArrayClass, param.ParamName); - cppw.Writeln(" v8instance->get%sArgument (isolate, args, param%s, %d);", argumentMethodCallType, param.ParamName, k); - } else { - cppw.Writeln(" %s param%s = %sv8instance->get%sArgument (isolate, args, %d);", cppParamType, param.ParamName, cppReturnValueCast, argumentMethodCallType, k); - } - } - - if (param.ParamPass == "out") { - if (argumentString != "") { - argumentString = argumentString + ", "; - } - argumentString = argumentString + "param" + param.ParamName; - - if (param.ParamType == "basicarray") { - cppw.Writeln(" std::vector<%s> param%s;", cppArrayClass, param.ParamName); - } else { - cppw.Writeln(" %s param%s = %s;", cppParamType, param.ParamName, argumentDefault); - } - - returnValueCall = "set" + argumentMethodCallType + "ReturnValue"; - - if (param.ParamType == "class") { - returnValueParameter = fmt.Sprintf ("createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s()))", param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod); - } else if (param.ParamType == "optionalclass") { - returnValueParameter = fmt.Sprintf ("param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local<v8::Object>()", param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod); - } else if (param.ParamType == "enum") { - returnValueParameter = "(uint32_t) param" + param.ParamName; - } else { - returnValueParameter = "param" + param.ParamName; - } - - } - - if (param.ParamPass == "return") { - - if (param.ParamType == "basicarray") { - cppw.Writeln(" std::vector<%s> param%s;", cppArrayClass, param.ParamName); - } else { - cppw.Writeln(" %s param%s = %s;", cppParamType, param.ParamName, argumentDefault); - } - resultString = "param" + param.ParamName + " = "; - returnValueCall = "set" + argumentMethodCallType + "ReturnValue"; - - if (param.ParamType == "class") { - returnValueParameter = fmt.Sprintf ("createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s()))", param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod); - } else if (param.ParamType == "optionalclass") { - returnValueParameter = fmt.Sprintf ("param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local<v8::Object>()", param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod); - } else if (param.ParamType == "enum") { - returnValueParameter = "(uint32_t) param" + param.ParamName; - } else { - returnValueParameter = "param" + param.ParamName; - } - } - } - - cppw.Writeln(" %sinstancePtr->%s (%s);", resultString, method.MethodName, argumentString); - if (returnValueCall != "") { - cppw.Writeln(" %s(isolate, args, %s);", returnValueCall, returnValueParameter); + + if param.ParamPass == "return" { + + if param.ParamType == "basicarray" { + cppw.Writeln(" std::vector<%s> param%s;", cppArrayClass, param.ParamName) + } else { + cppw.Writeln(" %s param%s = %s;", cppParamType, param.ParamName, argumentDefault) + } + resultString = "param" + param.ParamName + " = " + returnValueCall = "set" + argumentMethodCallType + "ReturnValue" + + if param.ParamType == "class" { + returnValueParameter = fmt.Sprintf("createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s()))", param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + } else if param.ParamType == "optionalclass" { + returnValueParameter = fmt.Sprintf("param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local<v8::Object>()", param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + } else if param.ParamType == "enum" { + returnValueParameter = "(uint32_t) param" + param.ParamName + } else { + returnValueParameter = "param" + param.ParamName + } } - cppw.Writeln(" "); - cppw.Writeln(""); - - cppw.Writeln(" }"); - cppw.Writeln(" catch (std::exception& E) {"); - cppw.Writeln(" throwV8Exception(isolate, E);"); - cppw.Writeln(" }"); - cppw.Writeln("}"); - cppw.Writeln(""); - + } - + cppw.Writeln(" %sinstancePtr->%s (%s);", resultString, method.MethodName, argumentString) + if returnValueCall != "" { + cppw.Writeln(" %s(isolate, args, %s);", returnValueCall, returnValueParameter) + } + cppw.Writeln(" ") cppw.Writeln("") - return nil; -} + cppw.Writeln(" }") + cppw.Writeln(" catch (std::exception& E) {") + cppw.Writeln(" throwV8Exception(isolate, E);") + cppw.Writeln(" }") + cppw.Writeln("}") + cppw.Writeln("") + + } + cppw.Writeln("") + + return nil +} func writeMapClassIdtoInjectionClassTypeFunction(w LanguageWriter, component ComponentDefinition, NameSpace string) { w.Writeln("") @@ -775,12 +757,11 @@ func writeMapClassIdtoInjectionClassTypeFunction(w LanguageWriter, component Com w.Writeln("}") } - // BuildJSDocumentation builds the Sphinx documentation of a library's C++-bindings -func BuildJSDocumentation(component ComponentDefinition, outputFolder string, ClassIdentifier string) (error) { +func BuildJSDocumentation(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 { @@ -791,7 +772,7 @@ func BuildJSDocumentation(component ComponentDefinition, outputFolder string, Cl 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 { @@ -801,10 +782,10 @@ func BuildJSDocumentation(component ComponentDefinition, outputFolder string, Cl 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 { @@ -817,7 +798,6 @@ func BuildJSDocumentation(component ComponentDefinition, outputFolder string, Cl } - err = buildJSDocumentationExample(component, outputFolder, ClassIdentifier, true, "_dynamic") if err != nil { return err @@ -826,14 +806,14 @@ func BuildJSDocumentation(component ComponentDefinition, outputFolder string, Cl if err != nil { return err } - + return nil } func buildJSDocumentationExample(component ComponentDefinition, outputFolder string, ClassIdentifier string, ExplicitLinking bool, suffix string) error { NameSpace := component.NameSpace - DynamicCPPExample := path.Join(outputFolder, NameSpace +"_example"+suffix+".cpp") + DynamicCPPExample := path.Join(outputFolder, NameSpace+"_example"+suffix+".cpp") log.Printf("Creating \"%s\"", DynamicCPPExample) dyncppexamplefile, err := CreateLanguageFile(DynamicCPPExample, " ") if err != nil { @@ -852,8 +832,8 @@ func buildJSDocumentationExample(component ComponentDefinition, outputFolder str } func writeJSDocumentationFunctionPointer(component ComponentDefinition, w LanguageWriter, - functiontype ComponentDefinitionFunctionType) (error) { - + functiontype ComponentDefinitionFunctionType) error { + NameSpace := component.NameSpace returnType := "void" parameters := "" @@ -861,14 +841,14 @@ func writeJSDocumentationFunctionPointer(component ComponentDefinition, w Langua 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 + "*" @@ -883,11 +863,11 @@ func writeJSDocumentationFunctionPointer(component ComponentDefinition, w Langua 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(" ") @@ -895,14 +875,13 @@ func writeJSDocumentationFunctionPointer(component ComponentDefinition, w Langua return nil } - -func buildJSDocumentationGlobal(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) (error) { +func buildJSDocumentationGlobal(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) @@ -918,12 +897,11 @@ func buildJSDocumentationGlobal(component ComponentDefinition, w LanguageWriter, 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) @@ -936,20 +914,19 @@ func buildJSDocumentationGlobal(component ComponentDefinition, w LanguageWriter, w.Writeln(".. cpp:type:: std::shared_ptr<%s> %s::P%s%s", wrapperName, NameSpace, ClassIdentifier, "Wrapper") w.Writeln(" ") - + // Load library functions // Check error functions of the base class return nil } - func writeJSDocumentationParameters(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string) { for k := 0; k < len(method.Params); k++ { param := method.Params[k] variableName := getBindingCppVariableName(param) - if (param.ParamPass == "return") { - w.Writeln(" :returns: %s", param.ParamDescription ) + if param.ParamPass == "return" { + w.Writeln(" :returns: %s", param.ParamDescription) } else { w.Writeln(" :param %s: %s ", variableName, param.ParamDescription) } @@ -957,17 +934,17 @@ func writeJSDocumentationParameters(method ComponentDefinitionMethod, w Language w.Writeln("") } -func buildJSDocumentationClass(component ComponentDefinition, w LanguageWriter, class ComponentDefinitionClass, ClassIdentifier string) (error) { - +func buildJSDocumentationClass(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) @@ -982,7 +959,7 @@ func buildJSDocumentationClass(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) @@ -1003,7 +980,7 @@ func buildJSDocumentationClass(component ComponentDefinition, w LanguageWriter, func buildJSDocumentationException(component ComponentDefinition, w LanguageWriter) { LibraryName := component.LibraryName - NameSpace := component.NameSpace + NameSpace := component.NameSpace ExceptionName := "E" + NameSpace + "Exception" w.Writeln(" ") @@ -1022,7 +999,6 @@ func buildJSDocumentationException(component ComponentDefinition, w LanguageWrit 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(" ") @@ -1032,10 +1008,9 @@ func buildJSDocumentationException(component ComponentDefinition, w LanguageWrit w.Writeln(" ") } - func buildJSDocumentationInputVector(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) { LibraryName := component.LibraryName - NameSpace := component.NameSpace + NameSpace := component.NameSpace InputVector := "C" + ClassIdentifier + "InputVector" w.Writeln(" ") @@ -1050,8 +1025,7 @@ func buildJSDocumentationInputVector(component ComponentDefinition, w LanguageWr 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<typename T> %s::%s", NameSpace, InputVector) w.Writeln(" ") w.Writeln(" .. cpp:function:: %s(const std::vector<T>& vec)", InputVector) @@ -1075,8 +1049,7 @@ func buildJSDocumentationInputVector(component ComponentDefinition, w LanguageWr w.Writeln(" ") } - -func buildJSDocumentationStructs(component ComponentDefinition, w LanguageWriter) (error) { +func buildJSDocumentationStructs(component ComponentDefinition, w LanguageWriter) error { if len(component.Structs) == 0 { return nil } @@ -1090,34 +1063,34 @@ func buildJSDocumentationStructs(component ComponentDefinition, w LanguageWriter 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 @@ -1129,7 +1102,7 @@ func buildJSDocumentationSimpleTypes(component ComponentDefinition, w LanguageWr 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(" ") @@ -1158,19 +1131,19 @@ func buildJSDocumentationEnums(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 buildJSDocumentationFunctionTypes(component ComponentDefinition, w LanguageWriter) (error) { +func buildJSDocumentationFunctionTypes(component ComponentDefinition, w LanguageWriter) error { if len(component.Functions) == 0 { return nil } @@ -1182,7 +1155,7 @@ func buildJSDocumentationFunctionTypes(component ComponentDefinition, w Language for i := 0; i < len(component.Functions); i++ { functiontype := component.Functions[i] err := writeJSDocumentationFunctionPointer(component, w, functiontype) - if (err!=nil) { + if err != nil { return err } } @@ -1191,7 +1164,7 @@ func buildJSDocumentationFunctionTypes(component ComponentDefinition, w Language return nil } -func buildJSDocumentationTypes(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) (error) { +func buildJSDocumentationTypes(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) error { LibraryName := component.LibraryName w.Writeln("") @@ -1202,13 +1175,13 @@ func buildJSDocumentationTypes(component ComponentDefinition, w LanguageWriter, buildJSDocumentationSimpleTypes(component, w) buildJSDocumentationEnums(component, w) - + err := buildJSDocumentationStructs(component, w) - if (err!=nil) { + if err != nil { return err } err = buildJSDocumentationFunctionTypes(component, w) - if (err!=nil) { + if err != nil { return err } buildJSDocumentationException(component, w) diff --git a/Source/componentdefinition.go b/Source/componentdefinition.go index 24be9903..045ad7b6 100644 --- a/Source/componentdefinition.go +++ b/Source/componentdefinition.go @@ -50,56 +50,56 @@ import ( ) const ( - eSpecialMethodNone = 0 - eSpecialMethodVersion = 1 - eSpecialMethodRelease = 2 - eSpecialMethodAcquire = 3 - eSpecialMethodError = 4 - eSpecialMethodInjection = 5 + eSpecialMethodNone = 0 + eSpecialMethodVersion = 1 + eSpecialMethodRelease = 2 + eSpecialMethodAcquire = 3 + eSpecialMethodError = 4 + eSpecialMethodInjection = 5 eSpecialMethodSymbolLookup = 6 - eSpecialMethodJournal = 7 - eSpecialMethodPrerelease = 8 - eSpecialMethodBuildinfo = 9 + eSpecialMethodJournal = 7 + eSpecialMethodPrerelease = 8 + eSpecialMethodBuildinfo = 9 ) // ComponentDefinitionParam definition of a method parameter used in the component's API type ComponentDefinitionParam struct { ComponentDiffableElement - XMLName xml.Name `xml:"param"` - ParamName string `xml:"name,attr"` - ParamType string `xml:"type,attr"` - ParamPass string `xml:"pass,attr"` - ParamClass string `xml:"class,attr"` - ParamDescription string `xml:"description,attr"` + XMLName xml.Name `xml:"param"` + ParamName string `xml:"name,attr"` + ParamType string `xml:"type,attr"` + ParamPass string `xml:"pass,attr"` + ParamClass string `xml:"class,attr"` + ParamDescription string `xml:"description,attr"` } // ComponentDefinitionMethod definition of a method provided by the component's API type ComponentDefinitionMethod struct { ComponentDiffableElement - XMLName xml.Name `xml:"method"` - MethodName string `xml:"name,attr"` - MethodDescription string `xml:"description,attr"` - DisableStringOutCache bool `xml:"disablestringoutcache,attr"` - Params []ComponentDefinitionParam `xml:"param"` + XMLName xml.Name `xml:"method"` + MethodName string `xml:"name,attr"` + MethodDescription string `xml:"description,attr"` + DisableStringOutCache bool `xml:"disablestringoutcache,attr"` + Params []ComponentDefinitionParam `xml:"param"` } // ComponentDefinitionClass definition of a class provided by the component's API type ComponentDefinitionClass struct { ComponentDiffableElement - XMLName xml.Name `xml:"class"` - ClassName string `xml:"name,attr"` - ClassDescription string `xml:"description,attr"` - ParentClass string `xml:"parent,attr"` - Methods []ComponentDefinitionMethod `xml:"method"` + XMLName xml.Name `xml:"class"` + ClassName string `xml:"name,attr"` + ClassDescription string `xml:"description,attr"` + ParentClass string `xml:"parent,attr"` + Methods []ComponentDefinitionMethod `xml:"method"` } // ComponentDefinitionFunctionType definition of a function interface provided by the component's API type ComponentDefinitionFunctionType struct { ComponentDiffableElement - XMLName xml.Name `xml:"functiontype"` - FunctionName string `xml:"name,attr"` - FunctionDescription string `xml:"description,attr"` - Params []ComponentDefinitionParam `xml:"param"` + XMLName xml.Name `xml:"functiontype"` + FunctionName string `xml:"name,attr"` + FunctionDescription string `xml:"description,attr"` + Params []ComponentDefinitionParam `xml:"param"` } // ComponentDefinitionBindingList definition of the language bindings to be generated for the component's API @@ -117,101 +117,101 @@ type ComponentDefinitionImplementationList struct { // ComponentDefinitionGlobal definition of global functions provided the component's API type ComponentDefinitionGlobal struct { ComponentDiffableElement - XMLName xml.Name `xml:"global"` - BaseClassName string `xml:"baseclassname,attr"` - StringOutBaseClassName string `xml:"stringoutclassname,attr"` - ErrorMethod string `xml:"errormethod,attr"` - ClassTypeIdMethod string `xml:"classtypeidmethod,attr"` - ReleaseMethod string `xml:"releasemethod,attr"` - AcquireMethod string `xml:"acquiremethod,attr"` - SymbolLookupMethod string `xml:"symbollookupmethod,attr"` - InjectionMethod string `xml:"injectionmethod,attr"` - JournalMethod string `xml:"journalmethod,attr"` - VersionMethod string `xml:"versionmethod,attr"` - PrereleaseMethod string `xml:"prereleasemethod,attr"` - BuildinfoMethod string `xml:"buildinfomethod,attr"` - Methods []ComponentDefinitionMethod `xml:"method"` + XMLName xml.Name `xml:"global"` + BaseClassName string `xml:"baseclassname,attr"` + StringOutBaseClassName string `xml:"stringoutclassname,attr"` + ErrorMethod string `xml:"errormethod,attr"` + ClassTypeIdMethod string `xml:"classtypeidmethod,attr"` + ReleaseMethod string `xml:"releasemethod,attr"` + AcquireMethod string `xml:"acquiremethod,attr"` + SymbolLookupMethod string `xml:"symbollookupmethod,attr"` + InjectionMethod string `xml:"injectionmethod,attr"` + JournalMethod string `xml:"journalmethod,attr"` + VersionMethod string `xml:"versionmethod,attr"` + PrereleaseMethod string `xml:"prereleasemethod,attr"` + BuildinfoMethod string `xml:"buildinfomethod,attr"` + Methods []ComponentDefinitionMethod `xml:"method"` } // ComponentDefinitionBinding definition of a specific languages for which bindings to the component's API will be generated type ComponentDefinitionBinding struct { ComponentDiffableElement - XMLName xml.Name `xml:"binding"` - Language string `xml:"language,attr"` - Indentation string `xml:"indentation,attr"` - ClassIdentifier string `xml:"classidentifier,attr"` - Documentation string `xml:"documentation,attr"` - Version string `xml:"version,attr"` + XMLName xml.Name `xml:"binding"` + Language string `xml:"language,attr"` + Indentation string `xml:"indentation,attr"` + ClassIdentifier string `xml:"classidentifier,attr"` + Documentation string `xml:"documentation,attr"` + Version string `xml:"version,attr"` } // ComponentDefinitionImplementation definition of a specific languages for which bindings to the component's API will be generated type ComponentDefinitionImplementation struct { ComponentDiffableElement - XMLName xml.Name `xml:"implementation"` - Language string `xml:"language,attr"` - Indentation string `xml:"indentation,attr"` - ClassIdentifier string `xml:"classidentifier,attr"` - StubIdentifier string `xml:"stubidentifier,attr"` + XMLName xml.Name `xml:"implementation"` + Language string `xml:"language,attr"` + Indentation string `xml:"indentation,attr"` + ClassIdentifier string `xml:"classidentifier,attr"` + StubIdentifier string `xml:"stubidentifier,attr"` } // ComponentDefinitionEnumOption definition of an enum used in the component's API type ComponentDefinitionEnumOption struct { ComponentDiffableElement - XMLName xml.Name `xml:"option"` - Name string `xml:"name,attr"` - Value int `xml:"value,attr"` - Description string `xml:"description,attr"` + XMLName xml.Name `xml:"option"` + Name string `xml:"name,attr"` + Value int `xml:"value,attr"` + Description string `xml:"description,attr"` } // ComponentDefinitionEnum definition of all enums used in the component's API type ComponentDefinitionEnum struct { ComponentDiffableElement - XMLName xml.Name `xml:"enum"` - Name string `xml:"name,attr"` - Description string `xml:"description,attr"` - Options []ComponentDefinitionEnumOption `xml:"option"` + XMLName xml.Name `xml:"enum"` + Name string `xml:"name,attr"` + Description string `xml:"description,attr"` + Options []ComponentDefinitionEnumOption `xml:"option"` } // ComponentDefinitionError definition of an error used in the component's API type ComponentDefinitionError struct { ComponentDiffableElement - XMLName xml.Name `xml:"error"` - Name string `xml:"name,attr"` - Code int `xml:"code,attr"` - Description string `xml:"description,attr"` + XMLName xml.Name `xml:"error"` + Name string `xml:"name,attr"` + Code int `xml:"code,attr"` + Description string `xml:"description,attr"` } // ComponentDefinitionErrors definition of errors in the component's API type ComponentDefinitionErrors struct { ComponentDiffableElement - XMLName xml.Name `xml:"errors"` - Errors []ComponentDefinitionError `xml:"error"` + XMLName xml.Name `xml:"errors"` + Errors []ComponentDefinitionError `xml:"error"` } // ComponentDefinitionImportComponent definition of errors in the component's API type ComponentDefinitionImportComponent struct { ComponentDiffableElement - XMLName xml.Name `xml:"importcomponent"` - URI string `xml:"uri,attr"` - Namespace string `xml:"namespace,attr"` + XMLName xml.Name `xml:"importcomponent"` + URI string `xml:"uri,attr"` + Namespace string `xml:"namespace,attr"` } // ComponentDefinitionMember definition of a single struct provided by the component's API type ComponentDefinitionMember struct { ComponentDiffableElement XMLName xml.Name `xml:"member"` - Name string `xml:"name,attr"` - Type string `xml:"type,attr"` - Class string `xml:"class,attr"` - Rows int `xml:"rows,attr"` - Columns int `xml:"columns,attr"` + Name string `xml:"name,attr"` + Type string `xml:"type,attr"` + Class string `xml:"class,attr"` + Rows int `xml:"rows,attr"` + Columns int `xml:"columns,attr"` } // ComponentDefinitionStruct definition of all structs provided by the component's API type ComponentDefinitionStruct struct { ComponentDiffableElement - XMLName xml.Name `xml:"struct"` - Name string `xml:"name,attr"` + XMLName xml.Name `xml:"struct"` + Name string `xml:"name,attr"` Members []ComponentDefinitionMember `xml:"member"` } @@ -219,39 +219,39 @@ type ComponentDefinitionStruct struct { type ComponentDefinitionLicenseLine struct { ComponentDiffableElement XMLName xml.Name `xml:"line"` - Value string `xml:"value,attr"` + Value string `xml:"value,attr"` } // ComponentDefinitionLicense the component's license type ComponentDefinitionLicense struct { ComponentDiffableElement - XMLName xml.Name `xml:"license"` + XMLName xml.Name `xml:"license"` Lines []ComponentDefinitionLicenseLine `xml:"line"` } // ComponentDefinition the complete definition of the component's API type ComponentDefinition struct { - ACTVersion string - XMLName xml.Name `xml:"component"` - Version string `xml:"version,attr"` - Copyright string `xml:"copyright,attr"` - Year int `xml:"year,attr"` - NameSpace string `xml:"namespace,attr"` - LibraryName string `xml:"libraryname,attr"` - BaseName string `xml:"basename,attr"` - License ComponentDefinitionLicense `xml:"license"` - Classes []ComponentDefinitionClass `xml:"class"` - Functions []ComponentDefinitionFunctionType `xml:"functiontype"` - BindingList ComponentDefinitionBindingList `xml:"bindings"` + ACTVersion string + XMLName xml.Name `xml:"component"` + Version string `xml:"version,attr"` + Copyright string `xml:"copyright,attr"` + Year int `xml:"year,attr"` + NameSpace string `xml:"namespace,attr"` + LibraryName string `xml:"libraryname,attr"` + BaseName string `xml:"basename,attr"` + License ComponentDefinitionLicense `xml:"license"` + Classes []ComponentDefinitionClass `xml:"class"` + Functions []ComponentDefinitionFunctionType `xml:"functiontype"` + BindingList ComponentDefinitionBindingList `xml:"bindings"` ImplementationList ComponentDefinitionImplementationList `xml:"implementations"` - Enums []ComponentDefinitionEnum `xml:"enum"` - Structs []ComponentDefinitionStruct `xml:"struct"` - Global ComponentDefinitionGlobal `xml:"global"` - Errors ComponentDefinitionErrors `xml:"errors"` - ImportComponents []ComponentDefinitionImportComponent `xml:"importcomponent"` + Enums []ComponentDefinitionEnum `xml:"enum"` + Structs []ComponentDefinitionStruct `xml:"struct"` + Global ComponentDefinitionGlobal `xml:"global"` + Errors ComponentDefinitionErrors `xml:"errors"` + ImportComponents []ComponentDefinitionImportComponent `xml:"importcomponent"` ImportedComponentDefinitions map[string]ComponentDefinition - NameMapsLookup NameMaps + NameMapsLookup NameMaps } // Normalize adds default values, changes deprecated constants to their later versions @@ -260,8 +260,8 @@ func (component *ComponentDefinition) Normalize() { component.Classes[i].Normalize() } component.Global.Normalize() - - for _, importedComponent := range component.ImportedComponentDefinitions { + + for _, importedComponent := range component.ImportedComponentDefinitions { importedComponent.Normalize() } } @@ -299,10 +299,10 @@ func ReadComponentDefinition(FileName string, ACTVersion string) (ComponentDefin var component ComponentDefinition component.ImportedComponentDefinitions = make(map[string]ComponentDefinition, 0) component.NameMapsLookup = NameMaps{ - enumMap : make(map[string]bool, 0), - structMap : make(map[string]bool, 0), - classMap : make(map[string]bool, 0), - functionTypeMap : make(map[string]bool, 0), + enumMap: make(map[string]bool, 0), + structMap: make(map[string]bool, 0), + classMap: make(map[string]bool, 0), + functionTypeMap: make(map[string]bool, 0), } absFileName, err := filepath.Abs(FileName) @@ -335,8 +335,8 @@ func ReadComponentDefinition(FileName string, ACTVersion string) (ComponentDefin if err != nil { return component, err } - if (subComponent.NameSpace != importComponent.Namespace) { - return component, fmt.Errorf("Namespace of imported component \"%s\" does not match declared namespace \"%s\"", importComponent.Namespace, subComponent.NameSpace); + if subComponent.NameSpace != importComponent.Namespace { + return component, fmt.Errorf("Namespace of imported component \"%s\" does not match declared namespace \"%s\"", importComponent.Namespace, subComponent.NameSpace) } component.ImportedComponentDefinitions[importComponent.Namespace] = subComponent } @@ -347,25 +347,25 @@ func ReadComponentDefinition(FileName string, ACTVersion string) (ComponentDefin func getIndentationString(str string) string { if str == "tabs" { - return "\t"; + return "\t" } - index := strings.Index(str, "spaces"); - if (index < 1) { - log.Printf ("invalid indentation: \"%s\". Using \"tabs\" instead\n", str); - return "\t"; + index := strings.Index(str, "spaces") + if index < 1 { + log.Printf("invalid indentation: \"%s\". Using \"tabs\" instead\n", str) + return "\t" } - numSpaces, err := strconv.ParseUint(str[0:index], 10, 64); - if err!=nil { - log.Printf ("invalid indentation: \"%s\". Using \"4spaces\" instead\n", str); - return " "; + numSpaces, err := strconv.ParseUint(str[0:index], 10, 64) + if err != nil { + log.Printf("invalid indentation: \"%s\". Using \"4spaces\" instead\n", str) + return " " } - indentString := ""; - var i uint64; + indentString := "" + var i uint64 for i < numSpaces { - indentString = indentString + " "; - i++; + indentString = indentString + " " + i++ } - return indentString; + return indentString } func (component *ComponentDefinition) checkImplementations() error { @@ -375,12 +375,12 @@ func (component *ComponentDefinition) checkImplementations() error { if len(implementation.ClassIdentifier) > 0 { if !nameSpaceIsValid(implementation.ClassIdentifier) { - return fmt.Errorf ("Invalid ClassIdentifier in implementation \"%s\"", implementation.Language); + return fmt.Errorf("Invalid ClassIdentifier in implementation \"%s\"", implementation.Language) } } if len(implementation.StubIdentifier) > 0 { if !stubIdentifierIsValid(implementation.StubIdentifier) { - return fmt.Errorf ("Invalid StubIdentifier in implementation \"%s\"", implementation.Language); + return fmt.Errorf("Invalid StubIdentifier in implementation \"%s\"", implementation.Language) } } } @@ -388,68 +388,68 @@ func (component *ComponentDefinition) checkImplementations() error { } func (component *ComponentDefinition) checkErrors() error { - errorNameList := make(map[string]bool, 0); - errorCodeList := make(map[int]bool, 0); + errorNameList := make(map[string]bool, 0) + errorCodeList := make(map[int]bool, 0) errors := component.Errors for i := 0; i < len(errors.Errors); i++ { - merror := errors.Errors[i]; + merror := errors.Errors[i] if !nameIsValidIdentifier(merror.Name) { - return fmt.Errorf( "invalid error name \"%s\"", merror.Name); + return fmt.Errorf("invalid error name \"%s\"", merror.Name) } - if (errorNameList[strings.ToLower(merror.Name)]) { - return fmt.Errorf( "duplicate error name \"%s\"", merror.Name); + if errorNameList[strings.ToLower(merror.Name)] { + return fmt.Errorf("duplicate error name \"%s\"", merror.Name) } - errorNameList[strings.ToLower(merror.Name)] = true; + errorNameList[strings.ToLower(merror.Name)] = true - if (errorCodeList[merror.Code]) { - return fmt.Errorf( "duplicate error code \"%d\" for error \"%s\"", merror.Code, merror.Name); + if errorCodeList[merror.Code] { + return fmt.Errorf("duplicate error code \"%d\" for error \"%s\"", merror.Code, merror.Name) } errorCodeList[merror.Code] = true if !errorDescriptionIsValid(merror.Description) { - return fmt.Errorf( "invalid error description \"%s\" for error \"%s\"", merror.Description, merror.Name); + return fmt.Errorf("invalid error description \"%s\" for error \"%s\"", merror.Description, merror.Name) } } requiredErrors := []string{"NOTIMPLEMENTED", "INVALIDPARAM", - "INVALIDCAST", "BUFFERTOOSMALL", "GENERICEXCEPTION", "COULDNOTLOADLIBRARY", "COULDNOTFINDLIBRARYEXPORT", "INCOMPATIBLEBINARYVERSION"} - for _, req := range requiredErrors { - if (!errorNameList[strings.ToLower(req)]) { - return fmt.Errorf( "component is missing the required error \"%s\"", req); - } + "INVALIDCAST", "BUFFERTOOSMALL", "GENERICEXCEPTION", "COULDNOTLOADLIBRARY", "COULDNOTFINDLIBRARYEXPORT", "INCOMPATIBLEBINARYVERSION"} + for _, req := range requiredErrors { + if !errorNameList[strings.ToLower(req)] { + return fmt.Errorf("component is missing the required error \"%s\"", req) } + } return nil } -func errorDescriptionIsValid (name string) bool { +func errorDescriptionIsValid(name string) bool { var IsValidIdentifier = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9_+\\-:,.=!/ ]*$").MatchString - if (name != "") { - return IsValidIdentifier(name); + if name != "" { + return IsValidIdentifier(name) } - - return false; + + return false } -func checkOptions(options[] ComponentDefinitionEnumOption) (error) { - optionLowerNameList := make(map[string]bool, 0); - optionValueList := make(map[int]bool, 0); +func checkOptions(options []ComponentDefinitionEnumOption) error { + optionLowerNameList := make(map[string]bool, 0) + optionValueList := make(map[int]bool, 0) for j := 0; j < len(options); j++ { option := options[j] if !nameIsValidIdentifier(option.Name) { return fmt.Errorf("invalid option name \"%s\"", option.Name) } - if (math.Abs( float64(option.Value)) > math.Exp2(31) - 1) { + if math.Abs(float64(option.Value)) > math.Exp2(31)-1 { return fmt.Errorf("option value out of range \"%d\" in \"%s\"", option.Value, option.Name) } if optionValueList[option.Value] { - return fmt.Errorf("duplicate option value \"%d\" in \"%s\"", option.Value, option.Name); + return fmt.Errorf("duplicate option value \"%d\" in \"%s\"", option.Value, option.Name) } if optionLowerNameList[strings.ToLower(option.Name)] { - return fmt.Errorf("duplicate option name \"%s\"", option.Name); + return fmt.Errorf("duplicate option name \"%s\"", option.Name) } optionValueList[option.Value] = true optionLowerNameList[strings.ToLower(option.Name)] = true @@ -457,24 +457,24 @@ func checkOptions(options[] ComponentDefinitionEnumOption) (error) { return nil } -func (component *ComponentDefinition) checkEnums() (error) { +func (component *ComponentDefinition) checkEnums() error { enums := component.Enums var enumNameList = &component.NameMapsLookup.enumMap - enumLowerNameList := make(map[string]bool, 0); + enumLowerNameList := make(map[string]bool, 0) for i := 0; i < len(enums); i++ { - enum := enums[i]; + enum := enums[i] if !nameIsValidIdentifier(enum.Name) { - return fmt.Errorf( "invalid enum name \"%s\"", enum.Name); + return fmt.Errorf("invalid enum name \"%s\"", enum.Name) } - - if (enumLowerNameList[strings.ToLower(enum.Name)]) { - return fmt.Errorf("duplicate enum name \"%s\"", enum.Name); + + if enumLowerNameList[strings.ToLower(enum.Name)] { + return fmt.Errorf("duplicate enum name \"%s\"", enum.Name) } err := checkOptions(enum.Options) if err != nil { - return fmt.Errorf(err.Error() + " in enum = \"%s\"", enum.Name); + return fmt.Errorf(err.Error()+" in enum = \"%s\"", enum.Name) } enumLowerNameList[strings.ToLower(enum.Name)] = true @@ -483,20 +483,19 @@ func (component *ComponentDefinition) checkEnums() (error) { return nil } - -func (component *ComponentDefinition) checkStructs() (error) { + +func (component *ComponentDefinition) checkStructs() error { structs := component.Structs var structNameList = &component.NameMapsLookup.structMap structLowerNameList := make(map[string]bool, 0) - for i := 0; i < len(structs); i++ { - mstruct := structs[i]; + mstruct := structs[i] if !nameIsValidIdentifier(mstruct.Name) { - return fmt.Errorf ("invalid struct name \"%s\"", mstruct.Name) + return fmt.Errorf("invalid struct name \"%s\"", mstruct.Name) } if structLowerNameList[mstruct.Name] == true { - return fmt.Errorf ("duplicate struct name \"%s\"", mstruct.Name) + return fmt.Errorf("duplicate struct name \"%s\"", mstruct.Name) } (*structNameList)[mstruct.Name] = true structLowerNameList[strings.ToLower(mstruct.Name)] = true @@ -504,14 +503,14 @@ func (component *ComponentDefinition) checkStructs() (error) { for j := 0; j < len(mstruct.Members); j++ { member := mstruct.Members[j] if !nameIsValidIdentifier(member.Name) { - return fmt.Errorf ("invalid member name \"%s\"", member.Name); + return fmt.Errorf("invalid member name \"%s\"", member.Name) } } } return nil } -func (component *ComponentDefinition) checkClasses() (error) { +func (component *ComponentDefinition) checkClasses() error { classes := component.Classes baseClassName := component.Global.BaseClassName var classNameList = &component.NameMapsLookup.classMap @@ -520,22 +519,22 @@ func (component *ComponentDefinition) checkClasses() (error) { classNameIndex := make(map[string]int, 0) classTypeIdIndex := make(map[uint64]int, 0) for i := 0; i < len(classes); i++ { - class := classes[i]; - classTypeHash, _ := class.classTypeId(component.NameSpace); + class := classes[i] + classTypeHash, _ := class.classTypeId(component.NameSpace) if !nameIsValidIdentifier(class.ClassName) { - return fmt.Errorf ("invalid class name \"%s\"", class.ClassName); + return fmt.Errorf("invalid class name \"%s\"", class.ClassName) } if classLowerNameList[strings.ToLower(class.ClassName)] == true { - return fmt.Errorf ("duplicate class name \"%s\"", class.ClassName); + return fmt.Errorf("duplicate class name \"%s\"", class.ClassName) } if len(class.ClassDescription) > 0 && !descriptionIsValid(class.ClassDescription) { - return fmt.Errorf ("invalid class description \"%s\" in class \"%s\"", class.ClassDescription, class.ClassName); + return fmt.Errorf("invalid class description \"%s\" in class \"%s\"", class.ClassDescription, class.ClassName) } collision, hashExists := classTypeIdIndex[classTypeHash] if hashExists { - return fmt.Errorf ("Classes \"%s\" and \"%s\" have a collision in their Class Type Id. Change class name.", classes[collision].ClassName, class.ClassName); + return fmt.Errorf("Classes \"%s\" and \"%s\" have a collision in their Class Type Id. Change class name.", classes[collision].ClassName, class.ClassName) } - + classLowerNameList[strings.ToLower(class.ClassName)] = true (*classNameList)[class.ClassName] = true classNameIndex[class.ClassName] = i @@ -544,23 +543,23 @@ func (component *ComponentDefinition) checkClasses() (error) { // Check parent class definitions for i := 0; i < len(classes); i++ { - class := classes[i]; - parentClass := class.ParentClass; - if ((baseClassName != class.ClassName) && (len(parentClass) == 0) ) { + class := classes[i] + parentClass := class.ParentClass + if (baseClassName != class.ClassName) && (len(parentClass) == 0) { parentClass = baseClassName } - if (len(parentClass) > 0) { + if len(parentClass) > 0 { if !nameIsValidIdentifier(parentClass) { - return fmt.Errorf ("invalid parent class name \"%s\"", parentClass); + return fmt.Errorf("invalid parent class name \"%s\"", parentClass) } - if ( (*classNameList)[parentClass] == false) { - return fmt.Errorf ("unknown parent class \"%s\" for class \"%s\"", parentClass, class.ClassName); + if (*classNameList)[parentClass] == false { + return fmt.Errorf("unknown parent class \"%s\" for class \"%s\"", parentClass, class.ClassName) } - if (classNameIndex[parentClass] >= i) { - return fmt.Errorf ("parent class \"%s\" for class \"%s\" is defined after its child class", parentClass, class.ClassName); + if classNameIndex[parentClass] >= i { + return fmt.Errorf("parent class \"%s\" for class \"%s\" is defined after its child class", parentClass, class.ClassName) } - if (strings.ToLower(class.ClassName) == strings.ToLower(parentClass)) { - return fmt.Errorf ("class \"%s\" cannot be its own parent class \"%s\"", class.ClassName, parentClass); + if strings.ToLower(class.ClassName) == strings.ToLower(parentClass) { + return fmt.Errorf("class \"%s\" cannot be its own parent class \"%s\"", class.ClassName, parentClass) } } } @@ -568,41 +567,41 @@ func (component *ComponentDefinition) checkClasses() (error) { return nil } -func (component *ComponentDefinition) checkFunctionTypes() ( error) { +func (component *ComponentDefinition) checkFunctionTypes() error { functions := component.Functions var functionNameList = &component.NameMapsLookup.functionTypeMap functionLowerNameList := make(map[string]bool, 0) for i := 0; i < len(functions); i++ { - function := functions[i]; + function := functions[i] if !nameIsValidIdentifier(function.FunctionName) { - return fmt.Errorf ("invalid functiontype name \"%s\"", function.FunctionName); + return fmt.Errorf("invalid functiontype name \"%s\"", function.FunctionName) } if functionLowerNameList[strings.ToLower(function.FunctionName)] == true { - return fmt.Errorf ("duplicate functiontype name \"%s\"", function.FunctionName); + return fmt.Errorf("duplicate functiontype name \"%s\"", function.FunctionName) } if len(function.FunctionDescription) > 0 && !descriptionIsValid(function.FunctionDescription) { - return fmt.Errorf ("invalid function description \"%s\" in functiontype \"%s\"", function.FunctionDescription, function.FunctionName); + return fmt.Errorf("invalid function description \"%s\" in functiontype \"%s\"", function.FunctionDescription, function.FunctionName) } - + functionLowerNameList[strings.ToLower(function.FunctionName)] = true (*functionNameList)[function.FunctionName] = true } return nil } -func checkDuplicateNames(nameMaps NameMaps) (error) { +func checkDuplicateNames(nameMaps NameMaps) error { enumList := nameMaps.enumMap structList := nameMaps.structMap classList := nameMaps.classMap functionTypeList := nameMaps.functionTypeMap allLowerList := make(map[string]string, 0) - + for k := range structList { if val, ok := allLowerList[strings.ToLower(k)]; ok { - if (val == "struct") { - return fmt.Errorf ("duplicate struct name \"%s\"", k) + if val == "struct" { + return fmt.Errorf("duplicate struct name \"%s\"", k) } return fmt.Errorf("struct with name \"%s\" conflicts with %s of same name", k, val) } @@ -611,8 +610,8 @@ func checkDuplicateNames(nameMaps NameMaps) (error) { for k := range enumList { if val, ok := allLowerList[strings.ToLower(k)]; ok { - if (val == "enum") { - return fmt.Errorf ("duplicate class name \"%s\"", k) + if val == "enum" { + return fmt.Errorf("duplicate class name \"%s\"", k) } return fmt.Errorf("enum with name \"%s\" conflicts with %s of same name", k, val) } @@ -621,8 +620,8 @@ func checkDuplicateNames(nameMaps NameMaps) (error) { for k := range classList { if val, ok := allLowerList[strings.ToLower(k)]; ok { - if (val == "class") { - return fmt.Errorf ("duplicate class name \"%s\"", k) + if val == "class" { + return fmt.Errorf("duplicate class name \"%s\"", k) } return fmt.Errorf("class with name \"%s\" conflicts with %s of same name", k, val) } @@ -631,8 +630,8 @@ func checkDuplicateNames(nameMaps NameMaps) (error) { for k := range functionTypeList { if val, ok := allLowerList[strings.ToLower(k)]; ok { - if (val == "functiontype") { - return fmt.Errorf ("duplicate functiontype name \"%s\"", k) + if val == "functiontype" { + return fmt.Errorf("duplicate functiontype name \"%s\"", k) } return fmt.Errorf("functiontype with name \"%s\" conflicts with %s of same name", k, val) } @@ -641,33 +640,33 @@ func checkDuplicateNames(nameMaps NameMaps) (error) { return nil } -func (component *ComponentDefinition) checkMethod(method ComponentDefinitionMethod, className string) (error) { +func (component *ComponentDefinition) checkMethod(method ComponentDefinitionMethod, className string) error { if !nameIsValidIdentifier(method.MethodName) { - return fmt.Errorf ("invalid name for method \"%s.%s\"", className, method.MethodName); + return fmt.Errorf("invalid name for method \"%s.%s\"", className, method.MethodName) } if !descriptionIsValid(method.MethodDescription) { - return fmt.Errorf ("invalid description for method \"%s.%s\"", className, method.MethodName); + return fmt.Errorf("invalid description for method \"%s.%s\"", className, method.MethodName) } paramNameList := make(map[string]bool, 0) for k := 0; k < len(method.Params); k++ { param := method.Params[k] if !nameIsValidIdentifier(param.ParamName) { - return fmt.Errorf("invalid param name \"%s\" in method \"%s.%s\"", param.ParamName, className, method.MethodName); + return fmt.Errorf("invalid param name \"%s\" in method \"%s.%s\"", param.ParamName, className, method.MethodName) } if !descriptionIsValid(method.MethodDescription) { - return fmt.Errorf("invalid description for parameter \"%s.%s(... %s ...)\"", className, method.MethodName, param.ParamName); + return fmt.Errorf("invalid description for parameter \"%s.%s(... %s ...)\"", className, method.MethodName, param.ParamName) } - if (paramNameList[strings.ToLower(param.ParamName)]) { + if paramNameList[strings.ToLower(param.ParamName)] { return fmt.Errorf("duplicate name \"%s\" for parameter in method \"%s.%s\"", param.ParamName, className, method.MethodName) } paramNameList[strings.ToLower(param.ParamName)] = true - if (isScalarType(param.ParamType) || param.ParamType == "string") { + if isScalarType(param.ParamType) || param.ParamType == "string" { // okay - } else if (param.ParamType == "basicarray") { + } else if param.ParamType == "basicarray" { if !isScalarType(param.ParamClass) { - return fmt.Errorf("parameter \"%s\" for method \"%s.%s\" is an unknown basic type \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass); + return fmt.Errorf("parameter \"%s\" for method \"%s.%s\" is an unknown basic type \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass) } } else { currentNameMaps := component.NameMapsLookup @@ -676,7 +675,7 @@ func (component *ComponentDefinition) checkMethod(method ComponentDefinitionMeth if err != nil { return err } - if len(namespace)>0 { + if len(namespace) > 0 { if subComponent, ok := component.ImportedComponentDefinitions[namespace]; ok { currentNameMaps = subComponent.NameMapsLookup } else { @@ -684,20 +683,20 @@ func (component *ComponentDefinition) checkMethod(method ComponentDefinitionMeth } } - if (param.ParamType == "class" || param.ParamType == "optionalclass" ) { - if (currentNameMaps.classMap[paramClassName] != true) { + if param.ParamType == "class" || param.ParamType == "optionalclass" { + if currentNameMaps.classMap[paramClassName] != true { return fmt.Errorf("parameter \"%s\" of method \"%s.%s\" is of unknown class \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass) } } else if (param.ParamType == "enum") || (param.ParamType == "enumarray") { - if (currentNameMaps.enumMap[paramClassName] != true) { + if currentNameMaps.enumMap[paramClassName] != true { return fmt.Errorf("parameter \"%s\" for method \"%s.%s\" is an unknown enum \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass) } } else if (param.ParamType == "structarray") || (param.ParamType == "struct") { - if (currentNameMaps.structMap[paramClassName] != true) { + if currentNameMaps.structMap[paramClassName] != true { return fmt.Errorf("parameter \"%s\" for method \"%s.%s\" is an unknown struct \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass) } - } else if (param.ParamType == "functiontype") { - if (currentNameMaps.functionTypeMap[paramClassName] != true) { + } else if param.ParamType == "functiontype" { + if currentNameMaps.functionTypeMap[paramClassName] != true { return fmt.Errorf("parameter \"%s\" for method \"%s.%s\" is an unknown function type \"%s\"", param.ParamName, className, method.MethodName, param.ParamClass) } } else { @@ -706,32 +705,30 @@ func (component *ComponentDefinition) checkMethod(method ComponentDefinitionMeth } } - - - if ((len (method.getStringOutParameters ()) > 0) && (len (method.getArrayOutParameters ()) > 0)) { - return fmt.Errorf ("String and Array out parameters for method \"%s.%s\"", className, method.MethodName); + + if (len(method.getStringOutParameters()) > 0) && (len(method.getArrayOutParameters()) > 0) { + return fmt.Errorf("String and Array out parameters for method \"%s.%s\"", className, method.MethodName) } return nil } - -func (component *ComponentDefinition) checkBaseClassMethods() (error) { +func (component *ComponentDefinition) checkBaseClassMethods() error { method := component.classTypeIdMethod() if method.MethodName == "" { - return fmt.Errorf ("ClassTypeId method is not defined in Base class"); + return fmt.Errorf("ClassTypeId method is not defined in Base class") } - if (method.MethodName == component.Global.ClassTypeIdMethod) { - if (len (method.Params) != 1) || (method.Params[0].ParamType != "uint64") || (method.Params[0].ParamPass != "return") { - return fmt.Errorf ("ClassTypeId method does not match the expected function template"); + if method.MethodName == component.Global.ClassTypeIdMethod { + if (len(method.Params) != 1) || (method.Params[0].ParamType != "uint64") || (method.Params[0].ParamPass != "return") { + return fmt.Errorf("ClassTypeId method does not match the expected function template") } } return nil } -func (component *ComponentDefinition) checkClassMethods() (error) { +func (component *ComponentDefinition) checkClassMethods() error { classes := component.Classes for i := 0; i < len(classes); i++ { @@ -740,14 +737,14 @@ func (component *ComponentDefinition) checkClassMethods() (error) { methodNameList := make(map[string]bool, 0) for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] - if (!component.isBaseClass(class) && (method.MethodName == component.Global.ClassTypeIdMethod)) { - return fmt.Errorf ("class type id method \"%s\" is redefined in \"%s\".%s\"", method.MethodName, class.ClassName) + if !component.isBaseClass(class) && (method.MethodName == component.Global.ClassTypeIdMethod) { + return fmt.Errorf("class type id method \"%s\" is redefined in \"%s\".%s\"", method.MethodName, class.ClassName) } - if (methodNameList[strings.ToLower(method.MethodName)]) { - return fmt.Errorf ("duplicate name for method \"%s.%s\"", class.ClassName, method.MethodName) + if methodNameList[strings.ToLower(method.MethodName)] { + return fmt.Errorf("duplicate name for method \"%s.%s\"", class.ClassName, method.MethodName) } methodNameList[strings.ToLower(method.MethodName)] = true - + err := component.checkMethod(method, class.ClassName) if err != nil { return err @@ -764,77 +761,77 @@ func decomposeParamClassName(paramClassName string) (string, string, error) { } namespaceRegexp := "[A-Z][a-zA-Z0-9_]{0,63}" - var IsValidParamClassName = regexp.MustCompile(fmt.Sprintf("^((%s):){0,1}([a-zA-Z0-9_]{0,64})$", namespaceRegexp) ) - + var IsValidParamClassName = regexp.MustCompile(fmt.Sprintf("^((%s):){0,1}([a-zA-Z0-9_]{0,64})$", namespaceRegexp)) + if !(IsValidParamClassName.MatchString(paramClassName)) { - return "","", fmt.Errorf("param class name \"%s\" is ill formatted", paramClassName); + return "", "", fmt.Errorf("param class name \"%s\" is ill formatted", paramClassName) } slices := IsValidParamClassName.FindStringSubmatch(paramClassName) - if (len(slices) != 4) { - return "","", fmt.Errorf("param class name \"%s\" is ill formatted", paramClassName); + if len(slices) != 4 { + return "", "", fmt.Errorf("param class name \"%s\" is ill formatted", paramClassName) } namespace := slices[2] className := slices[3] - + return namespace, className, nil } func nameIsValidIdentifier(name string) bool { var IsValidIdentifier = regexp.MustCompile("^[A-Z][a-zA-Z0-9_]{0,63}$").MatchString - if (name != "") { - return IsValidIdentifier(name); + if name != "" { + return IsValidIdentifier(name) } - return false; + return false } func descriptionIsValid(description string) bool { var IsValidMethodDescription = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9_\\\\/+\\-:,.=!?()'; |]*$").MatchString - if (description != "") { - return IsValidMethodDescription(description); + if description != "" { + return IsValidMethodDescription(description) } - return false; + return false } func isScalarType(typeStr string) bool { - switch (typeStr) { - case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double", "pointer": - return true + switch typeStr { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "bool", "single", "double", "pointer": + return true } return false } func majorVersion(version string) int { isValid, versions, _ := decomposeVersionString(version) - if (!isValid) { + if !isValid { log.Fatal("invalid version") } return versions[0] } func minorVersion(version string) int { isValid, versions, _ := decomposeVersionString(version) - if (!isValid) { + if !isValid { log.Fatal("invalid version") } return versions[1] } func microVersion(version string) int { isValid, versions, _ := decomposeVersionString(version) - if (!isValid) { + if !isValid { log.Fatal("invalid version") } return versions[2] } func preReleaseInfo(version string) string { isValid, _, additionalData := decomposeVersionString(version) - if (!isValid) { + if !isValid { log.Fatal("invalid version") } return additionalData[0] } func buildInfo(version string) string { isValid, _, additionalData := decomposeVersionString(version) - if (!isValid) { + if !isValid { log.Fatal("invalid version") } return additionalData[1] @@ -843,101 +840,100 @@ func buildInfo(version string) string { func decomposeVersionString(version string) (bool, [3]int, [2]string) { var IsValidVersion = regexp.MustCompile("^([0-9]+)\\.([0-9]+)\\.([0-9]+)(\\-[a-zA-Z0-9.\\-]+)?(\\+[a-zA-Z0-9.\\-]+)?$") - var vers [3]int; - var data [2]string; + var vers [3]int + var data [2]string if !(IsValidVersion.MatchString(version)) { - return false, vers, data; + return false, vers, data } slices := IsValidVersion.FindStringSubmatch(version) - if (len(slices) != 6) { - return false, vers, data; + if len(slices) != 6 { + return false, vers, data } for i := 0; i < 3; i++ { ver, err := strconv.Atoi(slices[i+1]) if err != nil { - return false, vers, data; + return false, vers, data } vers[i] = ver } for i := 0; i < 2; i++ { slice := slices[i+4] - if (len(slice)>0) { + if len(slice) > 0 { data[i] = slice[1:] } } - return true, vers, data; + return true, vers, data } func nameSpaceIsValid(namespace string) bool { var IsValidNamespace = regexp.MustCompile("^[A-Z][a-zA-Z0-9_]{0,63}$").MatchString - if (namespace != "") { - return IsValidNamespace(namespace); + if namespace != "" { + return IsValidNamespace(namespace) } - return false; + return false } func stubIdentifierIsValid(stubIdentifier string) bool { var IsValidStubIdentifier = regexp.MustCompile("[a-zA-Z0-9_]{0,63}$").MatchString - if (stubIdentifier != "") { - return IsValidStubIdentifier (stubIdentifier); + if stubIdentifier != "" { + return IsValidStubIdentifier(stubIdentifier) } - return false; + return false } func libraryNameIsValid(libraryname string) bool { var IsLibraryNameValid = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9_+\\-:,.=!/ ]*$").MatchString - if (libraryname != "") { - return IsLibraryNameValid (libraryname); + if libraryname != "" { + return IsLibraryNameValid(libraryname) } - return false; + return false } func baseNameIsValid(baseName string) bool { var IsBaseNameValid = regexp.MustCompile("^[a-zA-Z][a-zA-Z0-9_\\-.]*$").MatchString - if (baseName != "") { - return IsBaseNameValid (baseName); + if baseName != "" { + return IsBaseNameValid(baseName) } - return false; + return false } -func (component *ComponentDefinition) checkComponentHeader() (error) { +func (component *ComponentDefinition) checkComponentHeader() error { versionIsValid, _, _ := decomposeVersionString(component.Version) if !versionIsValid { return fmt.Errorf("Version \"%s\" is invalid", component.Version) } if component.Copyright == "" { - return errors.New ("no Copyright information given"); + return errors.New("no Copyright information given") } if (component.Year < 2000) || (component.Year > 2100) { - return errors.New ("invalid year given"); + return errors.New("invalid year given") } if !nameSpaceIsValid(component.NameSpace) { - return errors.New ("Invalid Namespace"); + return errors.New("Invalid Namespace") } if !libraryNameIsValid(component.LibraryName) { - return errors.New ("Invalid LilbraryName"); + return errors.New("Invalid LilbraryName") } if component.BaseName == "" { - log.Fatal ("Invalid export basename"); + log.Fatal("Invalid export basename") } if !baseNameIsValid(component.BaseName) { - return errors.New ("Invalid BaseName"); + return errors.New("Invalid BaseName") } return nil } // NameMaps contains maps of names of elements in a component type NameMaps struct { - enumMap map[string]bool - structMap map[string]bool - classMap map[string]bool + enumMap map[string]bool + structMap map[string]bool + classMap map[string]bool functionTypeMap map[string]bool } - // CheckComponentDefinition checks a component and returns an error, if it fails -func (component *ComponentDefinition) CheckComponentDefinition() (error) { +func (component *ComponentDefinition) CheckComponentDefinition() error { err := component.checkComponentHeader() if err != nil { return err @@ -964,7 +960,7 @@ func (component *ComponentDefinition) CheckComponentDefinition() (error) { if err != nil { return err } - + err = component.checkStructs() if err != nil { return err @@ -999,8 +995,8 @@ func (component *ComponentDefinition) CheckComponentDefinition() (error) { for i := 0; i < len(component.Global.Methods); i++ { method := component.Global.Methods[i] - if (globalMethodNameList[strings.ToLower(method.MethodName)]) { - return fmt.Errorf ("duplicate name for method \"%s.%s\"", "global", method.MethodName) + if globalMethodNameList[strings.ToLower(method.MethodName)] { + return fmt.Errorf("duplicate name for method \"%s.%s\"", "global", method.MethodName) } globalMethodNameList[strings.ToLower(method.MethodName)] = true @@ -1015,192 +1011,189 @@ func (component *ComponentDefinition) CheckComponentDefinition() (error) { } } - if (component.Global.BaseClassName == "") { - return errors.New ("No base class name specified"); + if component.Global.BaseClassName == "" { + return errors.New("No base class name specified") } found := 0 for i := 0; i < len(component.Classes); i++ { - if (component.Classes[i].ClassName == component.Global.BaseClassName) { + if component.Classes[i].ClassName == component.Global.BaseClassName { found++ } } - if (found==0) { - return errors.New ("Specified base class not found"); - } else if (found>1) { - return errors.New ("Base clase defined more than once"); + if found == 0 { + return errors.New("Specified base class not found") + } else if found > 1 { + return errors.New("Base clase defined more than once") } return nil } - // CheckHeaderSpecialFunction checks a special function of the header against their required definitions func CheckHeaderSpecialFunction(method ComponentDefinitionMethod, global ComponentDefinitionGlobal) (int, error) { - if (global.ReleaseMethod == "") { - return eSpecialMethodNone, errors.New ("No release method specified"); + if global.ReleaseMethod == "" { + return eSpecialMethodNone, errors.New("No release method specified") } - if (global.AcquireMethod == "") { - return eSpecialMethodNone, errors.New ("No acquire method specified"); + if global.AcquireMethod == "" { + return eSpecialMethodNone, errors.New("No acquire method specified") } - if (global.VersionMethod == "") { - return eSpecialMethodNone, errors.New ("No version method specified"); + if global.VersionMethod == "" { + return eSpecialMethodNone, errors.New("No version method specified") } - if (global.ErrorMethod == "") { - return eSpecialMethodNone, errors.New ("No error method specified"); + if global.ErrorMethod == "" { + return eSpecialMethodNone, errors.New("No error method specified") } - if (global.ClassTypeIdMethod == "") { - return eSpecialMethodNone, errors.New ("No ClassTypeId method specified"); + if global.ClassTypeIdMethod == "" { + return eSpecialMethodNone, errors.New("No ClassTypeId method specified") } - if (global.ReleaseMethod == global.JournalMethod) { - return eSpecialMethodNone, errors.New ("Release method can not be the same as the Journal method"); + if global.ReleaseMethod == global.JournalMethod { + return eSpecialMethodNone, errors.New("Release method can not be the same as the Journal method") } - if (global.ReleaseMethod == global.VersionMethod) { - return eSpecialMethodNone, errors.New ("Release method can not be the same as the Version method"); + if global.ReleaseMethod == global.VersionMethod { + return eSpecialMethodNone, errors.New("Release method can not be the same as the Version method") } - if (global.ReleaseMethod == global.AcquireMethod) { - return eSpecialMethodNone, errors.New ("Release method can not be the same as the Acquire method"); + if global.ReleaseMethod == global.AcquireMethod { + return eSpecialMethodNone, errors.New("Release method can not be the same as the Acquire method") } - if (global.JournalMethod == global.VersionMethod) { - return eSpecialMethodNone, errors.New ("Journal method can not be the same as the Version method"); + if global.JournalMethod == global.VersionMethod { + return eSpecialMethodNone, errors.New("Journal method can not be the same as the Version method") } - if (global.JournalMethod == global.AcquireMethod) { - return eSpecialMethodNone, errors.New ("Journal method can not be the same as the Acquire method"); + if global.JournalMethod == global.AcquireMethod { + return eSpecialMethodNone, errors.New("Journal method can not be the same as the Acquire method") } - if (method.MethodName == global.ReleaseMethod) { - if (len (method.Params) != 1) { - return eSpecialMethodNone, errors.New ("Release method does not match the expected function template"); + if method.MethodName == global.ReleaseMethod { + if len(method.Params) != 1 { + return eSpecialMethodNone, errors.New("Release method does not match the expected function template") } - + if (method.Params[0].ParamType != "class") || (method.Params[0].ParamClass != global.BaseClassName) || (method.Params[0].ParamPass != "in") { - return eSpecialMethodNone, errors.New ("Release method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Release method does not match the expected function template") } - return eSpecialMethodRelease, nil; + return eSpecialMethodRelease, nil } - if (method.MethodName == global.AcquireMethod) { - if (len (method.Params) != 1) { - return eSpecialMethodNone, errors.New ("Acquire method does not match the expected function template"); + if method.MethodName == global.AcquireMethod { + if len(method.Params) != 1 { + return eSpecialMethodNone, errors.New("Acquire method does not match the expected function template") } - + if (method.Params[0].ParamType != "class") || (method.Params[0].ParamClass != global.BaseClassName) || (method.Params[0].ParamPass != "in") { - return eSpecialMethodNone, errors.New ("Acquire method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Acquire method does not match the expected function template") } - return eSpecialMethodAcquire, nil; + return eSpecialMethodAcquire, nil } - if (method.MethodName == global.SymbolLookupMethod) { - if (len (method.Params) != 1) { - return eSpecialMethodNone, errors.New ("SymbolLookup method does not match the expected function template"); + if method.MethodName == global.SymbolLookupMethod { + if len(method.Params) != 1 { + return eSpecialMethodNone, errors.New("SymbolLookup method does not match the expected function template") } if (method.Params[0].ParamType != "pointer") || (method.Params[0].ParamPass != "return") { - return eSpecialMethodNone, errors.New ("SymbolLookup method does not match the expected function template"); + return eSpecialMethodNone, errors.New("SymbolLookup method does not match the expected function template") } - + return eSpecialMethodSymbolLookup, nil } - if (method.MethodName == global.InjectionMethod) { - if (len (method.Params) != 2) { - return eSpecialMethodNone, errors.New ("Injection method does not match the expected function template"); + if method.MethodName == global.InjectionMethod { + if len(method.Params) != 2 { + return eSpecialMethodNone, errors.New("Injection method does not match the expected function template") } if (method.Params[0].ParamType != "string") || (method.Params[0].ParamPass != "in") || (method.Params[1].ParamType != "pointer") || (method.Params[1].ParamPass != "in") { - return eSpecialMethodNone, errors.New ("Injection method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Injection method does not match the expected function template") } - + return eSpecialMethodInjection, nil } - if (method.MethodName == global.JournalMethod) { - if (len (method.Params) != 1) { - return eSpecialMethodNone, errors.New ("Journal method does not match the expected function template"); + if method.MethodName == global.JournalMethod { + if len(method.Params) != 1 { + return eSpecialMethodNone, errors.New("Journal method does not match the expected function template") } - + if (method.Params[0].ParamType != "string") || (method.Params[0].ParamPass != "in") { - return eSpecialMethodNone, errors.New ("Journal method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Journal method does not match the expected function template") } - - return eSpecialMethodJournal, nil; + + return eSpecialMethodJournal, nil } - if (method.MethodName == global.VersionMethod) { - if (len (method.Params) != 3) { - return eSpecialMethodNone, errors.New ("Version method does not match the expected function template"); + if method.MethodName == global.VersionMethod { + if len(method.Params) != 3 { + return eSpecialMethodNone, errors.New("Version method does not match the expected function template") } - - if (method.Params[0].ParamType != "uint32") || (method.Params[0].ParamPass != "out") || - (method.Params[1].ParamType != "uint32") || (method.Params[1].ParamPass != "out") || + + if (method.Params[0].ParamType != "uint32") || (method.Params[0].ParamPass != "out") || + (method.Params[1].ParamType != "uint32") || (method.Params[1].ParamPass != "out") || (method.Params[2].ParamType != "uint32") || (method.Params[2].ParamPass != "out") { - return eSpecialMethodNone, errors.New ("Version method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Version method does not match the expected function template") } - - return eSpecialMethodVersion, nil; + + return eSpecialMethodVersion, nil } - - if (method.MethodName == global.ErrorMethod) { - if (len (method.Params) != 3) { - return eSpecialMethodNone, errors.New ("Error method does not match the expected function template"); + + if method.MethodName == global.ErrorMethod { + if len(method.Params) != 3 { + return eSpecialMethodNone, errors.New("Error method does not match the expected function template") } - - if (method.Params[0].ParamType != "class") || (method.Params[0].ParamPass != "in") || - (method.Params[1].ParamType != "string") || (method.Params[1].ParamPass != "out") || + + if (method.Params[0].ParamType != "class") || (method.Params[0].ParamPass != "in") || + (method.Params[1].ParamType != "string") || (method.Params[1].ParamPass != "out") || (method.Params[2].ParamType != "bool") || (method.Params[2].ParamPass != "return") || (method.Params[0].ParamClass != global.BaseClassName) { - return eSpecialMethodNone, errors.New ("Error method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Error method does not match the expected function template") } - - return eSpecialMethodError, nil; + + return eSpecialMethodError, nil } - if len(global.PrereleaseMethod)>0 && (global.PrereleaseMethod == global.BuildinfoMethod) { - return eSpecialMethodNone, errors.New ("Prerelease method can not be the same as the buildinfo method"); + if len(global.PrereleaseMethod) > 0 && (global.PrereleaseMethod == global.BuildinfoMethod) { + return eSpecialMethodNone, errors.New("Prerelease method can not be the same as the buildinfo method") } - - if (method.MethodName == global.PrereleaseMethod) { - if (len (method.Params) != 2) { - return eSpecialMethodNone, errors.New ("Prerelease method does not match the expected function template"); + + if method.MethodName == global.PrereleaseMethod { + if len(method.Params) != 2 { + return eSpecialMethodNone, errors.New("Prerelease method does not match the expected function template") } - - if (method.Params[0].ParamType != "bool") || (method.Params[0].ParamPass != "return") || + + if (method.Params[0].ParamType != "bool") || (method.Params[0].ParamPass != "return") || (method.Params[1].ParamType != "string") || (method.Params[1].ParamPass != "out") { - return eSpecialMethodNone, errors.New ("Prerelease method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Prerelease method does not match the expected function template") } - - return eSpecialMethodPrerelease, nil; + + return eSpecialMethodPrerelease, nil } - if (method.MethodName == global.BuildinfoMethod) { - if (len (method.Params) != 2) { - return eSpecialMethodNone, errors.New ("Buildinfo method does not match the expected function template"); + if method.MethodName == global.BuildinfoMethod { + if len(method.Params) != 2 { + return eSpecialMethodNone, errors.New("Buildinfo method does not match the expected function template") } - - if (method.Params[0].ParamType != "bool") || (method.Params[0].ParamPass != "return") || + + if (method.Params[0].ParamType != "bool") || (method.Params[0].ParamPass != "return") || (method.Params[1].ParamType != "string") || (method.Params[1].ParamPass != "out") { - return eSpecialMethodNone, errors.New ("Buildinfo method does not match the expected function template"); + return eSpecialMethodNone, errors.New("Buildinfo method does not match the expected function template") } - - return eSpecialMethodBuildinfo, nil; - } - + return eSpecialMethodBuildinfo, nil + } - return eSpecialMethodNone, nil; + return eSpecialMethodNone, nil } // GetLastErrorMessageMethod returns the xml definition of the GetLastErrorMessage-method -func GetLastErrorMessageMethod() (ComponentDefinitionMethod) { +func GetLastErrorMessageMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod source := `<method name="GetLastErrorMessage" description = "Returns the last error registered of this class instance"> <param name="ErrorMessage" type="string" pass="out" description="Message of the last error registered" /> @@ -1211,7 +1204,7 @@ func GetLastErrorMessageMethod() (ComponentDefinitionMethod) { } // RegisterErrorMessageMethod returns the xml definition of the RegisterErrorMessage-method -func RegisterErrorMessageMethod() (ComponentDefinitionMethod) { +func RegisterErrorMessageMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod source := `<method name="RegisterErrorMessage" description = "Registers an error message with this class instance"> <param name="ErrorMessage" type="string" pass="in" description="Error message to register" /> @@ -1221,7 +1214,7 @@ func RegisterErrorMessageMethod() (ComponentDefinitionMethod) { } // ClearErrorMessageMethod returns the xml definition of the ClearErrorMessage-method -func ClearErrorMessageMethod() (ComponentDefinitionMethod) { +func ClearErrorMessageMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod source := ` <method name="ClearErrorMessages" description = "Clears all registered messages of this class instance"> </method>` @@ -1230,7 +1223,7 @@ func ClearErrorMessageMethod() (ComponentDefinitionMethod) { } // IncRefCountMethod returns the xml definition of the IncRefCount-method -func IncRefCountMethod() (ComponentDefinitionMethod) { +func IncRefCountMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod source := `<method name="IncRefCount" description = "Increases the reference count of a class instance"> </method>` @@ -1239,7 +1232,7 @@ func IncRefCountMethod() (ComponentDefinitionMethod) { } // DecRefCountMethod returns the xml definition of the DecRefCount-method -func DecRefCountMethod() (ComponentDefinitionMethod) { +func DecRefCountMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod source := `<method name="DecRefCount" description = "Decreases the reference count of a class instance and free releases it, if the last reference has been removed"> <param name="HasBeenReleased" type="bool" pass="return" description="Has the object been released" /> @@ -1249,7 +1242,7 @@ func DecRefCountMethod() (ComponentDefinitionMethod) { } // ReleaseBaseClassInterfaceMethod returns the xml definition of a method that should decrease the reference count of a BaseClass interface. -func ReleaseBaseClassInterfaceMethod(baseClassName string) (ComponentDefinitionMethod) { +func ReleaseBaseClassInterfaceMethod(baseClassName string) ComponentDefinitionMethod { var method ComponentDefinitionMethod source := `<method name="ReleaseBaseClassInterface" description = "Releases ownership of a base class interface. Deletes the reference, if necessary."> <param name="IBase" type="class" class="` + baseClassName + `" pass="in" description="The base class instance to release" /> @@ -1259,7 +1252,7 @@ func ReleaseBaseClassInterfaceMethod(baseClassName string) (ComponentDefinitionM } // AcquireBaseClassInterfaceMethod returns the xml definition of a method that should increase the reference count of a BaseClass interface. -func AcquireBaseClassInterfaceMethod(baseClassName string) (ComponentDefinitionMethod) { +func AcquireBaseClassInterfaceMethod(baseClassName string) ComponentDefinitionMethod { var method ComponentDefinitionMethod source := `<method name="AcquireBaseClassInterface" description = "Acquires shared ownership of a base class interface."> <param name="IBase" type="class" class="` + baseClassName + `" pass="in" description="The base class instance to acquire" /> @@ -1268,13 +1261,13 @@ func AcquireBaseClassInterfaceMethod(baseClassName string) (ComponentDefinitionM return method } -func (component *ComponentDefinition) isBaseClass(class ComponentDefinitionClass) (bool) { +func (component *ComponentDefinition) isBaseClass(class ComponentDefinitionClass) bool { return class.ClassName == component.Global.BaseClassName } -func (component *ComponentDefinition) baseClass() (ComponentDefinitionClass) { +func (component *ComponentDefinition) baseClass() ComponentDefinitionClass { for i := 0; i < len(component.Classes); i++ { - if (component.isBaseClass(component.Classes[i])) { + if component.isBaseClass(component.Classes[i]) { return component.Classes[i] } } @@ -1283,134 +1276,127 @@ func (component *ComponentDefinition) baseClass() (ComponentDefinitionClass) { return out } - -func (component *ComponentDefinition) isStringOutBaseClass(class ComponentDefinitionClass) (bool) { +func (component *ComponentDefinition) isStringOutBaseClass(class ComponentDefinitionClass) bool { return class.ClassName == component.Global.StringOutBaseClassName } +func (component *ComponentDefinition) isStringOutClass(class ComponentDefinitionClass) bool { -func (component *ComponentDefinition) isStringOutClass(class ComponentDefinitionClass) (bool) { - - if (component.isStringOutBaseClass (class)) { - return true; + if component.isStringOutBaseClass(class) { + return true } - - - parentClassName := class.ParentClass; - if ((parentClassName == "") && (class.ClassName != component.Global.BaseClassName)) { - parentClassName = component.Global.BaseClassName; + + parentClassName := class.ParentClass + if (parentClassName == "") && (class.ClassName != component.Global.BaseClassName) { + parentClassName = component.Global.BaseClassName } - - if (parentClassName != "") { - + + if parentClassName != "" { + for i := 0; i < len(component.Classes); i++ { - parentClass := component.Classes[i]; - if (parentClass.ClassName == parentClassName) { - return component.isStringOutClass (parentClass); + parentClass := component.Classes[i] + if parentClass.ClassName == parentClassName { + return component.isStringOutClass(parentClass) } } - - } - - return false; -} + } + return false +} -func (method *ComponentDefinitionMethod) countOutParameters() (uint32) { +func (method *ComponentDefinitionMethod) countOutParameters() uint32 { - var outParameters uint32; - outParameters = 0; + var outParameters uint32 + outParameters = 0 for i := 0; i < len(method.Params); i++ { - if ((method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return")) { - outParameters++; + if (method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return") { + outParameters++ } } - - return outParameters; -} + return outParameters +} -func (method *ComponentDefinitionMethod) getStringOutParameters() ([]string) { +func (method *ComponentDefinitionMethod) getStringOutParameters() []string { - var outParameters []string; + var outParameters []string for i := 0; i < len(method.Params); i++ { - if (method.Params[i].ParamType == "string") { - if ((method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return")) { - outParameters = append (outParameters, method.Params[i].ParamName); - } + if method.Params[i].ParamType == "string" { + if (method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return") { + outParameters = append(outParameters, method.Params[i].ParamName) + } } } - - return outParameters; + + return outParameters } -func (method *ComponentDefinitionMethod) getArrayOutParameters() ([]string) { +func (method *ComponentDefinitionMethod) getArrayOutParameters() []string { - var outParameters []string; + var outParameters []string for i := 0; i < len(method.Params); i++ { - if ((method.Params[i].ParamType == "basicarray") || (method.Params[i].ParamType == "structarray")) { - if ((method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return")) { - outParameters = append (outParameters, method.Params[i].ParamName); - } + if (method.Params[i].ParamType == "basicarray") || (method.Params[i].ParamType == "structarray") { + if (method.Params[i].ParamPass == "out") || (method.Params[i].ParamPass == "return") { + outParameters = append(outParameters, method.Params[i].ParamName) + } } } - - return outParameters; -} + return outParameters +} -func (class *ComponentDefinitionClass) countMaxOutParameters() (uint32) { +func (class *ComponentDefinitionClass) countMaxOutParameters() uint32 { - var maxOutParameters uint32; - maxOutParameters = 0; + var maxOutParameters uint32 + maxOutParameters = 0 for i := 0; i < len(class.Methods); i++ { - outParameters := class.Methods[i].countOutParameters (); - if (outParameters > maxOutParameters) { - maxOutParameters = outParameters; + outParameters := class.Methods[i].countOutParameters() + if outParameters > maxOutParameters { + maxOutParameters = outParameters } } - - return maxOutParameters; + + return maxOutParameters } -func (component *ComponentDefinition) countMaxOutParameters() (uint32) { +func (component *ComponentDefinition) countMaxOutParameters() uint32 { - var maxOutParameters uint32; - maxOutParameters = 0; + var maxOutParameters uint32 + maxOutParameters = 0 classes := component.Classes for i := 0; i < len(classes); i++ { class := classes[i] - - outParameters := class.countMaxOutParameters (); - if (outParameters > maxOutParameters) { - maxOutParameters = outParameters; + + outParameters := class.countMaxOutParameters() + if outParameters > maxOutParameters { + maxOutParameters = outParameters } } - - methods := component.Global.Methods; + + methods := component.Global.Methods for i := 0; i < len(methods); i++ { - outParameters := methods[i].countOutParameters (); - if (outParameters > maxOutParameters) { - maxOutParameters = outParameters; + outParameters := methods[i].countOutParameters() + if outParameters > maxOutParameters { + maxOutParameters = outParameters } } - return maxOutParameters; + return maxOutParameters } -func (component *ComponentDefinition) classTypeIdMethod() (ComponentDefinitionMethod) { +func (component *ComponentDefinition) classTypeIdMethod() ComponentDefinitionMethod { var method ComponentDefinitionMethod baseClass := component.baseClass() for j := 0; j < len(baseClass.Methods); j++ { - if (baseClass.Methods[j].MethodName == component.Global.ClassTypeIdMethod) { + if baseClass.Methods[j].MethodName == component.Global.ClassTypeIdMethod { return baseClass.Methods[j] break } From da06c96faf40a35e2fd6cfb994b1795dbc820dbb Mon Sep 17 00:00:00 2001 From: Ed <edwin.kilday@autodesk.com> Date: Thu, 20 Jul 2023 09:16:25 +0100 Subject: [PATCH 2/5] optional args --- Build/build.bat | 2 +- Build/build.sh | 2 +- Source/automaticcomponenttoolkit.go | 21 + Source/buildimplementationcpp.go | 2 +- Source/buildimplementationjs.go | 580 +++++++++++++++++----------- Source/buildimplementationts.go | 487 +++++++++++++++++++++++ Source/componentdefinition.go | 16 +- go.mod | 3 + 8 files changed, 878 insertions(+), 235 deletions(-) create mode 100644 Source/buildimplementationts.go create mode 100644 go.mod diff --git a/Build/build.bat b/Build/build.bat index f113776f..a125fd34 100644 --- a/Build/build.bat +++ b/Build/build.bat @@ -3,7 +3,7 @@ set startingDir="%CD%" set basepath="%~dp0" cd %basepath%\..\Source -set Sources=actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildimplementationcpp.go buildbindingjava.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go buildimplementationjs.go +set Sources=actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildimplementationcpp.go buildbindingjava.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go buildimplementationjs.go buildimplementationts.go set GOOS=windows set GOARCH=amd64 diff --git a/Build/build.sh b/Build/build.sh index fb74daf2..4050a422 100755 --- a/Build/build.sh +++ b/Build/build.sh @@ -6,7 +6,7 @@ startingpath="$(pwd)" basepath="$(cd "$(dirname "$0")" && pwd)" cd "$basepath/../Source" -Sources="actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go buildimplementationjs.go" +Sources="actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go buildimplementationjs.go buildimplementationts.go" echo "Build act.win64.exe" export GOARCH="amd64" diff --git a/Source/automaticcomponenttoolkit.go b/Source/automaticcomponenttoolkit.go index c8684727..8dc94fbb 100644 --- a/Source/automaticcomponenttoolkit.go +++ b/Source/automaticcomponenttoolkit.go @@ -594,7 +594,28 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin } } + + case "TS": + { + + output := path.Join(outfolderBase, "TS") + + err = os.MkdirAll(output, os.ModePerm) + if err != nil { + return err + } + + err = BuildImplementationTS( + component, + output, + implementation, + ) + if err != nil { + return err + } + } + default: log.Fatal("Unknown export") } diff --git a/Source/buildimplementationcpp.go b/Source/buildimplementationcpp.go index 0ee11ea4..b443f7c9 100644 --- a/Source/buildimplementationcpp.go +++ b/Source/buildimplementationcpp.go @@ -1648,7 +1648,7 @@ func generatePrePostCallCPPFunctionCode(component ComponentDefinition, method Co preCallCode = append(preCallCode, fmt.Sprintf("I%s%s* pI%s = dynamic_cast<I%s%s*>(pIBaseClass%s);", ClassIdentifier, param.ParamClass, param.ParamName, ClassIdentifier, param.ParamClass, param.ParamName)) } - if param.ParamType == "class" { + if param.ParamType == "class" && param.ParamOptional != "true" { preCallCode = append(preCallCode, fmt.Sprintf("if (!pI%s)", param.ParamName)) preCallCode = append(preCallCode, fmt.Sprintf(" throw E%sInterfaceException (%s_ERROR_INVALIDCAST);", NameSpace, strings.ToUpper(NameSpace))) preCallCode = append(preCallCode, "") diff --git a/Source/buildimplementationjs.go b/Source/buildimplementationjs.go index 09c66c55..ed980d85 100644 --- a/Source/buildimplementationjs.go +++ b/Source/buildimplementationjs.go @@ -35,7 +35,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package main import ( - "errors" "fmt" "log" "path" @@ -144,7 +143,6 @@ func BuildImplementationJS(component ComponentDefinition, outputFolder string, s } - //if (!suppressStub) { err := buildJSTypesFiles(component, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier) if err != nil { return err @@ -162,8 +160,6 @@ func BuildImplementationJS(component ComponentDefinition, outputFolder string, s } - //} - if outputFolderDocumentation != "" { err = BuildJSDocumentation(component, outputFolderDocumentation, implementation.ClassIdentifier) @@ -327,7 +323,7 @@ func buildJSInjectionClass(component ComponentDefinition, subComponent Component headerw.Writeln(" /* class helper methods */") headerw.Writeln(" static eInjectionClassType getClassType();") headerw.Writeln("") - headerw.Writeln(" static %s::P%s getInstance(const v8::FunctionCallbackInfo<v8::Value>& args);", subComponent.NameSpace, class.ClassName) + headerw.Writeln(" static %s::P%s getInstance(const v8::Local<v8::Object>& holder);", subComponent.NameSpace, class.ClassName) headerw.Writeln("") headerw.Writeln(" /* V8 Registration commands */") headerw.Writeln(" static void internalV8RegisterMethods(v8::Local<v8::FunctionTemplate> localClassTemplate, std::shared_ptr<Cv8objectCreator> pObjectCreator, v8::Local<v8::Object> target);") @@ -338,8 +334,13 @@ func buildJSInjectionClass(component ComponentDefinition, subComponent Component for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] - headerw.Writeln(" static void v8%s(const v8::FunctionCallbackInfo<v8::Value>& args);", method.MethodName) - + if method.PropertyGet != "" { + headerw.Writeln(" static void v8%s(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args);", method.MethodName) + } else if method.PropertySet != "" { + headerw.Writeln(" static void v8%s(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& args);", method.MethodName) + } else { + headerw.Writeln(" static void v8%s(const v8::FunctionCallbackInfo<v8::Value>& args);", method.MethodName) + } } //static void V8Data(const v8::FunctionCallbackInfo<v8::Value>& args); @@ -408,9 +409,9 @@ func buildJSInjectionClass(component ComponentDefinition, subComponent Component cppw.Writeln("}") cppw.Writeln("") - cppw.Writeln("%s::P%s Cv8%s::getInstance(const v8::FunctionCallbackInfo<v8::Value>& args)", subComponent.NameSpace, class.ClassName, class.ClassName) + cppw.Writeln("%s::P%s Cv8%s::getInstance(const v8::Local<v8::Object>& holder)", subComponent.NameSpace, class.ClassName, class.ClassName) cppw.Writeln("{") - cppw.Writeln(" auto objectWrapper = UnwrapBase(args.Holder());") + cppw.Writeln(" auto objectWrapper = UnwrapBase(holder);") cppw.Writeln(" if (objectWrapper == nullptr)") cppw.Writeln(" throw std::runtime_error (\"could not get %s instance wrapper.\");", class.ClassName) cppw.Writeln("") @@ -461,11 +462,27 @@ func buildJSInjectionClass(component ComponentDefinition, subComponent Component cppw.Writeln(" // Add functions to prototype object") for i := 0; i < len(class.Methods); i++ { method := class.Methods[i] - - lowerCaseMethodName := strings.ToLower(method.MethodName[:1]) + method.MethodName[1:] - - 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);", lowerCaseMethodName, class.ClassName, method.MethodName) + if method.PropertySet != "" { + // Ignore setters + } else if method.PropertyGet != "" { + readOnly := true + var getter = &method + var setter *ComponentDefinitionMethod + for _, method := range class.Methods { + if method.PropertySet == getter.PropertyGet { + setter = &method + readOnly = false + break + } + } + if readOnly { + cppw.Writeln(" Cv8toolsUtils::Set_proto_accessor(localClassTemplate, \"%s\", Cv8%s::v8%s);", getter.PropertyGet, class.ClassName, getter.MethodName) + } 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) + } + } else { + cppw.Writeln(" Cv8toolsUtils::Set_proto_method(localClassTemplate, \"%s\", Cv8%s::v8%s);", method.MethodName, class.ClassName, method.MethodName) + } } cppw.Writeln("") cppw.Writeln("}") @@ -485,246 +502,129 @@ func buildJSInjectionClass(component ComponentDefinition, subComponent Component for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] - argCount := 0 - argString := "" - for k := 0; k < len(method.Params); k++ { - if method.Params[k].ParamPass != "return" { - if argCount != 0 { - argString = argString + ", " - } - - argString = argString + method.Params[k].ParamName - - argCount = argCount + 1 - } + if method.PropertyGet != "" { + cppw.Writeln("void Cv8%s::v8%s(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value>& args)", class.ClassName, method.MethodName) + } else if method.PropertySet != "" { + cppw.Writeln("void Cv8%s::v8%s(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<void>& args)", class.ClassName, method.MethodName) + } else { + cppw.Writeln("void Cv8%s::v8%s(const v8::FunctionCallbackInfo<v8::Value>& args)", class.ClassName, method.MethodName) } - - cppw.Writeln("void Cv8%s::v8%s(const v8::FunctionCallbackInfo<v8::Value>& args)", class.ClassName, method.MethodName) cppw.Writeln("{") cppw.Writeln(" v8::Isolate* isolate = v8::Isolate::GetCurrent();") cppw.Writeln("") cppw.Writeln(" try {") - cppw.Writeln(" checkArgumentParameters(args, %d, \"%s.%s (%s)\");", argCount, class.ClassName, method.MethodName, argString) - cppw.Writeln("") - cppw.Writeln(" auto instancePtr = getInstance(args);") - cppw.Writeln("") - cppw.Writeln(" auto v8instance = UnwrapBase(args.Holder());") - cppw.Writeln(" if (v8instance == nullptr)") - cppw.Writeln(" throw std::runtime_error(\"could not get %s instance.\");", class.ClassName) - cppw.Writeln("") - cppw.Writeln(" auto objectCreator = v8instance->getObjectCreator();") - cppw.Writeln(" if (objectCreator == nullptr)") - cppw.Writeln(" throw std::runtime_error(\"invalid object creator.\");") - cppw.Writeln("") - - resultString := "" - argumentString := "" - returnValueCall := "" - returnValueParameter := "" - cppArrayClass := "" - - baseClassName := "P" + component.Global.BaseClassName - - outOrResultParameterCount := 0 - - for k := 0; k < len(method.Params); k++ { - param := method.Params[k] - if (param.ParamPass == "out") || (param.ParamPass == "return") { - outOrResultParameterCount = outOrResultParameterCount + 1 + cppw.Indentation += 2 + + if method.PropertySet == "" && method.PropertyGet == "" { + inArgs := filterPass(method.Params, "in") + optionalArgs := filterOptional(inArgs) + argString := "" + for k, param := range inArgs { + if k != 0 { + argString = argString + ", " + } + if param.ParamOptional == "true" { + argString = argString + "[" + param.ParamName + "]" + } else { + argString = argString + param.ParamName + } } + cppw.Writeln( + "checkArgumentParameters(args, %d, %d, \"%s.%s (%s)\");", + len(inArgs)-len(optionalArgs), + len(inArgs), + class.ClassName, + method.MethodName, + argString, + ) + cppw.Writeln("") } - for k := 0; k < len(method.Params); k++ { - param := method.Params[k] - - cppParamType := "" - argumentMethodCallType := "" - argumentDefault := "" - cppReturnValueCast := "" - - switch param.ParamType { - case "uint8": - cppParamType = param.ParamType + "_t" - argumentMethodCallType = "Uint8" - argumentDefault = "0" - case "uint16": - cppParamType = param.ParamType + "_t" - argumentMethodCallType = "Uint16" - argumentDefault = "0" - case "uint32": - cppParamType = param.ParamType + "_t" - argumentMethodCallType = "Uint32" - argumentDefault = "0" - case "uint64": - cppParamType = param.ParamType + "_t" - argumentMethodCallType = "Uint64" - argumentDefault = "0" - case "int8": - cppParamType = param.ParamType + "_t" - argumentMethodCallType = "Int8" - argumentDefault = "0" - case "int16": - cppParamType = param.ParamType + "_t" - argumentMethodCallType = "Int16" - argumentDefault = "0" - case "int32": - cppParamType = param.ParamType + "_t" - argumentMethodCallType = "Int32" - argumentDefault = "0" - case "int64": - cppParamType = param.ParamType + "_t" - argumentMethodCallType = "Int64" - argumentDefault = "0" - case "single": - cppParamType = "float" - argumentMethodCallType = "Float" - argumentDefault = "0.0f" - case "double": - cppParamType = "double" - argumentMethodCallType = "Double" - argumentDefault = "0.0" - case "string": - cppParamType = "std::string" - argumentMethodCallType = "String" - argumentDefault = "\"\"" - case "bool": - cppParamType = "bool" - argumentMethodCallType = "Bool" - argumentDefault = "false" - case "pointer": - cppParamType = "void *" - argumentMethodCallType = "Pointer" - argumentDefault = "nullptr" - case "class", "optionalclass": - cppParamType = subComponent.NameSpace + "::P" + param.ParamClass - argumentMethodCallType = "Object" - argumentDefault = "nullptr" - case "enum": - cppParamType = subComponent.NameSpace + "::e" + param.ParamClass - argumentMethodCallType = "Int32" - argumentDefault = "(" + subComponent.NameSpace + "::e" + param.ParamClass + ") 0" - cppReturnValueCast = "(" + subComponent.NameSpace + "::e" + param.ParamClass + ")" - case "basicarray": - switch param.ParamClass { - case "uint8": - argumentMethodCallType = "Uint8Array" - cppArrayClass = param.ParamClass + "_t" - case "uint16": - argumentMethodCallType = "Uint16Array" - cppArrayClass = param.ParamClass + "_t" - case "uint32": - argumentMethodCallType = "Uint32Array" - cppArrayClass = param.ParamClass + "_t" - case "uint64": - argumentMethodCallType = "Uint64Array" - cppArrayClass = param.ParamClass + "_t" - case "int8": - argumentMethodCallType = "Int8Array" - cppArrayClass = param.ParamClass + "_t" - case "int16": - argumentMethodCallType = "Int16Array" - cppArrayClass = param.ParamClass + "_t" - case "int32": - argumentMethodCallType = "Int32Array" - cppArrayClass = param.ParamClass + "_t" - case "int64": - argumentMethodCallType = "Int64Array" - cppArrayClass = param.ParamClass + "_t" - case "single": - argumentMethodCallType = "FloatArray" - cppArrayClass = "float" - case "double": - argumentMethodCallType = "DoubleArray" - cppArrayClass = "double" - case "bool": - argumentMethodCallType = "BoolArray" - cppArrayClass = "uint8_t" - default: - return errors.New("Invalid array class: " + param.ParamClass) - } - - default: - return errors.New("Invalid parameter type: " + param.ParamType) + // This is probably because I should be adding to the prototype + if method.PropertySet != "" || method.PropertyGet != "" { + cppw.Writeln("auto instancePtr = getInstance(args.This());") + cppw.Writeln("") + cppw.Writeln("auto v8instance = UnwrapBase(args.This());") + } else { + cppw.Writeln("auto instancePtr = getInstance(args.Holder());") + cppw.Writeln("") + cppw.Writeln("auto v8instance = UnwrapBase(args.Holder());") + } + cppw.Writeln("if (v8instance == nullptr)") + cppw.Writeln(" throw std::runtime_error(\"could not get %s instance.\");", class.ClassName) + cppw.Writeln("") + cppw.Writeln("auto objectCreator = v8instance->getObjectCreator();") + cppw.Writeln("if (objectCreator == nullptr)") + cppw.Writeln(" throw std::runtime_error(\"invalid object creator.\");") + cppw.Writeln("") - /* case "structarray": - case "struct": - case "functiontype": */ - } + baseClassName := "P" + component.Global.BaseClassName + argumentString := "" + for k, param := range method.Params { if param.ParamPass == "in" { - if argumentString != "" { - argumentString = argumentString + ", " + argName := "value" + if method.PropertySet == "" { + argName = fmt.Sprintf("args[%d]", k) } - argumentString = argumentString + "param" + param.ParamName + writeExtractV8InArg(param, k, subComponent, baseClassName, argName, cppw) + } + } - if param.ParamType == "class" { - cppw.Writeln(" %s::%s object%s = v8instance->get%sArgument (isolate, args, %d);", subComponent.NameSpace, baseClassName, param.ParamName, argumentMethodCallType, k) - cppw.Writeln(" %s param%s = std::dynamic_pointer_cast<%s::C%s> (object%s);", cppParamType, param.ParamName, subComponent.NameSpace, param.ParamClass, param.ParamName) - } else if param.ParamType == "optionalclass" { - cppw.Writeln(" %s::%s object%s = v8instance->get%sArgument (isolate, args, %d);", subComponent.NameSpace, baseClassName, param.ParamName, argumentMethodCallType, k) - cppw.Writeln(" %s param%s = std::dynamic_pointer_cast<%s::C%s> (object%s);", cppParamType, param.ParamName, subComponent.NameSpace, param.ParamClass, param.ParamName) - } else if param.ParamType == "basicarray" { - cppw.Writeln(" std::vector<%s> param%s;", cppArrayClass, param.ParamName) - cppw.Writeln(" v8instance->get%sArgument (isolate, args, param%s, %d);", argumentMethodCallType, param.ParamName, k) + for _, param := range method.Params { + if param.ParamPass == "out" || param.ParamPass == "return" { + if param.ParamType == "basicarray" { + cppw.Writeln("std::vector<%s> param%s;", cppArrayClass(param), param.ParamName) } else { - cppw.Writeln(" %s param%s = %sv8instance->get%sArgument (isolate, args, %d);", cppParamType, param.ParamName, cppReturnValueCast, argumentMethodCallType, k) + cppw.Writeln("%s param%s = %s;", cppParamType(param, subComponent), param.ParamName, argumentDefault(param, subComponent)) } } + } - if param.ParamPass == "out" { + resultString := "" + for _, param := range method.Params { + if param.ParamPass != "return" { if argumentString != "" { argumentString = argumentString + ", " } argumentString = argumentString + "param" + param.ParamName + } + } - if param.ParamType == "basicarray" { - cppw.Writeln(" std::vector<%s> param%s;", cppArrayClass, param.ParamName) - } else { - cppw.Writeln(" %s param%s = %s;", cppParamType, param.ParamName, argumentDefault) - } + returnArgs := filterPass(method.Params, "return") + if len(returnArgs) > 0 { + // Just take the first + param := returnArgs[0] + resultString = "param" + param.ParamName + " = " + } - returnValueCall = "set" + argumentMethodCallType + "ReturnValue" + cppw.Writeln("%sinstancePtr->%s (%s);", resultString, method.MethodName, argumentString) - if param.ParamType == "class" { - returnValueParameter = fmt.Sprintf("createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s()))", param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) - } else if param.ParamType == "optionalclass" { - returnValueParameter = fmt.Sprintf("param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local<v8::Object>()", param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) - } else if param.ParamType == "enum" { - returnValueParameter = "(uint32_t) param" + param.ParamName - } else { - returnValueParameter = "param" + param.ParamName - } + outArgs := filterPass(method.Params, "out") + if len(outArgs) > 0 { + cppw.Writeln("auto context = isolate->GetCurrentContext();") + cppw.Writeln("auto outArgs = v8::Array::New(isolate);") + for n, param := range outArgs { + argName := "v8" + param.ParamName + writeInsertV8OutArg(param, subComponent, argName, cppw) + cppw.Writeln("outArgs->Set(context, %d, %s);", n, argName) } - if param.ParamPass == "return" { - - if param.ParamType == "basicarray" { - cppw.Writeln(" std::vector<%s> param%s;", cppArrayClass, param.ParamName) - } else { - cppw.Writeln(" %s param%s = %s;", cppParamType, param.ParamName, argumentDefault) - } - resultString = "param" + param.ParamName + " = " - returnValueCall = "set" + argumentMethodCallType + "ReturnValue" - - if param.ParamType == "class" { - returnValueParameter = fmt.Sprintf("createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s()))", param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) - } else if param.ParamType == "optionalclass" { - returnValueParameter = fmt.Sprintf("param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local<v8::Object>()", param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) - } else if param.ParamType == "enum" { - returnValueParameter = "(uint32_t) param" + param.ParamName - } else { - returnValueParameter = "param" + param.ParamName + cppw.Writeln("args.GetReturnValue().Set(outArgs);") + } else { + for k := 0; k < len(method.Params); k++ { + param := method.Params[k] + if param.ParamPass == "return" { + if method.PropertySet == "" { + returnValueArg := generateReturnValue(param, subComponent) + cppw.Writeln("setReturnValue(isolate, args, %s);", returnValueArg) + } } } - } - - cppw.Writeln(" %sinstancePtr->%s (%s);", resultString, method.MethodName, argumentString) - if returnValueCall != "" { - cppw.Writeln(" %s(isolate, args, %s);", returnValueCall, returnValueParameter) - } - cppw.Writeln(" ") + cppw.Writeln("") + cppw.Indentation -= 2 cppw.Writeln("") cppw.Writeln(" }") @@ -733,9 +633,7 @@ func buildJSInjectionClass(component ComponentDefinition, subComponent Component cppw.Writeln(" }") cppw.Writeln("}") cppw.Writeln("") - } - cppw.Writeln("") return nil @@ -757,6 +655,236 @@ func writeMapClassIdtoInjectionClassTypeFunction(w LanguageWriter, component Com w.Writeln("}") } +func writeExtractV8InArg( + param ComponentDefinitionParam, + index int, + subComponent ComponentDefinition, + baseClassName string, + argName string, + writer LanguageWriter, +) { + switch param.ParamType { + case "class", "optionalclass": + writer.Writeln("%s::%s object%s;", subComponent.NameSpace, baseClassName, param.ParamName) + case "basicarray": + writer.Writeln("std::vector<%s> param%s;", cppArrayClass(param), param.ParamName) + case "string": + if param.ParamOptional == "true" { + writer.Writeln("%s param%s = \"%s\";", cppParamType(param, subComponent), param.ParamName, param.ParamDefaultValue) + } else { + writer.Writeln("%s param%s;", cppParamType(param, subComponent), param.ParamName) + } + case "enum": + if param.ParamOptional == "true" { + writer.Writeln("%s param%s = %s::%s;", cppParamType(param, subComponent), param.ParamName, cppParamType(param, subComponent), param.ParamDefaultValue) + } else { + writer.Writeln("%s param%s;", cppParamType(param, subComponent), param.ParamName) + } + default: + if param.ParamOptional == "true" { + writer.Writeln("%s param%s = %s;", cppParamType(param, subComponent), param.ParamName, param.ParamDefaultValue) + } else { + writer.Writeln("%s param%s;", cppParamType(param, subComponent), param.ParamName) + } + } + if param.ParamOptional == "true" { + writer.Writeln("if (args.Length() > %d) {", index) + writer.Indentation++ + } + switch param.ParamType { + case "class", "optionalclass": + writer.Writeln("object%s = v8instance->get%sArgument (isolate, %s);", param.ParamName, argumentMethodCallType(param), argName) + case "basicarray": + writer.Writeln("v8instance->get%sArgument (isolate, %s, param%s);", argumentMethodCallType(param), argName, param.ParamName) + default: + writer.Writeln("param%s = %sv8instance->get%sArgument (isolate, %s);", param.ParamName, cppReturnValueCast(param, subComponent), argumentMethodCallType(param), argName) + } + if param.ParamOptional == "true" { + writer.Indentation-- + writer.Writeln("}") + } + switch param.ParamType { + case "class", "optionalclass": + writer.Writeln("%s param%s = std::dynamic_pointer_cast<%s::C%s> (object%s);", cppParamType(param, subComponent), param.ParamName, subComponent.NameSpace, param.ParamClass, param.ParamName) + } +} + +func writeInsertV8OutArg( + param ComponentDefinitionParam, + subComponent ComponentDefinition, + argName string, + writer LanguageWriter, +) { + switch param.ParamType { + case "class": + writer.Writeln("auto %s = createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s()));", argName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + case "optionalclass": + writer.Writeln("auto %s = param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local<v8::Object>();", argName, param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + case "enum": + writer.Writeln("auto %s = v8::Number::New(isolate, (uint32_t)param%s);", argName, param.ParamName) + case "string": + writer.Writeln("auto %s = v8::String::NewFromUtf8(isolate, param%s.c_str()).ToLocalChecked();", argName, param.ParamName) + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": + writer.Writeln("auto %s = v8::Number::New(isolate, param%s);", argName, param.ParamName) + case "bool": + writer.Writeln("auto %s = v8::Boolean::New(isolate, param%s);", argName, param.ParamName) + case "basicarray": + writer.Writeln("auto %s = v8::Array::New(isolate);", argName) + writer.Writeln("for (size_t i = 0; i < param%s.size(); ++i) {", param.ParamName) + writer.Writeln(" const auto& %s = param%s.at(i);", strings.ToLower(param.ParamName), param.ParamName) + writer.Writeln(" %s->Set(context, i, v8::%s::New(isolate, %s));", argName, v8Type(param), strings.ToLower(param.ParamName)) + writer.Writeln("}") + default: + writer.Writeln("<" + param.ParamType + ">") + } +} + +func v8Type(param ComponentDefinitionParam) string { + if param.ParamType == "basicarray" { + return v8TypeString(param.ParamClass) + } + return v8TypeString(param.ParamType) +} + +func v8TypeString(paramType string) string { + v8type := "" + switch paramType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", "single", "double": + v8type = "Number" + case "bool": + v8type = "Boolean" + case "string": + v8type = "String" + default: + v8type = "<" + paramType + ">" + } + return v8type +} + +func 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) + } else if param.ParamType == "optionalclass" { + returnValue = fmt.Sprintf("param%s?createV8Instance(objectCreator, param%s, %s_MapClassIdToInjectionClassType(param%s->%s())):v8::Local<v8::Object>()", param.ParamName, param.ParamName, subComponent.NameSpace, param.ParamName, subComponent.Global.ClassTypeIdMethod) + } else if param.ParamType == "enum" { + returnValue = "(uint32_t) param" + param.ParamName + } else { + returnValue = "param" + param.ParamName + } + return returnValue +} + +func cppParamType( + param ComponentDefinitionParam, + subComponent ComponentDefinition, +) string { + result := "" + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": + result = param.ParamType + "_t" + case "single": + result = "float" + case "double": + result = "double" + case "string": + result = "std::string" + case "bool": + result = "bool" + case "pointer": + result = "void *" + case "class", "optionalclass": + result = subComponent.NameSpace + "::P" + param.ParamClass + case "enum": + result = subComponent.NameSpace + "::e" + param.ParamClass + default: + result = "<" + param.ParamType + ">" + } + return result +} + +func argumentMethodCallType(param ComponentDefinitionParam) string { + result := "" + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", + "single", "double", "string", "bool": + result = strings.Title(param.ParamType) + case "pointer": + result = "Pointer" + case "class", "optionalclass": + result = "Object" + case "enum": + result = "Int32" + case "basicarray": + switch param.ParamClass { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64", + "single", "double", "string", "bool": + result = strings.Title(param.ParamClass) + "Array" + default: + result = "<" + param.ParamType + "|" + param.ParamClass + ">" + } + default: + result = "<" + param.ParamType + ">" + } + return result +} + +func argumentDefault( + param ComponentDefinitionParam, + subComponent ComponentDefinition, +) string { + result := "" + switch param.ParamType { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": + result = "0" + case "single": + result = "0.0f" + case "double": + result = "0.0" + case "string": + result = "\"\"" + case "bool": + result = "false" + case "pointer", "class", "optionalclass": + result = "nullptr" + case "enum": + result = "(" + subComponent.NameSpace + "::e" + param.ParamClass + ") 0" + default: + result = "<" + param.ParamType + ">" + } + + return result +} + +func cppArrayClass(param ComponentDefinitionParam) string { + result := "" + if param.ParamType == "basicarray" { + switch param.ParamClass { + case "uint8", "uint16", "uint32", "uint64", "int8", "int16", "int32", "int64": + result = param.ParamClass + "_t" + case "single", "double": + result = "double" + case "bool": + result = "uint8_t" + default: + result = "<" + param.ParamClass + ">" + } + + } + return result +} + +func cppReturnValueCast( + param ComponentDefinitionParam, + subComponent ComponentDefinition, +) string { + result := "" + if param.ParamType == "enum" { + result = "(" + subComponent.NameSpace + "::e" + param.ParamClass + ")" + } + return result +} + // BuildJSDocumentation builds the Sphinx documentation of a library's C++-bindings func BuildJSDocumentation(component ComponentDefinition, outputFolder string, ClassIdentifier string) error { BaseName := component.BaseName diff --git a/Source/buildimplementationts.go b/Source/buildimplementationts.go new file mode 100644 index 00000000..4dfb7810 --- /dev/null +++ b/Source/buildimplementationts.go @@ -0,0 +1,487 @@ +/*++ + +Copyright (C) 2023 Autodesk Inc. (Original Author) + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--*/ + +////////////////////////////////////////////////////////////////////////////////////////////////////// +// buildimplementationts.go +// Builds typescript interface definitions. +////////////////////////////////////////////////////////////////////////////////////////////////////// + +package main + +import ( + "errors" + "log" + "path" + "strings" + "unicode" +) + +type TypeScriptOptions struct { + Camelize bool + JsArrays bool + LineLength int +} + +// BuildImplementationTS builds typescript interface definitions +func BuildImplementationTS( + component ComponentDefinition, + outputFolder string, + implementation ComponentDefinitionImplementation, +) error { + + log.Printf("Creating TypeScript Implementation") + + options := TypeScriptOptions{ + Camelize: false, + JsArrays: false, + LineLength: 80, + } + + filename := path.Join(outputFolder, "fusion-environment-act.d.ts") + log.Printf("Creating \"%s\"", filename) + file, err := CreateLanguageFile(filename, " ") + if err != nil { + return err + } + + file.WriteCLicenseHeader(component, "", true) + file.Writeln("") + file.Writeln("export namespace %s {", component.NameSpace) + + err = writeTypescriptInterfaces(component, file, options) + if err != nil { + return err + } + err = writeTypescriptEnums(component, file, options) + if err != nil { + return err + } + file.Writeln("} // %s ", component.NameSpace) + + return nil +} + +func writeTypescriptEnums( + component ComponentDefinition, + writer LanguageWriter, + options TypeScriptOptions, +) error { + + for _, enum := range component.Enums { + err := writeTypescriptEnum(enum, writer, options) + if err != nil { + return err + } + } + return nil +} + +func writeTypescriptEnum( + enum ComponentDefinitionEnum, + writer LanguageWriter, + options TypeScriptOptions, +) error { + writer.Writeln("const enum %s {", getId(enum.Name, options)) + writer.Indentation++ + for _, option := range enum.Options { + writeCommentEnumOption(option, writer, options) + identifier := getId(option.Name, options) + value := option.Value + writer.Writeln("%s = %d,", identifier, value) + } + writer.Indentation-- + writer.Writeln("}") + writer.Writeln("") + return nil +} + +func writeTypescriptInterfaces( + component ComponentDefinition, + writer LanguageWriter, + options TypeScriptOptions, +) error { + for _, class := range component.Classes { + err := writeTypescriptInterface(class, writer, options) + if err != nil { + return err + } + } + return nil +} + +func writeTypescriptInterface( + class ComponentDefinitionClass, + writer LanguageWriter, + options TypeScriptOptions, +) error { + writeCommentClass(class, writer, options) + identifier := getId(class.ClassName, options) + extends := "" + if class.ParentClass != "" { + extends = "extends " + class.ParentClass + " " + } + writer.Writeln("interface %s %s{", identifier, extends) + + for _, method := range class.Methods { + writer.Indentation++ + var err error + if method.PropertyGet != "" || method.PropertySet != "" { + err = writeTypescriptProperty(class, method, writer, options) + } else { + err = writeTypescriptMethod(class, method, writer, options) + } + if err != nil { + return err + } + writer.Indentation-- + } + writer.Writeln("}") + writer.Writeln("") + return nil +} + +func writeTypescriptMethod( + class ComponentDefinitionClass, + method ComponentDefinitionMethod, + writer LanguageWriter, + options TypeScriptOptions, +) error { + inParams := filterPass(method.Params, "in") + outParams := filterPass(method.Params, "out") + returnParams := filterPass(method.Params, "return") + + writer.Writeln("") + writeCommentMethod(class, method, writer, options) + writer.BeginLine() + writer.Printf("%s: (", getId(method.MethodName, options)) + for i, param := range inParams { + if param.ParamOptional == "true" { + writer.Printf( + "%s?: %s", + getId(param.ParamName, options), + getType(param, options), + ) + } else { + writer.Printf( + "%s: %s", + getId(param.ParamName, options), + getType(param, options), + ) + } + if i+1 < len(inParams) { + writer.Printf(", ") + } + } + writer.Printf(") => ") + + if len(outParams) > 0 { + writer.Printf("[") + for i, param := range outParams { + writer.Printf( + "%s: %s", + getId(param.ParamName, options), + getType(param, options), + ) + if i+1 < len(outParams) { + writer.Printf(", ") + } + } + writer.Printf("]") + } else { + if len(returnParams) > 1 { + return errors.New("More than one return value.") + } else if len(returnParams) == 1 { + writer.Printf(getType(returnParams[0], options)) + } else { + writer.Printf("void") + } + } + + writer.Printf(";") + writer.EndLine() + return nil +} + +func writeTypescriptProperty( + class ComponentDefinitionClass, + method ComponentDefinitionMethod, + writer LanguageWriter, + options TypeScriptOptions, +) error { + if method.PropertySet != "" { + // Ignore setters + return nil + } + getter := &method + var setter *ComponentDefinitionMethod + for _, method := range class.Methods { + if method.PropertySet == getter.PropertyGet { + setter = &method + continue + } + } + returnParams := filterPass(getter.Params, "return") + if len(returnParams) != 1 { + return errors.New("Property getters should have a single return value.") + } + readOnly := "readonly " + if setter != nil { + readOnly = "" + } + writer.Writeln("") + writeCommentProperty(class, *getter, writer, options) + writer.Writeln( + "%s%s: %s;", + readOnly, + getId(getter.PropertyGet, options), + getType(returnParams[0], options), + ) + return nil +} + +func filterPass( + params []ComponentDefinitionParam, + pass string, +) []ComponentDefinitionParam { + var result []ComponentDefinitionParam + for _, param := range params { + if param.ParamPass == pass { + result = append(result, param) + } + } + return result +} + +func filterOptional(params []ComponentDefinitionParam) []ComponentDefinitionParam { + var result []ComponentDefinitionParam + for _, param := range params { + if param.ParamOptional == "true" { + result = append(result, param) + } + } + return result +} + +func getId(identifier string, options TypeScriptOptions) string { + if options.Camelize { + return camelize(identifier) + } + return identifier +} + +func getType( + param ComponentDefinitionParam, + options TypeScriptOptions, +) string { + return getTypeString(param.ParamType, param.ParamClass, options) +} + +func getTypeString( + paramType string, + paramClass string, + options TypeScriptOptions, +) string { + if paramType == "class" || paramType == "enum" { + if options.JsArrays && strings.HasSuffix(paramClass, "Vector") { + return strings.TrimSuffix(paramClass, "Vector") + "[]" + } + return paramClass + } else if paramType == "basicarray" { + return getTypeString(paramClass, "", options) + "[]" + } else if paramType == "double" || + paramType == "int16" || + paramType == "int32" || + paramType == "int64" || + paramType == "uint16" || + paramType == "uint32" || + paramType == "uint64" { + return "number" + } else if paramType == "bool" { + return "boolean" + } + return paramType +} + +func camelize(identifier string) string { + if len(identifier) == 0 { + return identifier + } + result := []rune(identifier) + result[0] = unicode.ToLower(result[0]) + return string(result) +} + +func writeCommentEnumOption( + option ComponentDefinitionEnumOption, + writer LanguageWriter, + options TypeScriptOptions, +) { + writer.Writeln("/**") + lines := getCommentLines(" * ", option.Description, writer, options) + for _, line := range lines { + writer.Writeln(" * " + line) + } + writer.Writeln(" */") +} + +func writeCommentClass( + class ComponentDefinitionClass, + writer LanguageWriter, + options TypeScriptOptions, +) { + writer.Writeln("/**") + lines := getCommentLines(" * ", class.ClassDescription, writer, options) + for _, line := range lines { + writer.Writeln(" * " + line) + } + writer.Writeln(" */") +} + +func writeCommentMethod( + class ComponentDefinitionClass, + method ComponentDefinitionMethod, + writer LanguageWriter, + options TypeScriptOptions, +) { + writer.Writeln("/**") + lines := getCommentLines(" * ", method.MethodDescription, writer, options) + for _, line := range lines { + writer.Writeln(" * " + line) + } + inParams := filterPass(method.Params, "in") + outParams := filterPass(method.Params, "out") + returnParams := filterPass(method.Params, "return") + + writeCommentInParams(inParams, writer, options) + if len(outParams) > 0 { + writeCommentOutParams(outParams, writer, options) + } else { + writeCommentReturnParams(returnParams, writer, options) + } + writer.Writeln(" */") +} + +func writeCommentProperty( + class ComponentDefinitionClass, + method ComponentDefinitionMethod, + writer LanguageWriter, + options TypeScriptOptions, +) { + writer.Writeln("/**") + lines := getCommentLines(" * ", method.MethodDescription, writer, options) + for _, line := range lines { + writer.Writeln(" * " + line) + } + writer.Writeln(" */") +} + +func writeCommentInParams( + params []ComponentDefinitionParam, + writer LanguageWriter, + options TypeScriptOptions, +) { + for _, param := range params { + prefix := " * @param {" + getType(param, options) + "} " + + getId(param.ParamName, options) + " " + lines := getCommentLines(prefix, param.ParamDescription, writer, options) + if len(lines) > 0 { + writer.Writeln(prefix + lines[0]) + prefix = " * " + strings.Repeat(" ", len(prefix)-len(" * ")) + for i := 1; i < len(lines); i++ { + line := lines[i] + writer.Writeln(prefix + line) + } + } + } +} + +func writeCommentOutParams( + params []ComponentDefinitionParam, + writer LanguageWriter, + options TypeScriptOptions, +) { + for _, param := range params { + prefix := " * @returns {" + getType(param, options) + "} " + prefix2 := prefix + getId(param.ParamName, options) + " " + lines := getCommentLines(prefix2, param.ParamDescription, writer, options) + if len(lines) > 0 { + writer.Writeln(prefix2 + lines[0]) + prefix2 = " * " + strings.Repeat(" ", len(prefix2)-len(" * ")) + for i := 1; i < len(lines); i++ { + line := lines[i] + writer.Writeln(prefix2 + line) + } + } + } +} + +func writeCommentReturnParams( + params []ComponentDefinitionParam, + writer LanguageWriter, + options TypeScriptOptions, +) { + for _, param := range params { + prefix := " * @returns {" + getType(param, options) + "} " + lines := getCommentLines(prefix, param.ParamDescription, writer, options) + if len(lines) > 0 { + writer.Writeln(prefix + lines[0]) + prefix = " * " + strings.Repeat(" ", len(prefix)-len(" * ")) + for i := 1; i < len(lines); i++ { + line := lines[i] + writer.Writeln(prefix + line) + } + } + } +} + +func getCommentLines( + prefix string, + comment string, + writer LanguageWriter, + options TypeScriptOptions, +) []string { + indent := strings.Repeat(writer.IndentString, writer.Indentation) + lineLength := options.LineLength - len(indent) - len(prefix) + return getLines(comment, lineLength) +} + +func getLines(input string, width int) []string { + words := strings.Fields(input) + var lines []string + line := "" + for _, word := range words { + if len(line)+len(word) > width { + lines = append(lines, line) + line = word + " " + } else { + line += word + " " + } + } + lines = append(lines, line) + return lines +} diff --git a/Source/componentdefinition.go b/Source/componentdefinition.go index 045ad7b6..38b21d2a 100644 --- a/Source/componentdefinition.go +++ b/Source/componentdefinition.go @@ -65,12 +65,14 @@ const ( // ComponentDefinitionParam definition of a method parameter used in the component's API type ComponentDefinitionParam struct { ComponentDiffableElement - XMLName xml.Name `xml:"param"` - ParamName string `xml:"name,attr"` - ParamType string `xml:"type,attr"` - ParamPass string `xml:"pass,attr"` - ParamClass string `xml:"class,attr"` - ParamDescription string `xml:"description,attr"` + XMLName xml.Name `xml:"param"` + ParamName string `xml:"name,attr"` + ParamType string `xml:"type,attr"` + ParamPass string `xml:"pass,attr"` + ParamClass string `xml:"class,attr"` + ParamDefaultValue string `xml:"defaultvalue,attr"` + ParamOptional string `xml:"optional,attr"` + ParamDescription string `xml:"description,attr"` } // ComponentDefinitionMethod definition of a method provided by the component's API @@ -81,6 +83,8 @@ type ComponentDefinitionMethod struct { MethodDescription string `xml:"description,attr"` DisableStringOutCache bool `xml:"disablestringoutcache,attr"` Params []ComponentDefinitionParam `xml:"param"` + PropertyGet string `xml:"propertyget,attr"` + PropertySet string `xml:"propertyset,attr"` } // ComponentDefinitionClass definition of a class provided by the component's API diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..f2a17a7c --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module Source + +go 1.20 From 0b1a2560758eaebe44388f23844edd0458f73277 Mon Sep 17 00:00:00 2001 From: Ed <edwin.kilday@autodesk.com> Date: Thu, 20 Jul 2023 19:26:20 +0100 Subject: [PATCH 3/5] 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 2a4364ca92e293f254b6e6901b3bc3243af5b6cc Mon Sep 17 00:00:00 2001 From: Ed <edwin.kilday@autodesk.com> Date: Fri, 21 Jul 2023 12:04:31 +0100 Subject: [PATCH 4/5] 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 cfcf005e64b773b4892a0c9ab8331e1a1e2a12c2 Mon Sep 17 00:00:00 2001 From: Ed <edwin.kilday@autodesk.com> Date: Fri, 21 Jul 2023 12:14:14 +0100 Subject: [PATCH 5/5] 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."