Skip to content

Commit

Permalink
Generate polymorphci methods for anyOf param/result case
Browse files Browse the repository at this point in the history
  • Loading branch information
HaseenaSainul committed Jul 12, 2023
1 parent 4d22a4d commit 0264f88
Show file tree
Hide file tree
Showing 13 changed files with 224 additions and 38 deletions.
6 changes: 4 additions & 2 deletions languages/c/Types.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,8 @@ function getMethodSignatureParams(method, module, { destination, callback = fals
if ((callback === true) && (type === 'char*')) {
type = getFireboltStringType()
}
signatureParams += type + (!param.required ? '* ' : ' ') + param.name

signatureParams += type + ((!param.required && !type.includes('_t') && (type !== 'char*')) ? '* ' : ' ') + param.name
})
return signatureParams
}
Expand Down Expand Up @@ -349,6 +350,7 @@ function getSchemaTypeInfo(module = {}, json = {}, name = '', schemas = {}, pref
structure.namespace = getModuleName(module)
}
}

return structure
}

Expand Down Expand Up @@ -532,7 +534,7 @@ function getSchemaShapeInfo(json, module, schemas = {}, { name = '', prefix = ''

if (info.type && info.type.length > 0) {
let type = getArrayElementSchema(json, module, schemas, info.name)
let arrayName = capitalize(info.name) + capitalize(type.type)
let arrayName = capitalize(info.name);
let namespace = info.namespace
if (type && type.type === 'object') {
namespace = getModuleName(module)
Expand Down
3 changes: 2 additions & 1 deletion languages/c/language.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,6 @@
"/src/module_common.cpp",
"/src/jsondata_module.h"
],
"persistPermission": true
"persistPermission": true,
"createPolymorphicMethods": true
}
1 change: 0 additions & 1 deletion languages/c/templates/codeblocks/export.c
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@
export { default as ${info.title} } from './${info.title}/index.mjs'
4 changes: 2 additions & 2 deletions languages/c/templates/codeblocks/setter.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* ${method.name} - ${method.description} */
/* ${method.json.name} - ${method.description} */
uint32_t ${info.Title}_${method.Name}( ${method.signature.params} )
{
const string method = _T("${info.title}.${method.name}");
const string method = _T("${info.title}.${method.json.name}");
${if.params}${method.params.serialization}${end.if.params}
return FireboltSDK::Properties::Set(method, jsonParameters);
}
6 changes: 3 additions & 3 deletions languages/c/templates/methods/default.c
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* ${method.name} - ${method.description} */
/* ${method.json.name} - ${method.description} */
uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name}${end.if.result}${if.signature.empty}void${end.if.signature.empty} ) {

uint32_t status = FireboltSDKErrorUnavailable;
Expand All @@ -7,9 +7,9 @@ uint32_t ${info.Title}_${method.Name}( ${method.signature.params}${if.result}${i

${method.params.serialization.with.indent}
${method.result.json.type} jsonResult;
status = transport->Invoke("${info.title}.${method.name}", jsonParameters, jsonResult);
status = transport->Invoke("${info.title}.${method.json.name}", jsonParameters, jsonResult);
if (status == FireboltSDKErrorNone) {
FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module<FireboltSDK::Accessor>(), "${info.Title}.${method.name} is successfully invoked");
FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module<FireboltSDK::Accessor>(), "${info.Title}.${method.json.name} is successfully invoked");
${method.result.instantiation}
}

Expand Down
6 changes: 3 additions & 3 deletions languages/c/templates/methods/event.c
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* ${method.name} - ${method.description} */
/* ${method.json.name} - ${method.description} */
static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response )
{
${event.callback.params.serialization}
Expand All @@ -11,7 +11,7 @@ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void*
}
uint32_t ${info.Title}_Register_${method.Name}( ${event.signature.params}${if.event.params}, ${end.if.event.params}${info.Title}${method.Name}Callback userCB, const void* userData )
{
const string eventName = _T("${info.title}.${method.name}");
const string eventName = _T("${info.title}.${method.json.name}");
uint32_t status = FireboltSDKErrorNone;

if (userCB != nullptr) {
Expand All @@ -22,5 +22,5 @@ uint32_t ${info.Title}_Register_${method.Name}( ${event.signature.params}${if.ev
}
uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB)
{
return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title}.${method.name}"), reinterpret_cast<void*>(userCB));
return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title}.${method.json.name}"), reinterpret_cast<void*>(userCB));
}
8 changes: 4 additions & 4 deletions languages/c/templates/methods/polymorphic-pull-event.c
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/* ${method.name} - ${method.description} */
/* ${method.json.name} - ${method.description} */
static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void* userData, void* response )
{
${event.callback.params.serialization}
Expand Down Expand Up @@ -29,7 +29,7 @@ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void*
WPEFramework::Core::JSON::Boolean jsonResult;
uint32_t status = transport->Invoke(_T("${info.title}.${method.pulls.for}"), jsonParameters, jsonResult);
if (status == FireboltSDKErrorNone) {
FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module<FireboltSDK::Accessor>(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value());
FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module<FireboltSDK::Accessor>(), "${info.Title}.${method.json.name} is successfully pushed with status as %d", jsonResult.Value());
status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported;
}
} else {
Expand All @@ -39,7 +39,7 @@ static void ${info.Title}${method.Name}InnerCallback( void* userCB, const void*
}
uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callback userCB, const void* userData )
{
const string eventName = _T("${info.title}.${method.name}");
const string eventName = _T("${info.title}.${method.json.name}");
uint32_t status = FireboltSDKErrorNone;

if (userCB != nullptr) {
Expand All @@ -50,5 +50,5 @@ uint32_t ${info.Title}_Register_${method.Name}( ${info.Title}${method.Name}Callb
}
uint32_t ${info.Title}_Unregister_${method.Name}( ${info.Title}${method.Name}Callback userCB)
{
return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title}.${method.name}"), reinterpret_cast<void*>(userCB));
return FireboltSDK::Event::Instance().Unsubscribe(_T("${info.title}.${method.json.name}"), reinterpret_cast<void*>(userCB));
}
11 changes: 6 additions & 5 deletions languages/c/templates/methods/polymorphic-pull.c
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
/* ${method.name} - ${method.description} */
/* ${method.json.name} - ${method.description} */
uint32_t ${info.Title}_Push${method.Name}( ${method.signature.params} )
{
uint32_t status = FireboltSDKErrorUnavailable;

string correlationId = "";
${method.params.serialization}
FireboltSDK::Transport<WPEFramework::Core::JSON::IElement>* transport = FireboltSDK::Accessor::Instance().GetTransport();
if (transport != nullptr) {
string correlationId = "";
${method.params.serialization.with.indent}

WPEFramework::Core::JSON::Boolean jsonResult;
status = transport->Invoke(_T("${info.title}.${method.name}"), jsonParameters, jsonResult);
status = transport->Invoke(_T("${info.title}.${method.json.name}"), jsonParameters, jsonResult);
if (status == FireboltSDKErrorNone) {
FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module<FireboltSDK::Accessor>(), "${info.Title}.${method.name} is successfully pushed with status as %d", jsonResult.Value());
FIREBOLT_LOG_INFO(FireboltSDK::Logger::Category::OpenRPC, FireboltSDK::Logger::Module<FireboltSDK::Accessor>(), "${info.Title}.${method.json.name} is successfully pushed with status as %d", jsonResult.Value());
status = (jsonResult.Value() == true) ? FireboltSDKErrorNone : FireboltSDKErrorNotSupported;
}
} else {
Expand Down
4 changes: 2 additions & 2 deletions languages/c/templates/methods/property.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* ${method.name} - ${method.description} */
/* ${method.json.name} - ${method.description} */
uint32_t ${info.Title}_Get${method.Name}( ${method.signature.params}${if.params}, ${end.if.params}${method.result.type}* ${method.result.name} )
{
const string method = _T("${info.title}.${method.name}");
const string method = _T("${info.title}.${method.json.name}");
${if.params}${method.params.serialization}${end.if.params}
${method.result.json} jsonResult;
${if.params}uint32_t status = FireboltSDK::Properties::Get(method, jsonParameters, jsonResult);${end.if.params}
Expand Down
39 changes: 29 additions & 10 deletions src/macrofier/engine.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import isString from 'crocks/core/isString.js'
import predicates from 'crocks/predicates/index.js'
const { isObject, isArray, propEq, pathSatisfies, propSatisfies } = predicates

import { isRPCOnlyMethod, isProviderInterfaceMethod, getProviderInterface, getPayloadFromEvent, providerHasNoParameters, isTemporalSetMethod, hasMethodAttributes, getMethodAttributes, isEventMethodWithContext, getSemanticVersion, getSetterFor, getProvidedCapabilities, isPolymorphicPullMethod, hasPublicAPIs } from '../shared/modules.mjs'
import { isRPCOnlyMethod, isProviderInterfaceMethod, getProviderInterface, getPayloadFromEvent, providerHasNoParameters, isTemporalSetMethod, hasMethodAttributes, getMethodAttributes, isEventMethodWithContext, getSemanticVersion, getSetterFor, getProvidedCapabilities, isPolymorphicPullMethod, hasPublicAPIs, createPolymorphicMethods } from '../shared/modules.mjs'
import isEmpty from 'crocks/core/isEmpty.js'
import { getLinkedSchemaPaths, getSchemaConstraints, isSchema, localizeDependencies, isDefinitionReferencedBySchema } from '../shared/json-schema.mjs'

Expand Down Expand Up @@ -419,7 +419,7 @@ const generateMacros = (obj, templates, languages, options = {}) => {
const eventsEnum = generateEvents(obj, templates)
const examples = generateExamples(obj, templates, languages)

const allMethodsArray = generateMethods(obj, examples, templates)
const allMethodsArray = generateMethods(obj, examples, templates, { polymorphic : options.createPolymorphicMethods })
const methodsArray = allMethodsArray.filter(m => !m.event && (!options.hideExcluded || !m.excluded))
const eventsArray = allMethodsArray.filter(m => m.event && (!options.hideExcluded || !m.excluded))
const declarationsArray = allMethodsArray.filter(m => m.declaration)
Expand Down Expand Up @@ -934,12 +934,30 @@ function generateExamples(json = {}, mainTemplates = {}, languages = {}) {
return examples
}

function generateMethods(json = {}, examples = {}, templates = {}) {
function generateMethods(json = {}, examples = {}, templates = {}, options = { polymorphic: false }) {
const methods = compose(
option([]),
getMethods
)(json)

let methodList = []
if (options.polymorphic) {
methods.forEach(method => {
let polymorphicMethods = createPolymorphicMethods(method, json)
if (polymorphicMethods.length > 1) {
polymorphicMethods.forEach(polymorphicMethod => {
methodList.push(polymorphicMethod)
})
}
else {
methodList.push(method)
}
})
}
else {
methodList = methods
}

// Code to generate methods
const results = reduce((acc, methodObj, i, arr) => {
const result = {
Expand All @@ -953,21 +971,21 @@ function generateMethods(json = {}, examples = {}, templates = {}) {
let template = getTemplateForMethod(methodObj, templates);

if (template && template.length) {
let javascript = insertMethodMacros(template, methodObj, json, templates, examples)
let javascript = insertMethodMacros(template, methodObj, json, templates, options, examples)
result.body = javascript
}

template = getTemplateForDeclaration(methodObj, templates)

if (template && template.length) {
let javascript = insertMethodMacros(template, methodObj, json, templates, examples)
let javascript = insertMethodMacros(template, methodObj, json, templates, options, examples)
result.declaration = javascript
}

acc.push(result)

return acc
}, [], methods)
}, [], methodList)

// 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)) {
Expand Down Expand Up @@ -1005,7 +1023,7 @@ function generateMethods(json = {}, examples = {}, templates = {}) {
}

// TODO: this is called too many places... let's reduce that to just generateMethods
function insertMethodMacros(template, methodObj, json, templates, examples = {}) {
function insertMethodMacros(template, methodObj, json, templates, options = { polymorphic: false }, examples={}) {
const moduleName = getModuleName(json)

const info = {
Expand Down Expand Up @@ -1069,11 +1087,11 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {})
// grab some related methdos in case they are output together in a single template file
const puller = json.methods.find(method => method.tags.find(tag => tag['x-pulls-for'] === methodObj.name))
const pullsFor = methodObj.tags.find(t => t['x-pulls-for']) && json.methods.find(method => method.name === methodObj.tags.find(t => t['x-pulls-for'])['x-pulls-for'])
const pullerTemplate = (puller ? insertMethodMacros(getTemplate('/codeblocks/puller', templates), puller, json, templates, examples) : '')
const pullerTemplate = (puller ? insertMethodMacros(getTemplate('/codeblocks/puller', templates), puller, json, templates, options, examples) : '')
const setter = getSetterFor(methodObj.name, json)
const setterTemplate = (setter ? insertMethodMacros(getTemplate('/codeblocks/setter', templates), setter, json, templates, examples) : '')
const setterTemplate = (setter ? insertMethodMacros(getTemplate('/codeblocks/setter', templates), setter, json, templates, options, examples) : '')
const subscriber = json.methods.find(method => method.tags.find(tag => tag['x-alternative'] === methodObj.name))
const subscriberTemplate = (subscriber ? insertMethodMacros(getTemplate('/codeblocks/subscriber', templates), subscriber, json, templates, examples) : '')
const subscriberTemplate = (subscriber ? insertMethodMacros(getTemplate('/codeblocks/subscriber', templates), subscriber, json, templates, options, examples) : '')
const setterFor = methodObj.tags.find(t => t.name === 'setter') && methodObj.tags.find(t => t.name === 'setter')['x-setter-for'] || ''
const pullsResult = (puller || pullsFor) ? localizeDependencies(pullsFor || methodObj, json).params[1].schema : null
const pullsParams = (puller || pullsFor) ? localizeDependencies(getPayloadFromEvent(puller || methodObj), json, null, { mergeAllOfs: true }).properties.parameters : null
Expand Down Expand Up @@ -1113,6 +1131,7 @@ function insertMethodMacros(template, methodObj, json, templates, examples = {})
template = insertExampleMacros(template, examples[methodObj.name] || [], methodObj, json, templates)

template = template.replace(/\$\{method\.name\}/g, method.name)
.replace(/\$\{method\.json\.name\}/g, options.polymorphic ? methodObj.actualName || method.name : method.name)
.replace(/\$\{method\.summary\}/g, methodObj.summary)
.replace(/\$\{method\.description\}/g, methodObj.description
|| methodObj.summary)
Expand Down
7 changes: 4 additions & 3 deletions src/macrofier/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ const macrofy = async (
templatesPerModule,
templatesPerSchema,
persistPermission,
createPolymorphicMethods,
createModuleDirectories,
copySchemasIntoModules,
extractSubSchemas,
Expand Down Expand Up @@ -159,7 +160,7 @@ const macrofy = async (

// Pick the index and defaults templates for each module.
templatesPerModule.forEach(t => {
const macros = engine.generateMacros(module, templates, exampleTemplates, {hideExcluded: hideExcluded, copySchemasIntoModules: copySchemasIntoModules, destination: t})
const macros = engine.generateMacros(module, templates, exampleTemplates, {hideExcluded: hideExcluded, copySchemasIntoModules: copySchemasIntoModules, createPolymorphicMethods: createPolymorphicMethods, destination: t})
let content = getTemplateForModule(module.info.title, t, templates)

// NOTE: whichever insert is called first also needs to be called again last, so each phase can insert recursive macros from the other
Expand All @@ -174,7 +175,7 @@ const macrofy = async (
})

if (primaryOutput) {
const macros = engine.generateMacros(module, templates, exampleTemplates, {hideExcluded: hideExcluded, copySchemasIntoModules: copySchemasIntoModules, destination: primaryOutput})
const macros = engine.generateMacros(module, templates, exampleTemplates, {hideExcluded: hideExcluded, copySchemasIntoModules: copySchemasIntoModules, createPolymorphicMethods: createPolymorphicMethods, destination: primaryOutput})
macros.append = append
outputFiles[primaryOutput] = engine.insertMacros(outputFiles[primaryOutput], macros)
}
Expand Down Expand Up @@ -256,7 +257,7 @@ const macrofy = async (
Object.values(externalSchemas).forEach( document => {
if (templatesPerSchema) {
templatesPerSchema.forEach( t => {
const macros = engine.generateMacros(document, templates, exampleTemplates, {hideExcluded: hideExcluded, destination: t})
const macros = engine.generateMacros(document, templates, exampleTemplates, {hideExcluded: hideExcluded, createPolymorphicMethods: createPolymorphicMethods, destination: t})
let content = getTemplate('/schemas', t, templates)

// NOTE: whichever insert is called first also needs to be called again last, so each phase can insert recursive macros from the other
Expand Down
1 change: 1 addition & 0 deletions src/sdk/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ const run = async ({
templatesPerModule: config.templatesPerModule,
templatesPerSchema: config.templatesPerSchema,
persistPermission: config.persistPermission,
createPolymorphicMethods: config.createPolymorphicMethods,
operators: config.operators,
createModuleDirectories: config.createModuleDirectories,
copySchemasIntoModules: config.copySchemasIntoModules,
Expand Down
Loading

0 comments on commit 0264f88

Please sign in to comment.