From 9052462304d689fbf5b7cab91eea03d0046df86d Mon Sep 17 00:00:00 2001 From: HaseenaSainul Date: Tue, 10 Oct 2023 06:29:38 -0400 Subject: [PATCH 1/5] CPPSDK: aggregate files based on suffix type handling added, module and override module generation also handled --- languages/cpp/language.config.json | 7 +- .../cpp/src/shared/src/Transport/Transport.h | 12 +- .../shared/{src/Types.cpp => test/Main.cpp} | 36 ++--- .../cpp/templates/codeblocks/mock-import.c | 1 - .../cpp/templates/codeblocks/mock-parameter.c | 1 - .../codeblocks/module-include-private.cpp | 2 + .../cpp/templates/codeblocks/module-include.h | 2 + .../cpp/templates/codeblocks/module-init.cpp | 15 ++ .../cpp/templates/codeblocks/module-init.h | 3 + languages/cpp/templates/codeblocks/setter.c | 16 --- languages/cpp/templates/codeblocks/setter.cpp | 16 +++ .../clear.h} | 0 .../default.h} | 0 .../templates/declarations-override/event.h | 4 + .../listen.h} | 0 .../once.h} | 0 .../polymorphic-pull-event.h} | 0 .../polymorphic-pull.h} | 0 .../polymorphic-reducer.h} | 0 .../declarations-override/property.h | 5 + .../provide.h} | 0 .../templates/declarations-override/setter.h | 5 + .../{polymorphic-reducer.c => clear.h} | 0 .../declarations/{provide.c => default.h} | 0 .../declarations/{event.c => event.h} | 0 .../default.c => declarations/listen.h} | 0 .../property.c => declarations/once.h} | 0 .../polymorphic-pull-event.h} | 0 .../polymorphic-pull.h} | 0 .../polymorphic-reducer.h} | 0 .../once.c => declarations/provide.h} | 0 languages/cpp/templates/imports/default.impl | 1 + .../{calls-metrics.c => calls-metrics.cpp} | 0 .../{polymorphic-pull-event.c => clear.cpp} | 0 .../{polymorphic-pull.c => default.cpp} | 0 languages/cpp/templates/methods/event.c | 33 ----- languages/cpp/templates/methods/event.cpp | 35 +++++ .../{polymorphic-reducer.c => listen.cpp} | 0 .../templates/methods/{provide.c => once.cpp} | 0 .../{setter.c => polymorphic-pull-event.cpp} | 0 .../templates/methods/polymorphic-pull.cpp | 0 .../templates/methods/polymorphic-reducer.cpp | 0 languages/cpp/templates/methods/property.c | 17 --- languages/cpp/templates/methods/property.cpp | 18 +++ languages/cpp/templates/methods/provide.cpp | 0 languages/cpp/templates/methods/setter.cpp | 0 .../cpp/templates/modules/include/module.h | 7 +- .../cpp/templates/modules/src/module.cpp | 89 ------------ .../modules/src/module_impl.cpp} | 31 ++-- .../cpp/templates/modules/src/module_impl.h | 48 +++++++ .../cpp/templates/sdk/include/firebolt.h | 133 ++++++++++++++++++ .../cpp/templates/sdk/scripts/install.sh | 2 +- languages/cpp/templates/sdk/src/firebolt.cpp | 116 +++++++++++++++ .../sections/declarations-override.h | 1 + languages/javascript/language.config.json | 3 + src/macrofier/engine.mjs | 66 +++++++-- src/macrofier/index.mjs | 24 ++-- src/sdk/index.mjs | 2 +- src/shared/json-schema.mjs | 1 - 59 files changed, 531 insertions(+), 221 deletions(-) rename languages/cpp/src/shared/{src/Types.cpp => test/Main.cpp} (53%) delete mode 100644 languages/cpp/templates/codeblocks/mock-import.c delete mode 100644 languages/cpp/templates/codeblocks/mock-parameter.c create mode 100644 languages/cpp/templates/codeblocks/module-include-private.cpp create mode 100644 languages/cpp/templates/codeblocks/module-include.h create mode 100644 languages/cpp/templates/codeblocks/module-init.cpp create mode 100644 languages/cpp/templates/codeblocks/module-init.h delete mode 100644 languages/cpp/templates/codeblocks/setter.c create mode 100644 languages/cpp/templates/codeblocks/setter.cpp rename languages/cpp/templates/{codeblocks/export.c => declarations-override/clear.h} (100%) rename languages/cpp/templates/{codeblocks/module.c => declarations-override/default.h} (100%) create mode 100644 languages/cpp/templates/declarations-override/event.h rename languages/cpp/templates/{declarations/clear.c => declarations-override/listen.h} (100%) rename languages/cpp/templates/{declarations/default.c => declarations-override/once.h} (100%) rename languages/cpp/templates/{declarations/listen.c => declarations-override/polymorphic-pull-event.h} (100%) rename languages/cpp/templates/{declarations/once.c => declarations-override/polymorphic-pull.h} (100%) rename languages/cpp/templates/{declarations/polymorphic-pull-event.c => declarations-override/polymorphic-reducer.h} (100%) create mode 100644 languages/cpp/templates/declarations-override/property.h rename languages/cpp/templates/{declarations/polymorphic-pull.c => declarations-override/provide.h} (100%) create mode 100644 languages/cpp/templates/declarations-override/setter.h rename languages/cpp/templates/declarations/{polymorphic-reducer.c => clear.h} (100%) rename languages/cpp/templates/declarations/{provide.c => default.h} (100%) rename languages/cpp/templates/declarations/{event.c => event.h} (100%) rename languages/cpp/templates/{defaults/default.c => declarations/listen.h} (100%) rename languages/cpp/templates/{defaults/property.c => declarations/once.h} (100%) rename languages/cpp/templates/{methods/clear.c => declarations/polymorphic-pull-event.h} (100%) rename languages/cpp/templates/{methods/default.c => declarations/polymorphic-pull.h} (100%) rename languages/cpp/templates/{methods/listen.c => declarations/polymorphic-reducer.h} (100%) rename languages/cpp/templates/{methods/once.c => declarations/provide.h} (100%) create mode 100644 languages/cpp/templates/imports/default.impl rename languages/cpp/templates/methods/{calls-metrics.c => calls-metrics.cpp} (100%) rename languages/cpp/templates/methods/{polymorphic-pull-event.c => clear.cpp} (100%) rename languages/cpp/templates/methods/{polymorphic-pull.c => default.cpp} (100%) delete mode 100644 languages/cpp/templates/methods/event.c create mode 100644 languages/cpp/templates/methods/event.cpp rename languages/cpp/templates/methods/{polymorphic-reducer.c => listen.cpp} (100%) rename languages/cpp/templates/methods/{provide.c => once.cpp} (100%) rename languages/cpp/templates/methods/{setter.c => polymorphic-pull-event.cpp} (100%) create mode 100644 languages/cpp/templates/methods/polymorphic-pull.cpp create mode 100644 languages/cpp/templates/methods/polymorphic-reducer.cpp delete mode 100644 languages/cpp/templates/methods/property.c create mode 100644 languages/cpp/templates/methods/property.cpp create mode 100644 languages/cpp/templates/methods/provide.cpp create mode 100644 languages/cpp/templates/methods/setter.cpp delete mode 100644 languages/cpp/templates/modules/src/module.cpp rename languages/cpp/{src/shared/src/firebolt.cpp => templates/modules/src/module_impl.cpp} (66%) create mode 100644 languages/cpp/templates/modules/src/module_impl.h create mode 100644 languages/cpp/templates/sdk/include/firebolt.h create mode 100644 languages/cpp/templates/sdk/src/firebolt.cpp create mode 100644 languages/cpp/templates/sections/declarations-override.h diff --git a/languages/cpp/language.config.json b/languages/cpp/language.config.json index 491e9559..15a67fb5 100644 --- a/languages/cpp/language.config.json +++ b/languages/cpp/language.config.json @@ -6,9 +6,14 @@ "unwrapResultObjects": false, "createPolymorphicMethods": true, "excludeDeclarations":true, + "aggregateFiles": [ + "/include/firebolt.h", + "/src/firebolt.cpp" + ], "templatesPerModule": [ "/include/module.h", - "/src/module.cpp" + "/src/module_impl.h", + "/src/module_impl.cpp" ], "templatesPerSchema": [ "/include/common/module.h", diff --git a/languages/cpp/src/shared/src/Transport/Transport.h b/languages/cpp/src/shared/src/Transport/Transport.h index 87632dc1..e705c5c1 100644 --- a/languages/cpp/src/shared/src/Transport/Transport.h +++ b/languages/cpp/src/shared/src/Transport/Transport.h @@ -539,6 +539,7 @@ namespace FireboltSDK { , _scheduledTime(0) , _waitTime(waitTime) , _listener(listener) + , _connected(false) , _status(Firebolt::Error::NotConnected) { _channel->Register(*this); @@ -680,7 +681,10 @@ namespace FireboltSDK { virtual void Opened() { _status = Firebolt::Error::None; - _listener(true, _status); + if (_connected != true) { + _connected = true; + _listener(_connected, _status); + } } void Closed() @@ -696,7 +700,10 @@ namespace FireboltSDK { } _adminLock.Unlock(); - _listener(false, _status); + if (_connected != false) { + _connected = false; + _listener(_connected, _status); + } } int32_t Submit(const WPEFramework::Core::ProxyType& inbound) @@ -953,6 +960,7 @@ namespace FireboltSDK { uint64_t _scheduledTime; uint32_t _waitTime; Listener _listener; + bool _connected; Firebolt::Error _status; }; } diff --git a/languages/cpp/src/shared/src/Types.cpp b/languages/cpp/src/shared/test/Main.cpp similarity index 53% rename from languages/cpp/src/shared/src/Types.cpp rename to languages/cpp/src/shared/test/Main.cpp index 93f6a8d8..e41dff1d 100644 --- a/languages/cpp/src/shared/src/Types.cpp +++ b/languages/cpp/src/shared/test/Main.cpp @@ -16,25 +16,29 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "Module.h" -#include "types.h" -#include "TypesPriv.h" +#include "OpenRPCTests.h" -#ifdef __cplusplus -extern "C" { -#endif +int __cnt = 0; +int __pass = 0; -// String Type Handler Interfaces -const char* Firebolt_String(Firebolt_String_t handle) -{ - return ((reinterpret_cast(handle))->Value().c_str()); -} +int TotalTests = 0; +int TotalTestsPassed = 0; -void Firebolt_String_Release(Firebolt_String_t handle) +int main() { - delete reinterpret_cast(handle); -} + const std::string config = _T("{\ + \"waitTime\": 1000,\ + \"logLevel\": \"Info\",\ + \"workerPool\":{\ + \"queueSize\": 8,\ + \"threadCount\": 3\ + },\ + \"wsUrl\": \"ws://127.0.0.1:9998\"\ +}"); + FireboltSDK::Accessor::Instance(config); + FireboltSDK::Tests::Main(); + -#ifdef __cplusplus + printf("TOTAL: %i tests; %i PASSED, %i FAILED\n", TotalTests, TotalTestsPassed, (TotalTests - TotalTestsPassed)); + FireboltSDK::Accessor::Dispose(); } -#endif diff --git a/languages/cpp/templates/codeblocks/mock-import.c b/languages/cpp/templates/codeblocks/mock-import.c deleted file mode 100644 index 5d22512a..00000000 --- a/languages/cpp/templates/codeblocks/mock-import.c +++ /dev/null @@ -1 +0,0 @@ -import { default as _${info.title} } from './${info.title}/defaults.mjs' \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/mock-parameter.c b/languages/cpp/templates/codeblocks/mock-parameter.c deleted file mode 100644 index 63e63902..00000000 --- a/languages/cpp/templates/codeblocks/mock-parameter.c +++ /dev/null @@ -1 +0,0 @@ - ${info.title}: _${info.title}, \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/module-include-private.cpp b/languages/cpp/templates/codeblocks/module-include-private.cpp new file mode 100644 index 00000000..6d23ec5c --- /dev/null +++ b/languages/cpp/templates/codeblocks/module-include-private.cpp @@ -0,0 +1,2 @@ +${if.modules}#include "${info.title.lowercase}_impl.h" +${end.if.modules}${module.includes.private} diff --git a/languages/cpp/templates/codeblocks/module-include.h b/languages/cpp/templates/codeblocks/module-include.h new file mode 100644 index 00000000..c91e46d0 --- /dev/null +++ b/languages/cpp/templates/codeblocks/module-include.h @@ -0,0 +1,2 @@ +${if.modules}#include "${info.title.lowercase}.h" +${end.if.modules}${module.includes} \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/module-init.cpp b/languages/cpp/templates/codeblocks/module-init.cpp new file mode 100644 index 00000000..034ff7fe --- /dev/null +++ b/languages/cpp/templates/codeblocks/module-init.cpp @@ -0,0 +1,15 @@ +${if.modules} ${info.Title}::I${info.Title}& ${info.Title}Interface() const override + { + auto module = _moduleMap.find("${info.Title}"); + ${info.Title}::I${info.Title}* ${info.title.lowercase} = nullptr; + + if (module != _moduleMap.end()) { + ${info.title.lowercase} = reinterpret_cast<${info.Title}::I${info.Title}*>(module->second); + } else { + ${info.title.lowercase} = reinterpret_cast<${info.Title}::I${info.Title}*>(new ${info.Title}::${info.Title}Impl()); + _moduleMap.emplace("${info.Title}", reinterpret_cast(${info.title.lowercase})); + } + return *${info.title.lowercase}; + } + +${end.if.modules}${module.init} \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/module-init.h b/languages/cpp/templates/codeblocks/module-init.h new file mode 100644 index 00000000..c25e9380 --- /dev/null +++ b/languages/cpp/templates/codeblocks/module-init.h @@ -0,0 +1,3 @@ +${if.modules} virtual ${info.Title}::I${info.Title}& ${info.Title}Interface() const = 0; + +${end.if.modules}${module.init} \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/setter.c b/languages/cpp/templates/codeblocks/setter.c deleted file mode 100644 index ffe24fc6..00000000 --- a/languages/cpp/templates/codeblocks/setter.c +++ /dev/null @@ -1,16 +0,0 @@ - - /* ${method.rpc.name} - ${method.description} */ - void ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) - { - const string method = _T("${info.title.lowercase}.${method.rpc.name}"); - - JsonObject jsonParameters; -${if.params}${method.params.serialization}${end.if.params} - - Firebolt::Error status = FireboltSDK::Properties::Set(method, jsonParameters); - if (err != nullptr) { - *err = status; - } - - return; - } \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/setter.cpp b/languages/cpp/templates/codeblocks/setter.cpp new file mode 100644 index 00000000..6861be7f --- /dev/null +++ b/languages/cpp/templates/codeblocks/setter.cpp @@ -0,0 +1,16 @@ + + /* ${method.rpc.name} - ${method.description} */ + void ${info.Title}Impl::${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) + { + const string method = _T("${info.title.lowercase}.${method.rpc.name}"); + + JsonObject jsonParameters; +${if.params}${method.params.serialization}${end.if.params} + + Firebolt::Error status = FireboltSDK::Properties::Set(method, jsonParameters); + if (err != nullptr) { + *err = status; + } + + return; + } \ No newline at end of file diff --git a/languages/cpp/templates/codeblocks/export.c b/languages/cpp/templates/declarations-override/clear.h similarity index 100% rename from languages/cpp/templates/codeblocks/export.c rename to languages/cpp/templates/declarations-override/clear.h diff --git a/languages/cpp/templates/codeblocks/module.c b/languages/cpp/templates/declarations-override/default.h similarity index 100% rename from languages/cpp/templates/codeblocks/module.c rename to languages/cpp/templates/declarations-override/default.h diff --git a/languages/cpp/templates/declarations-override/event.h b/languages/cpp/templates/declarations-override/event.h new file mode 100644 index 00000000..025f525a --- /dev/null +++ b/languages/cpp/templates/declarations-override/event.h @@ -0,0 +1,4 @@ + // signature callback params: ${event.signature.callback.params} + // method result properties : ${method.result.properties} + void Subscribe( ${event.signature.params}${if.event.params}, ${end.if.event.params}I${info.Title}::I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) override; + void Unsubscribe( I${info.Title}::I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) override; diff --git a/languages/cpp/templates/declarations/clear.c b/languages/cpp/templates/declarations-override/listen.h similarity index 100% rename from languages/cpp/templates/declarations/clear.c rename to languages/cpp/templates/declarations-override/listen.h diff --git a/languages/cpp/templates/declarations/default.c b/languages/cpp/templates/declarations-override/once.h similarity index 100% rename from languages/cpp/templates/declarations/default.c rename to languages/cpp/templates/declarations-override/once.h diff --git a/languages/cpp/templates/declarations/listen.c b/languages/cpp/templates/declarations-override/polymorphic-pull-event.h similarity index 100% rename from languages/cpp/templates/declarations/listen.c rename to languages/cpp/templates/declarations-override/polymorphic-pull-event.h diff --git a/languages/cpp/templates/declarations/once.c b/languages/cpp/templates/declarations-override/polymorphic-pull.h similarity index 100% rename from languages/cpp/templates/declarations/once.c rename to languages/cpp/templates/declarations-override/polymorphic-pull.h diff --git a/languages/cpp/templates/declarations/polymorphic-pull-event.c b/languages/cpp/templates/declarations-override/polymorphic-reducer.h similarity index 100% rename from languages/cpp/templates/declarations/polymorphic-pull-event.c rename to languages/cpp/templates/declarations-override/polymorphic-reducer.h diff --git a/languages/cpp/templates/declarations-override/property.h b/languages/cpp/templates/declarations-override/property.h new file mode 100644 index 00000000..c7d6ac13 --- /dev/null +++ b/languages/cpp/templates/declarations-override/property.h @@ -0,0 +1,5 @@ + /* + * ${method.description} + * ${method.params} + */ + ${method.signature.result} ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) const override; \ No newline at end of file diff --git a/languages/cpp/templates/declarations/polymorphic-pull.c b/languages/cpp/templates/declarations-override/provide.h similarity index 100% rename from languages/cpp/templates/declarations/polymorphic-pull.c rename to languages/cpp/templates/declarations-override/provide.h diff --git a/languages/cpp/templates/declarations-override/setter.h b/languages/cpp/templates/declarations-override/setter.h new file mode 100644 index 00000000..7b8e11d9 --- /dev/null +++ b/languages/cpp/templates/declarations-override/setter.h @@ -0,0 +1,5 @@ + /* + * ${method.rpc.name} + * ${method.description} + */ + void ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) override; diff --git a/languages/cpp/templates/declarations/polymorphic-reducer.c b/languages/cpp/templates/declarations/clear.h similarity index 100% rename from languages/cpp/templates/declarations/polymorphic-reducer.c rename to languages/cpp/templates/declarations/clear.h diff --git a/languages/cpp/templates/declarations/provide.c b/languages/cpp/templates/declarations/default.h similarity index 100% rename from languages/cpp/templates/declarations/provide.c rename to languages/cpp/templates/declarations/default.h diff --git a/languages/cpp/templates/declarations/event.c b/languages/cpp/templates/declarations/event.h similarity index 100% rename from languages/cpp/templates/declarations/event.c rename to languages/cpp/templates/declarations/event.h diff --git a/languages/cpp/templates/defaults/default.c b/languages/cpp/templates/declarations/listen.h similarity index 100% rename from languages/cpp/templates/defaults/default.c rename to languages/cpp/templates/declarations/listen.h diff --git a/languages/cpp/templates/defaults/property.c b/languages/cpp/templates/declarations/once.h similarity index 100% rename from languages/cpp/templates/defaults/property.c rename to languages/cpp/templates/declarations/once.h diff --git a/languages/cpp/templates/methods/clear.c b/languages/cpp/templates/declarations/polymorphic-pull-event.h similarity index 100% rename from languages/cpp/templates/methods/clear.c rename to languages/cpp/templates/declarations/polymorphic-pull-event.h diff --git a/languages/cpp/templates/methods/default.c b/languages/cpp/templates/declarations/polymorphic-pull.h similarity index 100% rename from languages/cpp/templates/methods/default.c rename to languages/cpp/templates/declarations/polymorphic-pull.h diff --git a/languages/cpp/templates/methods/listen.c b/languages/cpp/templates/declarations/polymorphic-reducer.h similarity index 100% rename from languages/cpp/templates/methods/listen.c rename to languages/cpp/templates/declarations/polymorphic-reducer.h diff --git a/languages/cpp/templates/methods/once.c b/languages/cpp/templates/declarations/provide.h similarity index 100% rename from languages/cpp/templates/methods/once.c rename to languages/cpp/templates/declarations/provide.h diff --git a/languages/cpp/templates/imports/default.impl b/languages/cpp/templates/imports/default.impl new file mode 100644 index 00000000..caf84bc9 --- /dev/null +++ b/languages/cpp/templates/imports/default.impl @@ -0,0 +1 @@ +#include "jsondata_${info.title.lowercase}.h" diff --git a/languages/cpp/templates/methods/calls-metrics.c b/languages/cpp/templates/methods/calls-metrics.cpp similarity index 100% rename from languages/cpp/templates/methods/calls-metrics.c rename to languages/cpp/templates/methods/calls-metrics.cpp diff --git a/languages/cpp/templates/methods/polymorphic-pull-event.c b/languages/cpp/templates/methods/clear.cpp similarity index 100% rename from languages/cpp/templates/methods/polymorphic-pull-event.c rename to languages/cpp/templates/methods/clear.cpp diff --git a/languages/cpp/templates/methods/polymorphic-pull.c b/languages/cpp/templates/methods/default.cpp similarity index 100% rename from languages/cpp/templates/methods/polymorphic-pull.c rename to languages/cpp/templates/methods/default.cpp diff --git a/languages/cpp/templates/methods/event.c b/languages/cpp/templates/methods/event.c deleted file mode 100644 index 8745c653..00000000 --- a/languages/cpp/templates/methods/event.c +++ /dev/null @@ -1,33 +0,0 @@ - /* ${method.rpc.name} - ${method.description} */ - static void ${info.Title}${method.Name}InnerCallback( void* notification, const void* userData, void* jsonResponse ) - { -${event.callback.params.serialization} - ASSERT(proxyResponse->IsValid() == true); - - if (proxyResponse->IsValid() == true) { -${event.callback.result.instantiation} - proxyResponse->Release(); - - I${method.Name}Notification& notifier = *(reinterpret_cast(notification)); - notifier.${method.Name}(${event.callback.response.instantiation}); - } - } - void Subscribe( ${event.signature.params}${if.event.params}, ${end.if.event.params}I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) - { - const string eventName = _T("${info.title.lowercase}.${method.rpc.name}"); - Firebolt::Error status = Firebolt::Error::None; - - JsonObject jsonParameters; -${event.params.serialization} - status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(¬ification), nullptr); - if (err != nullptr) { - *err = status; - } - } - void Unsubscribe( I${method.Name}Notification& notification, Firebolt::Error *err = nullptr ) - { - Firebolt::Error status = FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(¬ification)); - if (err != nullptr) { - *err = status; - } - } \ No newline at end of file diff --git a/languages/cpp/templates/methods/event.cpp b/languages/cpp/templates/methods/event.cpp new file mode 100644 index 00000000..5cbcbea7 --- /dev/null +++ b/languages/cpp/templates/methods/event.cpp @@ -0,0 +1,35 @@ + /* ${method.rpc.name} - ${method.description} */ + static void ${info.Title}${method.Name}InnerCallback( void* notification, const void* userData, void* jsonResponse ) + { +${event.callback.params.serialization} + ASSERT(proxyResponse->IsValid() == true); + + if (proxyResponse->IsValid() == true) { +${event.callback.result.instantiation} + proxyResponse->Release(); + + I${info.Title}::I${method.Name}Notification& notifier = *(reinterpret_cast(notification)); + notifier.${method.Name}(${event.callback.response.instantiation}); + } + } + void ${info.Title}Impl::Subscribe( ${event.signature.params}${if.event.params}, ${end.if.event.params}I${info.Title}::I${method.Name}Notification& notification, Firebolt::Error *err ) + { + const string eventName = _T("${info.title.lowercase}.${method.rpc.name}"); + Firebolt::Error status = Firebolt::Error::None; + + JsonObject jsonParameters; +${event.params.serialization} + status = FireboltSDK::Event::Instance().Subscribe<${event.result.json.type}>(eventName, jsonParameters, ${info.Title}${method.Name}InnerCallback, reinterpret_cast(¬ification), nullptr); + + if (err != nullptr) { + *err = status; + } + } + void ${info.Title}Impl::Unsubscribe( I${info.Title}::I${method.Name}Notification& notification, Firebolt::Error *err ) + { + Firebolt::Error status = FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title.lowercase}.${method.rpc.name}"), reinterpret_cast(¬ification)); + + if (err != nullptr) { + *err = status; + } + } \ No newline at end of file diff --git a/languages/cpp/templates/methods/polymorphic-reducer.c b/languages/cpp/templates/methods/listen.cpp similarity index 100% rename from languages/cpp/templates/methods/polymorphic-reducer.c rename to languages/cpp/templates/methods/listen.cpp diff --git a/languages/cpp/templates/methods/provide.c b/languages/cpp/templates/methods/once.cpp similarity index 100% rename from languages/cpp/templates/methods/provide.c rename to languages/cpp/templates/methods/once.cpp diff --git a/languages/cpp/templates/methods/setter.c b/languages/cpp/templates/methods/polymorphic-pull-event.cpp similarity index 100% rename from languages/cpp/templates/methods/setter.c rename to languages/cpp/templates/methods/polymorphic-pull-event.cpp diff --git a/languages/cpp/templates/methods/polymorphic-pull.cpp b/languages/cpp/templates/methods/polymorphic-pull.cpp new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/methods/polymorphic-reducer.cpp b/languages/cpp/templates/methods/polymorphic-reducer.cpp new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/methods/property.c b/languages/cpp/templates/methods/property.c deleted file mode 100644 index f3d91141..00000000 --- a/languages/cpp/templates/methods/property.c +++ /dev/null @@ -1,17 +0,0 @@ - /* ${method.rpc.name} - ${method.description} */ - ${method.signature.result} ${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err = nullptr ) const - { - const string method = _T("${info.title.lowercase}.${method.rpc.name}"); - ${if.params}${method.params.serialization}${end.if.params} - ${method.result.json} jsonResult; -${method.result.initialization} - ${if.params}Firebolt::Error status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} - ${if.params.empty}Firebolt::Error status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} - if (status == Firebolt::Error::None) { -${method.result.instantiation} - } - if (err != nullptr) { - *err = status; - } - return ${method.result.name}; - }${method.setter} \ No newline at end of file diff --git a/languages/cpp/templates/methods/property.cpp b/languages/cpp/templates/methods/property.cpp new file mode 100644 index 00000000..acecc416 --- /dev/null +++ b/languages/cpp/templates/methods/property.cpp @@ -0,0 +1,18 @@ + /* ${method.rpc.name} - ${method.description} */ + ${method.signature.result} ${info.Title}Impl::${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}Firebolt::Error *err ) const + { + const string method = _T("${info.title.lowercase}.${method.rpc.name}"); + ${if.params}${method.params.serialization}${end.if.params} + ${method.result.json} jsonResult; +${method.result.initialization} + ${if.params}Firebolt::Error status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params} + ${if.params.empty}Firebolt::Error status = FireboltSDK::Properties::Get(method, jsonResult);${end.if.params.empty} + if (status == Firebolt::Error::None) { +${method.result.instantiation} + } + if (err != nullptr) { + *err = status; + } + + return ${method.result.name}; + }${method.setter} \ No newline at end of file diff --git a/languages/cpp/templates/methods/provide.cpp b/languages/cpp/templates/methods/provide.cpp new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/methods/setter.cpp b/languages/cpp/templates/methods/setter.cpp new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/modules/include/module.h b/languages/cpp/templates/modules/include/module.h index 6080265e..6ee534e4 100644 --- a/languages/cpp/templates/modules/include/module.h +++ b/languages/cpp/templates/modules/include/module.h @@ -31,17 +31,14 @@ namespace ${info.Title} { // Types /* ${TYPES} */ ${end.if.types} -struct I${info.Title} { - - static I${info.Title}& Instance(); - static void Dispose(); +${if.methods}struct I${info.Title} { virtual ~I${info.Title}() = default; // Methods & Events /* ${DECLARATIONS} */ -}; +};${end.if.methods} } //namespace ${info.Title} }${end.if.declarations} diff --git a/languages/cpp/templates/modules/src/module.cpp b/languages/cpp/templates/modules/src/module.cpp deleted file mode 100644 index ebdbb0b7..00000000 --- a/languages/cpp/templates/modules/src/module.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2023 Comcast Cable Communications Management, LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "FireboltSDK.h" -/* ${IMPORTS} */ -#include "${info.title.lowercase}.h" - -${if.implementations} -namespace Firebolt { -namespace ${info.Title} { -${if.enums} - -/* ${ENUMS:json-types} */${end.if.enums} -${if.types} - // Types -/* ${TYPES:json-types} */${end.if.types} - - ${if.definitions}class ${info.Title}Impl : public I${info.Title} { - - private: - ${info.Title}Impl() - { - ASSERT(_singleton == nullptr); - _singleton = this; - } - - public: - ${info.Title}Impl(const ${info.Title}Impl&) = delete; - ${info.Title}Impl& operator=(const ${info.Title}Impl&) = delete; - - ~${info.Title}Impl() - { - ASSERT(_singleton != nullptr); - _singleton = nullptr; - } - - static ${info.Title}Impl& Instance() - { - static ${info.Title}Impl* instance = new ${info.Title}Impl(); - ASSERT(instance != nullptr); - return *instance; - } - - static void Dispose() - { - if (_singleton != nullptr) { - delete _singleton; - } - } - - - // Methods - /* ${METHODS} */ - - // Events - /* ${EVENTS} */ - - private: - static ${info.Title}Impl* _singleton; - };${end.if.definitions} - - ${info.Title}Impl* ${info.Title}Impl::_singleton = nullptr; - - /* static */ I${info.Title}& I${info.Title}::Instance() - { - return (${info.Title}Impl::Instance()); - } - /* static */ void I${info.Title}::Dispose() - { - ${info.Title}Impl::Dispose(); - } - -}//namespace ${info.Title} -}${end.if.implementations} diff --git a/languages/cpp/src/shared/src/firebolt.cpp b/languages/cpp/templates/modules/src/module_impl.cpp similarity index 66% rename from languages/cpp/src/shared/src/firebolt.cpp rename to languages/cpp/templates/modules/src/module_impl.cpp index 90c54c5c..072cd1fc 100644 --- a/languages/cpp/src/shared/src/firebolt.cpp +++ b/languages/cpp/templates/modules/src/module_impl.cpp @@ -16,24 +16,25 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "FireboltSDK.h" +#include "${info.title.lowercase}_impl.h" +${if.implementations} +namespace Firebolt { +namespace ${info.Title} { -#ifdef __cplusplus -extern "C" { -#endif + // Methods + /* ${METHODS} */ + // Events + /* ${EVENTS} */ -int32_t FireboltSDK_Initialize(char* configLine) { - FireboltSDK::Accessor::Instance(configLine); - return FireboltSDKErrorNone; -} +}//namespace ${info.Title} +}${end.if.implementations} +${if.enums} -int32_t FireboltSDK_Deinitialize(void) { - FireboltSDK::Accessor::Dispose(); - return FireboltSDKErrorNone; -} +namespace WPEFramework { -#ifdef __cplusplus -} -#endif + +/* ${ENUMS} */ + +}${end.if.enums} diff --git a/languages/cpp/templates/modules/src/module_impl.h b/languages/cpp/templates/modules/src/module_impl.h new file mode 100644 index 00000000..d9127bae --- /dev/null +++ b/languages/cpp/templates/modules/src/module_impl.h @@ -0,0 +1,48 @@ +/* + * Copyright 2023 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "FireboltSDK.h" +#include "IModule.h" +/* ${IMPORTS} */ +#include "${info.title.lowercase}.h" + +${if.implementations} +namespace Firebolt { +namespace ${info.Title} { +${if.enums} + +/* ${ENUMS:json-types} */${end.if.enums} +${if.types} + // Types +/* ${TYPES:json-types} */${end.if.types} + ${if.methods}class ${info.Title}Impl : public I${info.Title}, public IModule { + + public: + ${info.Title}Impl() = default; + ${info.Title}Impl(const ${info.Title}Impl&) = delete; + ${info.Title}Impl& operator=(const ${info.Title}Impl&) = delete; + + ~${info.Title}Impl() override = default; + + // Methods & Events + /* ${DECLARATIONS_OVERRIDE} */ + + };${end.if.methods} + +}//namespace ${info.Title} +}${end.if.implementations} diff --git a/languages/cpp/templates/sdk/include/firebolt.h b/languages/cpp/templates/sdk/include/firebolt.h new file mode 100644 index 00000000..fbd99809 --- /dev/null +++ b/languages/cpp/templates/sdk/include/firebolt.h @@ -0,0 +1,133 @@ +/* + * Copyright 2023 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include "types.h" +#include "error.h" +${module.includes} + +namespace Firebolt { + +struct IFireboltAccessor { + + virtual ~IFireboltAccessor() = default; + + /** + * @brief Get the FireboltAccessor singleton instance + * + * @return FireboltAccessor Instance + * */ + static IFireboltAccessor& Instance(); + + /** + * @brief Inititalize the Firebolt SDK. Sets up the Transport, WorkerPool and Logging Subsystems. + * + * @param configLine JSON String with configuration options. At a minimum the user is expected to pass in the Websocket URL. + * + * CONFIG Format: + * { + * "waitTime": 1000, + * "logLevel": "Info", + * "workerPool":{ + * "queueSize": 8, + * "threadCount": 3 + * }, + * "wsUrl": "ws://127.0.0.1:9998" + * } + * + * + * @return Firebolt::Error + * + */ + + virtual Firebolt::Error Initialize ( const std::string& configLine ) = 0; + + /** + * @brief Deinititlize the SDK. + * + * @return Firebolt::Error + * + */ + virtual Firebolt::Error Deinitialize ( ) = 0; + + + /** + * @brief Connection status listener callback + * + * @param connected Connection status: true - Connected, false - Disconnected + * @param error Reason, if any. + * + * @return None + */ + using OnConnectionChanged = std::function; + + /** + * @brief Attempt a connection to the endpoint. This method is asynchronous and the user is expected to wait for the + * OnConnectionChanged callback to report successful connection before calling SDK methods + * + * @param listener Connection status listener + * + * @return Firebolt::Error + */ + virtual Firebolt::Error Connect ( OnConnectionChanged listener ) = 0; + + /** + * @brief Disconnects from the Websocket endpoint. + * + * @return Firebolt::Error + */ + virtual Firebolt::Error Disconnect ( ) = 0; + + /** + * @brief Dispose the FireboltAccessor instance and all associated module instances. + * + * @return None + * + */ + static void Dispose(); + + /** + * @brief Error callback when a method fails. + * + * @param method Name of the method e.g, "Device.id" + * @param payload JSONRPC Payload of the method. + * @param error Failure reason. + * + * @return None + */ + using OnError = std::function; + + /** + * @brief Register for Error notifications. + * + * @param notification OnError Notification callback. Passing a nullptr will unregister. + * + * @return None + */ + virtual void ErrorListener(OnError notification) = 0; + + + // Module Instance methods goes here. + // Instances are owned by the FireboltAcccessor and linked with its lifecycle. + +${module.init} +}; + +} diff --git a/languages/cpp/templates/sdk/scripts/install.sh b/languages/cpp/templates/sdk/scripts/install.sh index 24bd1c4c..2c4663af 100755 --- a/languages/cpp/templates/sdk/scripts/install.sh +++ b/languages/cpp/templates/sdk/scripts/install.sh @@ -45,7 +45,7 @@ cp -ar ${SdkPath}/include ${ReleasePath} cp -ar ${SdkPath}/cmake ${ReleasePath} cp -ar ${SdkPath}/scripts/build.sh ${ReleasePath} cp -ar ${SdkPath}/CMakeLists.txt ${ReleasePath} -cp -ar ${SdkPath}/ctest ${ReleasePath}/test +cp -ar ${SdkPath}/cpptest ${ReleasePath}/test sed -i '/EnableTest="ON";;/d' ${ReleasePath}/build.sh sed -i 's/getopts p:s:tch/getopts p:s:ch/g' ${ReleasePath}/build.sh diff --git a/languages/cpp/templates/sdk/src/firebolt.cpp b/languages/cpp/templates/sdk/src/firebolt.cpp new file mode 100644 index 00000000..a864c2c4 --- /dev/null +++ b/languages/cpp/templates/sdk/src/firebolt.cpp @@ -0,0 +1,116 @@ +/* + * Copyright 2023 Comcast Cable Communications Management, LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include "FireboltSDK.h" +${module.includes.private} + +namespace Firebolt { + + class FireboltAccessorImpl : public IFireboltAccessor { + private: + using ModuleMap = std::unordered_map; + + private: + FireboltAccessorImpl() + : _accessor(nullptr) + { + ASSERT(_singleton == nullptr); + _singleton = this; + } + public: + FireboltAccessorImpl(const FireboltAccessorImpl&) = delete; + FireboltAccessorImpl& operator=(const FireboltAccessorImpl&) = delete; + + ~FireboltAccessorImpl() + { + if (_accessor != nullptr) { + _accessor->Dispose(); + _accessor = nullptr; + } + + ASSERT(_singleton != nullptr); + _singleton = nullptr; + } + + static FireboltAccessorImpl& Instance() + { + static FireboltAccessorImpl* instance = new FireboltAccessorImpl(); + ASSERT(instance != nullptr); + return *instance; + } + + static void Dispose() + { + ModuleMap::iterator module = _moduleMap.begin(); + while (module != _moduleMap.end()) { + delete module->second; + module = _moduleMap.erase(module); + } + + ASSERT(_singleton != nullptr); + if (_singleton != nullptr) { + delete _singleton; + } + } + + Firebolt::Error Initialize( const std::string& configLine ) override + { + _accessor = &(FireboltSDK::Accessor::Instance(configLine)); + return Error::None; + } + + Firebolt::Error Deinitialize() override + { + return Error::None; + } + + Firebolt::Error Connect( OnConnectionChanged listener ) override + { + return _accessor->Connect(listener); + } + + Firebolt::Error Disconnect() override + { + return _accessor->Disconnect(); + } + + void ErrorListener(OnError notification) override + { + } + +${module.init} + private: + FireboltSDK::Accessor* _accessor; + static FireboltAccessorImpl* _singleton; + static ModuleMap _moduleMap; + }; + + FireboltAccessorImpl::ModuleMap FireboltAccessorImpl::_moduleMap; + + FireboltAccessorImpl* FireboltAccessorImpl::_singleton = nullptr; + + /* static */ IFireboltAccessor& IFireboltAccessor::Instance() + { + return (FireboltAccessorImpl::Instance()); + } + /* static */ void IFireboltAccessor::Dispose() + { + FireboltAccessorImpl::Dispose(); + } +} diff --git a/languages/cpp/templates/sections/declarations-override.h b/languages/cpp/templates/sections/declarations-override.h new file mode 100644 index 00000000..206f2638 --- /dev/null +++ b/languages/cpp/templates/sections/declarations-override.h @@ -0,0 +1 @@ +${declaration.override.list} diff --git a/languages/javascript/language.config.json b/languages/javascript/language.config.json index 540e6375..4044bffc 100644 --- a/languages/javascript/language.config.json +++ b/languages/javascript/language.config.json @@ -8,6 +8,9 @@ "createModuleDirectories": true, "copySchemasIntoModules": true, "aggregateFile": "/index.d.ts", + "aggregateFiles": [ + "/index.d.ts" + ], "treeshakePattern": "(import|export).*?from\\s+['\"](.*?)['\"]", "treeshakeTypes": [".js", ".mjs"], "operators": { diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 500bc3b1..d6f8ac88 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -107,6 +107,10 @@ const getTemplateForDeclaration = (method, templates) => { return getTemplateTypeForMethod(method, 'declarations', templates) } +const getTemplateForDeclarationOverride = (method, templates) => { + return getTemplateTypeForMethod(method, 'declarations-override', templates) +} + const getTemplateForExample = (method, templates) => { return getTemplateTypeForMethod(method, 'examples', templates) } @@ -459,7 +463,6 @@ const mergeAnyOfs = (obj) => { obj = JSON.parse(JSON.stringify(obj)) findAll('anyOf', obj, anyOf => mergeAnyOf(anyOf)) -// findAll('onyOf', obj, onyOf => mergeOnyOf(onyOf)) return obj } @@ -512,6 +515,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { const methodsArray = allMethodsArray.filter(m => m.body && !m.event && (!options.hideExcluded || !m.excluded)) const eventsArray = allMethodsArray.filter(m => m.body && m.event && (!options.hideExcluded || !m.excluded)) const declarationsArray = allMethodsArray.filter(m => m.declaration && (!config.excludeDeclarations || (!options.hideExcluded || !m.excluded))) + const declarationsOverrideArray = allMethodsArray.filter(m => m.declarationOverride && (!config.excludeDeclarations || (!options.hideExcluded || !m.excluded))) const imports = generateImports(obj, templates, { destination: (options.destination ? options.destination : '') }) const initialization = generateInitialization(obj, templates) @@ -520,12 +524,17 @@ const generateMacros = (obj, templates, languages, options = {}) => { const methods = methodsArray.length ? getTemplate('/sections/methods', templates).replace(/\$\{method.list\}/g, methodsArray.map(m => m.body).join('\n')) : '' const declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' const methodList = methodsArray.filter(m => m.body).map(m => m.name) - + const declarationsOverride = declarationsOverrideArray.length ? getTemplate('/sections/declarations-override', templates).replace(/\$\{declaration\.override\.list\}/g, declarationsOverrideArray.map(m => m.declarationOverride).join('\n')) : '' const providerInterfaces = generateProviderInterfaces(obj, templates) const events = eventsArray.length ? getTemplate('/sections/events', templates).replace(/\$\{event.list\}/g, eventsArray.map(m => m.body).join('\n')) : '' const eventList = eventsArray.map(m => makeEventName(m)) const defaults = generateDefaults(obj, templates) + + const suffix = options.destination ? options.destination.split('.').pop().trim() : '' const module = getTemplate('/codeblocks/module', templates) + const moduleInclude = getTemplate(suffix ? `/codeblocks/module-include.${suffix}` : '/codeblocks/module-include', templates) + const moduleIncludePrivate = getTemplate(suffix ? `/codeblocks/module-include-private.${suffix}` : '/codeblocks/module-include-private', templates) + const moduleInit = getTemplate(suffix ? `/codeblocks/module-init.${suffix}` : '/codeblocks/module-init', templates) Object.assign(macros, { imports, @@ -536,6 +545,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { methods, methodList, declarations, + declarationsOverride, defaults, examples, providerInterfaces, @@ -543,12 +553,23 @@ const generateMacros = (obj, templates, languages, options = {}) => { title: obj.info.title, description: obj.info.description, module: module, + moduleInclude: moduleInclude, + moduleIncludePrivate: moduleIncludePrivate, + moduleInit: moduleInit, public: hasPublicAPIs(obj) }) return macros } +const clearMacros = (fContents = '') => { + fContents = fContents.replace(/\$\{module\.includes\}/g, "") + fContents = fContents.replace(/\$\{module\.includes\.private\}/g, "") + fContents = fContents.replace(/\$\{module\.init\}/g, "") + + return fContents +} + const insertAggregateMacros = (fContents = '', aggregateMacros = {}) => { fContents = fContents.replace(/[ \t]*\/\* \$\{EXPORTS\} \*\/[ \t]*\n/, aggregateMacros.exports) fContents = fContents.replace(/[ \t]*\/\* \$\{MOCK_IMPORTS\} \*\/[ \t]*\n/, aggregateMacros.mockImports) @@ -560,7 +581,7 @@ const insertAggregateMacros = (fContents = '', aggregateMacros = {}) => { } const insertMacros = (fContents = '', macros = {}) => { - if (macros.append) { + if (macros.append && macros.module) { fContents += '\n' + macros.module } @@ -569,18 +590,27 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{if\.types\}(.*?)\$\{end\.if\.types\}/gms, macros.types.types.trim() ? '$1' : '') fContents = fContents.replace(/\$\{if\.schemas\}(.*?)\$\{end\.if\.schemas\}/gms, macros.schemas.types.trim() ? '$1' : '') - fContents = fContents.replace(/\$\{if\.declarations\}(.*?)\$\{end\.if\.declarations\}/gms, (macros.declarations.trim() || macros.enums.types.trim()) ? '$1' : '') - fContents = fContents.replace(/\$\{if\.definitions\}(.*?)\$\{end\.if\.definitions\}/gms, (macros.methods.trim() || macros.events.trim()) ? '$1' : '') + fContents = fContents.replace(/\$\{if\.enums\}(.*?)\$\{end\.if\.enums\}/gms, macros.enums.types.trim() ? '$1' : '') + fContents = fContents.replace(/\$\{if\.declarations\}(.*?)\$\{end\.if\.declarations\}/gms, (macros.declarations.trim() || macros.enums.types.trim()) || macros.types.types.trim()? '$1' : '') + + fContents = fContents.replace(/\$\{if\.methods\}(.*?)\$\{end\.if\.methods\}/gms, (macros.methods.trim() || macros.events.trim()) ? '$1' : '') + fContents = fContents.replace(/\$\{if\.implementations\}(.*?)\$\{end\.if\.implementations\}/gms, (macros.methods.trim() || macros.events.trim() || macros.schemas.types.trim()) ? '$1' : '') + + fContents = fContents.replace(/\$\{module\.list\}/g, macros.module) + fContents = fContents.replace(/\$\{module\.includes\}/g, macros.moduleInclude) + fContents = fContents.replace(/\$\{module\.includes\.private\}/g, macros.moduleIncludePrivate) + fContents = fContents.replace(/\$\{module\.init\}/g, macros.moduleInit) + + fContents = fContents.replace(/\$\{if\.modules\}(.*?)\$\{end\.if\.modules\}/gms, (macros.methods.trim() || macros.events.trim()) ? '$1' : '') - fContents = fContents.replace(/\$\{module.list\}/g, macros.module) fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods) fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations) + fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS_OVERRIDE\} \*\/[ \t]*\n/, macros.declarationsOverride) fContents = fContents.replace(/[ \t]*\/\* \$\{METHOD_LIST\} \*\/[ \t]*\n/, macros.methodList.join(',\n')) fContents = fContents.replace(/[ \t]*\/\* \$\{EVENTS\} \*\/[ \t]*\n/, macros.events) fContents = fContents.replace(/[ \t]*\/\* \$\{EVENT_LIST\} \*\/[ \t]*\n/, macros.eventList.join(',')) fContents = fContents.replace(/[ \t]*\/\* \$\{EVENTS_ENUM\} \*\/[ \t]*\n/, macros.eventsEnum) - // Output the originally supported non-configurable schema macros fContents = fContents.replace(/[ \t]*\/\* \$\{SCHEMAS\} \*\/[ \t]*\n/, macros.schemas.types) fContents = fContents.replace(/[ \t]*\/\* \$\{TYPES\} \*\/[ \t]*\n/, macros.types.types) @@ -927,16 +957,20 @@ const generateImports = (json, templates, options = { destination: '' }) => { if (methodsWithXMethodsInResult(json).length) { imports += getTemplate('/imports/x-method', templates) } - const suffix = options.destination.split('.').pop() - const prefix = options.destination.split('/').pop().split('_')[0].toLowerCase() + const suffix = options.destination.split('.').pop() if (callsMetrics(json).length) { imports += getTemplate(suffix ? `/imports/calls-metrics.${suffix}` : '/imports/calls-metrics', templates) } - let template = prefix ? getTemplate(`/imports/default.${prefix}`, templates) : '' + const destinationArray = options.destination.split('/').pop().split(/[_.]+/) + let template = '' + destinationArray.filter(value => value).every((suffix) => { + template = getTemplate(`/imports/default.${suffix}`, templates) + return template ? false: true + }) if (!template) { - template = getTemplate(suffix ? `/imports/default.${suffix}` : '/imports/default', templates) + template = getTemplate('/imports/default', templates) } if (json['x-schemas'] && Object.keys(json['x-schemas']).length > 0 && !json.info['x-uri-titles']) { @@ -1056,6 +1090,7 @@ function generateMethods(json = {}, examples = {}, templates = {}) { name: methodObj.name, body: '', declaration: '', + declarationOverride: '', excluded: methodObj.tags.find(t => t.name === 'exclude-from-sdk'), event: isEventMethod(methodObj) } @@ -1074,6 +1109,13 @@ function generateMethods(json = {}, examples = {}, templates = {}) { result.declaration = javascript } + template = getTemplateForDeclarationOverride(methodObj, templates) + + if (template && template.length) { + let javascript = insertMethodMacros(template, methodObj, json, templates, examples) + result.declarationOverride = javascript + } + acc.push(result) return acc @@ -1708,6 +1750,7 @@ function insertProviderParameterMacros(data = '', parameters, module = {}, optio export { generateMacros, + clearMacros, insertMacros, generateAggregateMacros, insertAggregateMacros @@ -1715,6 +1758,7 @@ export { export default { generateMacros, + clearMacros, insertMacros, generateAggregateMacros, insertAggregateMacros, diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 1899f310..2c86e4de 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -53,7 +53,7 @@ const macrofy = async ( convertTuplesToArraysOrObjects, additionalSchemaTemplates, excludeDeclarations, - aggregateFile, + aggregateFiles, operators, primitives, hidePrivate = true, @@ -144,22 +144,21 @@ const macrofy = async ( const outputFiles = Object.fromEntries(Object.entries(await readFiles( staticCodeList, staticContent)) .map( ([n, v]) => [path.join(output, n), v])) - let primaryOutput + let primaryOutput = [] Object.keys(templates).forEach(file => { if (file.startsWith(path.sep + outputDirectory + path.sep) || outputDirectory === '') { // Note: '/foo/bar/file.js'.split('/') => ['', 'foo', 'bar', 'file.js'] so we need to drop one more that you might suspect, hence slice(2) below... const dirsToDrop = outputDirectory === '' ? 1 : 2 let outputFile = path.sep + file.split(path.sep).slice(dirsToDrop).join(path.sep) - const isPrimary = outputFile === aggregateFile - + const isPrimary = (aggregateFiles && aggregateFiles.includes(outputFile)) if (rename[outputFile]) { outputFile = outputFile.split(path.sep).slice(0, -1).concat([rename[outputFile]]).join(path.sep) } if (isPrimary) { - primaryOutput = path.join(output, outputFile) - } + primaryOutput.push(path.join(output, outputFile)) + } const content = engine.insertAggregateMacros(templates[file], aggregateMacros) outputFiles[path.join(output, outputFile)] = content @@ -193,15 +192,18 @@ const macrofy = async ( logSuccess(`Generated macros for module ${path.relative(output, location)}`) }) - if (primaryOutput) { - const macros = engine.generateMacros(module, templates, exampleTemplates, {hideExcluded: hideExcluded, copySchemasIntoModules: copySchemasIntoModules, createPolymorphicMethods: createPolymorphicMethods, destination: primaryOutput}) + primaryOutput.forEach(output => { + const macros = engine.generateMacros(module, templates, exampleTemplates, {hideExcluded: hideExcluded, copySchemasIntoModules: copySchemasIntoModules, createPolymorphicMethods: createPolymorphicMethods, destination: output}) macros.append = append - outputFiles[primaryOutput] = engine.insertMacros(outputFiles[primaryOutput], macros) - } + outputFiles[output] = engine.insertMacros(outputFiles[output], macros) + }) append = true }) - + primaryOutput.forEach(output => { + outputFiles[output] = engine.clearMacros(outputFiles[output]); + }) + if (treeshakePattern && treeshakeEntry) { const importedFiles = (code, base) => Array.from(new Set([...code.matchAll(treeshakePattern)].map(arr => arr[2]))).map(i => path.join(output, base, i)) diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 8e17366a..e851f108 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -71,7 +71,7 @@ const run = async ({ excludeDeclarations: config.excludeDeclarations, staticModuleNames: staticModuleNames, hideExcluded: true, - aggregateFile: config.aggregateFile, + aggregateFiles: config.aggregateFiles, rename: mainFilename ? { '/index.mjs': mainFilename, '/index.d.ts': declarationsFilename } : {}, treeshakePattern: config.treeshakePattern ? new RegExp(config.treeshakePattern, "g") : undefined, treeshakeTypes: config.treeshakeTypes, diff --git a/src/shared/json-schema.mjs b/src/shared/json-schema.mjs index 8b65d9a9..97ac6ff7 100644 --- a/src/shared/json-schema.mjs +++ b/src/shared/json-schema.mjs @@ -233,7 +233,6 @@ const localizeDependencies = (json, document, schemas = {}, options = defaultLoc path.pop() // drop ref if (refToPath(ref).length > 1) { let resolvedSchema = JSON.parse(JSON.stringify(getPathOr(null, refToPath(ref), document))) - if (schemaReferencesItself(resolvedSchema, refToPath(ref))) { resolvedSchema = null } From f82ef7b7e0ae37428025dc958868de0e591225f3 Mon Sep 17 00:00:00 2001 From: HaseenaSainul Date: Thu, 19 Oct 2023 05:57:59 -0400 Subject: [PATCH 2/5] CPPSDK: support to generate declarations for both dynamic and static configured templates --- languages/cpp/language.config.json | 3 +- .../declarations-override/rpc-only.h | 0 .../cpp/templates/modules/src/module_impl.h | 3 +- .../sections/declarations-override.h | 1 - src/macrofier/engine.mjs | 71 +++++++++---------- src/macrofier/index.mjs | 2 + src/sdk/index.mjs | 1 + 7 files changed, 41 insertions(+), 40 deletions(-) create mode 100644 languages/cpp/templates/declarations-override/rpc-only.h delete mode 100644 languages/cpp/templates/sections/declarations-override.h diff --git a/languages/cpp/language.config.json b/languages/cpp/language.config.json index 15a67fb5..786bf191 100644 --- a/languages/cpp/language.config.json +++ b/languages/cpp/language.config.json @@ -28,5 +28,6 @@ "string": "std::string" }, "langVersion" : "c++17", - "additionalSchemaTemplates": [ "json-types" ] + "additionalSchemaTemplates": [ "json-types" ], + "additionalDeclarationTemplates": [ "declarations-override" ] } diff --git a/languages/cpp/templates/declarations-override/rpc-only.h b/languages/cpp/templates/declarations-override/rpc-only.h new file mode 100644 index 00000000..e69de29b diff --git a/languages/cpp/templates/modules/src/module_impl.h b/languages/cpp/templates/modules/src/module_impl.h index d9127bae..8051139e 100644 --- a/languages/cpp/templates/modules/src/module_impl.h +++ b/languages/cpp/templates/modules/src/module_impl.h @@ -40,8 +40,7 @@ namespace ${info.Title} { ~${info.Title}Impl() override = default; // Methods & Events - /* ${DECLARATIONS_OVERRIDE} */ - + /* ${DECLARATIONS:declarations-override} */ };${end.if.methods} }//namespace ${info.Title} diff --git a/languages/cpp/templates/sections/declarations-override.h b/languages/cpp/templates/sections/declarations-override.h deleted file mode 100644 index 206f2638..00000000 --- a/languages/cpp/templates/sections/declarations-override.h +++ /dev/null @@ -1 +0,0 @@ -${declaration.override.list} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index d6f8ac88..84c7a8a2 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -103,12 +103,8 @@ const getTemplateForMethod = (method, templates) => { return getTemplateTypeForMethod(method, 'methods', templates) } -const getTemplateForDeclaration = (method, templates) => { - return getTemplateTypeForMethod(method, 'declarations', templates) -} - -const getTemplateForDeclarationOverride = (method, templates) => { - return getTemplateTypeForMethod(method, 'declarations-override', templates) +const getTemplateForDeclaration = (method, templates, templateDir) => { + return getTemplateTypeForMethod(method, templateDir, templates) } const getTemplateForExample = (method, templates) => { @@ -499,7 +495,8 @@ const generateMacros = (obj, templates, languages, options = {}) => { const macros = { schemas: {}, types: {}, - enums: {} + enums: {}, + declarations: {} } Array.from(new Set(['types'].concat(config.additionalSchemaTemplates))).forEach(dir => { @@ -509,22 +506,25 @@ const generateMacros = (obj, templates, languages, options = {}) => { macros.types[dir] = getTemplate('/sections/types', templates).replace(/\$\{schema.list\}/g, schemasArray.filter(x => !x.enum).map(s => s.body).filter(body => body).join('\n')) macros.enums[dir] = getTemplate('/sections/enums', templates).replace(/\$\{schema.list\}/g, schemasArray.filter(x => x.enum).map(s => s.body).filter(body => body).join('\n')) }) + state.typeTemplateDir = 'types' const examples = generateExamples(obj, templates, languages) const allMethodsArray = generateMethods(obj, examples, templates) const methodsArray = allMethodsArray.filter(m => m.body && !m.event && (!options.hideExcluded || !m.excluded)) const eventsArray = allMethodsArray.filter(m => m.body && m.event && (!options.hideExcluded || !m.excluded)) - const declarationsArray = allMethodsArray.filter(m => m.declaration && (!config.excludeDeclarations || (!options.hideExcluded || !m.excluded))) - const declarationsOverrideArray = allMethodsArray.filter(m => m.declarationOverride && (!config.excludeDeclarations || (!options.hideExcluded || !m.excluded))) const imports = generateImports(obj, templates, { destination: (options.destination ? options.destination : '') }) const initialization = generateInitialization(obj, templates) const eventsEnum = generateEvents(obj, templates) const methods = methodsArray.length ? getTemplate('/sections/methods', templates).replace(/\$\{method.list\}/g, methodsArray.map(m => m.body).join('\n')) : '' - const declarations = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration).join('\n')) : '' const methodList = methodsArray.filter(m => m.body).map(m => m.name) - const declarationsOverride = declarationsOverrideArray.length ? getTemplate('/sections/declarations-override', templates).replace(/\$\{declaration\.override\.list\}/g, declarationsOverrideArray.map(m => m.declarationOverride).join('\n')) : '' + + Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).forEach(dir => { + const declarationsArray = allMethodsArray.filter(m => m.declaration[dir] && (!config.excludeDeclarations || (!options.hideExcluded || !m.excluded))) + macros.declarations[dir] = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration[dir]).join('\n')) : '' + }) + const providerInterfaces = generateProviderInterfaces(obj, templates) const events = eventsArray.length ? getTemplate('/sections/events', templates).replace(/\$\{event.list\}/g, eventsArray.map(m => m.body).join('\n')) : '' const eventList = eventsArray.map(m => makeEventName(m)) @@ -544,8 +544,6 @@ const generateMacros = (obj, templates, languages, options = {}) => { eventsEnum, methods, methodList, - declarations, - declarationsOverride, defaults, examples, providerInterfaces, @@ -591,7 +589,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{if\.types\}(.*?)\$\{end\.if\.types\}/gms, macros.types.types.trim() ? '$1' : '') fContents = fContents.replace(/\$\{if\.schemas\}(.*?)\$\{end\.if\.schemas\}/gms, macros.schemas.types.trim() ? '$1' : '') fContents = fContents.replace(/\$\{if\.enums\}(.*?)\$\{end\.if\.enums\}/gms, macros.enums.types.trim() ? '$1' : '') - fContents = fContents.replace(/\$\{if\.declarations\}(.*?)\$\{end\.if\.declarations\}/gms, (macros.declarations.trim() || macros.enums.types.trim()) || macros.types.types.trim()? '$1' : '') + fContents = fContents.replace(/\$\{if\.declarations\}(.*?)\$\{end\.if\.declarations\}/gms, (macros.declarations.declarations.trim() || macros.enums.types.trim()) || macros.types.types.trim()? '$1' : '') fContents = fContents.replace(/\$\{if\.methods\}(.*?)\$\{end\.if\.methods\}/gms, (macros.methods.trim() || macros.events.trim()) ? '$1' : '') fContents = fContents.replace(/\$\{if\.implementations\}(.*?)\$\{end\.if\.implementations\}/gms, (macros.methods.trim() || macros.events.trim() || macros.schemas.types.trim()) ? '$1' : '') @@ -603,9 +601,17 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{if\.modules\}(.*?)\$\{end\.if\.modules\}/gms, (macros.methods.trim() || macros.events.trim()) ? '$1' : '') + // Output the originally supported non-configurable declarations macros + fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations.declarations) + // Output all declarations with all dynamically configured templates + Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).forEach(dir => { + ['DECLARATIONS'].forEach(type => { + const regex = new RegExp('[ \\t]*\\/\\* \\$\\{' + type + '\\:' + dir + '\\} \\*\\/[ \\t]*\\n', 'g') + fContents = fContents.replace(regex, macros[type.toLowerCase()][dir]) + }) + }) + fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods) - fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations) - fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS_OVERRIDE\} \*\/[ \t]*\n/, macros.declarationsOverride) fContents = fContents.replace(/[ \t]*\/\* \$\{METHOD_LIST\} \*\/[ \t]*\n/, macros.methodList.join(',\n')) fContents = fContents.replace(/[ \t]*\/\* \$\{EVENTS\} \*\/[ \t]*\n/, macros.events) fContents = fContents.replace(/[ \t]*\/\* \$\{EVENT_LIST\} \*\/[ \t]*\n/, macros.eventList.join(',')) @@ -622,7 +628,7 @@ const insertMacros = (fContents = '', macros = {}) => { const regex = new RegExp('[ \\t]*\\/\\* \\$\\{' + type + '\\:' + dir + '\\} \\*\\/[ \\t]*\\n', 'g') fContents = fContents.replace(regex, macros[type.toLowerCase()][dir]) }) - }) + }) fContents = fContents.replace(/[ \t]*\/\* \$\{PROVIDERS\} \*\/[ \t]*\n/, macros.providerInterfaces) fContents = fContents.replace(/[ \t]*\/\* \$\{IMPORTS\} \*\/[ \t]*\n/, macros.imports) @@ -1089,32 +1095,25 @@ function generateMethods(json = {}, examples = {}, templates = {}) { const result = { name: methodObj.name, body: '', - declaration: '', - declarationOverride: '', + declaration: {}, excluded: methodObj.tags.find(t => t.name === 'exclude-from-sdk'), event: isEventMethod(methodObj) } let template = getTemplateForMethod(methodObj, templates); - if (template && template.length) { let javascript = insertMethodMacros(template, methodObj, json, templates, examples) result.body = javascript } - template = getTemplateForDeclaration(methodObj, templates) - - if (template && template.length) { - let javascript = insertMethodMacros(template, methodObj, json, templates, examples) - result.declaration = javascript - } - - template = getTemplateForDeclarationOverride(methodObj, templates) - - if (template && template.length) { - let javascript = insertMethodMacros(template, methodObj, json, templates, examples) - result.declarationOverride = javascript - } + // Generate declarations for both dynamic and static configured templates + Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).forEach(dir => { + template = getTemplateForDeclaration(methodObj, templates, dir) + if (template && template.length) { + let javascript = insertMethodMacros(template, methodObj, json, templates, examples) + result.declaration[dir] = javascript + } + }) acc.push(result) @@ -1327,9 +1326,9 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.result\.summary\}/g, result.summary) .replace(/\$\{method\.result\.link\}/g, getLinkForSchema(result.schema, json, { name: result.name })) //, baseUrl: options.baseUrl .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, { name: result.name, templateDir: state.typeTemplateDir, title: true, asPath: false, destination: state.destination, result: true })) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.json\}/, types.getSchemaType(result.schema, json, { name: result.name, templateDir: 'json-types', destination: state.destination, section: state.section, title: true, code: false, link: false, asPath: false, expandEnums: false, namespace: true })) + .replace(/\$\{method\.result\.json\}/g, types.getSchemaType(result.schema, json, { name: result.name, templateDir: 'json-types', destination: state.destination, section: state.section, title: true, code: false, link: false, asPath: false, expandEnums: false, namespace: true })) // todo: what does prefix do? - .replace(/\$\{event\.result\.type\}/, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, prefix: method.alternative, templateDir: state.typeTemplateDir, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') + .replace(/\$\{event\.result\.type\}/g, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, prefix: method.alternative, templateDir: state.typeTemplateDir, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{event\.result\.json\.type\}/g, callbackResultJsonType) .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) @@ -1348,7 +1347,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.pulls\.params.type\}/g, pullsParams ? pullsParams.title : '') .replace(/\$\{method\.pulls\.params\}/g, pullsParamsType) .replace(/\$\{method\.pulls\.param\.type\}/g, pullsForParamType) - .replace(/\$\{method\.pulls\.param\.json.type\}/g, pullsForParamJsonType) + .replace(/\$\{method\.pulls\.param\.json\.type\}/g, pullsForParamJsonType) .replace(/\$\{method\.setter\.for\}/g, setterFor) .replace(/\$\{method\.puller\}/g, pullerTemplate) // must be last!! .replace(/\$\{method\.setter\}/g, setterTemplate) // must be last!! diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 2c86e4de..a91a493a 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -52,6 +52,7 @@ const macrofy = async ( allocatedPrimitiveProxies, convertTuplesToArraysOrObjects, additionalSchemaTemplates, + additionalDeclarationTemplates, excludeDeclarations, aggregateFiles, operators, @@ -94,6 +95,7 @@ const macrofy = async ( primitives, allocatedPrimitiveProxies, additionalSchemaTemplates, + additionalDeclarationTemplates, excludeDeclarations, operators }) diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index e851f108..49a8bd15 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -68,6 +68,7 @@ const run = async ({ unwrapResultObjects: config.unwrapResultObjects, allocatedPrimitiveProxies: config.allocatedPrimitiveProxies, additionalSchemaTemplates: config.additionalSchemaTemplates, + additionalDeclarationTemplates: config.additionalDeclarationTemplates, excludeDeclarations: config.excludeDeclarations, staticModuleNames: staticModuleNames, hideExcluded: true, From 07eb2fc38e507ad431300af1aa3aace7a175237d Mon Sep 17 00:00:00 2001 From: HaseenaSainul Date: Thu, 19 Oct 2023 07:02:36 -0400 Subject: [PATCH 3/5] CPPSDK: resolve conflict + some more cleanup --- src/macrofier/engine.mjs | 61 ++++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 84c7a8a2..41125cfe 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -61,7 +61,6 @@ let config = { const state = { destination: undefined, - section: undefined, typeTemplateDir: 'types', section: undefined } @@ -116,11 +115,11 @@ const getTemplateForExampleResult = (method, templates) => { return template || JSON.stringify(method.examples[0].result.value, null, '\t') } -const getLinkForSchema = (schema, json, { name = '' } = {}) => { +const getLinkForSchema = (schema, json) => { const dirs = config.createModuleDirectories const copySchemasIntoModules = config.copySchemasIntoModules - const type = types.getSchemaType(schema, json, { name: name, templateDir: state.typeTemplateDir, destination: state.destination, section: state.section }) + const type = types.getSchemaType(schema, json, { templateDir: state.typeTemplateDir, destination: state.destination, section: state.section }) // local - insert a bogus link, that we'll update later based on final table-of-contents if (json.components.schemas[type]) { @@ -862,7 +861,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/\$\{if\.description\}(.*?)\{end\.if\.description\}/gms, '$1') } - const schemaShape = types.getSchemaShape(schema, json, { name, prefix, templateDir: state.typeTemplateDir, destination: state.destination, section: options.section }) + const schemaShape = types.getSchemaShape(schema, json, { templateDir: state.typeTemplateDir, destination: state.destination, section: options.section }) content = content .replace(/\$\{schema.title\}/, (schema.title || name)) @@ -880,7 +879,7 @@ function generateSchemas(json, templates, options) { else { content = content.replace(/.*\$\{schema.seeAlso\}/, '') } -// content = content.trim().length ? content.trimEnd() : content.trim() + content = content.trim().length ? content : content.trim() const isEnum = x => x.type === 'string' && Array.isArray(x.enum) && x.title @@ -926,7 +925,7 @@ function getRelatedSchemaLinks(schema = {}, json = {}, templates = {}, options = .map(path => path.substring(2).split('/')) .map(path => getPathOr(null, path, json)) .filter(schema => schema.title) - .map(schema => '[' + types.getSchemaType(schema, json, { name: schema.title, templateDir: state.typeTemplateDir, destination: state.destination, section: state.section }) + '](' + getLinkForSchema(schema, json, { name: schema.title }) + ')') // need full module here, not just the schema + .map(schema => '[' + types.getSchemaType(schema, json, { templateDir: state.typeTemplateDir, destination: state.destination, section: state.section }) + '](' + getLinkForSchema(schema, json, { name: schema.title }) + ')') // need full module here, not just the schema .filter(link => link) .join('\n') @@ -1237,20 +1236,20 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) const serializedEventParams = event ? flattenedMethod.params.filter(p => p.name !== 'listen').map(param => types.getSchemaShape(param.schema, json, {templateDir: 'parameter-serialization', property: param.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true })).join('\n') : '' // this was wrong... check when we merge if it was fixed const callbackSerializedParams = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'parameter-serialization', property: result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) : '' - const callbackResultInst = event ? types.getSchemaShape(event, json, { name: event.name, templateDir: 'result-instantiation' }) : '' + const callbackResultInst = event ? types.getSchemaShape(event, json, { templateDir: 'result-instantiation' }) : '' // const callbackResponseInst = event ? types.getSchemaInstantiation(event, json, event.name, { instantiationType: 'callback.response' }) : '' // hmm... how is this different from callbackSerializedParams? i guess they get merged? const callbackResponseInst = event ? types.getSchemaShape(event.result.schema, json, { templateDir: 'parameter-serialization', property: result.name, destination: state.destination, section: state.section, level: 1, skipTitleOnce: true }) : '' - const resultType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name, templateDir: state.typeTemplateDir }) : '' - const resultJsonType = result.schema ? types.getSchemaType(result.schema, json, { name: result.name, templateDir: 'json-types' }) : '' + const resultType = result.schema ? types.getSchemaType(result.schema, json, { templateDir: state.typeTemplateDir }) : '' + const resultJsonType = result.schema ? types.getSchemaType(result.schema, json, { templateDir: 'json-types' }) : '' const resultParams = generateResultParams(result.schema, json, templates, { name: result.name}) // todo: what does prefix do in Types.mjs? need to account for it somehow - const callbackResultJsonType = event && result.schema ? types.getSchemaType(result.schema, json, { name: result.name, prefix: method.alternative, templateDir: 'json-types' }) : '' + const callbackResultJsonType = event && result.schema ? types.getSchemaType(result.schema, json, { templateDir: 'json-types' }) : '' - const pullsForParamType = pullsParams ? types.getSchemaType(pullsParams, json, { destination: state.destination, section: state.section }) : '' - const pullsForJsonType = pullsResult ? types.getSchemaType(pullsResult, json, { name: result.name, templateDir: 'json-types' }) : '' - const pullsForParamJsonType = pullsParams ? types.getSchemaType(pullsParams, json, { name: pullsParams.title , templateDir: 'json-types' }) : '' + const pullsForParamType = pullsParams ? types.getSchemaType(pullsParams, json, { destination: state.destination, section: state.section }) : '' + const pullsForJsonType = pullsResult ? types.getSchemaType(pullsResult, json, { templateDir: 'json-types' }) : '' + const pullsForParamJsonType = pullsParams ? types.getSchemaType(pullsParams, json, { templateDir: 'json-types' }) : '' const pullsEventParamName = event ? types.getSchemaInstantiation(event.result, json, event.name, { instantiationType: 'pull.param.name' }) : '' @@ -1286,6 +1285,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.params\.count}/g, methodObj.params ? methodObj.params.length : 0) .replace(/\$\{if\.params\}(.*?)\$\{end\.if\.params\}/gms, method.params.length ? '$1' : '') .replace(/\$\{if\.result\}(.*?)\$\{end\.if\.result\}/gms, resultType ? '$1' : '') + .replace(/\$\{if\.result.nonvoid\}(.*?)\$\{end\.if\.result.nonvoid\}/gms, resultType && resultType !== 'void' ? '$1' : '') .replace(/\$\{if\.result\.properties\}(.*?)\$\{end\.if\.result\.properties\}/gms, resultParams ? '$1' : '') .replace(/\$\{if\.params\.empty\}(.*?)\$\{end\.if\.params\.empty\}/gms, method.params.length === 0 ? '$1' : '') .replace(/\$\{if\.signature\.empty\}(.*?)\$\{end\.if\.signature\.empty\}/gms, (method.params.length === 0 && resultType === '') ? '$1' : '') @@ -1294,6 +1294,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.params\.serialization\.with\.indent\}/g, indent(serializedParams, ' ')) // Typed signature stuff .replace(/\$\{method\.signature\.params\}/g, types.getMethodSignatureParams(methodObj, json, { destination: state.destination, section: state.section })) + .replace(/\$\{method\.signature\.result\}/g, types.getMethodSignatureResult(methodObj, json, { destination: state.destination, section: state.section })) .replace(/\$\{method\.context\}/g, method.context.join(', ')) .replace(/\$\{method\.context\.array\}/g, JSON.stringify(method.context)) .replace(/\$\{method\.context\.count}/g, method.context ? method.context.length : 0) @@ -1324,11 +1325,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {}) .replace(/\$\{method\.capabilities\}/g, capabilities) .replace(/\$\{method\.result\.name\}/g, result.name) .replace(/\$\{method\.result\.summary\}/g, result.summary) - .replace(/\$\{method\.result\.link\}/g, getLinkForSchema(result.schema, json, { name: result.name })) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, { name: result.name, templateDir: state.typeTemplateDir, title: true, asPath: false, destination: state.destination, result: true })) //, baseUrl: options.baseUrl - .replace(/\$\{method\.result\.json\}/g, types.getSchemaType(result.schema, json, { name: result.name, templateDir: 'json-types', destination: state.destination, section: state.section, title: true, code: false, link: false, asPath: false, expandEnums: false, namespace: true })) + .replace(/\$\{method\.result\.link\}/g, getLinkForSchema(result.schema, json)) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.type\}/g, types.getSchemaType(result.schema, json, { templateDir: state.typeTemplateDir, title: true, asPath: false, destination: state.destination, result: true })) //, baseUrl: options.baseUrl + .replace(/\$\{method\.result\.json\}/, types.getSchemaType(result.schema, json, { templateDir: 'json-types', destination: state.destination, section: state.section, title: true, code: false, link: false, asPath: false, expandEnums: false, namespace: true })) // todo: what does prefix do? - .replace(/\$\{event\.result\.type\}/g, isEventMethod(methodObj) ? types.getSchemaType(result.schema, json, { name: result.name, prefix: method.alternative, templateDir: state.typeTemplateDir, destination: state.destination, event: true, description: methodObj.result.summary, asPath: false }) : '') + .replace(/\$\{event\.result\.type\}/g, isEventMethod(methodObj) ? types.getMethodSignatureResult(event, json, { destination: state.destination, section: state.section, callback: true }) : '') .replace(/\$\{event\.result\.json\.type\}/g, resultJsonType) .replace(/\$\{event\.result\.json\.type\}/g, callbackResultJsonType) .replace(/\$\{event\.pulls\.param\.name\}/g, pullsEventParamName) @@ -1470,7 +1471,7 @@ function insertExampleMacros(template, examples, method, json, templates) { function generateResult(result, json, templates, { name = '' } = {}) { - const type = types.getSchemaType(result, json, { name: name, templateDir: state.typeTemplateDir, destination: state.destination, section: state.section }) + const type = types.getSchemaType(result, json, { templateDir: state.typeTemplateDir, destination: state.destination, section: state.section }) if (result.type === 'object' && result.properties) { let content = getTemplate('/types/object', templates).split('\n') @@ -1487,7 +1488,7 @@ function generateResult(result, json, templates, { name = '' } = {}) { return insertSchemaMacros(getTemplate('/types/enum', templates), name, result, json) } else if (result.$ref) { - const link = getLinkForSchema(result, json, { name: name }) + const link = getLinkForSchema(result, json) // if we get a real link use it if (link !== '#') { @@ -1497,7 +1498,7 @@ function generateResult(result, json, templates, { name = '' } = {}) { else { const schema = localizeDependencies(result, json) return getTemplate('/types/default', templates) - .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { name: result.$ref.split("/").pop(), templateDir: state.typeTemplateDir })) + .replace(/\$\{type\}/, types.getSchemaShape(schema, json, { templateDir: state.typeTemplateDir })) } } else { @@ -1505,7 +1506,7 @@ function generateResult(result, json, templates, { name = '' } = {}) { } } -function generateResultParams(result, json, templates, {name = ''}={}) { +function generateResultParams(result, json, templates, { name = '' } = {}) { let moduleTitle = json.info.title while (result.$ref) { @@ -1524,7 +1525,7 @@ function generateResultParams(result, json, templates, {name = ''}={}) { const template = getTemplate('/parameters/result', templates) return Object.entries(result.properties).map( ([name, type]) => template .replace(/\$\{method\.param\.name\}/g, name) - .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(type, json, {name: name, moduleTitle: moduleTitle, result: true, namespace: true})) + .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(type, json, { moduleTitle: moduleTitle, result: true, namespace: true})) ).join(', ') // most languages separate params w/ a comma, so leaving this here for now } // tuples get unwrapped @@ -1533,14 +1534,14 @@ function generateResultParams(result, json, templates, {name = ''}={}) { const template = getTemplate('/parameters/result', templates) return result.items.map( (type) => template .replace(/\$\{method\.param\.name\}/g, type['x-property']) - .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(type, json, {name: name, moduleTitle: moduleTitle, result: true, namespace: true})) + .replace(/\$\{method\.param\.type\}/g, types.getSchemaType(type, json, { moduleTitle: moduleTitle, result: true, namespace: true})) ).join(', ') } // everything else is just output as-is else { const template = getTemplate('/parameters/result', templates) - const type = types.getSchemaType(result, json, {name: name, moduleTitle: moduleTitle, result: true, namespace: true}) + const type = types.getSchemaType(result, json, { moduleTitle: moduleTitle, result: true, namespace: true}) if (type === 'undefined') { console.log(`Warning: undefined type for ${name}`) } @@ -1553,8 +1554,8 @@ function generateResultParams(result, json, templates, {name = ''}={}) { function insertSchemaMacros(template, title, schema, module) { return template.replace(/\$\{property\}/g, title) - .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { name: title, templateDir: state.typeTemplateDir, destination: state.destination, section: state.section, code: false })) - .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module, { name: title })) + .replace(/\$\{type\}/g, types.getSchemaType(schema, module, { templateDir: state.typeTemplateDir, destination: state.destination, section: state.section, code: false })) + .replace(/\$\{type.link\}/g, getLinkForSchema(schema, module)) .replace(/\$\{description\}/g, schema.description || '') .replace(/\$\{name\}/g, title || '') } @@ -1564,9 +1565,9 @@ function insertParameterMacros(template, param, method, module) { //| `${method.param.name}` | ${method.param.type} | ${method.param.required} | ${method.param.summary} ${method.param.constraints} | let constraints = getSchemaConstraints(param, module) - let type = types.getSchemaType(param.schema, module, { name: param.name, templateDir: state.typeTemplateDir, destination: state.destination, section: state.section, code: false, link: false, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl - let typeLink = getLinkForSchema(param.schema, module, { name: param.name }) - let jsonType = types.getSchemaType(param.schema, module, { name: param.name, templateDir: 'json-types', destination: state.destination, section: state.section, code: false, link: false, asPath: false, expandEnums: false }) + let type = types.getSchemaType(param.schema, module, { templateDir: state.typeTemplateDir, destination: state.destination, section: state.section, code: false, link: false, asPath: false, expandEnums: false }) //baseUrl: options.baseUrl + let typeLink = getLinkForSchema(param.schema, module) + let jsonType = types.getSchemaType(param.schema, module, { templateDir: 'json-types', destination: state.destination, section: state.section, code: false, link: false, asPath: false, expandEnums: false }) if (constraints && type) { constraints = '
' + constraints @@ -1579,7 +1580,7 @@ function insertParameterMacros(template, param, method, module) { .replace(/\$\{method.param.required\}/g, param.required || 'false') .replace(/\$\{method.param.type\}/g, type) .replace(/\$\{json.param.type\}/g, jsonType) - .replace(/\$\{method.param.link\}/g, getLinkForSchema(param.schema, module, { name: param.name })) //getType(param)) + .replace(/\$\{method.param.link\}/g, getLinkForSchema(param.schema, module)) //getType(param)) .replace(/\$\{method.param.constraints\}/g, constraints) //getType(param)) } From ae3cfefde91b047c3fd598fb7d3b9919fc05d52d Mon Sep 17 00:00:00 2001 From: HaseenaSainul Date: Fri, 20 Oct 2023 02:33:24 -0400 Subject: [PATCH 4/5] CPPSDK: support to generate implementation of methods & events for both dynamic and static configured templates --- src/macrofier/engine.mjs | 133 +++++++++++++++++++++++---------------- src/macrofier/index.mjs | 2 + src/sdk/index.mjs | 1 + 3 files changed, 81 insertions(+), 55 deletions(-) diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index 41125cfe..a0bbab03 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -98,8 +98,8 @@ const getTemplateTypeForMethod = (method, type, templates) => { return getTemplate(path, templates) } -const getTemplateForMethod = (method, templates) => { - return getTemplateTypeForMethod(method, 'methods', templates) +const getTemplateForMethod = (method, templates, templateDir) => { + return getTemplateTypeForMethod(method, templateDir, templates) } const getTemplateForDeclaration = (method, templates, templateDir) => { @@ -495,10 +495,14 @@ const generateMacros = (obj, templates, languages, options = {}) => { schemas: {}, types: {}, enums: {}, - declarations: {} + declarations: {}, + methods: {}, + events: {}, + methodList: '', + eventList: '' } - Array.from(new Set(['types'].concat(config.additionalSchemaTemplates))).forEach(dir => { + Array.from(new Set(['types'].concat(config.additionalSchemaTemplates))).filter(dir => dir).forEach(dir => { state.typeTemplateDir = dir const schemasArray = generateSchemas(obj, templates, { baseUrl: '', section: 'schemas' }).filter(s => (options.copySchemasIntoModules || !s.uri)) macros.schemas[dir] = getTemplate('/sections/schemas', templates).replace(/\$\{schema.list\}/g, schemasArray.map(s => s.body).filter(body => body).join('\n')) @@ -507,26 +511,32 @@ const generateMacros = (obj, templates, languages, options = {}) => { }) state.typeTemplateDir = 'types' - const examples = generateExamples(obj, templates, languages) - const allMethodsArray = generateMethods(obj, examples, templates) - const methodsArray = allMethodsArray.filter(m => m.body && !m.event && (!options.hideExcluded || !m.excluded)) - const eventsArray = allMethodsArray.filter(m => m.body && m.event && (!options.hideExcluded || !m.excluded)) - const imports = generateImports(obj, templates, { destination: (options.destination ? options.destination : '') }) const initialization = generateInitialization(obj, templates) const eventsEnum = generateEvents(obj, templates) - const methods = methodsArray.length ? getTemplate('/sections/methods', templates).replace(/\$\{method.list\}/g, methodsArray.map(m => m.body).join('\n')) : '' - const methodList = methodsArray.filter(m => m.body).map(m => m.name) + const examples = generateExamples(obj, templates, languages) + const allMethodsArray = generateMethods(obj, examples, templates) - Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).forEach(dir => { + Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).filter(dir => dir).forEach(dir => { const declarationsArray = allMethodsArray.filter(m => m.declaration[dir] && (!config.excludeDeclarations || (!options.hideExcluded || !m.excluded))) macros.declarations[dir] = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration[dir]).join('\n')) : '' }) + Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { + const methodsArray = allMethodsArray.filter(m => m.body[dir] && !m.event && (!options.hideExcluded || !m.excluded)) + macros.methods[dir] = methodsArray.length ? getTemplate('/sections/methods', templates).replace(/\$\{method.list\}/g, methodsArray.map(m => m.body[dir]).join('\n')) : '' + + const eventsArray = allMethodsArray.filter(m => m.body[dir] && m.event && (!options.hideExcluded || !m.excluded)) + macros.events[dir] = eventsArray.length ? getTemplate('/sections/events', templates).replace(/\$\{event.list\}/g, eventsArray.map(m => m.body[dir]).join('\n')) : '' + + if (dir === 'methods') { + macros.methodList = methodsArray.filter(m => m.body).map(m => m.name) + macros.eventList = eventsArray.map(m => makeEventName(m)) + } + }) + const providerInterfaces = generateProviderInterfaces(obj, templates) - const events = eventsArray.length ? getTemplate('/sections/events', templates).replace(/\$\{event.list\}/g, eventsArray.map(m => m.body).join('\n')) : '' - const eventList = eventsArray.map(m => makeEventName(m)) const defaults = generateDefaults(obj, templates) const suffix = options.destination ? options.destination.split('.').pop().trim() : '' @@ -538,11 +548,7 @@ const generateMacros = (obj, templates, languages, options = {}) => { Object.assign(macros, { imports, initialization, - events, - eventList, eventsEnum, - methods, - methodList, defaults, examples, providerInterfaces, @@ -590,39 +596,48 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{if\.enums\}(.*?)\$\{end\.if\.enums\}/gms, macros.enums.types.trim() ? '$1' : '') fContents = fContents.replace(/\$\{if\.declarations\}(.*?)\$\{end\.if\.declarations\}/gms, (macros.declarations.declarations.trim() || macros.enums.types.trim()) || macros.types.types.trim()? '$1' : '') - fContents = fContents.replace(/\$\{if\.methods\}(.*?)\$\{end\.if\.methods\}/gms, (macros.methods.trim() || macros.events.trim()) ? '$1' : '') - fContents = fContents.replace(/\$\{if\.implementations\}(.*?)\$\{end\.if\.implementations\}/gms, (macros.methods.trim() || macros.events.trim() || macros.schemas.types.trim()) ? '$1' : '') + fContents = fContents.replace(/\$\{if\.methods\}(.*?)\$\{end\.if\.methods\}/gms, (macros.methods.methods.trim() || macros.events.methods.trim()) ? '$1' : '') + fContents = fContents.replace(/\$\{if\.implementations\}(.*?)\$\{end\.if\.implementations\}/gms, (macros.methods.methods.trim() || macros.events.methods.trim() || macros.schemas.types.trim()) ? '$1' : '') fContents = fContents.replace(/\$\{module\.list\}/g, macros.module) fContents = fContents.replace(/\$\{module\.includes\}/g, macros.moduleInclude) fContents = fContents.replace(/\$\{module\.includes\.private\}/g, macros.moduleIncludePrivate) fContents = fContents.replace(/\$\{module\.init\}/g, macros.moduleInit) - fContents = fContents.replace(/\$\{if\.modules\}(.*?)\$\{end\.if\.modules\}/gms, (macros.methods.trim() || macros.events.trim()) ? '$1' : '') + fContents = fContents.replace(/\$\{if\.modules\}(.*?)\$\{end\.if\.modules\}/gms, (macros.methods.methods.trim() || macros.events.methods.trim()) ? '$1' : '') // Output the originally supported non-configurable declarations macros fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations.declarations) // Output all declarations with all dynamically configured templates - Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).forEach(dir => { + Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).filter(dir => dir).forEach(dir => { ['DECLARATIONS'].forEach(type => { const regex = new RegExp('[ \\t]*\\/\\* \\$\\{' + type + '\\:' + dir + '\\} \\*\\/[ \\t]*\\n', 'g') fContents = fContents.replace(regex, macros[type.toLowerCase()][dir]) }) }) - fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods) + // Output the originally supported non-configurable methods & events macros + fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods.methods) fContents = fContents.replace(/[ \t]*\/\* \$\{METHOD_LIST\} \*\/[ \t]*\n/, macros.methodList.join(',\n')) - fContents = fContents.replace(/[ \t]*\/\* \$\{EVENTS\} \*\/[ \t]*\n/, macros.events) + fContents = fContents.replace(/[ \t]*\/\* \$\{EVENTS\} \*\/[ \t]*\n/, macros.events.methods) fContents = fContents.replace(/[ \t]*\/\* \$\{EVENT_LIST\} \*\/[ \t]*\n/, macros.eventList.join(',')) fContents = fContents.replace(/[ \t]*\/\* \$\{EVENTS_ENUM\} \*\/[ \t]*\n/, macros.eventsEnum) + // Output all methods & events with all dynamically configured templates + Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { + ['METHODS', 'EVENTS'].forEach(type => { + const regex = new RegExp('[ \\t]*\\/\\* \\$\\{' + type + '\\:' + dir + '\\} \\*\\/[ \\t]*\\n', 'g') + fContents = fContents.replace(regex, macros[type.toLowerCase()][dir]) + }) + }) + // Output the originally supported non-configurable schema macros fContents = fContents.replace(/[ \t]*\/\* \$\{SCHEMAS\} \*\/[ \t]*\n/, macros.schemas.types) fContents = fContents.replace(/[ \t]*\/\* \$\{TYPES\} \*\/[ \t]*\n/, macros.types.types) fContents = fContents.replace(/[ \t]*\/\* \$\{ENUMS\} \*\/[ \t]*\n/, macros.enums.types) // Output all schemas with all dynamically configured templates - Array.from(new Set(['types'].concat(config.additionalSchemaTemplates))).forEach(dir => { + Array.from(new Set(['types'].concat(config.additionalSchemaTemplates))).filter(dir => dir).forEach(dir => { ['SCHEMAS', 'TYPES', 'ENUMS'].forEach(type => { const regex = new RegExp('[ \\t]*\\/\\* \\$\\{' + type + '\\:' + dir + '\\} \\*\\/[ \\t]*\\n', 'g') fContents = fContents.replace(regex, macros[type.toLowerCase()][dir]) @@ -1083,6 +1098,29 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) { return examples } +function generateMethodResult(type, templates) { + const result = { + name: type, + body: {}, + declaration: {}, + } + + Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).filter(dir => dir).forEach(dir => { + const template = getTemplate(('/' + dir + '/' + type), templates) + if (template) { + result.declaration[dir] = template + } + }) + + Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { + const template = getTemplate(('/' + dir + '/' + type), templates) + if (template) { + result.body[dir] = template + } + }) + return result +} + function generateMethods(json = {}, examples = {}, templates = {}) { const methods = compose( option([]), @@ -1093,27 +1131,30 @@ function generateMethods(json = {}, examples = {}, templates = {}) { const results = reduce((acc, methodObj, i, arr) => { const result = { name: methodObj.name, - body: '', + body: {}, declaration: {}, excluded: methodObj.tags.find(t => t.name === 'exclude-from-sdk'), event: isEventMethod(methodObj) } - let template = getTemplateForMethod(methodObj, templates); - if (template && template.length) { - let javascript = insertMethodMacros(template, methodObj, json, templates, examples) - result.body = javascript - } - // Generate declarations for both dynamic and static configured templates - Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).forEach(dir => { - template = getTemplateForDeclaration(methodObj, templates, dir) + Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).filter(dir => dir).forEach(dir => { + const template = getTemplateForDeclaration(methodObj, templates, dir) if (template && template.length) { let javascript = insertMethodMacros(template, methodObj, json, templates, examples) result.declaration[dir] = javascript } }) + // Generate implementation of methods/events for both dynamic and static configured templates + Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { + const template = getTemplateForMethod(methodObj, templates, dir) + if (template && template.length) { + let javascript = insertMethodMacros(template, methodObj, json, templates, examples) + result.body[dir] = javascript + } + }) + acc.push(result) return acc @@ -1121,31 +1162,13 @@ function generateMethods(json = {}, examples = {}, templates = {}) { // TODO: might be useful to pass in local macro for an array with all capability & provider interface names if (json.methods && json.methods.find(isProviderInterfaceMethod)) { - results.push({ - name: "provide", - body: getTemplate('/methods/provide', templates), - declaration: getTemplate('/declarations/provide', templates), - }) + results.push(generateMethodResult('provide', templates)) } // TODO: might be useful to pass in local macro for an array with all event names if (json.methods && json.methods.find(isPublicEventMethod)) { - results.push({ - name: "listen", - body: getTemplate('/methods/listen', templates), - declaration: getTemplate('/declarations/listen', templates) - }) - - results.push({ - name: "once", - body: getTemplate('/methods/once', templates), - declaration: getTemplate('/declarations/once', templates) - }) - - results.push({ - name: "clear", - body: getTemplate('/methods/clear', templates), - declaration: getTemplate('/declarations/clear', templates) + ['listen', 'once', 'clear'].forEach(type => { + results.push(generateMethodResult(type, templates)) }) } diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index a91a493a..2b24c9d5 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -53,6 +53,7 @@ const macrofy = async ( convertTuplesToArraysOrObjects, additionalSchemaTemplates, additionalDeclarationTemplates, + additionalMethodTemplates, excludeDeclarations, aggregateFiles, operators, @@ -96,6 +97,7 @@ const macrofy = async ( allocatedPrimitiveProxies, additionalSchemaTemplates, additionalDeclarationTemplates, + additionalMethodTemplates, excludeDeclarations, operators }) diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 49a8bd15..562af9e0 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -69,6 +69,7 @@ const run = async ({ allocatedPrimitiveProxies: config.allocatedPrimitiveProxies, additionalSchemaTemplates: config.additionalSchemaTemplates, additionalDeclarationTemplates: config.additionalDeclarationTemplates, + additionalMethodTemplates: config.additionalMethodTemplates, excludeDeclarations: config.excludeDeclarations, staticModuleNames: staticModuleNames, hideExcluded: true, From 0b5fac54ef9e199189189576efcd9828d2da9458 Mon Sep 17 00:00:00 2001 From: HaseenaSainul Date: Fri, 20 Oct 2023 10:44:18 -0400 Subject: [PATCH 5/5] additionalDeclarationTemplates combined to additionalMethodTemplates --- languages/cpp/language.config.json | 2 +- .../cpp/templates/modules/include/module.h | 2 +- .../cpp/templates/modules/src/module_impl.h | 2 +- languages/javascript/language.config.json | 3 +- .../templates/codeblocks/module.mjs | 4 +- src/macrofier/engine.mjs | 82 ++++++++----------- src/macrofier/index.mjs | 2 - src/sdk/index.mjs | 1 - 8 files changed, 41 insertions(+), 57 deletions(-) diff --git a/languages/cpp/language.config.json b/languages/cpp/language.config.json index 786bf191..debc539d 100644 --- a/languages/cpp/language.config.json +++ b/languages/cpp/language.config.json @@ -29,5 +29,5 @@ }, "langVersion" : "c++17", "additionalSchemaTemplates": [ "json-types" ], - "additionalDeclarationTemplates": [ "declarations-override" ] + "additionalMethodTemplates": [ "declarations", "declarations-override" ] } diff --git a/languages/cpp/templates/modules/include/module.h b/languages/cpp/templates/modules/include/module.h index 6ee534e4..de58e77a 100644 --- a/languages/cpp/templates/modules/include/module.h +++ b/languages/cpp/templates/modules/include/module.h @@ -36,7 +36,7 @@ namespace ${info.Title} { virtual ~I${info.Title}() = default; // Methods & Events - /* ${DECLARATIONS} */ + /* ${METHODS:declarations} */ };${end.if.methods} diff --git a/languages/cpp/templates/modules/src/module_impl.h b/languages/cpp/templates/modules/src/module_impl.h index 8051139e..33e6e005 100644 --- a/languages/cpp/templates/modules/src/module_impl.h +++ b/languages/cpp/templates/modules/src/module_impl.h @@ -40,7 +40,7 @@ namespace ${info.Title} { ~${info.Title}Impl() override = default; // Methods & Events - /* ${DECLARATIONS:declarations-override} */ + /* ${METHODS:declarations-override} */ };${end.if.methods} }//namespace ${info.Title} diff --git a/languages/javascript/language.config.json b/languages/javascript/language.config.json index 4044bffc..529ac99a 100644 --- a/languages/javascript/language.config.json +++ b/languages/javascript/language.config.json @@ -23,5 +23,6 @@ "number": "number", "string": "string", "object": "object" - } + }, + "additionalMethodTemplates": [ "declarations" ] } \ No newline at end of file diff --git a/languages/javascript/templates/codeblocks/module.mjs b/languages/javascript/templates/codeblocks/module.mjs index cb5ca256..def593af 100644 --- a/languages/javascript/templates/codeblocks/module.mjs +++ b/languages/javascript/templates/codeblocks/module.mjs @@ -4,8 +4,8 @@ ${if.events} type Event = ${events} ${end.if.events} /* ${SCHEMAS} */ - /* ${DECLARATIONS} */ + /* ${METHODS:declarations} */ /* ${PROVIDERS} */ -} \ No newline at end of file +} diff --git a/src/macrofier/engine.mjs b/src/macrofier/engine.mjs index a0bbab03..b1d2dd89 100644 --- a/src/macrofier/engine.mjs +++ b/src/macrofier/engine.mjs @@ -495,7 +495,6 @@ const generateMacros = (obj, templates, languages, options = {}) => { schemas: {}, types: {}, enums: {}, - declarations: {}, methods: {}, events: {}, methodList: '', @@ -518,21 +517,23 @@ const generateMacros = (obj, templates, languages, options = {}) => { const examples = generateExamples(obj, templates, languages) const allMethodsArray = generateMethods(obj, examples, templates) - Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).filter(dir => dir).forEach(dir => { - const declarationsArray = allMethodsArray.filter(m => m.declaration[dir] && (!config.excludeDeclarations || (!options.hideExcluded || !m.excluded))) - macros.declarations[dir] = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration[dir]).join('\n')) : '' - }) - Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { - const methodsArray = allMethodsArray.filter(m => m.body[dir] && !m.event && (!options.hideExcluded || !m.excluded)) - macros.methods[dir] = methodsArray.length ? getTemplate('/sections/methods', templates).replace(/\$\{method.list\}/g, methodsArray.map(m => m.body[dir]).join('\n')) : '' - const eventsArray = allMethodsArray.filter(m => m.body[dir] && m.event && (!options.hideExcluded || !m.excluded)) - macros.events[dir] = eventsArray.length ? getTemplate('/sections/events', templates).replace(/\$\{event.list\}/g, eventsArray.map(m => m.body[dir]).join('\n')) : '' + if (dir.includes('declarations')) { + const declarationsArray = allMethodsArray.filter(m => m.declaration[dir] && (!config.excludeDeclarations || (!options.hideExcluded || !m.excluded))) + macros.methods[dir] = declarationsArray.length ? getTemplate('/sections/declarations', templates).replace(/\$\{declaration\.list\}/g, declarationsArray.map(m => m.declaration[dir]).join('\n')) : '' + } + else if (dir.includes('methods')) { + const methodsArray = allMethodsArray.filter(m => m.body[dir] && !m.event && (!options.hideExcluded || !m.excluded)) + macros.methods[dir] = methodsArray.length ? getTemplate('/sections/methods', templates).replace(/\$\{method.list\}/g, methodsArray.map(m => m.body[dir]).join('\n')) : '' + + const eventsArray = allMethodsArray.filter(m => m.body[dir] && m.event && (!options.hideExcluded || !m.excluded)) + macros.events[dir] = eventsArray.length ? getTemplate('/sections/events', templates).replace(/\$\{event.list\}/g, eventsArray.map(m => m.body[dir]).join('\n')) : '' - if (dir === 'methods') { - macros.methodList = methodsArray.filter(m => m.body).map(m => m.name) - macros.eventList = eventsArray.map(m => makeEventName(m)) + if (dir === 'methods') { + macros.methodList = methodsArray.filter(m => m.body).map(m => m.name) + macros.eventList = eventsArray.map(m => makeEventName(m)) + } } }) @@ -594,9 +595,9 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{if\.types\}(.*?)\$\{end\.if\.types\}/gms, macros.types.types.trim() ? '$1' : '') fContents = fContents.replace(/\$\{if\.schemas\}(.*?)\$\{end\.if\.schemas\}/gms, macros.schemas.types.trim() ? '$1' : '') fContents = fContents.replace(/\$\{if\.enums\}(.*?)\$\{end\.if\.enums\}/gms, macros.enums.types.trim() ? '$1' : '') - fContents = fContents.replace(/\$\{if\.declarations\}(.*?)\$\{end\.if\.declarations\}/gms, (macros.declarations.declarations.trim() || macros.enums.types.trim()) || macros.types.types.trim()? '$1' : '') + fContents = fContents.replace(/\$\{if\.declarations\}(.*?)\$\{end\.if\.declarations\}/gms, (macros.methods.declarations && macros.methods.declarations.trim() || macros.enums.types.trim()) || macros.types.types.trim()? '$1' : '') - fContents = fContents.replace(/\$\{if\.methods\}(.*?)\$\{end\.if\.methods\}/gms, (macros.methods.methods.trim() || macros.events.methods.trim()) ? '$1' : '') + fContents = fContents.replace(/\$\{if\.methods\}(.*?)\$\{end\.if\.methods\}/gms, macros.methods.methods.trim() || macros.events.methods.trim() ? '$1' : '') fContents = fContents.replace(/\$\{if\.implementations\}(.*?)\$\{end\.if\.implementations\}/gms, (macros.methods.methods.trim() || macros.events.methods.trim() || macros.schemas.types.trim()) ? '$1' : '') fContents = fContents.replace(/\$\{module\.list\}/g, macros.module) @@ -606,16 +607,6 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/\$\{if\.modules\}(.*?)\$\{end\.if\.modules\}/gms, (macros.methods.methods.trim() || macros.events.methods.trim()) ? '$1' : '') - // Output the originally supported non-configurable declarations macros - fContents = fContents.replace(/[ \t]*\/\* \$\{DECLARATIONS\} \*\/[ \t]*\n/, macros.declarations.declarations) - // Output all declarations with all dynamically configured templates - Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).filter(dir => dir).forEach(dir => { - ['DECLARATIONS'].forEach(type => { - const regex = new RegExp('[ \\t]*\\/\\* \\$\\{' + type + '\\:' + dir + '\\} \\*\\/[ \\t]*\\n', 'g') - fContents = fContents.replace(regex, macros[type.toLowerCase()][dir]) - }) - }) - // Output the originally supported non-configurable methods & events macros fContents = fContents.replace(/[ \t]*\/\* \$\{METHODS\} \*\/[ \t]*\n/, macros.methods.methods) fContents = fContents.replace(/[ \t]*\/\* \$\{METHOD_LIST\} \*\/[ \t]*\n/, macros.methodList.join(',\n')) @@ -623,7 +614,7 @@ const insertMacros = (fContents = '', macros = {}) => { fContents = fContents.replace(/[ \t]*\/\* \$\{EVENT_LIST\} \*\/[ \t]*\n/, macros.eventList.join(',')) fContents = fContents.replace(/[ \t]*\/\* \$\{EVENTS_ENUM\} \*\/[ \t]*\n/, macros.eventsEnum) - // Output all methods & events with all dynamically configured templates + // Output all declarations, methods & events with all dynamically configured templates Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { ['METHODS', 'EVENTS'].forEach(type => { const regex = new RegExp('[ \\t]*\\/\\* \\$\\{' + type + '\\:' + dir + '\\} \\*\\/[ \\t]*\\n', 'g') @@ -1105,17 +1096,15 @@ function generateMethodResult(type, templates) { declaration: {}, } - Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).filter(dir => dir).forEach(dir => { - const template = getTemplate(('/' + dir + '/' + type), templates) - if (template) { - result.declaration[dir] = template - } - }) - Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { const template = getTemplate(('/' + dir + '/' + type), templates) if (template) { - result.body[dir] = template + if (dir.includes('declarations')) { + result.declaration[dir] = template + } + else if (dir.includes('methods')) { + result.body[dir] = template + } } }) return result @@ -1137,21 +1126,19 @@ function generateMethods(json = {}, examples = {}, templates = {}) { event: isEventMethod(methodObj) } - // Generate declarations for both dynamic and static configured templates - Array.from(new Set(['declarations'].concat(config.additionalDeclarationTemplates))).filter(dir => dir).forEach(dir => { - const template = getTemplateForDeclaration(methodObj, templates, dir) - if (template && template.length) { - let javascript = insertMethodMacros(template, methodObj, json, templates, examples) - result.declaration[dir] = javascript - } - }) - // Generate implementation of methods/events for both dynamic and static configured templates Array.from(new Set(['methods'].concat(config.additionalMethodTemplates))).filter(dir => dir).forEach(dir => { - const template = getTemplateForMethod(methodObj, templates, dir) - if (template && template.length) { - let javascript = insertMethodMacros(template, methodObj, json, templates, examples) - result.body[dir] = javascript + if (dir.includes('declarations')) { + const template = getTemplateForDeclaration(methodObj, templates, dir) + if (template && template.length) { + result.declaration[dir] = insertMethodMacros(template, methodObj, json, templates, examples) + } + } + else if (dir.includes('methods')) { + const template = getTemplateForMethod(methodObj, templates, dir) + if (template && template.length) { + result.body[dir] = insertMethodMacros(template, methodObj, json, templates, examples) + } } }) @@ -1173,7 +1160,6 @@ function generateMethods(json = {}, examples = {}, templates = {}) { } results.sort((a, b) => a.name.localeCompare(b.name)) - return results } diff --git a/src/macrofier/index.mjs b/src/macrofier/index.mjs index 2b24c9d5..04cdd9fb 100644 --- a/src/macrofier/index.mjs +++ b/src/macrofier/index.mjs @@ -52,7 +52,6 @@ const macrofy = async ( allocatedPrimitiveProxies, convertTuplesToArraysOrObjects, additionalSchemaTemplates, - additionalDeclarationTemplates, additionalMethodTemplates, excludeDeclarations, aggregateFiles, @@ -96,7 +95,6 @@ const macrofy = async ( primitives, allocatedPrimitiveProxies, additionalSchemaTemplates, - additionalDeclarationTemplates, additionalMethodTemplates, excludeDeclarations, operators diff --git a/src/sdk/index.mjs b/src/sdk/index.mjs index 562af9e0..763b6c9e 100755 --- a/src/sdk/index.mjs +++ b/src/sdk/index.mjs @@ -68,7 +68,6 @@ const run = async ({ unwrapResultObjects: config.unwrapResultObjects, allocatedPrimitiveProxies: config.allocatedPrimitiveProxies, additionalSchemaTemplates: config.additionalSchemaTemplates, - additionalDeclarationTemplates: config.additionalDeclarationTemplates, additionalMethodTemplates: config.additionalMethodTemplates, excludeDeclarations: config.excludeDeclarations, staticModuleNames: staticModuleNames,