diff --git a/Build/build.bat b/Build/build.bat index 91fce019..dd6be40b 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 buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go +set Sources=actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppsplit.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationcppsplit.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go set GOOS=windows set GOARCH=amd64 diff --git a/Build/build.sh b/Build/build.sh index 6a9b3065..767e833d 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 buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go" +Sources="actutils.go automaticcomponenttoolkit.go buildbindingccpp.go buildbindingccppsplit.go buildbindingccppdocumentation.go buildbindingcsharp.go buildbindinggo.go buildbindingnode.go buildbindingpascal.go buildbindingpython.go buildbindingwasm.go buildbindingjava.go buildimplementationcpp.go buildimplementationcppsplit.go buildimplementationpascal.go componentdefinition.go componentdiff.go languagewriter.go languagec.go languagecpp.go languagepascal.go" echo "Build act.win64.exe" export GOARCH="amd64" diff --git a/Documentation/IDL.md b/Documentation/IDL.md index 2a9b8447..caf1245e 100644 --- a/Documentation/IDL.md +++ b/Documentation/IDL.md @@ -168,6 +168,7 @@ of type **CT\_Export** | indentation | **ST\_Indentation** | optional | 4spaces | Which string should be used to denote a single level of indentation in the generated source code files. | | stubidentifier | **ST\_StubIdentifier** | optional | "" | Generated sources files of this export will follow the naming schme "...${BaseName}_${stubidentifier}...". Only used in \ right now. | | classidentifier | **ST\_ClassIdentifier** | optional | "" | Generated classes of this export will follow the naming schme "...${ClassIdentifier}_${ClassName}...". The only binding that supports this are the C++-bindings.| +| splitclasses | **xs:boolean** | optional | false | Split the generated source code by class: one header per class, the umbrella header keeps the usual name. In \ language="Cpp" this applies to the interface headers. In \ language="CppDynamic" the method bodies, the function table and the polymorphic factory move into a single source file that has to be compiled and linked, so the output is no longer header-only. Ignored by all other languages. | ## 8. Global Element **\** of type **CT\_Global** diff --git a/Source/ACT.xsd b/Source/ACT.xsd index 0fdfb5d3..ff4618f9 100644 --- a/Source/ACT.xsd +++ b/Source/ACT.xsd @@ -79,6 +79,7 @@ + diff --git a/Source/automaticcomponenttoolkit.go b/Source/automaticcomponenttoolkit.go index 0526dcd1..590b88fb 100644 --- a/Source/automaticcomponenttoolkit.go +++ b/Source/automaticcomponenttoolkit.go @@ -166,7 +166,7 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin } outputFolderExampleCppDynamic := "" - if !suppressExamples { + if !suppressExamples && !binding.SplitClasses { outputFolderExampleCppDynamic = outputFolderExamples + "/CppDynamic" err = os.MkdirAll(outputFolderExampleCppDynamic, os.ModePerm) if err != nil { @@ -180,8 +180,13 @@ func createComponent(component ComponentDefinition, outfolderBase string, bindin return err } - err = BuildBindingCppExplicit(component, outputFolderBindingCppDynamic, outputFolderExampleCppDynamic, - outputFolderDocumentationCppExplicit, indentString, binding.ClassIdentifier) + if binding.SplitClasses { + log.Printf("Creating the split C++ dynamic binding (one header per class, one source file)") + err = BuildBindingCppSplit(component, outputFolderBindingCppDynamic, indentString, binding.ClassIdentifier) + } else { + err = BuildBindingCppExplicit(component, outputFolderBindingCppDynamic, outputFolderExampleCppDynamic, + outputFolderDocumentationCppExplicit, indentString, binding.ClassIdentifier) + } if err != nil { return err } @@ -685,7 +690,6 @@ func main() { if os.Args[idx] == "-suppressexamples" { suppressExamples = true } - if os.Args[idx] == "-suppresscmake" { suppressCmake = true } diff --git a/Source/buildbindingccpp.go b/Source/buildbindingccpp.go index 84cf0dd1..a877f2f3 100644 --- a/Source/buildbindingccpp.go +++ b/Source/buildbindingccpp.go @@ -581,17 +581,42 @@ func getDynamicCPPMethodParameters(method ComponentDefinitionMethod, NameSpace s return parameters, returntype, nil } -func writeDynamicCPPMethodDeclaration(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string, ClassIdentifier string, ClassName string) error { +// dynamicBindingStyle selects how the dynamic C++ binding is laid out. +type dynamicBindingStyle int + +const ( + // dynamicBindingHeaderOnly puts the declarations and all method bodies into one header. + dynamicBindingHeaderOnly dynamicBindingStyle = iota + // dynamicBindingSplit declares the classes in headers and defines everything in one source file that reaches the + // function table through the m_pTable pointer of the wrapper. + dynamicBindingSplit +) + +func (style dynamicBindingStyle) inlineSpecifier() string { + if style == dynamicBindingSplit { + return "" + } + return "inline " +} + +func (style dynamicBindingStyle) tableMember() string { + if style == dynamicBindingSplit { + return "m_pTable->" + } + return "m_WrapperTable." +} + +func writeDynamicCPPMethodDeclaration(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string, ClassIdentifier string, ClassName string, style dynamicBindingStyle) error { parameters, returntype, err := getDynamicCPPMethodParameters(method, NameSpace, ClassIdentifier, ClassName) if err != nil { return err } - w.Writeln(" inline %s %s(%s);", returntype, method.MethodName, parameters) + w.Writeln(" %s%s %s(%s);", style.inlineSpecifier(), returntype, method.MethodName, parameters) return nil } func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, NameSpace string, ClassIdentifier string, ClassName string, - implementationLines []string, isGlobal bool, includeComments bool, doNotThrow bool, useCPPTypes bool, ExplicitLinking bool, forWASM bool, multiThreadedEnv bool, classThreadSafetyOption ThreadSafetyOption) error { + implementationLines []string, isGlobal bool, includeComments bool, doNotThrow bool, useCPPTypes bool, ExplicitLinking bool, forWASM bool, multiThreadedEnv bool, classThreadSafetyOption ThreadSafetyOption, style dynamicBindingStyle) error { WASMPrefix := "" WASMCast := "" @@ -626,7 +651,7 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N if isGlobal { if ExplicitLinking { - CMethodName = fmt.Sprintf("m_WrapperTable.m_%s", method.MethodName) + CMethodName = fmt.Sprintf("%sm_%s", style.tableMember(), method.MethodName) } else { CMethodName = fmt.Sprintf("%s%s_%s", WASMPrefix, strings.ToLower(NameSpace), strings.ToLower(method.MethodName)) } @@ -634,7 +659,7 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N makeSharedParameter = "this" } else { if ExplicitLinking { - CMethodName = fmt.Sprintf("m_pWrapper->m_WrapperTable.m_%s_%s", ClassName, method.MethodName) + CMethodName = fmt.Sprintf("m_pWrapper->%sm_%s_%s", style.tableMember(), ClassName, method.MethodName) } else { CMethodName = fmt.Sprintf("%s%s_%s_%s", WASMPrefix, strings.ToLower(NameSpace), strings.ToLower(ClassName), strings.ToLower(method.MethodName)) } @@ -883,7 +908,7 @@ func writeDynamicCPPMethod(method ComponentDefinitionMethod, w LanguageWriter, N nameSpaceQualifier := cppClassName + "::" if isGlobal { - w.Writeln(" inline %s %s%s(%s)", returntype, nameSpaceQualifier, method.MethodName, parameters) + w.Writeln(" %s%s %s%s(%s)", style.inlineSpecifier(), returntype, nameSpaceQualifier, method.MethodName, parameters) } else { w.Writeln(" %s %s%s(%s)", returntype, nameSpaceQualifier, method.MethodName, parameters) } @@ -1348,20 +1373,28 @@ func writeExceptionClass(w LanguageWriter, NameSpace string, errors ComponentDef w.Writeln("};") } -func writeCheckBinaryVersion(w LanguageWriter, NameSpace string, component ComponentDefinition) { - w.Writeln(" %sResult checkBinaryVersion()", NameSpace) - w.Writeln(" {") - w.Writeln(" %s_uint32 nMajor, nMinor, nMicro;", NameSpace) - w.Writeln(" %s(nMajor, nMinor, nMicro);", component.Global.VersionMethod) +// writeCheckBinaryVersion writes the check of the binary version, as a method inside of the wrapper class. If +// outOfClassWrapperName is given, it writes the definition of the method of that class instead. +func writeCheckBinaryVersion(w LanguageWriter, NameSpace string, component ComponentDefinition, outOfClassWrapperName string) { + ind := " " + if outOfClassWrapperName == "" { + w.Writeln(" %sResult checkBinaryVersion()", NameSpace) + } else { + ind = "" + w.Writeln("%sResult %s::checkBinaryVersion()", NameSpace, outOfClassWrapperName) + } + w.Writeln(ind + "{") + w.Writeln(ind+" %s_uint32 nMajor, nMinor, nMicro;", NameSpace) + w.Writeln(ind+" %s(nMajor, nMinor, nMicro);", component.Global.VersionMethod) if minorVersion(component.Version) > 0 { - w.Writeln(" if ( (nMajor != %s_VERSION_MAJOR) || (nMinor < %s_VERSION_MINOR) ) {", strings.ToUpper(NameSpace), strings.ToUpper(NameSpace)) + w.Writeln(ind+" if ( (nMajor != %s_VERSION_MAJOR) || (nMinor < %s_VERSION_MINOR) ) {", strings.ToUpper(NameSpace), strings.ToUpper(NameSpace)) } else { - w.Writeln(" if (nMajor != %s_VERSION_MAJOR) {", strings.ToUpper(NameSpace)) + w.Writeln(ind+" if (nMajor != %s_VERSION_MAJOR) {", strings.ToUpper(NameSpace)) } - w.Writeln(" return %s_ERROR_INCOMPATIBLEBINARYVERSION;", strings.ToUpper(NameSpace)) - w.Writeln(" }") - w.Writeln(" return %s_SUCCESS;", strings.ToUpper(NameSpace)) - w.Writeln(" }") + w.Writeln(ind+" return %s_ERROR_INCOMPATIBLEBINARYVERSION;", strings.ToUpper(NameSpace)) + w.Writeln(ind + " }") + w.Writeln(ind+" return %s_SUCCESS;", strings.ToUpper(NameSpace)) + w.Writeln(ind + "}") } func writeWrapperTableHandling(w LanguageWriter, component ComponentDefinition, NameSpace string, cppClassPrefix string, ClassIdentifier string, BaseName string) { @@ -1398,72 +1431,104 @@ func writeWrapperTableHandling(w LanguageWriter, component ComponentDefinition, w.Writeln("") } +// buildInjectionImplementationLines returns the code of the injection method, which registers the wrapper of an imported component. +func buildInjectionImplementationLines(component ComponentDefinition, method ComponentDefinitionMethod, isSpecialFunction int, NameSpace string) []string { + implementationLines := make([]string, 0) + if isSpecialFunction == eSpecialMethodInjection { + implementationLines = append(implementationLines, "bool bNameSpaceFound = false;") + sParamName := "s" + method.Params[0].ParamName + for _, subComponent := range component.ImportedComponentDefinitions { + theNameSpace := subComponent.NameSpace + implementationLines = append(implementationLines, fmt.Sprintf("if (%s == \"%s\") {", sParamName, theNameSpace)) + implementationLines = append(implementationLines, fmt.Sprintf(" if (m_p%sWrapper != nullptr) {", theNameSpace)) + implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Library with namespace \" + %s + \" is already registered.\");", NameSpace, strings.ToUpper(NameSpace), sParamName)) + implementationLines = append(implementationLines, fmt.Sprintf(" }")) + + implementationLines = append(implementationLines, fmt.Sprintf(" m_p%sWrapper = %s::CWrapper::loadLibraryFromSymbolLookupMethod(p%s);", theNameSpace, theNameSpace, method.Params[1].ParamName)) + implementationLines = append(implementationLines, fmt.Sprintf(" bNameSpaceFound = true;")) + implementationLines = append(implementationLines, fmt.Sprintf("}")) + } + implementationLines = append(implementationLines, "if (!bNameSpaceFound)") + implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Unknown namespace \" + %s);", NameSpace, strings.ToUpper(NameSpace), sParamName)) + } + return implementationLines +} + func writeClassDeclarations(w LanguageWriter, component ComponentDefinition, cppClassPrefix string, ClassIdentifier string, NameSpace string, BaseName string) error { - baseClass := component.baseClass() for _, class := range component.Classes { - cppClassName := cppClassPrefix + ClassIdentifier + class.ClassName - cppParentClassName, inheritanceSpecifier := getCPPInheritanceSpecifier(component, class, cppClassPrefix, ClassIdentifier) + err := writeClassDeclaration(w, component, class, cppClassPrefix, ClassIdentifier, NameSpace, BaseName, dynamicBindingHeaderOnly) + if err != nil { + return err + } + } + return nil +} - w.Writeln(" ") - w.Writeln("/*************************************************************************************************************************") - w.Writeln(" Class %s ", cppClassName) - w.Writeln("**************************************************************************************************************************/") - w.Writeln("class %s %s{", cppClassName, inheritanceSpecifier) - w.Writeln("public:") - w.Writeln(" ") - if !component.isBaseClass(class) { - w.Writeln(" /**") - w.Writeln(" * %s::%s - Constructor for %s class.", cppClassName, cppClassName, class.ClassName) - w.Writeln(" */") - w.Writeln(" %s(%s%sWrapper* pWrapper, %sHandle pHandle)", cppClassName, cppClassPrefix, ClassIdentifier, NameSpace) - if cppParentClassName != "" { - w.Writeln(" : %s(pWrapper, pHandle)", cppParentClassName) - } - w.Writeln(" {") - w.Writeln(" }") - w.Writeln(" ") +// writeClassDeclaration writes the declaration of one binding class. +func writeClassDeclaration(w LanguageWriter, component ComponentDefinition, class ComponentDefinitionClass, cppClassPrefix string, ClassIdentifier string, NameSpace string, BaseName string, style dynamicBindingStyle) error { + baseClass := component.baseClass() + cppClassName := cppClassPrefix + ClassIdentifier + class.ClassName + cppParentClassName, inheritanceSpecifier := getCPPInheritanceSpecifier(component, class, cppClassPrefix, ClassIdentifier) - for _, method := range class.Methods { - err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, cppClassName) - if err != nil { - return err - } - } + w.Writeln(" ") + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Class %s ", cppClassName) + w.Writeln("**************************************************************************************************************************/") + w.Writeln("class %s %s{", cppClassName, inheritanceSpecifier) + w.Writeln("public:") + w.Writeln(" ") + if !component.isBaseClass(class) { + w.Writeln(" /**") + w.Writeln(" * %s::%s - Constructor for %s class.", cppClassName, cppClassName, class.ClassName) + w.Writeln(" */") + w.Writeln(" %s(%s%sWrapper* pWrapper, %sHandle pHandle)", cppClassName, cppClassPrefix, ClassIdentifier, NameSpace) + if cppParentClassName != "" { + w.Writeln(" : %s(pWrapper, pHandle)", cppParentClassName) + } + w.Writeln(" {") + w.Writeln(" }") + w.Writeln(" ") - } else { - err := writeDynamicCppBaseClassMethods(component, baseClass, w, NameSpace, BaseName, cppClassPrefix, ClassIdentifier) + for _, method := range class.Methods { + err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, cppClassName, style) if err != nil { return err } + } - extraBaseClassMethods := []ComponentDefinitionMethod{} - for _, method := range class.Methods { - if method.isExtraBaseClassmethod() { - extraBaseClassMethods = append(extraBaseClassMethods, method) - } else { - err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, cppClassName) - if err != nil { - return err - } - } - } + } else { + err := writeDynamicCppBaseClassMethods(component, baseClass, w, NameSpace, BaseName, cppClassPrefix, ClassIdentifier) + if err != nil { + return err + } - w.Writeln(" ") - w.Writeln("protected:") - for _, method := range extraBaseClassMethods { - err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, cppClassName) + extraBaseClassMethods := []ComponentDefinitionMethod{} + for _, method := range class.Methods { + if method.isExtraBaseClassmethod() { + extraBaseClassMethods = append(extraBaseClassMethods, method) + } else { + err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, cppClassName, style) if err != nil { return err } } } - - w.Writeln("};") + + w.Writeln(" ") + w.Writeln("protected:") + for _, method := range extraBaseClassMethods { + err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, cppClassName, style) + if err != nil { + return err + } + } } + + w.Writeln("};") return nil } -func writePolymorphicFactoryImplementation(w LanguageWriter, component ComponentDefinition, NameSpace string, cppClassPrefix string, ClassIdentifier string, ExplicitLinking bool, forWASM bool) { +func writePolymorphicFactoryImplementation(w LanguageWriter, component ComponentDefinition, NameSpace string, cppClassPrefix string, ClassIdentifier string, ExplicitLinking bool, forWASM bool, style dynamicBindingStyle) { WASMPrefix := "" WASMCast := "" WASMCastp := "" @@ -1485,11 +1550,11 @@ func writePolymorphicFactoryImplementation(w LanguageWriter, component Component w.Writeln("* %s%sWrapper::AcquireInstance(C%s object) must be called after instantiating new object.", cppClassPrefix, ClassIdentifier, component.Global.BaseClassName) w.Writeln("* This is important to keep reference count matching between application and library sides.") w.Writeln("*/") - w.Writeln("inline C%s* %s%sWrapper::polymorphicFactory(%sHandle pHandle)", component.Global.BaseClassName, cppClassPrefix, ClassIdentifier, NameSpace) + w.Writeln("%sC%s* %s%sWrapper::polymorphicFactory(%sHandle pHandle)", style.inlineSpecifier(), component.Global.BaseClassName, cppClassPrefix, ClassIdentifier, NameSpace) w.Writeln("{") w.Writeln(" %s_uint64 resultClassTypeId = 0;", NameSpace) if ExplicitLinking { - w.Writeln(" CheckError(nullptr, m_WrapperTable.m_%s_%s(pHandle, &resultClassTypeId));", component.Global.BaseClassName, component.Global.ClassTypeIdMethod) + w.Writeln(" CheckError(nullptr, %sm_%s_%s(pHandle, &resultClassTypeId));", style.tableMember(), component.Global.BaseClassName, component.Global.ClassTypeIdMethod) } else { w.Writeln(" CheckError(nullptr, %s%s_%s_%s(%spHandle, %s&resultClassTypeId));", WASMPrefix, strings.ToLower(NameSpace), strings.ToLower(component.Global.BaseClassName), strings.ToLower(component.Global.ClassTypeIdMethod), WASMCastp, WASMCast) } @@ -1505,11 +1570,11 @@ func writePolymorphicFactoryImplementation(w LanguageWriter, component Component w.Writeln("}") } -func writeCheckErrorImplementation(w LanguageWriter, ErrorMethodName string, ClassIdentifier string, cppBaseClassName string, NameSpace string, multiThreadedEnv bool) { +func writeCheckErrorImplementation(w LanguageWriter, ErrorMethodName string, ClassIdentifier string, cppBaseClassName string, NameSpace string, multiThreadedEnv bool, style dynamicBindingStyle) { if multiThreadedEnv { - w.Writeln(" inline void C%sWrapper::CheckError(%s * pBaseClass, %sResult nResult, bool unlockIfError)", ClassIdentifier, cppBaseClassName, NameSpace) + w.Writeln(" %svoid C%sWrapper::CheckError(%s * pBaseClass, %sResult nResult, bool unlockIfError)", style.inlineSpecifier(), ClassIdentifier, cppBaseClassName, NameSpace) } else { - w.Writeln(" inline void C%sWrapper::CheckError(%s * pBaseClass, %sResult nResult)", ClassIdentifier, cppBaseClassName, NameSpace) + w.Writeln(" %svoid C%sWrapper::CheckError(%s * pBaseClass, %sResult nResult)", style.inlineSpecifier(), ClassIdentifier, cppBaseClassName, NameSpace) } w.Writeln(" {") w.Writeln(" if (nResult != 0) {") @@ -1613,7 +1678,7 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s for j := 0; j < len(global.Methods); j++ { method := global.Methods[j] - err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, "Wrapper") + err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, "Wrapper", dynamicBindingHeaderOnly) if err != nil { return err } @@ -1637,7 +1702,7 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s } w.Writeln(" ") - writeCheckBinaryVersion(w, NameSpace, component) + writeCheckBinaryVersion(w, NameSpace, component, "") if ExplicitLinking { w.Writeln(" %sResult initWrapperTable(s%sDynamicWrapperTable * pWrapperTable);", NameSpace, NameSpace) @@ -1663,7 +1728,7 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s return err } - writePolymorphicFactoryImplementation(w, component, NameSpace, cppClassPrefix, ClassIdentifier, ExplicitLinking, false) + writePolymorphicFactoryImplementation(w, component, NameSpace, cppClassPrefix, ClassIdentifier, ExplicitLinking, false, dynamicBindingHeaderOnly) for _, method := range component.Global.Methods { isSpecialFunction, err := CheckHeaderSpecialFunction(method, component.Global) @@ -1671,26 +1736,9 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s return err } - implementationLines := make([]string, 0) - if isSpecialFunction == eSpecialMethodInjection { - implementationLines = append(implementationLines, "bool bNameSpaceFound = false;") - sParamName := "s" + method.Params[0].ParamName - for _, subComponent := range component.ImportedComponentDefinitions { - theNameSpace := subComponent.NameSpace - implementationLines = append(implementationLines, fmt.Sprintf("if (%s == \"%s\") {", sParamName, theNameSpace)) - implementationLines = append(implementationLines, fmt.Sprintf(" if (m_p%sWrapper != nullptr) {", theNameSpace)) - implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Library with namespace \" + %s + \" is already registered.\");", NameSpace, strings.ToUpper(NameSpace), sParamName)) - implementationLines = append(implementationLines, fmt.Sprintf(" }")) - - implementationLines = append(implementationLines, fmt.Sprintf(" m_p%sWrapper = %s::CWrapper::loadLibraryFromSymbolLookupMethod(p%s);", theNameSpace, theNameSpace, method.Params[1].ParamName)) - implementationLines = append(implementationLines, fmt.Sprintf(" bNameSpaceFound = true;")) - implementationLines = append(implementationLines, fmt.Sprintf("}")) - } - implementationLines = append(implementationLines, "if (!bNameSpaceFound)") - implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Unknown namespace \" + %s);", NameSpace, strings.ToUpper(NameSpace), sParamName)) - } + implementationLines := buildInjectionImplementationLines(component, method, isSpecialFunction, NameSpace) - err = writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, "Wrapper", implementationLines, true, true, false, useCPPTypes, ExplicitLinking, false, component.isMultiThreadedEnv(), eThreadSafetyNone) + err = writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, "Wrapper", implementationLines, true, true, false, useCPPTypes, ExplicitLinking, false, component.isMultiThreadedEnv(), eThreadSafetyNone, dynamicBindingHeaderOnly) if err != nil { return err } @@ -1698,7 +1746,7 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s } w.Writeln("") - writeCheckErrorImplementation(w, component.Global.ErrorMethod, ClassIdentifier, cppBaseClassName, NameSpace, component.isMultiThreadedEnv()) + writeCheckErrorImplementation(w, component.Global.ErrorMethod, ClassIdentifier, cppBaseClassName, NameSpace, component.isMultiThreadedEnv(), dynamicBindingHeaderOnly) w.Writeln("") if ExplicitLinking { @@ -1716,7 +1764,7 @@ func buildCppHeader(component ComponentDefinition, w LanguageWriter, NameSpace s w.Writeln(" */") for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] - err := writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, class.ClassName, make([]string, 0), false, true, false, useCPPTypes, ExplicitLinking, false, component.isMultiThreadedEnv(), component.getRealThreadSafetyOption(&class)) + err := writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, class.ClassName, make([]string, 0), false, true, false, useCPPTypes, ExplicitLinking, false, component.isMultiThreadedEnv(), component.getRealThreadSafetyOption(&class), dynamicBindingHeaderOnly) if err != nil { return err } @@ -2228,7 +2276,7 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na w.Writeln("") for _, method := range component.Global.Methods { - err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, "Wrapper") + err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, "Wrapper", dynamicBindingHeaderOnly) if err != nil { return err } @@ -2238,7 +2286,7 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na w.Writeln("") w.Writeln("private:") - writeCheckBinaryVersion(w, NameSpace, component) + writeCheckBinaryVersion(w, NameSpace, component, "") w.Writeln("") for i := 0; i < len(component.Classes); i++ { @@ -2255,7 +2303,7 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na return err } - writePolymorphicFactoryImplementation(w, component, NameSpace, cppClassPrefix, ClassIdentifier, false, true) + writePolymorphicFactoryImplementation(w, component, NameSpace, cppClassPrefix, ClassIdentifier, false, true, dynamicBindingHeaderOnly) w.Writeln("") useCPPTypes := true @@ -2285,14 +2333,14 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na implementationLines = append(implementationLines, fmt.Sprintf(" throw E%sException(%s_ERROR_COULDNOTLOADLIBRARY, \"Unknown namespace \" + %s);", NameSpace, strings.ToUpper(NameSpace), sParamName)) } - err = writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, "Wrapper", implementationLines, true, true, false, useCPPTypes, ExplicitLinking, true, false, eThreadSafetyNone) + err = writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, "Wrapper", implementationLines, true, true, false, useCPPTypes, ExplicitLinking, true, false, eThreadSafetyNone, dynamicBindingHeaderOnly) if err != nil { return err } } w.Writeln("") - writeCheckErrorImplementation(w, component.Global.ErrorMethod, ClassIdentifier, cppBaseClassName, NameSpace, false) + writeCheckErrorImplementation(w, component.Global.ErrorMethod, ClassIdentifier, cppBaseClassName, NameSpace, false, dynamicBindingHeaderOnly) w.Writeln("") for i := 0; i < len(component.Classes); i++ { @@ -2304,7 +2352,7 @@ func buildCppwasmGuestHeader(component ComponentDefinition, w LanguageWriter, Na w.Writeln(" */") for j := 0; j < len(class.Methods); j++ { method := class.Methods[j] - err := writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, class.ClassName, make([]string, 0), false, true, false, useCPPTypes, ExplicitLinking, true, false, eThreadSafetyNone) + err := writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, class.ClassName, make([]string, 0), false, true, false, useCPPTypes, ExplicitLinking, true, false, eThreadSafetyNone, dynamicBindingHeaderOnly) if err != nil { return err } diff --git a/Source/buildbindingccppsplit.go b/Source/buildbindingccppsplit.go new file mode 100644 index 00000000..54371f67 --- /dev/null +++ b/Source/buildbindingccppsplit.go @@ -0,0 +1,421 @@ +/*++ + +Copyright (C) 2019 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 AUTODESK INC. 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. + +*/ + +////////////////////////////////////////////////////////////////////////////////////////////////////// +// buildbindingccppsplit.go +// The "split" variant of the dynamic C++ binding (splitclasses="true" on a element). +// +// The default binding puts everything into _dynamic.hpp. In the split variant +// - the public headers only declare the classes (one header per class, _dynamic.hpp includes all of them), +// - the method bodies, the function table, the library loading and the polymorphic factory are generated into +// one source file that is compiled once, so a change of one class only affects the files using that class. +////////////////////////////////////////////////////////////////////////////////////////////////////// + +package main + +import ( + "fmt" + "path" + "strings" +) + +func cppSplitBindingClassHeaderName(BaseName string, ClassName string) string { + return fmt.Sprintf("%s_dynamic_%s.hpp", BaseName, strings.ToLower(ClassName)) +} + +func writeSplitNamespaceOpen(w LanguageWriter, NameSpace string) { + w.Writeln("namespace %s {", NameSpace) + w.Writeln("") +} + +func writeSplitNamespaceClose(w LanguageWriter, NameSpace string) { + w.Writeln("") + w.Writeln("} // namespace %s", NameSpace) + w.Writeln("") +} +// BuildBindingCppSplit generates the split variant of the dynamic C++ binding into outputFolder. +func BuildBindingCppSplit(component ComponentDefinition, outputFolder string, indentString string, ClassIdentifier string) error { + NameSpace := component.NameSpace + BaseName := component.BaseName + LibraryName := component.LibraryName + upperNameSpace := strings.ToUpper(NameSpace) + + for _, class := range component.Classes { + switch strings.ToLower(class.ClassName) { + case "fwd", "wrapper", "table": + return fmt.Errorf("class \"%s\" clashes with a header name of the split C++ binding", class.ClassName) + } + } + + CPPTypesHeaderName := path.Join(outputFolder, BaseName+"_types.hpp") + err := CreateCPPTypesHeader(component, CPPTypesHeaderName, false) + if err != nil { + return err + } + + fwdHeaderName := BaseName + "_dynamic_fwd.hpp" + wrapperHeaderName := BaseName + "_dynamic_wrapper.hpp" + tableHeaderName := BaseName + "_dynamic_table.hpp" + umbrellaHeaderName := BaseName + "_dynamic.hpp" + + // ------------------------------------------------------------------ forward declarations + w, err := createCppSplitFile(path.Join(outputFolder, fwdHeaderName), indentString, component, + fmt.Sprintf("This is an autogenerated C++-Header file with the forward declarations of the\n classes of %s. Include %s to call their methods.", LibraryName, umbrellaHeaderName)) + if err != nil { + return err + } + w.Writeln("#ifndef __%s_CPPHEADER_SPLIT_FWD", upperNameSpace) + w.Writeln("#define __%s_CPPHEADER_SPLIT_FWD", upperNameSpace) + w.Writeln("") + w.Writeln("#include \"%s_types.hpp\"", BaseName) + w.Writeln("") + w.Writeln("#include ") + w.Writeln("") + writeSplitNamespaceOpen(w, NameSpace) + buildBindingCPPAllForwardDeclarations(component, w, NameSpace, "C", ClassIdentifier) + writeSplitNamespaceClose(w, NameSpace) + w.Writeln("#endif // __%s_CPPHEADER_SPLIT_FWD", upperNameSpace) + closeLanguageFile(w) + + // ------------------------------------------------------------------ wrapper class and shared helpers + err = buildSplitWrapperHeader(component, outputFolder, indentString, ClassIdentifier, fwdHeaderName, wrapperHeaderName) + if err != nil { + return err + } + + // ------------------------------------------------------------------ one header per class + baseClass := component.baseClass() + for _, class := range component.Classes { + w, err := createCppSplitFile(path.Join(outputFolder, cppSplitBindingClassHeaderName(BaseName, class.ClassName)), indentString, component, + fmt.Sprintf("This is an autogenerated C++-Header file with the declaration of class %s of %s.", class.ClassName, LibraryName)) + if err != nil { + return err + } + guard := fmt.Sprintf("__%s_CPPHEADER_SPLIT_%s", upperNameSpace, strings.ToUpper(class.ClassName)) + w.Writeln("#ifndef %s", guard) + w.Writeln("#define %s", guard) + w.Writeln("") + w.Writeln("#include \"%s\"", wrapperHeaderName) + if !component.isBaseClass(class) { + parentName := class.ParentClass + if parentName == "" { + parentName = baseClass.ClassName + } + w.Writeln("#include \"%s\"", cppSplitBindingClassHeaderName(BaseName, parentName)) + } + w.Writeln("") + writeSplitNamespaceOpen(w, NameSpace) + err = writeClassDeclaration(w, component, class, "C", ClassIdentifier, NameSpace, BaseName, dynamicBindingSplit) + if err != nil { + return err + } + writeSplitNamespaceClose(w, NameSpace) + w.Writeln("#endif // %s", guard) + closeLanguageFile(w) + } + + // ------------------------------------------------------------------ umbrella header + w, err = createCppSplitFile(path.Join(outputFolder, umbrellaHeaderName), indentString, component, + fmt.Sprintf("This is an autogenerated C++-Header file in order to allow an easy\n use of %s. It includes the declarations of all classes.", LibraryName)) + if err != nil { + return err + } + w.Writeln("#ifndef __%s_CPPHEADER_SPLIT", upperNameSpace) + w.Writeln("#define __%s_CPPHEADER_SPLIT", upperNameSpace) + w.Writeln("") + w.Writeln("#include \"%s\"", wrapperHeaderName) + for _, class := range component.Classes { + w.Writeln("#include \"%s\"", cppSplitBindingClassHeaderName(BaseName, class.ClassName)) + } + w.Writeln("") + w.Writeln("#endif // __%s_CPPHEADER_SPLIT", upperNameSpace) + closeLanguageFile(w) + + // ------------------------------------------------------------------ function table, only needed by the sources + w, err = createCppSplitFile(path.Join(outputFolder, tableHeaderName), indentString, component, + fmt.Sprintf("This is an autogenerated C++-Header file with the function table of %s. Only the\n source files of the split binding include it.", LibraryName)) + if err != nil { + return err + } + err = buildDynamicCCPPHeader(component, w, NameSpace, BaseName, true, true, false) + if err != nil { + return err + } + w.Writeln("#include \"%s\"", wrapperHeaderName) + w.Writeln("") + writeSplitNamespaceOpen(w, NameSpace) + w.Writeln("struct C%sWrapper::sTable : public s%sDynamicWrapperTable {", ClassIdentifier, NameSpace) + w.Writeln("};") + writeSplitNamespaceClose(w, NameSpace) + w.Writeln("#endif // __%s_DYNAMICHEADER_CPPTYPES", upperNameSpace) + closeLanguageFile(w) + + // ------------------------------------------------------------------ source + return buildSplitSource(component, outputFolder, indentString, ClassIdentifier, umbrellaHeaderName, tableHeaderName) +} + +func buildSplitWrapperHeader(component ComponentDefinition, outputFolder string, indentString string, ClassIdentifier string, fwdHeaderName string, wrapperHeaderName string) error { + NameSpace := component.NameSpace + upperNameSpace := strings.ToUpper(NameSpace) + cppClassPrefix := "C" + cppBaseClassName := cppClassPrefix + ClassIdentifier + component.baseClass().ClassName + wrapperName := cppClassPrefix + ClassIdentifier + "Wrapper" + + w, err := createCppSplitFile(path.Join(outputFolder, wrapperHeaderName), indentString, component, + fmt.Sprintf("This is an autogenerated C++-Header file with the declaration of the wrapper class of %s.", component.LibraryName)) + if err != nil { + return err + } + w.Writeln("#ifndef __%s_CPPHEADER_SPLIT_WRAPPER", upperNameSpace) + w.Writeln("#define __%s_CPPHEADER_SPLIT_WRAPPER", upperNameSpace) + w.Writeln("") + w.Writeln("#include \"%s\"", fwdHeaderName) + w.Writeln("") + for _, subComponent := range component.ImportedComponentDefinitions { + w.Writeln("#include \"%s_dynamic.hpp\"", subComponent.BaseName) + } + w.Writeln("") + w.Writeln("#include ") + w.Writeln("#include ") + w.Writeln("#include ") + w.Writeln("#include ") + w.Writeln("#include ") + w.Writeln("") + writeSplitNamespaceOpen(w, NameSpace) + + writeClassParamDefinition(w, NameSpace) + w.Writeln("") + writeExceptionClass(w, NameSpace, component.Errors) + w.Writeln("") + writeCPPInputVector(w, NameSpace, ClassIdentifier) + w.Writeln("") + + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Class %s ", wrapperName) + w.Writeln("**************************************************************************************************************************/") + w.Writeln("class %s {", wrapperName) + w.Writeln("public:") + w.Writeln(" explicit %s(void* pSymbolLookupMethod);", wrapperName) + w.Writeln(" explicit %s(const std::string &sFileName);", wrapperName) + w.Writeln(" static P%sWrapper loadLibrary(const std::string &sFileName);", ClassIdentifier) + w.Writeln(" static P%sWrapper loadLibraryFromSymbolLookupMethod(void* pSymbolLookupMethod);", ClassIdentifier) + w.Writeln(" ~%s();", wrapperName) + w.Writeln(" ") + if component.isMultiThreadedEnv() { + w.Writeln(" void CheckError(%s * pBaseClass, %sResult nResult, bool unlockIfError = false);", cppBaseClassName, NameSpace) + } else { + w.Writeln(" void CheckError(%s * pBaseClass, %sResult nResult);", cppBaseClassName, NameSpace) + } + w.Writeln("") + for _, method := range component.Global.Methods { + err := writeDynamicCPPMethodDeclaration(method, w, NameSpace, ClassIdentifier, "Wrapper", dynamicBindingSplit) + if err != nil { + return err + } + } + w.Writeln("") + w.Writeln(" C%s* polymorphicFactory(%sHandle);", component.Global.BaseClassName, NameSpace) + w.Writeln("") + w.Writeln("private:") + if len(component.ImportedComponentDefinitions) > 0 { + w.Writeln(" // Injected Components") + for _, subComponent := range component.ImportedComponentDefinitions { + w.Writeln(" %s::PWrapper m_p%sWrapper;", subComponent.NameSpace, subComponent.NameSpace) + } + w.Writeln("") + } + w.Writeln(" %sResult checkBinaryVersion();", NameSpace) + w.Writeln("") + w.Writeln(" // The function table is only visible to the source files of the binding.") + w.Writeln(" struct sTable;") + w.Writeln(" std::unique_ptr m_pTable;") + w.Writeln("") + for _, class := range component.Classes { + w.Writeln(" friend class %s;", cppClassPrefix+ClassIdentifier+class.ClassName) + } + w.Writeln("};") + writeSplitNamespaceClose(w, NameSpace) + w.Writeln("#endif // __%s_CPPHEADER_SPLIT_WRAPPER", upperNameSpace) + closeLanguageFile(w) + return nil +} + +func writeSplitSourcePrologue(w LanguageWriter, umbrellaHeaderName string, tableHeaderName string) { + w.Writeln("#include \"%s\"", umbrellaHeaderName) + w.Writeln("#include \"%s\"", tableHeaderName) + w.Writeln("") + w.Writeln("#ifdef _WIN32") + w.Writeln("#include ") + w.Writeln("#else // _WIN32") + w.Writeln("#include ") + w.Writeln("#endif // _WIN32") + w.Writeln("") +} + +// writeSplitWrapperImplementation writes the function table handling, the life time handling, the error handling, +// the polymorphic factory and the global methods of the wrapper class. +func writeSplitWrapperImplementation(component ComponentDefinition, w LanguageWriter, ClassIdentifier string) error { + NameSpace := component.NameSpace + BaseName := component.BaseName + cppClassPrefix := "C" + cppBaseClassName := cppClassPrefix + ClassIdentifier + component.baseClass().ClassName + wrapperName := cppClassPrefix + ClassIdentifier + "Wrapper" + tableType := "s" + NameSpace + "DynamicWrapperTable" + + // function table handling + w.Writeln("namespace {") + w.Writeln("") + w.Writeln("%sResult initWrapperTable(%s * pWrapperTable)", NameSpace, tableType) + w.Writeln("{") + w.AddIndentationLevel(1) + buildDynamicCInitTableCode(component, w, NameSpace, BaseName, false) + w.AddIndentationLevel(-1) + w.Writeln("}") + w.Writeln("") + w.Writeln("%sResult releaseWrapperTable(%s * pWrapperTable)", NameSpace, tableType) + w.Writeln("{") + w.AddIndentationLevel(1) + buildDynamicCReleaseTableCode(component, w, NameSpace, BaseName, "initWrapperTable", false) + w.AddIndentationLevel(-1) + w.Writeln("}") + w.Writeln("") + w.Writeln("%sResult loadWrapperTable(%s * pWrapperTable, const char * pLibraryFileName)", NameSpace, tableType) + w.Writeln("{") + w.AddIndentationLevel(1) + buildDynamicCLoadTableCode(component, w, NameSpace, BaseName, false) + w.AddIndentationLevel(-1) + w.Writeln("}") + w.Writeln("") + w.Writeln("%sResult loadWrapperTableFromSymbolLookupMethod(%s * pWrapperTable, void* pSymbolLookupMethod)", NameSpace, tableType) + w.Writeln("{") + w.AddIndentationLevel(1) + buildDynamicCLoadTableFromSymbolLookupMethodCode(component, w, NameSpace, BaseName, false) + w.AddIndentationLevel(-1) + w.Writeln("}") + w.Writeln("") + w.Writeln("} // anonymous namespace") + w.Writeln("") + + // life time handling + w.Writeln("%s::%s(void* pSymbolLookupMethod)", wrapperName, wrapperName) + w.Writeln(" : m_pTable(new sTable())") + w.Writeln("{") + w.Writeln(" CheckError(nullptr, initWrapperTable(m_pTable.get()));") + w.Writeln(" CheckError(nullptr, loadWrapperTableFromSymbolLookupMethod(m_pTable.get(), pSymbolLookupMethod));") + w.Writeln(" ") + w.Writeln(" CheckError(nullptr, checkBinaryVersion());") + w.Writeln("}") + w.Writeln("") + w.Writeln("%s::%s(const std::string &sFileName)", wrapperName, wrapperName) + w.Writeln(" : m_pTable(new sTable())") + w.Writeln("{") + w.Writeln(" CheckError(nullptr, initWrapperTable(m_pTable.get()));") + w.Writeln(" CheckError(nullptr, loadWrapperTable(m_pTable.get(), sFileName.c_str()));") + w.Writeln(" ") + w.Writeln(" CheckError(nullptr, checkBinaryVersion());") + w.Writeln("}") + w.Writeln("") + w.Writeln("P%sWrapper %s::loadLibrary(const std::string &sFileName)", ClassIdentifier, wrapperName) + w.Writeln("{") + w.Writeln(" return std::make_shared<%s>(sFileName);", wrapperName) + w.Writeln("}") + w.Writeln("") + w.Writeln("P%sWrapper %s::loadLibraryFromSymbolLookupMethod(void* pSymbolLookupMethod)", ClassIdentifier, wrapperName) + w.Writeln("{") + w.Writeln(" return std::make_shared<%s>(pSymbolLookupMethod);", wrapperName) + w.Writeln("}") + w.Writeln("") + w.Writeln("%s::~%s()", wrapperName, wrapperName) + w.Writeln("{") + w.Writeln(" if (m_pTable)") + w.Writeln(" releaseWrapperTable(m_pTable.get());") + w.Writeln("}") + w.Writeln("") + + writeCheckBinaryVersion(w, NameSpace, component, wrapperName) + w.Writeln("") + + writeCheckErrorImplementation(w, component.Global.ErrorMethod, ClassIdentifier, cppBaseClassName, NameSpace, component.isMultiThreadedEnv(), dynamicBindingSplit) + w.Writeln("") + + writePolymorphicFactoryImplementation(w, component, NameSpace, cppClassPrefix, ClassIdentifier, true, false, dynamicBindingSplit) + w.Writeln("") + + // global methods + for _, method := range component.Global.Methods { + isSpecialFunction, err := CheckHeaderSpecialFunction(method, component.Global) + if err != nil { + return err + } + + implementationLines := buildInjectionImplementationLines(component, method, isSpecialFunction, NameSpace) + + err = writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, "Wrapper", implementationLines, true, true, false, true, true, false, component.isMultiThreadedEnv(), eThreadSafetyNone, dynamicBindingSplit) + if err != nil { + return err + } + } + return nil +} + +// buildSplitSource writes the single source file of the split binding: the wrapper implementation and the +// methods of all classes. +func buildSplitSource(component ComponentDefinition, outputFolder string, indentString string, ClassIdentifier string, umbrellaHeaderName string, tableHeaderName string) error { + NameSpace := component.NameSpace + + w, err := createCppSplitFile(path.Join(outputFolder, component.BaseName+"_dynamic.cpp"), indentString, component, + fmt.Sprintf("This is an autogenerated C++ source file with the implementation of the classes of %s.", component.LibraryName)) + if err != nil { + return err + } + writeSplitSourcePrologue(w, umbrellaHeaderName, tableHeaderName) + writeSplitNamespaceOpen(w, NameSpace) + + err = writeSplitWrapperImplementation(component, w, ClassIdentifier) + if err != nil { + return err + } + + for _, class := range component.Classes { + cppClassName := "C" + ClassIdentifier + class.ClassName + w.Writeln(" ") + w.Writeln(" /**") + w.Writeln(" * Method definitions for class %s", cppClassName) + w.Writeln(" */") + for _, method := range class.Methods { + err := writeDynamicCPPMethod(method, w, NameSpace, ClassIdentifier, class.ClassName, make([]string, 0), false, true, false, true, true, false, component.isMultiThreadedEnv(), component.getRealThreadSafetyOption(&class), dynamicBindingSplit) + if err != nil { + return err + } + } + } + + writeSplitNamespaceClose(w, NameSpace) + closeLanguageFile(w) + return nil +} diff --git a/Source/buildimplementationcpp.go b/Source/buildimplementationcpp.go index 06a01a61..322f43bd 100644 --- a/Source/buildimplementationcpp.go +++ b/Source/buildimplementationcpp.go @@ -47,7 +47,9 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, forceRecreation := false doJournal := len (component.Global.JournalMethod) > 0; - + + splitClasses := implementation.SplitClasses + NameSpace := component.NameSpace; ImplementationSubNameSpace := "Impl" LibraryName := component.LibraryName; @@ -86,6 +88,12 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, return err } + if splitClasses { + err = buildCPPInterfacesSplit(component, outputFolder, indentString, ImplementationSubNameSpace, implementation.ClassIdentifier) + if err != nil { + return err + } + } else { IntfHeaderName := path.Join(outputFolder, BaseName+"_interfaces.hpp"); log.Printf("Creating \"%s\"", IntfHeaderName) interfaceshppfile, err := CreateLanguageFile (IntfHeaderName, indentString) @@ -99,6 +107,7 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, if err != nil { return err } + } IntfWrapperImplName := path.Join(outputFolder, BaseName+"_interfacewrapper.cpp"); log.Printf("Creating \"%s\"", IntfWrapperImplName) @@ -145,7 +154,7 @@ func BuildImplementationCPP(component ComponentDefinition, outputFolder string, if (!suppressStub) { - err := buildCPPStub(component, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier, forceRecreation) + err := buildCPPStub(component, NameSpace, ImplementationSubNameSpace, implementation.ClassIdentifier, BaseName, stubOutputFolder, indentString, stubIdentifier, forceRecreation, splitClasses) if err != nil { return err } @@ -623,50 +632,10 @@ func buildCPPInterfaces(component ComponentDefinition, w LanguageWriter, NameSpa writeParameterCacheDefinitions(component, w, NameSpaceImplementation, ClassIdentifier) writeClassDefinitions(component, w, NameSpaceImplementation, ClassIdentifier) - - w.Writeln("") - w.Writeln("/*************************************************************************************************************************") - w.Writeln(" Global functions declarations") - w.Writeln("**************************************************************************************************************************/") - - w.Writeln("class C%sWrapper {", ClassIdentifier) - w.Writeln("public:") - - if len(component.ImportedComponentDefinitions) > 0 { - w.Writeln(" // Injected Components") - for _, subComponent := range(component.ImportedComponentDefinitions) { - subNameSpace := subComponent.NameSpace - w.Writeln(" static %s::PWrapper sP%sWrapper;", subNameSpace, subNameSpace) - } - w.Writeln("") - } - - 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); - if err != nil { - return err - } - if (isSpecialFunction == eSpecialMethodJournal) || (isSpecialFunction == eSpecialMethodInjection) || - (isSpecialFunction == eSpecialMethodSymbolLookup) { - continue - } - - methodstring, _, err := buildCPPInterfaceMethodDeclaration(method, BaseName, NameSpace, ClassIdentifier, "Wrapper", w.IndentString, true, false, true) - if err != nil { - return err - } - w.Writeln("%s;", methodstring) - w.Writeln("") + err := writeCPPGlobalWrapperDeclaration(component, w, NameSpaceImplementation, ClassIdentifier) + if err != nil { + return err } - 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) @@ -959,7 +928,6 @@ func buildCPPInterfaceWrapper(component ComponentDefinition, w LanguageWriter, N return nil } - func buildOutCacheTemplateParameters (method ComponentDefinitionMethod, NameSpace string, BaseClassName string, ClassIdentifier string) (string, error) { result := ""; @@ -1176,7 +1144,7 @@ func writeCImplementationMethod(component ComponentDefinition, method ComponentD } -func buildCPPStubClass(component ComponentDefinition, class ComponentDefinitionClass, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string, forceRecreation bool) error { +func buildCPPStubClass(component ComponentDefinition, class ComponentDefinitionClass, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string, forceRecreation bool, splitClasses bool) error { outClassName := "C" + ClassIdentifier + class.ClassName StubHeaderFileName := path.Join(outputFolder, BaseName + stubIdentifier + "_" +strings.ToLower(class.ClassName)+".hpp"); @@ -1209,7 +1177,11 @@ func buildCPPStubClass(component ComponentDefinition, class ComponentDefinitionC stubheaderw.Writeln("#define __%s_%s", strings.ToUpper(NameSpace), strings.ToUpper(class.ClassName)) stubheaderw.Writeln("") - stubheaderw.Writeln("#include \"%s_interfaces.hpp\"", BaseName) + if splitClasses { + stubheaderw.Writeln("#include \"%s\"", cppSplitInterfaceHeaderName(BaseName, class.ClassName)) + } else { + stubheaderw.Writeln("#include \"%s_interfaces.hpp\"", BaseName) + } if (component.isBaseClass(class)) { stubheaderw.Writeln("#include ") stubheaderw.Writeln("#include ") @@ -1384,11 +1356,11 @@ func buildCPPStubClass(component ComponentDefinition, class ComponentDefinitionC return nil } -func buildCPPStub(component ComponentDefinition, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string, forceRecreation bool) error { +func buildCPPStub(component ComponentDefinition, NameSpace string, NameSpaceImplementation string, ClassIdentifier string, BaseName string, outputFolder string, indentString string, stubIdentifier string, forceRecreation bool, splitClasses bool) error { 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, splitClasses) if err != nil { return err } @@ -2532,3 +2504,56 @@ func buildJournalingCPP(component ComponentDefinition, headerw LanguageWriter, i return nil; } + +func writeCPPGlobalWrapperDeclaration(component ComponentDefinition, w LanguageWriter, NameSpaceImplementation string, ClassIdentifier string) error { + NameSpace := component.NameSpace + BaseName := component.BaseName + + + w.Writeln("") + w.Writeln("/*************************************************************************************************************************") + w.Writeln(" Global functions declarations") + w.Writeln("**************************************************************************************************************************/") + + w.Writeln("class C%sWrapper {", ClassIdentifier) + w.Writeln("public:") + + if len(component.ImportedComponentDefinitions) > 0 { + w.Writeln(" // Injected Components") + for _, subComponent := range(component.ImportedComponentDefinitions) { + subNameSpace := subComponent.NameSpace + w.Writeln(" static %s::PWrapper sP%sWrapper;", subNameSpace, subNameSpace) + } + w.Writeln("") + } + + 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); + if err != nil { + return err + } + if (isSpecialFunction == eSpecialMethodJournal) || (isSpecialFunction == eSpecialMethodInjection) || + (isSpecialFunction == eSpecialMethodSymbolLookup) { + continue + } + + methodstring, _, err := buildCPPInterfaceMethodDeclaration(method, BaseName, NameSpace, ClassIdentifier, "Wrapper", w.IndentString, true, false, true) + if err != nil { + return err + } + w.Writeln("%s;", methodstring) + w.Writeln("") + } + w.Writeln("};") + w.Writeln("") + + w.Writeln("%sResult %s_GetProcAddress (const char * pProcName, void ** ppProcAddress);", NameSpace, NameSpace) + w.Writeln("") + + return nil +} + diff --git a/Source/buildimplementationcppsplit.go b/Source/buildimplementationcppsplit.go new file mode 100644 index 00000000..4d9f88a0 --- /dev/null +++ b/Source/buildimplementationcppsplit.go @@ -0,0 +1,215 @@ +/*++ + +Copyright (C) 2019 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 AUTODESK INC. 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. + +*/ + +////////////////////////////////////////////////////////////////////////////////////////////////////// +// buildimplementationcppsplit.go +// Optional "split" output of the C++ implementation interfaces (see the -splitcpp flag): +// - one interface header per class, plus an umbrella header with the original name +// - new stubs include only the header of their own class +////////////////////////////////////////////////////////////////////////////////////////////////////// + +package main + +import ( + "fmt" + "io" + "log" + "path" + "strings" +) + +func closeLanguageFile(w LanguageWriter) { + if closer, ok := w.Writer.(io.Closer); ok { + closer.Close() + } +} + +func cppSplitInterfaceHeaderName(BaseName string, ClassName string) string { + return fmt.Sprintf("%s_interface_%s.hpp", BaseName, strings.ToLower(ClassName)) +} + +func createCppSplitFile(fileName string, indentString string, component ComponentDefinition, description string) (LanguageWriter, error) { + log.Printf("Creating \"%s\"", fileName) + file, err := CreateLanguageFile(fileName, indentString) + if err != nil { + return file, err + } + file.WriteCLicenseHeader(component, description, true) + return file, nil +} + +func buildCPPInterfacesSplit(component ComponentDefinition, outputFolder string, indentString string, NameSpaceImplementation string, ClassIdentifier string) error { + NameSpace := component.NameSpace + BaseName := component.BaseName + upperNameSpace := strings.ToUpper(NameSpace) + LibraryName := component.LibraryName + + // Forward declarations, shared by all class headers + fwdFileName := BaseName + "_interfaces_fwd.hpp" + w, err := createCppSplitFile(path.Join(outputFolder, fwdFileName), indentString, component, + fmt.Sprintf("This is an autogenerated C++ header file with the forward declarations of the\ninterface classes of %s.", LibraryName)) + if err != nil { + return err + } + w.Writeln("") + w.Writeln("#ifndef __%s_CPPINTERFACES_FWD", upperNameSpace) + w.Writeln("#define __%s_CPPINTERFACES_FWD", upperNameSpace) + w.Writeln("") + w.Writeln("#include ") + w.Writeln("#include ") + if component.isMultiThreadedEnv() { + w.Writeln("#include ") + } + w.Writeln("") + w.Writeln("#include \"%s_types.hpp\"", BaseName) + w.Writeln("") + for _, subComponent := range component.ImportedComponentDefinitions { + w.Writeln("#include \"%s_dynamic.hpp\"", subComponent.BaseName) + } + w.Writeln("") + w.Writeln("namespace %s {", NameSpace) + w.Writeln("namespace %s {", NameSpaceImplementation) + w.Writeln("") + w.Writeln("/**") + w.Writeln(" Forward declarations of class interfaces") + w.Writeln("*/") + for _, class := range component.Classes { + w.Writeln("class I%s%s;", ClassIdentifier, class.ClassName) + } + w.Writeln("") + writeParameterCacheDefinitions(component, w, NameSpaceImplementation, ClassIdentifier) + w.Writeln("") + w.Writeln("} // namespace %s", NameSpaceImplementation) + w.Writeln("} // namespace %s", NameSpace) + w.Writeln("") + w.Writeln("#endif // __%s_CPPINTERFACES_FWD", upperNameSpace) + closeLanguageFile(w) + + // One header per class + for _, class := range component.Classes { + classHeaderName := cppSplitInterfaceHeaderName(BaseName, class.ClassName) + w, err := createCppSplitFile(path.Join(outputFolder, classHeaderName), indentString, component, + fmt.Sprintf("This is an autogenerated C++ header file with the interface of class %s of %s.", class.ClassName, LibraryName)) + if err != nil { + return err + } + guard := fmt.Sprintf("__%s_CPPINTERFACE_%s", upperNameSpace, strings.ToUpper(class.ClassName)) + w.Writeln("") + w.Writeln("#ifndef %s", guard) + w.Writeln("#define %s", guard) + w.Writeln("") + w.Writeln("#include \"%s\"", fwdFileName) + if !component.isBaseClass(class) { + w.Writeln("#include \"%s\"", cppSplitInterfaceHeaderName(BaseName, class.ParentClass)) + } + for _, returnedClassName := range cppSplitCovariantReturnClasses(component, class) { + w.Writeln("#include \"%s\"", cppSplitInterfaceHeaderName(BaseName, returnedClassName)) + } + w.Writeln("") + w.Writeln("namespace %s {", NameSpace) + w.Writeln("namespace %s {", NameSpaceImplementation) + err = writeCPPClassInterface(component, class, w, NameSpace, NameSpaceImplementation, ClassIdentifier, BaseName) + if err != nil { + return err + } + w.Writeln("") + w.Writeln("} // namespace %s", NameSpaceImplementation) + w.Writeln("} // namespace %s", NameSpace) + w.Writeln("") + w.Writeln("#endif // %s", guard) + closeLanguageFile(w) + } + + // Umbrella header with the name of the monolithic header + w, err = createCppSplitFile(path.Join(outputFolder, BaseName+"_interfaces.hpp"), indentString, component, + fmt.Sprintf("This is an autogenerated C++ header file in order to allow easy\ndevelopment of %s. The implementer of %s needs to\nderive concrete classes from the abstract classes in the headers included here.", LibraryName, LibraryName)) + if err != nil { + return err + } + w.Writeln("") + w.Writeln("#ifndef __%s_CPPINTERFACES", upperNameSpace) + w.Writeln("#define __%s_CPPINTERFACES", upperNameSpace) + w.Writeln("") + w.Writeln("#include \"%s\"", fwdFileName) + for _, class := range component.Classes { + w.Writeln("#include \"%s\"", cppSplitInterfaceHeaderName(BaseName, class.ClassName)) + } + w.Writeln("") + w.Writeln("namespace %s {", NameSpace) + w.Writeln("namespace %s {", NameSpaceImplementation) + err = writeCPPGlobalWrapperDeclaration(component, w, NameSpaceImplementation, ClassIdentifier) + if err != nil { + return err + } + w.Writeln("} // namespace %s", NameSpaceImplementation) + w.Writeln("} // namespace %s", NameSpace) + w.Writeln("") + w.Writeln("#endif // __%s_CPPINTERFACES", upperNameSpace) + closeLanguageFile(w) + + return nil +} + +// cppSplitCovariantReturnClasses lists the classes returned by methods that override a method of an ancestor. +// C++ only accepts such covariant return types if the returned class is complete, so their headers must be included. +func cppSplitCovariantReturnClasses(component ComponentDefinition, class ComponentDefinitionClass) []string { + ancestorMethodNames := make(map[string]bool) + classesByName := make(map[string]ComponentDefinitionClass) + for _, c := range component.Classes { + classesByName[c.ClassName] = c + } + for current := class; !component.isBaseClass(current); { + parent, found := classesByName[current.ParentClass] + if !found { + break + } + for _, method := range parent.Methods { + ancestorMethodNames[strings.ToLower(method.MethodName)] = true + } + current = parent + } + + result := make([]string, 0) + seen := make(map[string]bool) + for _, method := range class.Methods { + if !ancestorMethodNames[strings.ToLower(method.MethodName)] { + continue + } + for _, param := range method.Params { + if param.ParamPass != "return" || (param.ParamType != "class" && param.ParamType != "optionalclass") { + continue + } + className := param.ParamClass + if _, known := classesByName[className]; known && className != class.ClassName && !seen[className] { + seen[className] = true + result = append(result, className) + } + } + } + return result +} diff --git a/Source/componentdefinition.go b/Source/componentdefinition.go index a16b4ee6..f7ffb726 100644 --- a/Source/componentdefinition.go +++ b/Source/componentdefinition.go @@ -163,6 +163,7 @@ type ComponentDefinitionBinding struct { ClassIdentifier string `xml:"classidentifier,attr"` Documentation string `xml:"documentation,attr"` Version string `xml:"version,attr"` + SplitClasses bool `xml:"splitclasses,attr"` } // ComponentDefinitionImplementation definition of a specific languages for which bindings to the component's API will be generated @@ -173,6 +174,7 @@ type ComponentDefinitionImplementation struct { Indentation string `xml:"indentation,attr"` ClassIdentifier string `xml:"classidentifier,attr"` StubIdentifier string `xml:"stubidentifier,attr"` + SplitClasses bool `xml:"splitclasses,attr"` } // ComponentDefinitionEnumOption definition of an enum used in the component's API